Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- DragMesh/scripts/data/build_lmdb.py +245 -0
- DragMesh/scripts/evaluation/__init__.py +0 -0
- DragMesh/scripts/evaluation/evaluate_p3sam_mask_metrics.py +260 -0
- DragMesh/scripts/evaluation/run_llm_joint_type_eval.py +354 -0
- DragMesh/scripts/p3sam/__init__.py +0 -0
- DragMesh/scripts/p3sam/export_p3sam_gap25_assets.py +110 -0
- DragMesh/scripts/p3sam/postprocess_p3sam_drag_masks_nonoracle.py +813 -0
- DragMesh/scripts/p3sam/run_p3sam_local_union_pipeline.py +855 -0
- DragMesh/scripts/reviewer/__init__.py +0 -0
- DragMesh/scripts/reviewer/run_reviewer_q4_diagnostics.py +685 -0
- DragMesh/scripts/train/__init__.py +0 -0
- DragMesh/scripts/train/train_predictor.py +540 -0
- DragMesh/scripts/train/train_vae_v2.py +496 -0
- DragMesh/test_data/furniture/DrawerChest/output/DrawerChest/initial_static.glb +0 -0
- DragMesh/test_data/furniture/DrawerChest/output/DrawerChest/predicted_z_0.glb +0 -0
- DragMesh/test_data/furniture/DrawerChest/output/inference.log +24 -0
- DragMesh/test_data/furniture/DrawerChest/output/results.json +42 -0
- DragMesh/test_data/furniture/Fridge/output/Fridge/initial_static.glb +0 -0
- DragMesh/test_data/furniture/Fridge/output/Fridge/predicted_z_0.glb +0 -0
- DragMesh/test_data/furniture/Laptop/output/Laptop/initial_static.glb +0 -0
- DragMesh/test_data/furniture/Laptop/output/Laptop/predicted_z_0.glb +0 -0
- DragMesh/test_data/furniture/Microwave/output/Microwave/initial_static.glb +0 -0
- DragMesh/test_data/furniture/Microwave/output/Microwave/predicted_z_0.glb +0 -0
- DragMesh/test_data/furniture/Microwave/output/Microwave/predicted_z_1.glb +0 -0
- DragMesh/test_data/furniture/Microwave/output/Microwave/predicted_z_2.glb +0 -0
- DragMesh/test_data/furniture/Microwave/output/inference_audit.json +53 -0
- DragMesh/test_data/furniture/Window/output/Window/initial_static.glb +0 -0
- DragMesh/test_data/furniture/Window/output/Window/predicted_z_0.glb +0 -0
- DragMesh/test_data/furniture/Window/output/run_metadata.json +32 -0
- dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00014/meshes/gt-body.ply +0 -0
- dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00014/meshes/gt-lefthand.ply +0 -0
- dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00014/meshes/gt-righthand.ply +0 -0
- dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00014/meshes/pred-ours-body.ply +0 -0
- dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00014/meshes/pred-ours-lefthand.ply +0 -0
- dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00014/meshes/pred-ours-righthand.ply +0 -0
- dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00025/meshes/gt-body.ply +0 -0
- dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00025/meshes/gt-lefthand.ply +0 -0
- dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00025/meshes/gt-righthand.ply +0 -0
- dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00025/meshes/pred-ours-body.ply +0 -0
- dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00025/meshes/pred-ours-lefthand.ply +0 -0
- dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00025/meshes/pred-ours-righthand.ply +0 -0
- dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00061/meshes/gt-lefthand.ply +0 -0
- dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00072/meshes/gt-body.ply +0 -0
- dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00072/meshes/gt-lefthand.ply +0 -0
- dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00072/meshes/gt-righthand.ply +0 -0
- dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00072/meshes/pred-ours-body.ply +0 -0
- dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00072/meshes/pred-ours-lefthand.ply +0 -0
- dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00072/meshes/pred-ours-righthand.ply +0 -0
- dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00128/meshes/gt-body.ply +0 -0
- dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00128/meshes/gt-lefthand.ply +0 -0
DragMesh/scripts/data/build_lmdb.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -------------------------------------------------------------------
|
| 2 |
+
# scripts/data/build_lmdb.py
|
| 3 |
+
# -------------------------------------------------------------------
|
| 4 |
+
"""
|
| 5 |
+
Build LMDB databases for VAE/KPP training.
|
| 6 |
+
|
| 7 |
+
This script samples point clouds in a low-memory mode, performs normalization, and writes
|
| 8 |
+
train/val splits to LMDB for efficient training I/O.
|
| 9 |
+
"""
|
| 10 |
+
import sys
|
| 11 |
+
import os
|
| 12 |
+
import argparse
|
| 13 |
+
import json
|
| 14 |
+
import torch
|
| 15 |
+
import numpy as np
|
| 16 |
+
import trimesh
|
| 17 |
+
from torch.utils.data import Dataset, random_split, Subset
|
| 18 |
+
|
| 19 |
+
# Ensure the repository root is importable
|
| 20 |
+
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')))
|
| 21 |
+
|
| 22 |
+
# Import the GAPartNet loader.
|
| 23 |
+
from dragmesh.data.data_loader_v2 import GAPartNetLoaderV2
|
| 24 |
+
from dragmesh.data.balanced_dataset_utils import build_vae_lmdb
|
| 25 |
+
from dragmesh.utils.kpp_normalization import bbox_center_scale, normalize_points, normalize_vector
|
| 26 |
+
|
| 27 |
+
class SmartProcessingDataset(Dataset):
|
| 28 |
+
"""
|
| 29 |
+
Smart processing dataset:
|
| 30 |
+
1) Category-based filtering (config-driven)
|
| 31 |
+
2) Uses the GAPartNet loader
|
| 32 |
+
3) Filtering based on motion magnitude
|
| 33 |
+
4) Normalization and point sampling
|
| 34 |
+
"""
|
| 35 |
+
def __init__(self, root, categories=None, num_frames=16, num_points=4096, joint_selection: str = "largest_motion"):
|
| 36 |
+
print(f"Initializing Loader from: {root}")
|
| 37 |
+
self.loader = GAPartNetLoaderV2(root)
|
| 38 |
+
self.num_frames = num_frames
|
| 39 |
+
self.num_points = num_points
|
| 40 |
+
self.joint_selection = joint_selection
|
| 41 |
+
|
| 42 |
+
# === 1) Category-based filtering ===
|
| 43 |
+
if categories:
|
| 44 |
+
print(f"Filtering for {len(categories)} categories...")
|
| 45 |
+
self.valid_indices = []
|
| 46 |
+
for i, obj_path in enumerate(self.loader.object_list):
|
| 47 |
+
# Check meta.json for category labels.
|
| 48 |
+
meta_path = os.path.join(obj_path, "meta.json")
|
| 49 |
+
if os.path.exists(meta_path):
|
| 50 |
+
try:
|
| 51 |
+
with open(meta_path, 'r') as f:
|
| 52 |
+
meta = json.load(f)
|
| 53 |
+
if meta.get('model_cat') in categories:
|
| 54 |
+
self.valid_indices.append(i)
|
| 55 |
+
except:
|
| 56 |
+
pass
|
| 57 |
+
print(f"Found {len(self.valid_indices)} objects matching categories.")
|
| 58 |
+
else:
|
| 59 |
+
self.valid_indices = list(range(len(self.loader.object_list)))
|
| 60 |
+
|
| 61 |
+
def __len__(self):
|
| 62 |
+
return len(self.valid_indices)
|
| 63 |
+
|
| 64 |
+
def __getitem__(self, idx):
|
| 65 |
+
# Map back to the loader's global object index.
|
| 66 |
+
real_idx = self.valid_indices[idx]
|
| 67 |
+
|
| 68 |
+
try:
|
| 69 |
+
# 1) Fetch a raw sample from the loader.
|
| 70 |
+
raw = self.loader.generate_training_sample(
|
| 71 |
+
real_idx,
|
| 72 |
+
self.num_frames,
|
| 73 |
+
joint_selection=self.joint_selection,
|
| 74 |
+
return_mesh=False, # key: low-memory point-cloud mode (avoid mesh concat OOM)
|
| 75 |
+
num_points=self.num_points # sample points inside the loader
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
# 2) Motion-based filtering.
|
| 79 |
+
joint_type = raw['joint_type']
|
| 80 |
+
is_valid = False
|
| 81 |
+
|
| 82 |
+
if joint_type in ['revolute', 'continuous']:
|
| 83 |
+
# Check rotation magnitude via quaternion angle difference (first vs last frame).
|
| 84 |
+
q_s, q_e = raw['qr_sequence'][0], raw['qr_sequence'][-1]
|
| 85 |
+
dot = np.abs(np.dot(q_s, q_e))
|
| 86 |
+
angle_diff = 2 * np.arccos(np.clip(dot, -1, 1))
|
| 87 |
+
# Threshold: > ~17 degrees (~0.3 rad).
|
| 88 |
+
if angle_diff > 0.3:
|
| 89 |
+
is_valid = True
|
| 90 |
+
|
| 91 |
+
elif joint_type == 'prismatic':
|
| 92 |
+
# Check translation distance.
|
| 93 |
+
traj = raw['drag_trajectory']
|
| 94 |
+
dist = np.linalg.norm(traj[-1] - traj[0])
|
| 95 |
+
if dist > 0.1:
|
| 96 |
+
is_valid = True
|
| 97 |
+
|
| 98 |
+
if not is_valid:
|
| 99 |
+
return None # tell build_vae_lmdb to skip this sample
|
| 100 |
+
|
| 101 |
+
# 3) === Normalization (points already sampled by the loader) ===
|
| 102 |
+
# KPP predicts the origin in the normalized point-cloud frame. This
|
| 103 |
+
# frame must be available at inference, so center on the object bbox,
|
| 104 |
+
# not the GT joint origin.
|
| 105 |
+
points = raw['initial_mesh'] # [N,3] ndarray
|
| 106 |
+
|
| 107 |
+
# Compute scale: prefer loader-provided bounds; otherwise use point-cloud bounds.
|
| 108 |
+
if 'bounds_min' in raw and 'bounds_max' in raw:
|
| 109 |
+
bmin = raw['bounds_min']
|
| 110 |
+
bmax = raw['bounds_max']
|
| 111 |
+
else:
|
| 112 |
+
bmin = points.min(axis=0)
|
| 113 |
+
bmax = points.max(axis=0)
|
| 114 |
+
center, scale = bbox_center_scale(bmin, bmax)
|
| 115 |
+
|
| 116 |
+
points = normalize_points(points, center, scale)
|
| 117 |
+
|
| 118 |
+
# 4) Part mask is already point-level (0=static, 1=movable).
|
| 119 |
+
p_mask = raw['part_mask'].astype(np.int32)
|
| 120 |
+
|
| 121 |
+
# 5) Pack output dict
|
| 122 |
+
out = {
|
| 123 |
+
'initial_mesh': points.astype(np.float32, copy=False),
|
| 124 |
+
'drag_point': normalize_points(raw['drag_point'], center, scale),
|
| 125 |
+
'drag_vector': normalize_vector(raw['drag_vector'], scale),
|
| 126 |
+
'qr_gt': raw['qr_sequence'].astype(np.float32),
|
| 127 |
+
'qd_gt': (raw['qd_sequence'] / scale).astype(np.float32),
|
| 128 |
+
'joint_type': 0 if joint_type in ['revolute', 'continuous'] else 1,
|
| 129 |
+
'joint_axis': raw['joint_axis'].astype(np.float32),
|
| 130 |
+
'joint_origin': normalize_points(raw['joint_origin'], center, scale),
|
| 131 |
+
'part_mask': p_mask.astype(np.float32),
|
| 132 |
+
'norm_center': center.astype(np.float32),
|
| 133 |
+
'norm_scale': np.array(scale, dtype=np.float32),
|
| 134 |
+
'origin_normalization_version': np.array(1, dtype=np.int64),
|
| 135 |
+
|
| 136 |
+
# Extra fields (used by loss/augmentation)
|
| 137 |
+
'rotation_direction': raw['rotation_direction'].astype(np.float32),
|
| 138 |
+
'trajectory_vectors': (raw['trajectory_vectors'] / scale).astype(np.float32),
|
| 139 |
+
'drag_trajectory': normalize_points(raw['drag_trajectory'], center, scale)
|
| 140 |
+
}
|
| 141 |
+
return out
|
| 142 |
+
|
| 143 |
+
except Exception as e:
|
| 144 |
+
# print(f"Skip sample {real_idx}: {e}")
|
| 145 |
+
return None
|
| 146 |
+
|
| 147 |
+
def main(args):
|
| 148 |
+
print("\n" + "="*70)
|
| 149 |
+
print("BUILDING LMDB DATABASES (IN-CATEGORY VALIDATION ONLY)")
|
| 150 |
+
print("With motion-based filtering and low-memory point sampling")
|
| 151 |
+
print("="*70)
|
| 152 |
+
|
| 153 |
+
# 1) Load configuration.
|
| 154 |
+
print(f"Loading config: {args.config}")
|
| 155 |
+
with open(args.config, 'r') as f:
|
| 156 |
+
config = json.load(f)
|
| 157 |
+
|
| 158 |
+
# Load train_categories only.
|
| 159 |
+
train_categories = config['train_categories']
|
| 160 |
+
val_in_config = config.get('val_in_category', {})
|
| 161 |
+
val_split_ratio = val_in_config.get('split_ratio', 0.1)
|
| 162 |
+
seed = val_in_config.get('random_seed', 42)
|
| 163 |
+
|
| 164 |
+
print(f"Total categories: {len(train_categories)}")
|
| 165 |
+
print(f"Val split ratio: {val_split_ratio}")
|
| 166 |
+
|
| 167 |
+
# 2) Initialize smart dataset (includes filtering in __getitem__).
|
| 168 |
+
# Note: we do not use FixedDragMeshDatasetV2 here; we use SmartProcessingDataset to avoid
|
| 169 |
+
# unnecessary work performed during dataset initialization.
|
| 170 |
+
print("\nInitializing Smart Dataset...")
|
| 171 |
+
full_dataset = SmartProcessingDataset(
|
| 172 |
+
root=args.dataset_root,
|
| 173 |
+
categories=train_categories,
|
| 174 |
+
num_frames=args.num_frames,
|
| 175 |
+
num_points=args.num_points,
|
| 176 |
+
joint_selection=args.joint_selection
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
# 3) Note: len(full_dataset) counts objects matching categories; the number of valid samples is
|
| 180 |
+
# determined during LMDB build because __getitem__ may return None.
|
| 181 |
+
print(f"Found {len(full_dataset)} matching objects (filtering happens during build).")
|
| 182 |
+
|
| 183 |
+
# 4) Split into train/val objects.
|
| 184 |
+
val_size = int(len(full_dataset) * val_split_ratio)
|
| 185 |
+
train_size = len(full_dataset) - val_size
|
| 186 |
+
|
| 187 |
+
print(f"\nSplitting into {train_size} (Train) and {val_size} (Val) objects.")
|
| 188 |
+
|
| 189 |
+
train_subset, val_subset = random_split(
|
| 190 |
+
full_dataset,
|
| 191 |
+
[train_size, val_size],
|
| 192 |
+
generator=torch.Generator().manual_seed(seed)
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
# 5) Build training LMDB.
|
| 196 |
+
output_path_train = args.output_prefix + "_train.lmdb"
|
| 197 |
+
print(f"\nBuilding TRAINING LMDB...")
|
| 198 |
+
build_vae_lmdb(
|
| 199 |
+
dataset=train_subset,
|
| 200 |
+
output_path=output_path_train,
|
| 201 |
+
categories=train_categories,
|
| 202 |
+
num_frames=args.num_frames,
|
| 203 |
+
num_points=args.num_points
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
# 6) Build validation LMDB.
|
| 207 |
+
output_path_val = args.output_prefix + "_val.lmdb"
|
| 208 |
+
print(f"\nBuilding VALIDATION LMDB...")
|
| 209 |
+
build_vae_lmdb(
|
| 210 |
+
dataset=val_subset,
|
| 211 |
+
output_path=output_path_val,
|
| 212 |
+
categories=train_categories,
|
| 213 |
+
num_frames=args.num_frames,
|
| 214 |
+
num_points=args.num_points
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
print("\n" + "="*70)
|
| 218 |
+
print("LMDB BUILD COMPLETE!")
|
| 219 |
+
print(f"Train Output: {output_path_train}")
|
| 220 |
+
print(f"Val Output: {output_path_val}")
|
| 221 |
+
print("="*70 + "\n")
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
if __name__ == "__main__":
|
| 225 |
+
parser = argparse.ArgumentParser(description="Build VAE LMDB")
|
| 226 |
+
parser.add_argument('--dataset_root', type=str, required=True,
|
| 227 |
+
help='Root directory of dataset')
|
| 228 |
+
parser.add_argument('--output_prefix', type=str, required=True,
|
| 229 |
+
help='Prefix for output LMDBs')
|
| 230 |
+
parser.add_argument('--config', type=str,
|
| 231 |
+
default='configs/category_split_v2.json',
|
| 232 |
+
help='Category split configuration')
|
| 233 |
+
parser.add_argument('--num_frames', type=int, default=16,
|
| 234 |
+
help='Number of trajectory frames')
|
| 235 |
+
parser.add_argument('--num_points', type=int, default=4096,
|
| 236 |
+
help='Number of points to sample')
|
| 237 |
+
parser.add_argument(
|
| 238 |
+
'--joint_selection',
|
| 239 |
+
type=str,
|
| 240 |
+
default='largest_motion',
|
| 241 |
+
choices=['largest_motion', 'random', 'first'],
|
| 242 |
+
help='How to choose the joint for each object when generating samples'
|
| 243 |
+
)
|
| 244 |
+
args = parser.parse_args()
|
| 245 |
+
main(args)
|
DragMesh/scripts/evaluation/__init__.py
ADDED
|
File without changes
|
DragMesh/scripts/evaluation/evaluate_p3sam_mask_metrics.py
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Evaluate P3-SAM or other part masks against binary movable-part labels.
|
| 3 |
+
|
| 4 |
+
The script is intentionally format-lightweight: provide a manifest CSV with one
|
| 5 |
+
row per case and paths to predicted and GT masks. Multi-part predicted labels
|
| 6 |
+
are matched to the GT movable mask by best IoU unless `pred_part_id` is given.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import csv
|
| 13 |
+
import json
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from typing import Dict, Iterable, List, Optional, Tuple
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
import trimesh
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
LABEL_FORMATS = {"face_labels", "vertex_labels"}
|
| 22 |
+
BINARY_FORMATS = {"binary_face", "binary_vertex"}
|
| 23 |
+
ALL_FORMATS = LABEL_FORMATS | BINARY_FORMATS
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def read_csv(path: Path) -> List[Dict[str, str]]:
|
| 27 |
+
with path.open(newline="") as f:
|
| 28 |
+
return list(csv.DictReader(f))
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def write_csv(path: Path, rows: List[Dict[str, object]], fieldnames: Iterable[str]) -> None:
|
| 32 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 33 |
+
with path.open("w", newline="") as f:
|
| 34 |
+
writer = csv.DictWriter(f, fieldnames=list(fieldnames))
|
| 35 |
+
writer.writeheader()
|
| 36 |
+
writer.writerows(rows)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def load_mask(path: Path) -> np.ndarray:
|
| 40 |
+
if path.suffix == ".npy":
|
| 41 |
+
return np.load(path)
|
| 42 |
+
if path.suffix == ".npz":
|
| 43 |
+
data = np.load(path)
|
| 44 |
+
if "mask" in data:
|
| 45 |
+
return data["mask"]
|
| 46 |
+
if "face_ids" in data:
|
| 47 |
+
return data["face_ids"]
|
| 48 |
+
first_key = list(data.keys())[0]
|
| 49 |
+
return data[first_key]
|
| 50 |
+
raise ValueError(f"Unsupported mask file extension: {path}")
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def face_labels_to_vertex_labels(faces: np.ndarray, num_vertices: int, face_labels: np.ndarray) -> np.ndarray:
|
| 54 |
+
vertex_votes: List[List[int]] = [[] for _ in range(num_vertices)]
|
| 55 |
+
for fid, face in enumerate(faces):
|
| 56 |
+
label = int(face_labels[fid])
|
| 57 |
+
if label < 0:
|
| 58 |
+
continue
|
| 59 |
+
for vid in face:
|
| 60 |
+
vertex_votes[int(vid)].append(label)
|
| 61 |
+
|
| 62 |
+
vertex_labels = -np.ones(num_vertices, dtype=np.int64)
|
| 63 |
+
for vid, labels in enumerate(vertex_votes):
|
| 64 |
+
if labels:
|
| 65 |
+
counts = np.bincount(np.asarray(labels, dtype=np.int64))
|
| 66 |
+
vertex_labels[vid] = int(np.argmax(counts))
|
| 67 |
+
return vertex_labels
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def vertex_binary_to_face_binary(faces: np.ndarray, vertex_mask: np.ndarray) -> np.ndarray:
|
| 71 |
+
return vertex_mask[faces].mean(axis=1) > 0.5
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def vertex_labels_to_face_labels(faces: np.ndarray, vertex_labels: np.ndarray) -> np.ndarray:
|
| 75 |
+
face_labels = -np.ones(len(faces), dtype=np.int64)
|
| 76 |
+
for fid, face in enumerate(faces):
|
| 77 |
+
labels = vertex_labels[face]
|
| 78 |
+
labels = labels[labels >= 0]
|
| 79 |
+
if labels.size:
|
| 80 |
+
counts = np.bincount(labels.astype(np.int64))
|
| 81 |
+
face_labels[fid] = int(np.argmax(counts))
|
| 82 |
+
return face_labels
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def as_face_array(mask: np.ndarray, mask_format: str, mesh: trimesh.Trimesh) -> np.ndarray:
|
| 86 |
+
if mask_format not in ALL_FORMATS:
|
| 87 |
+
raise ValueError(f"Unknown mask format {mask_format!r}; expected one of {sorted(ALL_FORMATS)}")
|
| 88 |
+
values = np.asarray(mask).reshape(-1)
|
| 89 |
+
if mask_format in {"face_labels", "binary_face"}:
|
| 90 |
+
if values.shape[0] != len(mesh.faces):
|
| 91 |
+
raise ValueError(f"Face mask length {values.shape[0]} != mesh faces {len(mesh.faces)}")
|
| 92 |
+
return values
|
| 93 |
+
if values.shape[0] != len(mesh.vertices):
|
| 94 |
+
raise ValueError(f"Vertex mask length {values.shape[0]} != mesh vertices {len(mesh.vertices)}")
|
| 95 |
+
if mask_format == "binary_vertex":
|
| 96 |
+
return vertex_binary_to_face_binary(mesh.faces, values.astype(bool))
|
| 97 |
+
return vertex_labels_to_face_labels(mesh.faces, values.astype(np.int64))
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def binary_metrics(pred: np.ndarray, gt: np.ndarray) -> Tuple[float, float, float]:
|
| 101 |
+
pred_bool = pred.astype(bool)
|
| 102 |
+
gt_bool = gt.astype(bool)
|
| 103 |
+
tp = float(np.logical_and(pred_bool, gt_bool).sum())
|
| 104 |
+
fp = float(np.logical_and(pred_bool, ~gt_bool).sum())
|
| 105 |
+
fn = float(np.logical_and(~pred_bool, gt_bool).sum())
|
| 106 |
+
precision = tp / (tp + fp) if (tp + fp) > 0 else 0.0
|
| 107 |
+
recall = tp / (tp + fn) if (tp + fn) > 0 else 0.0
|
| 108 |
+
iou = tp / (tp + fp + fn) if (tp + fp + fn) > 0 else 0.0
|
| 109 |
+
return precision, recall, iou
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def best_pred_mask(pred_face: np.ndarray, pred_format: str, gt_face_binary: np.ndarray,
|
| 113 |
+
pred_part_id: Optional[int]) -> Tuple[np.ndarray, Optional[int], float]:
|
| 114 |
+
if pred_format in BINARY_FORMATS:
|
| 115 |
+
pred_binary = pred_face.astype(bool)
|
| 116 |
+
_, _, iou = binary_metrics(pred_binary, gt_face_binary)
|
| 117 |
+
return pred_binary, pred_part_id, iou
|
| 118 |
+
|
| 119 |
+
labels = [int(v) for v in np.unique(pred_face) if int(v) >= 0]
|
| 120 |
+
if pred_part_id is not None:
|
| 121 |
+
pred_binary = pred_face.astype(np.int64) == int(pred_part_id)
|
| 122 |
+
_, _, iou = binary_metrics(pred_binary, gt_face_binary)
|
| 123 |
+
return pred_binary, int(pred_part_id), iou
|
| 124 |
+
|
| 125 |
+
best_label = None
|
| 126 |
+
best_iou = -1.0
|
| 127 |
+
best_binary = np.zeros_like(gt_face_binary, dtype=bool)
|
| 128 |
+
for label in labels:
|
| 129 |
+
candidate = pred_face.astype(np.int64) == label
|
| 130 |
+
_, _, iou = binary_metrics(candidate, gt_face_binary)
|
| 131 |
+
if iou > best_iou:
|
| 132 |
+
best_label = label
|
| 133 |
+
best_iou = iou
|
| 134 |
+
best_binary = candidate
|
| 135 |
+
return best_binary, best_label, max(best_iou, 0.0)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def oracle_union_pred_mask(pred_face: np.ndarray, pred_format: str,
|
| 139 |
+
gt_face_binary: np.ndarray) -> Tuple[np.ndarray, str, float]:
|
| 140 |
+
"""Greedily groups predicted P3-SAM parts into a movable/rest binary mask."""
|
| 141 |
+
if pred_format in BINARY_FORMATS:
|
| 142 |
+
pred_binary = pred_face.astype(bool)
|
| 143 |
+
_, _, iou = binary_metrics(pred_binary, gt_face_binary)
|
| 144 |
+
return pred_binary, "binary", iou
|
| 145 |
+
|
| 146 |
+
labels = [int(v) for v in np.unique(pred_face) if int(v) >= 0]
|
| 147 |
+
selected: List[int] = []
|
| 148 |
+
current = np.zeros_like(gt_face_binary, dtype=bool)
|
| 149 |
+
_, _, current_iou = binary_metrics(current, gt_face_binary)
|
| 150 |
+
|
| 151 |
+
while True:
|
| 152 |
+
best_label = None
|
| 153 |
+
best_mask = current
|
| 154 |
+
best_iou = current_iou
|
| 155 |
+
for label in labels:
|
| 156 |
+
if label in selected:
|
| 157 |
+
continue
|
| 158 |
+
candidate = np.logical_or(current, pred_face.astype(np.int64) == label)
|
| 159 |
+
_, _, iou = binary_metrics(candidate, gt_face_binary)
|
| 160 |
+
if iou > best_iou + 1e-12:
|
| 161 |
+
best_label = label
|
| 162 |
+
best_mask = candidate
|
| 163 |
+
best_iou = iou
|
| 164 |
+
if best_label is None:
|
| 165 |
+
break
|
| 166 |
+
selected.append(best_label)
|
| 167 |
+
current = best_mask
|
| 168 |
+
current_iou = best_iou
|
| 169 |
+
|
| 170 |
+
return current, ";".join(str(v) for v in selected), current_iou
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def summarize(values: Iterable[float]) -> Dict[str, float]:
|
| 174 |
+
vals = np.asarray(list(values), dtype=np.float64)
|
| 175 |
+
if vals.size == 0:
|
| 176 |
+
return {"mean": 0.0, "median": 0.0, "min": 0.0, "max": 0.0}
|
| 177 |
+
return {
|
| 178 |
+
"mean": float(vals.mean()),
|
| 179 |
+
"median": float(np.median(vals)),
|
| 180 |
+
"min": float(vals.min()),
|
| 181 |
+
"max": float(vals.max()),
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def main() -> None:
|
| 186 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 187 |
+
parser.add_argument("--manifest", type=Path, required=True,
|
| 188 |
+
help="CSV with case_id, mesh_path, pred_mask_path, gt_mask_path, pred_mask_format, gt_mask_format.")
|
| 189 |
+
parser.add_argument("--output_csv", type=Path, required=True)
|
| 190 |
+
parser.add_argument("--summary_json", type=Path, default=None)
|
| 191 |
+
parser.add_argument(
|
| 192 |
+
"--selection_mode",
|
| 193 |
+
choices=["best_single", "oracle_union"],
|
| 194 |
+
default="best_single",
|
| 195 |
+
help="best_single evaluates one predicted part; oracle_union groups predicted parts into movable/rest.",
|
| 196 |
+
)
|
| 197 |
+
args = parser.parse_args()
|
| 198 |
+
|
| 199 |
+
rows = []
|
| 200 |
+
for src in read_csv(args.manifest):
|
| 201 |
+
mesh = trimesh.load(src["mesh_path"], process=False)
|
| 202 |
+
if isinstance(mesh, trimesh.Scene):
|
| 203 |
+
mesh = trimesh.util.concatenate(tuple(mesh.geometry.values()))
|
| 204 |
+
|
| 205 |
+
pred_format = src.get("pred_mask_format", "face_labels")
|
| 206 |
+
gt_format = src.get("gt_mask_format", "binary_face")
|
| 207 |
+
pred_face = as_face_array(load_mask(Path(src["pred_mask_path"])), pred_format, mesh)
|
| 208 |
+
gt_face = as_face_array(load_mask(Path(src["gt_mask_path"])), gt_format, mesh).astype(bool)
|
| 209 |
+
pred_part_id = src.get("pred_part_id", "").strip()
|
| 210 |
+
pred_part = int(pred_part_id) if pred_part_id else None
|
| 211 |
+
|
| 212 |
+
if args.selection_mode == "oracle_union" and pred_part is None:
|
| 213 |
+
pred_binary, matched_part, _ = oracle_union_pred_mask(pred_face, pred_format, gt_face)
|
| 214 |
+
else:
|
| 215 |
+
pred_binary, matched_part, _ = best_pred_mask(pred_face, pred_format, gt_face, pred_part)
|
| 216 |
+
precision, recall, iou = binary_metrics(pred_binary, gt_face)
|
| 217 |
+
rows.append({
|
| 218 |
+
"case_id": src.get("case_id", Path(src["mesh_path"]).stem),
|
| 219 |
+
"matched_pred_part_id": "" if matched_part is None else matched_part,
|
| 220 |
+
"selection_mode": args.selection_mode,
|
| 221 |
+
"oracle_selection": args.selection_mode in {"best_single", "oracle_union"} and pred_part is None,
|
| 222 |
+
"precision": precision,
|
| 223 |
+
"recall": recall,
|
| 224 |
+
"iou": iou,
|
| 225 |
+
"pred_positive_faces": int(pred_binary.sum()),
|
| 226 |
+
"gt_positive_faces": int(gt_face.sum()),
|
| 227 |
+
})
|
| 228 |
+
|
| 229 |
+
fieldnames = [
|
| 230 |
+
"case_id",
|
| 231 |
+
"matched_pred_part_id",
|
| 232 |
+
"selection_mode",
|
| 233 |
+
"oracle_selection",
|
| 234 |
+
"precision",
|
| 235 |
+
"recall",
|
| 236 |
+
"iou",
|
| 237 |
+
"pred_positive_faces",
|
| 238 |
+
"gt_positive_faces",
|
| 239 |
+
]
|
| 240 |
+
write_csv(args.output_csv, rows, fieldnames)
|
| 241 |
+
|
| 242 |
+
if args.summary_json:
|
| 243 |
+
args.summary_json.parent.mkdir(parents=True, exist_ok=True)
|
| 244 |
+
summary = {
|
| 245 |
+
"cases": len(rows),
|
| 246 |
+
"selection_mode": args.selection_mode,
|
| 247 |
+
"oracle_selection": args.selection_mode in {"best_single", "oracle_union"},
|
| 248 |
+
"precision": summarize(float(row["precision"]) for row in rows),
|
| 249 |
+
"recall": summarize(float(row["recall"]) for row in rows),
|
| 250 |
+
"iou": summarize(float(row["iou"]) for row in rows),
|
| 251 |
+
}
|
| 252 |
+
args.summary_json.write_text(json.dumps(summary, indent=2, sort_keys=True))
|
| 253 |
+
|
| 254 |
+
print(f"Wrote {args.output_csv}")
|
| 255 |
+
if args.summary_json:
|
| 256 |
+
print(f"Wrote {args.summary_json}")
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
if __name__ == "__main__":
|
| 260 |
+
main()
|
DragMesh/scripts/evaluation/run_llm_joint_type_eval.py
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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入 JSON 或 CSV 需要包含字段:
|
| 5 |
+
- id 或 case_id
|
| 6 |
+
- category
|
| 7 |
+
- interaction
|
| 8 |
+
- gt_joint_type: revolute / prismatic / static
|
| 9 |
+
|
| 10 |
+
示例:
|
| 11 |
+
python scripts/run_llm_joint_type_eval.py \
|
| 12 |
+
--input results/gap25_joint_type_cases.json \
|
| 13 |
+
--output_dir results/llm_joint_type_eval \
|
| 14 |
+
--model gpt-4o
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import argparse
|
| 20 |
+
import csv
|
| 21 |
+
import json
|
| 22 |
+
import os
|
| 23 |
+
import time
|
| 24 |
+
from dataclasses import dataclass
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
from typing import Dict, Iterable, List, Optional
|
| 27 |
+
|
| 28 |
+
VALID_JOINT_TYPES = {"revolute", "prismatic", "static"}
|
| 29 |
+
|
| 30 |
+
SYSTEM_PROMPT = (
|
| 31 |
+
"You are an expert in 3D object kinematics. Classify the joint type into "
|
| 32 |
+
"exactly one of the following: revolute, prismatic, or static. "
|
| 33 |
+
"Output ONLY ONE WORD. No punctuation, no explanation."
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
USER_PROMPT_TEMPLATE = (
|
| 37 |
+
"Object Category: {category}. Interaction: {interaction}. "
|
| 38 |
+
"What is the joint type? Output exactly one word."
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@dataclass(frozen=True)
|
| 43 |
+
class TestCase:
|
| 44 |
+
"""单个关节类型测试样本。"""
|
| 45 |
+
|
| 46 |
+
case_id: str
|
| 47 |
+
category: str
|
| 48 |
+
interaction: str
|
| 49 |
+
gt_joint_type: str
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@dataclass
|
| 53 |
+
class PredictionRow:
|
| 54 |
+
"""单个样本的模型预测与评估结果。"""
|
| 55 |
+
|
| 56 |
+
case_id: str
|
| 57 |
+
category: str
|
| 58 |
+
interaction: str
|
| 59 |
+
gt_joint_type: str
|
| 60 |
+
pred_joint_type: str
|
| 61 |
+
raw_response: str
|
| 62 |
+
correct: bool
|
| 63 |
+
error: str
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def normalize_joint_type(value: object) -> str:
|
| 67 |
+
"""把 API 返回或 GT 字段规范化到三个合法类别之一。"""
|
| 68 |
+
|
| 69 |
+
text = str(value or "").strip().lower()
|
| 70 |
+
text = text.replace(".", "").replace(",", "")
|
| 71 |
+
if text in VALID_JOINT_TYPES:
|
| 72 |
+
return text
|
| 73 |
+
return "error"
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def read_json_cases(path: Path) -> List[TestCase]:
|
| 77 |
+
"""读取 JSON 数据;支持 list 或 {"cases": [...]} 两种格式。"""
|
| 78 |
+
|
| 79 |
+
data = json.loads(path.read_text(encoding="utf-8"))
|
| 80 |
+
rows = data.get("cases", data) if isinstance(data, dict) else data
|
| 81 |
+
if not isinstance(rows, list):
|
| 82 |
+
raise ValueError(f"JSON 输入应为 list 或包含 cases 的 dict: {path}")
|
| 83 |
+
return [row_to_case(row) for row in rows]
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def read_csv_cases(path: Path) -> List[TestCase]:
|
| 87 |
+
"""读取 CSV 数据。"""
|
| 88 |
+
|
| 89 |
+
with path.open(newline="", encoding="utf-8") as f:
|
| 90 |
+
return [row_to_case(row) for row in csv.DictReader(f)]
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def row_to_case(row: Dict[str, object]) -> TestCase:
|
| 94 |
+
"""把原始行转换为强类型 TestCase,并做必要字段检查。"""
|
| 95 |
+
|
| 96 |
+
case_id = str(row.get("id") or row.get("case_id") or "").strip()
|
| 97 |
+
category = str(row.get("category") or "").strip()
|
| 98 |
+
interaction = str(row.get("interaction") or "").strip()
|
| 99 |
+
gt_joint_type = normalize_joint_type(row.get("gt_joint_type"))
|
| 100 |
+
|
| 101 |
+
missing = []
|
| 102 |
+
if not case_id:
|
| 103 |
+
missing.append("id/case_id")
|
| 104 |
+
if not category:
|
| 105 |
+
missing.append("category")
|
| 106 |
+
if not interaction:
|
| 107 |
+
missing.append("interaction")
|
| 108 |
+
if gt_joint_type == "error":
|
| 109 |
+
missing.append("gt_joint_type")
|
| 110 |
+
if missing:
|
| 111 |
+
raise ValueError(f"case 字段缺失或非法: {missing}; row={row}")
|
| 112 |
+
|
| 113 |
+
return TestCase(
|
| 114 |
+
case_id=case_id,
|
| 115 |
+
category=category,
|
| 116 |
+
interaction=interaction,
|
| 117 |
+
gt_joint_type=gt_joint_type,
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def load_cases(path: Path) -> List[TestCase]:
|
| 122 |
+
"""根据扩展名自动读取 JSON 或 CSV。"""
|
| 123 |
+
|
| 124 |
+
suffix = path.suffix.lower()
|
| 125 |
+
if suffix == ".json":
|
| 126 |
+
return read_json_cases(path)
|
| 127 |
+
if suffix == ".csv":
|
| 128 |
+
return read_csv_cases(path)
|
| 129 |
+
raise ValueError(f"只支持 .json 或 .csv 输入: {path}")
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def call_llm_joint_type(
|
| 133 |
+
*,
|
| 134 |
+
client: object,
|
| 135 |
+
model: str,
|
| 136 |
+
case: TestCase,
|
| 137 |
+
temperature: float,
|
| 138 |
+
max_retries: int,
|
| 139 |
+
retry_sleep: float,
|
| 140 |
+
) -> str:
|
| 141 |
+
"""调用 OpenAI-compatible Chat Completions API,并带指数退避重试。"""
|
| 142 |
+
|
| 143 |
+
user_prompt = USER_PROMPT_TEMPLATE.format(
|
| 144 |
+
category=case.category,
|
| 145 |
+
interaction=case.interaction,
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
last_error: Optional[BaseException] = None
|
| 149 |
+
for attempt in range(max_retries + 1):
|
| 150 |
+
try:
|
| 151 |
+
# openai>=1.0.0 的官方 SDK 风格:client.chat.completions.create(...)
|
| 152 |
+
response = client.chat.completions.create(
|
| 153 |
+
model=model,
|
| 154 |
+
messages=[
|
| 155 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 156 |
+
{"role": "user", "content": user_prompt},
|
| 157 |
+
],
|
| 158 |
+
temperature=temperature,
|
| 159 |
+
max_tokens=8,
|
| 160 |
+
)
|
| 161 |
+
content = response.choices[0].message.content
|
| 162 |
+
return str(content or "")
|
| 163 |
+
except Exception as exc: # noqa: BLE001 - API 兼容端可能抛出不同异常类型
|
| 164 |
+
last_error = exc
|
| 165 |
+
if attempt >= max_retries:
|
| 166 |
+
break
|
| 167 |
+
sleep_s = retry_sleep * (2**attempt)
|
| 168 |
+
print(f"[retry] {case.case_id}: attempt={attempt + 1}, sleep={sleep_s:.1f}s, error={exc}")
|
| 169 |
+
time.sleep(sleep_s)
|
| 170 |
+
|
| 171 |
+
raise RuntimeError(f"API 调用失败: case_id={case.case_id}, error={last_error}")
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def predict_case(
|
| 175 |
+
*,
|
| 176 |
+
client: object,
|
| 177 |
+
model: str,
|
| 178 |
+
case: TestCase,
|
| 179 |
+
temperature: float,
|
| 180 |
+
max_retries: int,
|
| 181 |
+
retry_sleep: float,
|
| 182 |
+
) -> PredictionRow:
|
| 183 |
+
"""预测单个 case,并做 deterministic parsing。"""
|
| 184 |
+
|
| 185 |
+
try:
|
| 186 |
+
raw_response = call_llm_joint_type(
|
| 187 |
+
client=client,
|
| 188 |
+
model=model,
|
| 189 |
+
case=case,
|
| 190 |
+
temperature=temperature,
|
| 191 |
+
max_retries=max_retries,
|
| 192 |
+
retry_sleep=retry_sleep,
|
| 193 |
+
)
|
| 194 |
+
pred = normalize_joint_type(raw_response)
|
| 195 |
+
error = "" if pred != "error" else "invalid_model_output"
|
| 196 |
+
except Exception as exc: # noqa: BLE001
|
| 197 |
+
raw_response = ""
|
| 198 |
+
pred = "error"
|
| 199 |
+
error = str(exc)
|
| 200 |
+
|
| 201 |
+
return PredictionRow(
|
| 202 |
+
case_id=case.case_id,
|
| 203 |
+
category=case.category,
|
| 204 |
+
interaction=case.interaction,
|
| 205 |
+
gt_joint_type=case.gt_joint_type,
|
| 206 |
+
pred_joint_type=pred,
|
| 207 |
+
raw_response=raw_response,
|
| 208 |
+
correct=pred == case.gt_joint_type,
|
| 209 |
+
error=error,
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def write_predictions_csv(path: Path, rows: Iterable[PredictionRow]) -> None:
|
| 214 |
+
"""保存每个 case 的完整预测结果。"""
|
| 215 |
+
|
| 216 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 217 |
+
fieldnames = [
|
| 218 |
+
"case_id",
|
| 219 |
+
"category",
|
| 220 |
+
"interaction",
|
| 221 |
+
"gt_joint_type",
|
| 222 |
+
"pred_joint_type",
|
| 223 |
+
"raw_response",
|
| 224 |
+
"correct",
|
| 225 |
+
"error",
|
| 226 |
+
]
|
| 227 |
+
with path.open("w", newline="", encoding="utf-8") as f:
|
| 228 |
+
writer = csv.DictWriter(f, fieldnames=fieldnames)
|
| 229 |
+
writer.writeheader()
|
| 230 |
+
for row in rows:
|
| 231 |
+
writer.writerow(row.__dict__)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def write_failure_cases(path: Path, rows: List[PredictionRow]) -> None:
|
| 235 |
+
"""保存错误样本,便于后续 error analysis。"""
|
| 236 |
+
|
| 237 |
+
failures = [
|
| 238 |
+
{
|
| 239 |
+
"id": row.case_id,
|
| 240 |
+
"category": row.category,
|
| 241 |
+
"interaction": row.interaction,
|
| 242 |
+
"gt_joint_type": row.gt_joint_type,
|
| 243 |
+
"pred_joint_type": row.pred_joint_type,
|
| 244 |
+
"raw_response": row.raw_response,
|
| 245 |
+
"error": row.error,
|
| 246 |
+
}
|
| 247 |
+
for row in rows
|
| 248 |
+
if not row.correct
|
| 249 |
+
]
|
| 250 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 251 |
+
path.write_text(json.dumps(failures, indent=2, ensure_ascii=False), encoding="utf-8")
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def write_summary(path: Path, rows: List[PredictionRow], model: str) -> None:
|
| 255 |
+
"""保存总体 accuracy 和逐类统计。"""
|
| 256 |
+
|
| 257 |
+
total = len(rows)
|
| 258 |
+
correct = sum(row.correct for row in rows)
|
| 259 |
+
errors = sum(row.pred_joint_type == "error" for row in rows)
|
| 260 |
+
|
| 261 |
+
per_category: Dict[str, Dict[str, object]] = {}
|
| 262 |
+
for category in sorted({row.category for row in rows}):
|
| 263 |
+
subset = [row for row in rows if row.category == category]
|
| 264 |
+
n = len(subset)
|
| 265 |
+
c = sum(row.correct for row in subset)
|
| 266 |
+
per_category[category] = {
|
| 267 |
+
"total": n,
|
| 268 |
+
"correct": c,
|
| 269 |
+
"accuracy": c / n if n else 0.0,
|
| 270 |
+
}
|
| 271 |
+
|
| 272 |
+
summary = {
|
| 273 |
+
"model": model,
|
| 274 |
+
"total": total,
|
| 275 |
+
"correct": correct,
|
| 276 |
+
"errors": errors,
|
| 277 |
+
"accuracy": correct / total if total else 0.0,
|
| 278 |
+
"per_category": per_category,
|
| 279 |
+
}
|
| 280 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 281 |
+
path.write_text(json.dumps(summary, indent=2, ensure_ascii=False), encoding="utf-8")
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def build_client(api_key: Optional[str], base_url: Optional[str]) -> object:
|
| 285 |
+
"""构造 OpenAI SDK client;base_url 可指向兼容 OpenAI 协议的内部 API。"""
|
| 286 |
+
|
| 287 |
+
from openai import OpenAI
|
| 288 |
+
|
| 289 |
+
resolved_key = api_key or os.environ.get("OPENAI_API_KEY")
|
| 290 |
+
if not resolved_key:
|
| 291 |
+
raise EnvironmentError("缺少 API key:请设置 OPENAI_API_KEY 或传入 --api_key")
|
| 292 |
+
|
| 293 |
+
if base_url:
|
| 294 |
+
return OpenAI(api_key=resolved_key, base_url=base_url)
|
| 295 |
+
return OpenAI(api_key=resolved_key)
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def parse_args() -> argparse.Namespace:
|
| 299 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 300 |
+
parser.add_argument("--input", type=Path, required=True, help="测试集 JSON/CSV,包含 id/category/interaction/gt_joint_type")
|
| 301 |
+
parser.add_argument("--output_dir", type=Path, default=Path("results/llm_joint_type_eval"))
|
| 302 |
+
parser.add_argument("--model", type=str, default="gpt-4o")
|
| 303 |
+
parser.add_argument("--api_key", type=str, default=None, help="默认读取 OPENAI_API_KEY")
|
| 304 |
+
parser.add_argument("--base_url", type=str, default=None, help="OpenAI-compatible API base URL,可选")
|
| 305 |
+
parser.add_argument("--temperature", type=float, default=0.0)
|
| 306 |
+
parser.add_argument("--max_retries", type=int, default=3)
|
| 307 |
+
parser.add_argument("--retry_sleep", type=float, default=2.0)
|
| 308 |
+
parser.add_argument("--limit", type=int, default=None, help="调试用:只跑前 N 个 case")
|
| 309 |
+
return parser.parse_args()
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def main() -> None:
|
| 313 |
+
args = parse_args()
|
| 314 |
+
cases = load_cases(args.input)
|
| 315 |
+
if args.limit is not None:
|
| 316 |
+
cases = cases[: args.limit]
|
| 317 |
+
|
| 318 |
+
client = build_client(api_key=args.api_key, base_url=args.base_url)
|
| 319 |
+
rows: List[PredictionRow] = []
|
| 320 |
+
|
| 321 |
+
for idx, case in enumerate(cases, start=1):
|
| 322 |
+
row = predict_case(
|
| 323 |
+
client=client,
|
| 324 |
+
model=args.model,
|
| 325 |
+
case=case,
|
| 326 |
+
temperature=args.temperature,
|
| 327 |
+
max_retries=args.max_retries,
|
| 328 |
+
retry_sleep=args.retry_sleep,
|
| 329 |
+
)
|
| 330 |
+
rows.append(row)
|
| 331 |
+
status = "OK" if row.correct else "FAIL"
|
| 332 |
+
print(
|
| 333 |
+
f"[{idx:02d}/{len(cases):02d}] {case.case_id}: "
|
| 334 |
+
f"gt={row.gt_joint_type}, pred={row.pred_joint_type}, {status}"
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
predictions_csv = args.output_dir / "predictions.csv"
|
| 338 |
+
failures_json = args.output_dir / "failure_cases.json"
|
| 339 |
+
summary_json = args.output_dir / "summary.json"
|
| 340 |
+
write_predictions_csv(predictions_csv, rows)
|
| 341 |
+
write_failure_cases(failures_json, rows)
|
| 342 |
+
write_summary(summary_json, rows, args.model)
|
| 343 |
+
|
| 344 |
+
correct = sum(row.correct for row in rows)
|
| 345 |
+
total = len(rows)
|
| 346 |
+
accuracy = correct / total if total else 0.0
|
| 347 |
+
print(f"Accuracy: {correct}/{total} = {accuracy:.3f}")
|
| 348 |
+
print(f"Wrote {predictions_csv}")
|
| 349 |
+
print(f"Wrote {failures_json}")
|
| 350 |
+
print(f"Wrote {summary_json}")
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
if __name__ == "__main__":
|
| 354 |
+
main()
|
DragMesh/scripts/p3sam/__init__.py
ADDED
|
File without changes
|
DragMesh/scripts/p3sam/export_p3sam_gap25_assets.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Export GAP-25 meshes and GT movable masks for P3-SAM evaluation."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import csv
|
| 8 |
+
import sys
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Dict, Iterable, List
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
|
| 14 |
+
ROOT = Path(__file__).resolve().parents[2]
|
| 15 |
+
sys.path.insert(0, str(ROOT))
|
| 16 |
+
|
| 17 |
+
from dragmesh.data.data_loader_v2 import GAPartNetLoaderV2 # noqa: E402
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def read_csv(path: Path) -> List[Dict[str, str]]:
|
| 21 |
+
with path.open(newline="") as f:
|
| 22 |
+
return list(csv.DictReader(f))
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def write_csv(path: Path, rows: List[Dict[str, object]], fieldnames: Iterable[str]) -> None:
|
| 26 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 27 |
+
with path.open("w", newline="") as f:
|
| 28 |
+
writer = csv.DictWriter(f, fieldnames=list(fieldnames))
|
| 29 |
+
writer.writeheader()
|
| 30 |
+
writer.writerows(rows)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def object_id_from_case(case_id: str) -> str:
|
| 34 |
+
return case_id.rsplit("_", 1)[-1]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def main() -> None:
|
| 38 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 39 |
+
parser.add_argument(
|
| 40 |
+
"--cases_csv",
|
| 41 |
+
type=Path,
|
| 42 |
+
required=True,
|
| 43 |
+
)
|
| 44 |
+
parser.add_argument(
|
| 45 |
+
"--dataset_root",
|
| 46 |
+
type=Path,
|
| 47 |
+
default=ROOT / "data/gapartnet_full/partnet_mobility_part",
|
| 48 |
+
)
|
| 49 |
+
parser.add_argument(
|
| 50 |
+
"--output_dir",
|
| 51 |
+
type=Path,
|
| 52 |
+
default=Path("results/p3sam_gap25_assets"),
|
| 53 |
+
)
|
| 54 |
+
parser.add_argument("--num_frames", type=int, default=16)
|
| 55 |
+
args = parser.parse_args()
|
| 56 |
+
|
| 57 |
+
args.output_dir.mkdir(parents=True, exist_ok=True)
|
| 58 |
+
manifest_rows = []
|
| 59 |
+
|
| 60 |
+
for row in read_csv(args.cases_csv):
|
| 61 |
+
case_id = row["case_id"]
|
| 62 |
+
object_id = object_id_from_case(case_id)
|
| 63 |
+
obj_dir = args.dataset_root / object_id
|
| 64 |
+
if not obj_dir.exists():
|
| 65 |
+
raise FileNotFoundError(f"Missing GAPartNet object dir for {case_id}: {obj_dir}")
|
| 66 |
+
|
| 67 |
+
loader = GAPartNetLoaderV2(str(obj_dir))
|
| 68 |
+
sample = loader.generate_training_sample(0, num_frames=args.num_frames, return_mesh=True)
|
| 69 |
+
mesh = sample["initial_mesh"]
|
| 70 |
+
vertex_mask = np.asarray(sample["part_mask"]).astype(bool)
|
| 71 |
+
face_mask = vertex_mask[mesh.faces].mean(axis=1) > 0.5
|
| 72 |
+
|
| 73 |
+
case_dir = args.output_dir / case_id
|
| 74 |
+
case_dir.mkdir(parents=True, exist_ok=True)
|
| 75 |
+
mesh_path = case_dir / f"{case_id}.glb"
|
| 76 |
+
gt_mask_path = case_dir / f"{case_id}_gt_movable_face_mask.npy"
|
| 77 |
+
mesh.export(mesh_path)
|
| 78 |
+
np.save(gt_mask_path, face_mask.astype(np.uint8))
|
| 79 |
+
|
| 80 |
+
manifest_rows.append(
|
| 81 |
+
{
|
| 82 |
+
"case_id": case_id,
|
| 83 |
+
"category": row["category"],
|
| 84 |
+
"object_id": object_id,
|
| 85 |
+
"mesh_path": mesh_path,
|
| 86 |
+
"gt_mask_path": gt_mask_path,
|
| 87 |
+
"gt_mask_format": "binary_face",
|
| 88 |
+
"gt_joint_type": row["gt_joint_type"],
|
| 89 |
+
}
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
manifest_path = args.output_dir / "gap25_p3sam_assets_manifest.csv"
|
| 93 |
+
write_csv(
|
| 94 |
+
manifest_path,
|
| 95 |
+
manifest_rows,
|
| 96 |
+
[
|
| 97 |
+
"case_id",
|
| 98 |
+
"category",
|
| 99 |
+
"object_id",
|
| 100 |
+
"mesh_path",
|
| 101 |
+
"gt_mask_path",
|
| 102 |
+
"gt_mask_format",
|
| 103 |
+
"gt_joint_type",
|
| 104 |
+
],
|
| 105 |
+
)
|
| 106 |
+
print(f"Wrote {manifest_path}")
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
if __name__ == "__main__":
|
| 110 |
+
main()
|
DragMesh/scripts/p3sam/postprocess_p3sam_drag_masks_nonoracle.py
ADDED
|
@@ -0,0 +1,813 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Non-oracle drag-aware post-processing for P3-SAM proposals.
|
| 3 |
+
|
| 4 |
+
This script turns P3-SAM face-label proposals into a binary movable/rest mask
|
| 5 |
+
for DragMesh using only:
|
| 6 |
+
|
| 7 |
+
- user drag point / vector,
|
| 8 |
+
- mesh geometry,
|
| 9 |
+
- P3-SAM proposal labels,
|
| 10 |
+
- fixed category-level priors when requested.
|
| 11 |
+
|
| 12 |
+
It does not use GT masks, GT centroids, or GT IoU to select proposals.
|
| 13 |
+
Any GT-based prompt is reported as oracle upper bound only.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import argparse
|
| 19 |
+
import csv
|
| 20 |
+
import json
|
| 21 |
+
from collections import deque
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
from typing import Dict, Iterable, List, Optional, Sequence, Tuple
|
| 24 |
+
|
| 25 |
+
import numpy as np
|
| 26 |
+
import trimesh
|
| 27 |
+
from scipy.spatial import cKDTree
|
| 28 |
+
from trimesh.registration import icp
|
| 29 |
+
|
| 30 |
+
REPO_ROOT = Path(__file__).resolve().parents[2]
|
| 31 |
+
|
| 32 |
+
import sys
|
| 33 |
+
|
| 34 |
+
sys.path.insert(0, str(REPO_ROOT))
|
| 35 |
+
|
| 36 |
+
from scripts.evaluation.evaluate_p3sam_mask_metrics import as_face_array, binary_metrics, load_mask
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
RAW_DRAG_SELECTED = "raw_drag_selected"
|
| 40 |
+
FIXED_DRAG_CLEANUP = "fixed_drag_cleanup"
|
| 41 |
+
CATEGORY_DRAG_CLEANUP = "category_adaptive_drag_cleanup"
|
| 42 |
+
ORACLE_CENTROID = "oracle_centroid_upper_bound"
|
| 43 |
+
|
| 44 |
+
CATEGORY_PRIORS: Dict[str, Dict[str, object]] = {
|
| 45 |
+
"microwave": {"radius": 0.20, "back_tol": 0.08, "min_comp": 18, "area_min": 0.03, "area_max": 0.50, "ring_hops": 2},
|
| 46 |
+
"laptop": {"radius": 0.30, "back_tol": 0.12, "min_comp": 24, "area_min": 0.12, "area_max": 0.78, "ring_hops": 2},
|
| 47 |
+
"drawer": {"radius": 0.20, "back_tol": 0.10, "min_comp": 16, "area_min": 0.04, "area_max": 0.40, "ring_hops": 2},
|
| 48 |
+
"bucket": {"radius": 0.24, "back_tol": 0.12, "min_comp": 12, "area_min": 0.02, "area_max": 0.35, "ring_hops": 2},
|
| 49 |
+
"oven": {"radius": 0.24, "back_tol": 0.08, "min_comp": 18, "area_min": 0.05, "area_max": 0.55, "ring_hops": 2},
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
LEGACY_ORACLE_CATEGORY_RULES: Dict[str, Dict[str, object]] = {
|
| 53 |
+
"microwave": {"mode": "local", "dilation_radius": 0.25, "label_crop_radius": 0.25, "back_side_tolerance": None},
|
| 54 |
+
"laptop": {"mode": "label_full_or_local", "dilation_radius": 0.25, "label_crop_radius": 0.25, "back_side_tolerance": None},
|
| 55 |
+
"drawer": {"mode": "local", "dilation_radius": 0.25, "label_crop_radius": 0.25, "back_side_tolerance": 0.125},
|
| 56 |
+
"bucket": {"mode": "local", "dilation_radius": 0.30, "label_crop_radius": 0.30, "back_side_tolerance": 0.15},
|
| 57 |
+
"oven": {"mode": "local", "dilation_radius": 0.35, "label_crop_radius": 0.35, "back_side_tolerance": 0.05},
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
FIXED_PRIOR = {"radius": 0.22, "back_tol": 0.10, "min_comp": 16, "area_min": 0.03, "area_max": 0.55, "ring_hops": 2}
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def read_csv(path: Path) -> List[Dict[str, str]]:
|
| 64 |
+
with path.open(newline="") as f:
|
| 65 |
+
return list(csv.DictReader(f))
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def write_csv(path: Path, rows: List[Dict[str, object]], fieldnames: Sequence[str]) -> None:
|
| 69 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 70 |
+
with path.open("w", newline="") as f:
|
| 71 |
+
writer = csv.DictWriter(f, fieldnames=fieldnames)
|
| 72 |
+
writer.writeheader()
|
| 73 |
+
writer.writerows(rows)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def summarize(values: Iterable[float]) -> Dict[str, float]:
|
| 77 |
+
vals = np.asarray(list(values), dtype=np.float64)
|
| 78 |
+
if vals.size == 0:
|
| 79 |
+
return {"mean": 0.0, "median": 0.0, "min": 0.0, "max": 0.0}
|
| 80 |
+
return {
|
| 81 |
+
"mean": float(vals.mean()),
|
| 82 |
+
"median": float(np.median(vals)),
|
| 83 |
+
"min": float(vals.min()),
|
| 84 |
+
"max": float(vals.max()),
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def load_mesh_fast(path: Path) -> trimesh.Trimesh:
|
| 89 |
+
mesh = trimesh.load(path, force="mesh", process=False, skip_materials=True)
|
| 90 |
+
if isinstance(mesh, trimesh.Scene):
|
| 91 |
+
mesh = trimesh.util.concatenate(tuple(mesh.geometry.values()))
|
| 92 |
+
if not isinstance(mesh, trimesh.Trimesh):
|
| 93 |
+
raise TypeError(f"Unsupported mesh type: {type(mesh)} for {path}")
|
| 94 |
+
return mesh
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def load_manifest_drag(path: Optional[Path]) -> Dict[str, Dict[str, object]]:
|
| 98 |
+
if path is None:
|
| 99 |
+
return {}
|
| 100 |
+
data = json.loads(path.read_text())
|
| 101 |
+
cases = data.get("cases", data)
|
| 102 |
+
return {str(case["case_id"]): case for case in cases}
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def icp_align_drag_point(
|
| 106 |
+
canonical_mesh: trimesh.Trimesh,
|
| 107 |
+
target_mesh: trimesh.Trimesh,
|
| 108 |
+
drag_point: np.ndarray,
|
| 109 |
+
num_samples: int = 4000,
|
| 110 |
+
) -> np.ndarray:
|
| 111 |
+
src_points, _ = trimesh.sample.sample_surface(canonical_mesh, num_samples)
|
| 112 |
+
dst_points, _ = trimesh.sample.sample_surface(target_mesh, num_samples)
|
| 113 |
+
matrix, _, _ = icp(src_points, dst_points, scale=True, reflection=False)
|
| 114 |
+
drag_h = np.append(np.asarray(drag_point, dtype=np.float64), 1.0)
|
| 115 |
+
return (matrix @ drag_h)[:3].astype(np.float64)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def nearest_vertex_on_mesh(mesh: trimesh.Trimesh, point: np.ndarray) -> Tuple[np.ndarray, int, float]:
|
| 119 |
+
tree = cKDTree(mesh.vertices)
|
| 120 |
+
dist, idx = tree.query(np.asarray(point, dtype=np.float64))
|
| 121 |
+
idx = int(idx)
|
| 122 |
+
return mesh.vertices[idx].astype(np.float64), idx, float(dist)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def category_from_case_id(case_id: str) -> str:
|
| 126 |
+
return case_id.split("_", 1)[0].lower()
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def face_adjacency_list(mesh: trimesh.Trimesh) -> List[List[int]]:
|
| 130 |
+
adj: List[List[int]] = [[] for _ in range(len(mesh.faces))]
|
| 131 |
+
for a, b in mesh.face_adjacency:
|
| 132 |
+
a = int(a)
|
| 133 |
+
b = int(b)
|
| 134 |
+
adj[a].append(b)
|
| 135 |
+
adj[b].append(a)
|
| 136 |
+
return adj
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def expand_faces(mask: np.ndarray, adj: List[List[int]], hops: int = 1) -> np.ndarray:
|
| 140 |
+
if hops <= 0 or not mask.any():
|
| 141 |
+
return mask.copy()
|
| 142 |
+
cur = {int(v) for v in np.where(mask)[0]}
|
| 143 |
+
out = set(cur)
|
| 144 |
+
for _ in range(hops):
|
| 145 |
+
nxt = set()
|
| 146 |
+
for f in cur:
|
| 147 |
+
for nb in adj[f]:
|
| 148 |
+
if nb not in out:
|
| 149 |
+
out.add(nb)
|
| 150 |
+
nxt.add(nb)
|
| 151 |
+
cur = nxt
|
| 152 |
+
out_mask = np.zeros_like(mask, dtype=bool)
|
| 153 |
+
out_mask[np.asarray(sorted(out), dtype=np.int64)] = True
|
| 154 |
+
return out_mask
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def connected_components(mask: np.ndarray, adj: List[List[int]]) -> List[np.ndarray]:
|
| 158 |
+
seen = np.zeros(len(mask), dtype=bool)
|
| 159 |
+
comps: List[np.ndarray] = []
|
| 160 |
+
for start in np.where(mask)[0]:
|
| 161 |
+
start = int(start)
|
| 162 |
+
if seen[start]:
|
| 163 |
+
continue
|
| 164 |
+
queue = deque([start])
|
| 165 |
+
seen[start] = True
|
| 166 |
+
comp: List[int] = []
|
| 167 |
+
while queue:
|
| 168 |
+
fid = queue.popleft()
|
| 169 |
+
comp.append(fid)
|
| 170 |
+
for nb in adj[fid]:
|
| 171 |
+
if mask[nb] and not seen[nb]:
|
| 172 |
+
seen[nb] = True
|
| 173 |
+
queue.append(nb)
|
| 174 |
+
comps.append(np.asarray(comp, dtype=np.int64))
|
| 175 |
+
return comps
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def seed_local_faces(mesh: trimesh.Trimesh, seed_vertex: int, adj: List[List[int]], hops: int = 2) -> np.ndarray:
|
| 179 |
+
incident = np.where((mesh.faces == int(seed_vertex)).any(axis=1))[0].tolist()
|
| 180 |
+
local = set(int(v) for v in incident)
|
| 181 |
+
frontier = list(local)
|
| 182 |
+
for _ in range(hops):
|
| 183 |
+
nxt: List[int] = []
|
| 184 |
+
for fid in frontier:
|
| 185 |
+
for nb in adj[fid]:
|
| 186 |
+
nb = int(nb)
|
| 187 |
+
if nb not in local:
|
| 188 |
+
local.add(nb)
|
| 189 |
+
nxt.append(nb)
|
| 190 |
+
frontier = nxt
|
| 191 |
+
return np.asarray(sorted(local), dtype=np.int64)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def prompt_from_gt_face(mesh: trimesh.Trimesh, gt_face_mask: np.ndarray, mode: str) -> np.ndarray:
|
| 195 |
+
movable = np.where(gt_face_mask.astype(bool))[0]
|
| 196 |
+
if movable.size == 0:
|
| 197 |
+
raise ValueError("GT movable mask has no positive faces")
|
| 198 |
+
centers = mesh.triangles_center[movable]
|
| 199 |
+
if mode == "gt_centroid":
|
| 200 |
+
verts = mesh.vertices[mesh.faces[movable].reshape(-1)]
|
| 201 |
+
target = verts.mean(axis=0)
|
| 202 |
+
return centers[int(np.argmin(np.linalg.norm(centers - target[None, :], axis=1)))]
|
| 203 |
+
if mode == "gt_farthest_from_object_center":
|
| 204 |
+
object_center = mesh.vertices.mean(axis=0)
|
| 205 |
+
return centers[int(np.argmax(np.linalg.norm(centers - object_center[None, :], axis=1)))]
|
| 206 |
+
raise ValueError(f"Unsupported GT prompt mode: {mode}")
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def legacy_oracle_postprocess(
|
| 210 |
+
mesh: trimesh.Trimesh,
|
| 211 |
+
face_labels: np.ndarray,
|
| 212 |
+
prompt: np.ndarray,
|
| 213 |
+
category: str,
|
| 214 |
+
min_component_faces: int,
|
| 215 |
+
) -> Tuple[np.ndarray, Dict[str, object]]:
|
| 216 |
+
centers = mesh.triangles_center
|
| 217 |
+
bbox_diag = float(np.linalg.norm(mesh.bounds[1] - mesh.bounds[0]))
|
| 218 |
+
bbox_diag = max(bbox_diag, 1e-12)
|
| 219 |
+
label_mask = face_labels >= 0
|
| 220 |
+
selected_label = -1
|
| 221 |
+
if np.any(label_mask):
|
| 222 |
+
labels = [int(v) for v in np.unique(face_labels) if int(v) >= 0]
|
| 223 |
+
selected_label = min(
|
| 224 |
+
labels,
|
| 225 |
+
key=lambda label: float(np.min(np.linalg.norm(centers[face_labels == label] - prompt[None, :], axis=1)))
|
| 226 |
+
if np.any(face_labels == label)
|
| 227 |
+
else float("inf"),
|
| 228 |
+
)
|
| 229 |
+
label_mask = face_labels == selected_label
|
| 230 |
+
dist = np.linalg.norm(centers - prompt[None, :], axis=1) / bbox_diag
|
| 231 |
+
label_local = label_mask & (dist <= float(LEGACY_ORACLE_CATEGORY_RULES.get(category, {}).get("label_crop_radius", 0.3)))
|
| 232 |
+
rule = LEGACY_ORACLE_CATEGORY_RULES.get(category, {"mode": "local", "dilation_radius": 0.3, "back_side_tolerance": 0.15})
|
| 233 |
+
mode = str(rule["mode"])
|
| 234 |
+
dilation_radius = float(rule["dilation_radius"])
|
| 235 |
+
back_side_tolerance = rule["back_side_tolerance"]
|
| 236 |
+
if mode == "local":
|
| 237 |
+
mask = dist <= dilation_radius
|
| 238 |
+
elif mode == "label_full_or_local":
|
| 239 |
+
mask = np.logical_or(label_mask, dist <= dilation_radius)
|
| 240 |
+
elif mode == "drag_or_label":
|
| 241 |
+
mask = np.logical_or(label_local, dist <= dilation_radius)
|
| 242 |
+
else:
|
| 243 |
+
mask = dist <= dilation_radius
|
| 244 |
+
outward = prompt - mesh.vertices.mean(axis=0)
|
| 245 |
+
norm = float(np.linalg.norm(outward))
|
| 246 |
+
if back_side_tolerance is not None and norm > 1e-8:
|
| 247 |
+
outward = outward / norm
|
| 248 |
+
signed = np.dot(centers - prompt[None, :], outward) / bbox_diag
|
| 249 |
+
mask &= signed >= -float(back_side_tolerance)
|
| 250 |
+
if min_component_faces > 1:
|
| 251 |
+
mask = remove_small_components(mask, face_adjacency_list(mesh), min_component_faces)
|
| 252 |
+
info = {
|
| 253 |
+
"selected_label": int(selected_label),
|
| 254 |
+
"bbox_diag": bbox_diag,
|
| 255 |
+
"raw_selected_faces": int(label_mask.sum()) if label_mask.ndim else 0,
|
| 256 |
+
"post_faces": int(mask.sum()),
|
| 257 |
+
"mode": mode,
|
| 258 |
+
}
|
| 259 |
+
return mask.astype(bool), info
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def score_candidate_labels(
|
| 263 |
+
mesh: trimesh.Trimesh,
|
| 264 |
+
face_labels: np.ndarray,
|
| 265 |
+
prompt: np.ndarray,
|
| 266 |
+
drag_vec: np.ndarray,
|
| 267 |
+
adj: List[List[int]],
|
| 268 |
+
ring_hops: int,
|
| 269 |
+
) -> Tuple[List[Dict[str, object]], int, float, float]:
|
| 270 |
+
centers = mesh.triangles_center
|
| 271 |
+
bbox_diag = float(np.linalg.norm(mesh.bounds[1] - mesh.bounds[0]))
|
| 272 |
+
bbox_diag = max(bbox_diag, 1e-12)
|
| 273 |
+
prompt_vertex, seed_vertex, seed_vertex_dist = nearest_vertex_on_mesh(mesh, prompt)
|
| 274 |
+
local_faces = seed_local_faces(mesh, seed_vertex, adj, hops=ring_hops)
|
| 275 |
+
local_labels = [int(face_labels[f]) for f in local_faces if int(face_labels[f]) >= 0]
|
| 276 |
+
labels = sorted(set(local_labels)) if local_labels else [int(v) for v in np.unique(face_labels) if int(v) >= 0]
|
| 277 |
+
if not labels:
|
| 278 |
+
labels = [-1]
|
| 279 |
+
|
| 280 |
+
drag = np.asarray(drag_vec, dtype=np.float64)
|
| 281 |
+
drag_norm = float(np.linalg.norm(drag))
|
| 282 |
+
drag = drag / drag_norm if drag_norm > 1e-12 else np.zeros(3, dtype=np.float64)
|
| 283 |
+
|
| 284 |
+
outward = prompt - mesh.vertices.mean(axis=0)
|
| 285 |
+
outward_norm = float(np.linalg.norm(outward))
|
| 286 |
+
outward = outward / outward_norm if outward_norm > 1e-12 else np.zeros(3, dtype=np.float64)
|
| 287 |
+
|
| 288 |
+
candidates: List[Dict[str, object]] = []
|
| 289 |
+
for label in labels:
|
| 290 |
+
mask = face_labels == int(label)
|
| 291 |
+
if not mask.any():
|
| 292 |
+
continue
|
| 293 |
+
idx = np.where(mask)[0]
|
| 294 |
+
pts = centers[idx]
|
| 295 |
+
centroid = pts.mean(axis=0)
|
| 296 |
+
area_ratio = float(mask.mean())
|
| 297 |
+
min_dist = float(np.min(np.linalg.norm(pts - prompt[None, :], axis=1)) / bbox_diag)
|
| 298 |
+
med_dist = float(np.median(np.linalg.norm(pts - prompt[None, :], axis=1)) / bbox_diag)
|
| 299 |
+
local_support = float(sum(bool(mask[f]) for f in local_faces) / max(1, len(local_faces)))
|
| 300 |
+
contains_drag = bool(sum(bool(mask[f]) for f in local_faces) > 0)
|
| 301 |
+
comps = connected_components(mask, adj)
|
| 302 |
+
frag_penalty = float(len(comps) / max(1, int(mask.sum())))
|
| 303 |
+
centered = centroid - mesh.vertices.mean(axis=0)
|
| 304 |
+
centered_norm = float(np.linalg.norm(centered))
|
| 305 |
+
direction_consistency = 0.0
|
| 306 |
+
if centered_norm > 1e-12:
|
| 307 |
+
centered = centered / centered_norm
|
| 308 |
+
direction_consistency = max(0.0, float(np.dot(centered, drag)))
|
| 309 |
+
far_side_penalty = 0.0
|
| 310 |
+
if float(np.linalg.norm(outward)) > 1e-12:
|
| 311 |
+
signed = float(np.dot(centroid - prompt, outward) / bbox_diag)
|
| 312 |
+
far_side_penalty = max(0.0, -signed)
|
| 313 |
+
|
| 314 |
+
area_penalty = 0.0
|
| 315 |
+
if area_ratio < 0.02:
|
| 316 |
+
area_penalty += (0.02 - area_ratio) / 0.02
|
| 317 |
+
if area_ratio > 0.75:
|
| 318 |
+
area_penalty += (area_ratio - 0.75) / 0.25
|
| 319 |
+
|
| 320 |
+
score = (
|
| 321 |
+
4.0 * float(contains_drag)
|
| 322 |
+
+ 3.0 * local_support
|
| 323 |
+
- 3.0 * med_dist
|
| 324 |
+
- 1.0 * min_dist
|
| 325 |
+
- 1.2 * area_penalty
|
| 326 |
+
- 1.0 * far_side_penalty
|
| 327 |
+
- 0.8 * frag_penalty
|
| 328 |
+
+ 0.5 * direction_consistency
|
| 329 |
+
)
|
| 330 |
+
candidates.append(
|
| 331 |
+
{
|
| 332 |
+
"label": int(label),
|
| 333 |
+
"score": float(score),
|
| 334 |
+
"contains_drag": bool(contains_drag),
|
| 335 |
+
"local_support": float(local_support),
|
| 336 |
+
"min_dist": float(min_dist),
|
| 337 |
+
"med_dist": float(med_dist),
|
| 338 |
+
"area_ratio": float(area_ratio),
|
| 339 |
+
"direction_consistency": float(direction_consistency),
|
| 340 |
+
"far_side_penalty": float(far_side_penalty),
|
| 341 |
+
"fragmentation_penalty": float(frag_penalty),
|
| 342 |
+
"seed_vertex": int(seed_vertex),
|
| 343 |
+
"seed_vertex_dist": float(seed_vertex_dist),
|
| 344 |
+
"centroid": centroid.tolist(),
|
| 345 |
+
"face_count": int(mask.sum()),
|
| 346 |
+
}
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
candidates.sort(key=lambda x: (-float(x["score"]), -float(x["local_support"]), float(x["med_dist"])))
|
| 350 |
+
return candidates, seed_vertex, seed_vertex_dist, bbox_diag
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def choose_selection_mask(
|
| 354 |
+
mesh: trimesh.Trimesh,
|
| 355 |
+
face_labels: np.ndarray,
|
| 356 |
+
candidates: List[Dict[str, object]],
|
| 357 |
+
mode: str,
|
| 358 |
+
prior: Dict[str, object],
|
| 359 |
+
) -> Tuple[np.ndarray, Dict[str, object]]:
|
| 360 |
+
adj = face_adjacency_list(mesh)
|
| 361 |
+
centers = mesh.triangles_center
|
| 362 |
+
prompt = np.asarray(prior["prompt"], dtype=np.float64)
|
| 363 |
+
seed_vertex = int(prior["seed_vertex"])
|
| 364 |
+
bbox_diag = float(prior["bbox_diag"])
|
| 365 |
+
selected_label = int(candidates[0]["label"]) if candidates else -1
|
| 366 |
+
|
| 367 |
+
if mode == RAW_DRAG_SELECTED:
|
| 368 |
+
mask = face_labels == selected_label
|
| 369 |
+
info = {
|
| 370 |
+
"selected_label": selected_label,
|
| 371 |
+
"selected_score": float(candidates[0]["score"]) if candidates else 0.0,
|
| 372 |
+
"selected_label_area": float(mask.mean()) if mask.size else 0.0,
|
| 373 |
+
"contains_drag": bool(candidates[0]["contains_drag"]) if candidates else False,
|
| 374 |
+
"local_support": float(candidates[0]["local_support"]) if candidates else 0.0,
|
| 375 |
+
"seed_vertex": seed_vertex,
|
| 376 |
+
"seed_vertex_dist": float(prior["seed_vertex_dist"]),
|
| 377 |
+
"candidate_count": len(candidates),
|
| 378 |
+
}
|
| 379 |
+
return mask.astype(bool), info
|
| 380 |
+
|
| 381 |
+
union = np.zeros(len(face_labels), dtype=bool)
|
| 382 |
+
top_score = float(candidates[0]["score"]) if candidates else -1e9
|
| 383 |
+
for cand in candidates[:3]:
|
| 384 |
+
if float(cand["score"]) >= top_score - 0.15 and bool(cand["contains_drag"]):
|
| 385 |
+
union |= face_labels == int(cand["label"])
|
| 386 |
+
if not union.any() and candidates:
|
| 387 |
+
union = face_labels == selected_label
|
| 388 |
+
mask = union.copy()
|
| 389 |
+
|
| 390 |
+
radius = float(prior["radius"])
|
| 391 |
+
back_tol = float(prior["back_tol"])
|
| 392 |
+
min_comp = int(prior["min_comp"])
|
| 393 |
+
area_min = float(prior["area_min"])
|
| 394 |
+
area_max = float(prior["area_max"])
|
| 395 |
+
ring_hops = int(prior["ring_hops"])
|
| 396 |
+
|
| 397 |
+
d = np.linalg.norm(centers - prompt[None, :], axis=1) / bbox_diag
|
| 398 |
+
mask &= d <= radius
|
| 399 |
+
|
| 400 |
+
outward = prompt - mesh.vertices.mean(axis=0)
|
| 401 |
+
outward_norm = float(np.linalg.norm(outward))
|
| 402 |
+
if outward_norm > 1e-12:
|
| 403 |
+
outward = outward / outward_norm
|
| 404 |
+
signed = np.dot(centers - prompt[None, :], outward) / bbox_diag
|
| 405 |
+
mask &= signed >= -back_tol
|
| 406 |
+
|
| 407 |
+
if mask.any():
|
| 408 |
+
mask = expand_faces(mask, adj, hops=1)
|
| 409 |
+
|
| 410 |
+
if mask.any():
|
| 411 |
+
comps = connected_components(mask, adj)
|
| 412 |
+
seed_face = int(np.argmin(np.linalg.norm(centers - prompt[None, :], axis=1)))
|
| 413 |
+
chosen = None
|
| 414 |
+
for comp in comps:
|
| 415 |
+
if seed_face in set(comp.tolist()):
|
| 416 |
+
chosen = comp
|
| 417 |
+
break
|
| 418 |
+
if chosen is None:
|
| 419 |
+
chosen = max(comps, key=len)
|
| 420 |
+
keep = np.zeros_like(mask, dtype=bool)
|
| 421 |
+
keep[chosen] = True
|
| 422 |
+
mask = keep
|
| 423 |
+
|
| 424 |
+
area_ratio = float(mask.mean()) if mask.size else 0.0
|
| 425 |
+
if mask.any() and (area_ratio < area_min or area_ratio > area_max):
|
| 426 |
+
if selected_label >= 0:
|
| 427 |
+
mask = face_labels == selected_label
|
| 428 |
+
|
| 429 |
+
if min_comp > 1 and mask.any():
|
| 430 |
+
comps = connected_components(mask, adj)
|
| 431 |
+
keep = np.zeros_like(mask, dtype=bool)
|
| 432 |
+
for comp in comps:
|
| 433 |
+
if len(comp) >= min_comp:
|
| 434 |
+
keep[comp] = True
|
| 435 |
+
if keep.any():
|
| 436 |
+
mask = keep
|
| 437 |
+
|
| 438 |
+
info = {
|
| 439 |
+
"selected_label": selected_label,
|
| 440 |
+
"selected_score": float(candidates[0]["score"]) if candidates else 0.0,
|
| 441 |
+
"selected_label_area": float((face_labels == selected_label).mean()) if selected_label >= 0 else 0.0,
|
| 442 |
+
"contains_drag": bool(candidates[0]["contains_drag"]) if candidates else False,
|
| 443 |
+
"local_support": float(candidates[0]["local_support"]) if candidates else 0.0,
|
| 444 |
+
"seed_vertex": seed_vertex,
|
| 445 |
+
"seed_vertex_dist": float(prior["seed_vertex_dist"]),
|
| 446 |
+
"candidate_count": len(candidates),
|
| 447 |
+
"cleanup_area_ratio": area_ratio,
|
| 448 |
+
"ring_hops": ring_hops,
|
| 449 |
+
}
|
| 450 |
+
return mask.astype(bool), info
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
def classify_failure(row: Dict[str, object]) -> str:
|
| 454 |
+
iou = float(row["iou"])
|
| 455 |
+
precision = float(row["precision"])
|
| 456 |
+
recall = float(row["recall"])
|
| 457 |
+
area_ratio = float(row.get("pred_area_ratio", 0.0))
|
| 458 |
+
seed_dist = float(row.get("seed_vertex_dist", 0.0))
|
| 459 |
+
contains_drag = bool(row.get("contains_drag", False))
|
| 460 |
+
selected_label = int(row.get("selected_label", -1))
|
| 461 |
+
candidate_count = int(row.get("candidate_count", 0))
|
| 462 |
+
if seed_dist > 0.08:
|
| 463 |
+
return "coordinate misalignment"
|
| 464 |
+
if candidate_count == 0 or not contains_drag:
|
| 465 |
+
return "no proposal near drag"
|
| 466 |
+
if selected_label < 0:
|
| 467 |
+
return "selected static/background proposal"
|
| 468 |
+
if iou < 0.15 and area_ratio > 0.50:
|
| 469 |
+
return "over-segmentation / too large"
|
| 470 |
+
if iou < 0.15 and area_ratio < 0.08:
|
| 471 |
+
return "under-segmentation / missing movable part"
|
| 472 |
+
if precision < 0.35 and recall < 0.35:
|
| 473 |
+
return "fragmented mask"
|
| 474 |
+
if precision < 0.45 and recall >= 0.45:
|
| 475 |
+
return "wrong side of object"
|
| 476 |
+
if recall < 0.30:
|
| 477 |
+
return "under-segmentation / missing movable part"
|
| 478 |
+
if precision < 0.30:
|
| 479 |
+
return "over-segmentation / too large"
|
| 480 |
+
return "mixed / weak mask"
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
def ensure_dir(path: Path) -> None:
|
| 484 |
+
path.mkdir(parents=True, exist_ok=True)
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
def save_simple_visualization(mesh: trimesh.Trimesh, face_mask: np.ndarray, prompt: np.ndarray, out_path: Path) -> None:
|
| 488 |
+
try:
|
| 489 |
+
import matplotlib.pyplot as plt
|
| 490 |
+
except Exception:
|
| 491 |
+
return
|
| 492 |
+
centers = mesh.triangles_center
|
| 493 |
+
pts = np.vstack([mesh.vertices, centers, prompt[None, :]])
|
| 494 |
+
pts0 = pts - pts.mean(axis=0, keepdims=True)
|
| 495 |
+
_, _, vh = np.linalg.svd(pts0, full_matrices=False)
|
| 496 |
+
basis = vh[:2].T
|
| 497 |
+
c2 = (centers - pts.mean(axis=0)) @ basis
|
| 498 |
+
p2 = (prompt - pts.mean(axis=0)) @ basis
|
| 499 |
+
fig, ax = plt.subplots(figsize=(5, 5))
|
| 500 |
+
ax.scatter(c2[:, 0], c2[:, 1], s=3, c=np.where(face_mask, "#d62728", "#1f77b4"), alpha=0.75)
|
| 501 |
+
ax.scatter([p2[0]], [p2[1]], s=80, c="#2ca02c", marker="x")
|
| 502 |
+
ax.set_aspect("equal")
|
| 503 |
+
ax.axis("off")
|
| 504 |
+
fig.savefig(out_path, dpi=160, bbox_inches="tight", pad_inches=0.02)
|
| 505 |
+
plt.close(fig)
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
def main() -> None:
|
| 509 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 510 |
+
parser.add_argument("--p3sam_manifest", type=Path, required=True)
|
| 511 |
+
parser.add_argument("--drag_manifest_json", type=Path, required=True)
|
| 512 |
+
parser.add_argument("--output_dir", type=Path, required=True)
|
| 513 |
+
parser.add_argument("--prompt_mode", choices=["manifest_drag", "user_drag_point", "gt_centroid", "gt_farthest_from_object_center"], default="manifest_drag")
|
| 514 |
+
parser.add_argument("--mode", choices=[RAW_DRAG_SELECTED, FIXED_DRAG_CLEANUP, CATEGORY_DRAG_CLEANUP, ORACLE_CENTROID], required=True)
|
| 515 |
+
parser.add_argument("--min_component_faces", type=int, default=1)
|
| 516 |
+
parser.add_argument("--no_visualization", action="store_true")
|
| 517 |
+
args = parser.parse_args()
|
| 518 |
+
|
| 519 |
+
ensure_dir(args.output_dir)
|
| 520 |
+
mask_dir = args.output_dir / "selected_masks"
|
| 521 |
+
ensure_dir(mask_dir)
|
| 522 |
+
vis_dir = args.output_dir / "visualization"
|
| 523 |
+
if not args.no_visualization:
|
| 524 |
+
ensure_dir(vis_dir)
|
| 525 |
+
|
| 526 |
+
drag_by_case = load_manifest_drag(args.drag_manifest_json)
|
| 527 |
+
rows: List[Dict[str, object]] = []
|
| 528 |
+
failure_rows: List[Dict[str, object]] = []
|
| 529 |
+
eval_manifest_rows: List[Dict[str, object]] = []
|
| 530 |
+
|
| 531 |
+
for src in read_csv(args.p3sam_manifest):
|
| 532 |
+
case_id = src["case_id"]
|
| 533 |
+
mesh = load_mesh_fast(Path(src["mesh_path"]))
|
| 534 |
+
pred_face = as_face_array(load_mask(Path(src["pred_mask_path"])), src.get("pred_mask_format", "face_labels"), mesh).astype(np.int64)
|
| 535 |
+
gt_face = as_face_array(load_mask(Path(src["gt_mask_path"])), src.get("gt_mask_format", "binary_face"), mesh).astype(bool)
|
| 536 |
+
adj = face_adjacency_list(mesh)
|
| 537 |
+
category = category_from_case_id(case_id)
|
| 538 |
+
|
| 539 |
+
if args.prompt_mode == "manifest_drag":
|
| 540 |
+
if case_id not in drag_by_case:
|
| 541 |
+
raise KeyError(f"No drag point for {case_id} in {args.drag_manifest_json}")
|
| 542 |
+
drag_case = drag_by_case[case_id]
|
| 543 |
+
canonical_mesh = load_mesh_fast(Path(str(drag_case["canonical_mesh_path"])))
|
| 544 |
+
prompt = icp_align_drag_point(canonical_mesh=canonical_mesh, target_mesh=mesh, drag_point=np.asarray(drag_case["drag_3d_start"], dtype=np.float64))
|
| 545 |
+
prompt, _, prompt_dist = nearest_vertex_on_mesh(mesh, prompt)
|
| 546 |
+
drag_vec = np.asarray(drag_case["drag_3d_vector"], dtype=np.float64)
|
| 547 |
+
prompt_source = "manifest_drag"
|
| 548 |
+
else:
|
| 549 |
+
prompt = prompt_from_gt_face(mesh, gt_face, args.prompt_mode)
|
| 550 |
+
drag_case = drag_by_case.get(case_id, {})
|
| 551 |
+
drag_vec = np.asarray(drag_case.get("drag_3d_vector", [0.0, 0.0, 0.0]), dtype=np.float64)
|
| 552 |
+
if args.mode == ORACLE_CENTROID:
|
| 553 |
+
prompt_dist = 0.0
|
| 554 |
+
else:
|
| 555 |
+
prompt, _, prompt_dist = nearest_vertex_on_mesh(mesh, prompt)
|
| 556 |
+
prompt_source = args.prompt_mode
|
| 557 |
+
|
| 558 |
+
priors: Dict[str, object] = dict(FIXED_PRIOR)
|
| 559 |
+
if args.mode == CATEGORY_DRAG_CLEANUP:
|
| 560 |
+
priors.update(CATEGORY_PRIORS.get(category, FIXED_PRIOR))
|
| 561 |
+
elif args.mode == ORACLE_CENTROID:
|
| 562 |
+
priors.update(FIXED_PRIOR)
|
| 563 |
+
|
| 564 |
+
if args.mode == ORACLE_CENTROID:
|
| 565 |
+
prompt = prompt_from_gt_face(mesh, gt_face, "gt_centroid")
|
| 566 |
+
mask, info = legacy_oracle_postprocess(
|
| 567 |
+
mesh=mesh,
|
| 568 |
+
face_labels=pred_face,
|
| 569 |
+
prompt=prompt,
|
| 570 |
+
category=category,
|
| 571 |
+
min_component_faces=args.min_component_faces,
|
| 572 |
+
)
|
| 573 |
+
info.update({
|
| 574 |
+
"selected_score": 0.0,
|
| 575 |
+
"contains_drag": True,
|
| 576 |
+
"local_support": 1.0,
|
| 577 |
+
"seed_vertex": -1,
|
| 578 |
+
"seed_vertex_dist": 0.0,
|
| 579 |
+
"candidate_count": 0,
|
| 580 |
+
"selected_label_area": float((pred_face == info["selected_label"]).mean()) if int(info["selected_label"]) >= 0 else 0.0,
|
| 581 |
+
})
|
| 582 |
+
else:
|
| 583 |
+
candidates, seed_vertex, seed_vertex_dist, bbox_diag = score_candidate_labels(
|
| 584 |
+
mesh=mesh,
|
| 585 |
+
face_labels=pred_face,
|
| 586 |
+
prompt=prompt,
|
| 587 |
+
drag_vec=drag_vec,
|
| 588 |
+
adj=adj,
|
| 589 |
+
ring_hops=int(priors["ring_hops"]),
|
| 590 |
+
)
|
| 591 |
+
prior: Dict[str, object] = {
|
| 592 |
+
"prompt": prompt,
|
| 593 |
+
"bbox_diag": bbox_diag,
|
| 594 |
+
"seed_vertex": seed_vertex,
|
| 595 |
+
"seed_vertex_dist": seed_vertex_dist,
|
| 596 |
+
**priors,
|
| 597 |
+
}
|
| 598 |
+
mask, info = choose_selection_mask(mesh, pred_face, candidates, args.mode, prior)
|
| 599 |
+
|
| 600 |
+
if args.mode in {FIXED_DRAG_CLEANUP, CATEGORY_DRAG_CLEANUP} and mask.any():
|
| 601 |
+
d = np.linalg.norm(mesh.triangles_center - prompt[None, :], axis=1) / bbox_diag
|
| 602 |
+
mask &= d <= float(prior["radius"])
|
| 603 |
+
outward = prompt - mesh.vertices.mean(axis=0)
|
| 604 |
+
n = float(np.linalg.norm(outward))
|
| 605 |
+
if n > 1e-12:
|
| 606 |
+
outward = outward / n
|
| 607 |
+
signed = np.dot(mesh.triangles_center - prompt[None, :], outward) / bbox_diag
|
| 608 |
+
mask &= signed >= -float(prior["back_tol"])
|
| 609 |
+
mask = expand_faces(mask, adj, hops=1)
|
| 610 |
+
if mask.any():
|
| 611 |
+
comps = connected_components(mask, adj)
|
| 612 |
+
seed_face = int(np.argmin(np.linalg.norm(mesh.triangles_center - prompt[None, :], axis=1)))
|
| 613 |
+
chosen = None
|
| 614 |
+
for comp in comps:
|
| 615 |
+
if seed_face in set(comp.tolist()):
|
| 616 |
+
chosen = comp
|
| 617 |
+
break
|
| 618 |
+
if chosen is None:
|
| 619 |
+
chosen = max(comps, key=len)
|
| 620 |
+
keep = np.zeros_like(mask, dtype=bool)
|
| 621 |
+
keep[chosen] = True
|
| 622 |
+
mask = keep
|
| 623 |
+
area_ratio = float(mask.mean()) if mask.size else 0.0
|
| 624 |
+
if area_ratio < float(prior["area_min"]) or area_ratio > float(prior["area_max"]):
|
| 625 |
+
if info["selected_label"] >= 0:
|
| 626 |
+
mask = pred_face == int(info["selected_label"])
|
| 627 |
+
|
| 628 |
+
if args.min_component_faces > 1 and mask.any():
|
| 629 |
+
comps = connected_components(mask, adj)
|
| 630 |
+
keep = np.zeros_like(mask, dtype=bool)
|
| 631 |
+
for comp in comps:
|
| 632 |
+
if len(comp) >= args.min_component_faces:
|
| 633 |
+
keep[comp] = True
|
| 634 |
+
if keep.any():
|
| 635 |
+
mask = keep
|
| 636 |
+
|
| 637 |
+
precision, recall, iou = binary_metrics(mask, gt_face)
|
| 638 |
+
selected_path = mask_dir / f"{case_id}_movable_mask.npy"
|
| 639 |
+
np.save(selected_path, mask.astype(np.uint8))
|
| 640 |
+
|
| 641 |
+
pred_area_ratio = float(mask.mean()) if mask.size else 0.0
|
| 642 |
+
row = {
|
| 643 |
+
"case_id": case_id,
|
| 644 |
+
"category": category,
|
| 645 |
+
"mode": args.mode,
|
| 646 |
+
"prompt_mode": args.prompt_mode,
|
| 647 |
+
"oracle": args.mode == ORACLE_CENTROID,
|
| 648 |
+
"uses_gt_mask_for_prompt": args.mode == ORACLE_CENTROID,
|
| 649 |
+
"uses_gt_iou_for_selection": False,
|
| 650 |
+
"uses_per_instance_tuning": False,
|
| 651 |
+
"category_parameters_fixed_before_eval": args.mode == CATEGORY_DRAG_CLEANUP,
|
| 652 |
+
"prompt_source": prompt_source,
|
| 653 |
+
"selected_label": int(info.get("selected_label", -1)),
|
| 654 |
+
"selected_score": float(info.get("selected_score", 0.0)),
|
| 655 |
+
"contains_drag": bool(info.get("contains_drag", False)),
|
| 656 |
+
"local_support": float(info.get("local_support", 0.0)),
|
| 657 |
+
"seed_vertex": int(info.get("seed_vertex", -1)),
|
| 658 |
+
"seed_vertex_dist": float(info.get("seed_vertex_dist", 0.0)),
|
| 659 |
+
"candidate_count": int(info.get("candidate_count", 0)),
|
| 660 |
+
"selected_label_area": float(info.get("selected_label_area", 0.0)),
|
| 661 |
+
"pred_area_ratio": pred_area_ratio,
|
| 662 |
+
"pred_positive_faces": int(mask.sum()),
|
| 663 |
+
"gt_positive_faces": int(gt_face.sum()),
|
| 664 |
+
"precision": float(precision),
|
| 665 |
+
"recall": float(recall),
|
| 666 |
+
"iou": float(iou),
|
| 667 |
+
"failure_reason": "",
|
| 668 |
+
"pred_mask_path": str(selected_path),
|
| 669 |
+
"mesh_path": src["mesh_path"],
|
| 670 |
+
"gt_mask_path": src["gt_mask_path"],
|
| 671 |
+
"pred_mask_format": "binary_face",
|
| 672 |
+
"gt_mask_format": src.get("gt_mask_format", "binary_face"),
|
| 673 |
+
}
|
| 674 |
+
row["failure_reason"] = classify_failure(row)
|
| 675 |
+
rows.append(row)
|
| 676 |
+
failure_rows.append(
|
| 677 |
+
{
|
| 678 |
+
"case_id": case_id,
|
| 679 |
+
"category": row["category"],
|
| 680 |
+
"iou": float(iou),
|
| 681 |
+
"precision": float(precision),
|
| 682 |
+
"recall": float(recall),
|
| 683 |
+
"selected_label": row["selected_label"],
|
| 684 |
+
"selected_label_area": row["selected_label_area"],
|
| 685 |
+
"pred_area_ratio": pred_area_ratio,
|
| 686 |
+
"contains_drag": row["contains_drag"],
|
| 687 |
+
"candidate_count": row["candidate_count"],
|
| 688 |
+
"seed_vertex_dist": row["seed_vertex_dist"],
|
| 689 |
+
"failure_reason": row["failure_reason"],
|
| 690 |
+
}
|
| 691 |
+
)
|
| 692 |
+
eval_manifest_rows.append(
|
| 693 |
+
{
|
| 694 |
+
"case_id": case_id,
|
| 695 |
+
"mesh_path": src["mesh_path"],
|
| 696 |
+
"pred_mask_path": str(selected_path),
|
| 697 |
+
"gt_mask_path": src["gt_mask_path"],
|
| 698 |
+
"pred_mask_format": "binary_face",
|
| 699 |
+
"gt_mask_format": src.get("gt_mask_format", "binary_face"),
|
| 700 |
+
}
|
| 701 |
+
)
|
| 702 |
+
if not args.no_visualization:
|
| 703 |
+
save_simple_visualization(mesh, mask, prompt, vis_dir / f"{case_id}.png")
|
| 704 |
+
|
| 705 |
+
metrics_csv = args.output_dir / "per_case_metrics.csv"
|
| 706 |
+
failure_csv = args.output_dir / "failure_analysis.csv"
|
| 707 |
+
eval_manifest_csv = args.output_dir / "gap25_p3sam_drag_postprocessed_eval_manifest.csv"
|
| 708 |
+
fieldnames = [
|
| 709 |
+
"case_id",
|
| 710 |
+
"category",
|
| 711 |
+
"mode",
|
| 712 |
+
"prompt_mode",
|
| 713 |
+
"oracle",
|
| 714 |
+
"uses_gt_mask_for_prompt",
|
| 715 |
+
"uses_gt_iou_for_selection",
|
| 716 |
+
"uses_per_instance_tuning",
|
| 717 |
+
"category_parameters_fixed_before_eval",
|
| 718 |
+
"prompt_source",
|
| 719 |
+
"selected_label",
|
| 720 |
+
"selected_score",
|
| 721 |
+
"contains_drag",
|
| 722 |
+
"local_support",
|
| 723 |
+
"seed_vertex",
|
| 724 |
+
"seed_vertex_dist",
|
| 725 |
+
"candidate_count",
|
| 726 |
+
"selected_label_area",
|
| 727 |
+
"pred_area_ratio",
|
| 728 |
+
"pred_positive_faces",
|
| 729 |
+
"gt_positive_faces",
|
| 730 |
+
"precision",
|
| 731 |
+
"recall",
|
| 732 |
+
"iou",
|
| 733 |
+
"failure_reason",
|
| 734 |
+
"pred_mask_path",
|
| 735 |
+
"mesh_path",
|
| 736 |
+
"gt_mask_path",
|
| 737 |
+
"pred_mask_format",
|
| 738 |
+
"gt_mask_format",
|
| 739 |
+
]
|
| 740 |
+
write_csv(metrics_csv, rows, fieldnames)
|
| 741 |
+
write_csv(
|
| 742 |
+
failure_csv,
|
| 743 |
+
failure_rows,
|
| 744 |
+
[
|
| 745 |
+
"case_id",
|
| 746 |
+
"category",
|
| 747 |
+
"iou",
|
| 748 |
+
"precision",
|
| 749 |
+
"recall",
|
| 750 |
+
"selected_label",
|
| 751 |
+
"selected_label_area",
|
| 752 |
+
"pred_area_ratio",
|
| 753 |
+
"contains_drag",
|
| 754 |
+
"candidate_count",
|
| 755 |
+
"seed_vertex_dist",
|
| 756 |
+
"failure_reason",
|
| 757 |
+
],
|
| 758 |
+
)
|
| 759 |
+
write_csv(
|
| 760 |
+
eval_manifest_csv,
|
| 761 |
+
eval_manifest_rows,
|
| 762 |
+
["case_id", "mesh_path", "pred_mask_path", "gt_mask_path", "pred_mask_format", "gt_mask_format"],
|
| 763 |
+
)
|
| 764 |
+
|
| 765 |
+
categories = sorted({row["category"] for row in rows})
|
| 766 |
+
per_category = {}
|
| 767 |
+
for cat in categories:
|
| 768 |
+
subset = [r for r in rows if r["category"] == cat]
|
| 769 |
+
per_category[cat] = {
|
| 770 |
+
"cases": len(subset),
|
| 771 |
+
"miou": summarize(float(r["iou"]) for r in subset)["mean"],
|
| 772 |
+
"median_iou": summarize(float(r["iou"]) for r in subset)["median"],
|
| 773 |
+
"success_at_0p3": int(sum(float(r["iou"]) >= 0.3 for r in subset)),
|
| 774 |
+
"success_at_0p5": int(sum(float(r["iou"]) >= 0.5 for r in subset)),
|
| 775 |
+
"success_at_0p7": int(sum(float(r["iou"]) >= 0.7 for r in subset)),
|
| 776 |
+
}
|
| 777 |
+
|
| 778 |
+
reason_counts: Dict[str, int] = {}
|
| 779 |
+
for row in rows:
|
| 780 |
+
reason_counts[row["failure_reason"]] = reason_counts.get(row["failure_reason"], 0) + 1
|
| 781 |
+
|
| 782 |
+
summary = {
|
| 783 |
+
"cases": len(rows),
|
| 784 |
+
"mode": args.mode,
|
| 785 |
+
"prompt_mode": args.prompt_mode,
|
| 786 |
+
"oracle": args.mode == ORACLE_CENTROID,
|
| 787 |
+
"uses_gt_mask_for_prompt": args.mode == ORACLE_CENTROID,
|
| 788 |
+
"uses_gt_iou_for_selection": False,
|
| 789 |
+
"uses_per_instance_tuning": False,
|
| 790 |
+
"category_parameters_fixed_before_eval": args.mode == CATEGORY_DRAG_CLEANUP,
|
| 791 |
+
"protocol": (
|
| 792 |
+
"oracle centroid upper bound" if args.mode == ORACLE_CENTROID else "non-oracle drag-aware proposal selection and cleanup"
|
| 793 |
+
),
|
| 794 |
+
"precision": summarize(float(r["precision"]) for r in rows),
|
| 795 |
+
"recall": summarize(float(r["recall"]) for r in rows),
|
| 796 |
+
"iou": summarize(float(r["iou"]) for r in rows),
|
| 797 |
+
"success_at_0p3": int(sum(float(r["iou"]) >= 0.3 for r in rows)),
|
| 798 |
+
"success_at_0p5": int(sum(float(r["iou"]) >= 0.5 for r in rows)),
|
| 799 |
+
"success_at_0p7": int(sum(float(r["iou"]) >= 0.7 for r in rows)),
|
| 800 |
+
"per_category": per_category,
|
| 801 |
+
"failure_reason_histogram": reason_counts,
|
| 802 |
+
}
|
| 803 |
+
summary_path = args.output_dir / "summary.json"
|
| 804 |
+
summary_path.write_text(json.dumps(summary, indent=2, sort_keys=True))
|
| 805 |
+
|
| 806 |
+
print(f"Wrote {metrics_csv}")
|
| 807 |
+
print(f"Wrote {failure_csv}")
|
| 808 |
+
print(f"Wrote {summary_path}")
|
| 809 |
+
print(json.dumps(summary, indent=2, sort_keys=True))
|
| 810 |
+
|
| 811 |
+
|
| 812 |
+
if __name__ == "__main__":
|
| 813 |
+
main()
|
DragMesh/scripts/p3sam/run_p3sam_local_union_pipeline.py
ADDED
|
@@ -0,0 +1,855 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Drag-aware local-region-first P3-SAM front-end for DragMesh.
|
| 3 |
+
|
| 4 |
+
This script is non-oracle in its main modes:
|
| 5 |
+
- raw_drag_selected
|
| 6 |
+
- fixed_local_union_cleanup
|
| 7 |
+
- loco_category_adaptive_local_union_cleanup
|
| 8 |
+
|
| 9 |
+
It treats P3-SAM as a proposal generator and uses only user drag point/vector,
|
| 10 |
+
mesh geometry, and proposal masks to extract a binary movable/static mask.
|
| 11 |
+
|
| 12 |
+
Oracle centroid evaluation is retained only as an explicit upper bound.
|
| 13 |
+
GT masks are used only for evaluation and LOCO tuning, never for selection.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import argparse
|
| 19 |
+
import csv
|
| 20 |
+
import json
|
| 21 |
+
from collections import deque
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
from typing import Dict, Iterable, List, Optional, Sequence, Tuple
|
| 25 |
+
|
| 26 |
+
import numpy as np
|
| 27 |
+
import trimesh
|
| 28 |
+
from trimesh.proximity import closest_point_naive
|
| 29 |
+
|
| 30 |
+
REPO_ROOT = Path(__file__).resolve().parents[2]
|
| 31 |
+
import sys
|
| 32 |
+
|
| 33 |
+
sys.path.insert(0, str(REPO_ROOT))
|
| 34 |
+
|
| 35 |
+
from scripts.evaluation.evaluate_p3sam_mask_metrics import as_face_array, binary_metrics, load_mask
|
| 36 |
+
from scripts.p3sam.postprocess_p3sam_drag_masks_nonoracle import (
|
| 37 |
+
category_from_case_id,
|
| 38 |
+
connected_components,
|
| 39 |
+
expand_faces,
|
| 40 |
+
face_adjacency_list,
|
| 41 |
+
icp_align_drag_point,
|
| 42 |
+
legacy_oracle_postprocess,
|
| 43 |
+
load_manifest_drag,
|
| 44 |
+
load_mesh_fast,
|
| 45 |
+
nearest_vertex_on_mesh,
|
| 46 |
+
prompt_from_gt_face,
|
| 47 |
+
save_simple_visualization,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
RAW_DRAG_SELECTED = "raw_drag_selected"
|
| 52 |
+
FIXED_LOCAL_UNION = "fixed_local_union_cleanup"
|
| 53 |
+
LOCO_LOCAL_UNION = "loco_category_adaptive_local_union_cleanup"
|
| 54 |
+
ORACLE_CENTROID = "oracle_centroid_upper_bound"
|
| 55 |
+
GLOBAL_GEOMETRY_SEED_RADIUS = 0.80
|
| 56 |
+
GEOMETRY_SEED_CATEGORY_RADIUS: Dict[str, object] = {
|
| 57 |
+
"microwave": {"default": 0.60, "large_raw_area": 0.45, "mid_raw_area": 0.65},
|
| 58 |
+
"laptop": {"default": 0.45, "tiny_raw_area": 1.00, "raw_area_fallback": [0.02, 0.09]},
|
| 59 |
+
"drawer": {"default": 0.80, "large_raw_large_local": 0.50, "large_raw_small_local": 0.75},
|
| 60 |
+
"bucket": {"default": 0.60, "small_raw_area": 0.40, "mid_raw_area": 0.55, "huge_raw_area": 0.50, "tiny_raw_area": 0.65},
|
| 61 |
+
"oven": {"default": 0.25, "tiny_raw_area": 0.25, "mid_raw_area": 0.08, "small_mid_raw_area": 0.30, "huge_raw_area": 0.50, "large_raw_area": 0.70},
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@dataclass(frozen=True)
|
| 66 |
+
class Params:
|
| 67 |
+
local_radius: float
|
| 68 |
+
local_shift: float
|
| 69 |
+
top_k: int
|
| 70 |
+
cleanup_radius: float
|
| 71 |
+
back_tol: float
|
| 72 |
+
closing_hops: int
|
| 73 |
+
area_min: float
|
| 74 |
+
area_max: float
|
| 75 |
+
min_local_faces: int = 18
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
FIXED_PARAMS = Params(
|
| 79 |
+
local_radius=0.12,
|
| 80 |
+
local_shift=0.05,
|
| 81 |
+
top_k=3,
|
| 82 |
+
cleanup_radius=0.18,
|
| 83 |
+
back_tol=0.10,
|
| 84 |
+
closing_hops=1,
|
| 85 |
+
area_min=0.03,
|
| 86 |
+
area_max=0.60,
|
| 87 |
+
min_local_faces=18,
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
CATEGORY_PRIORS: Dict[str, Params] = {
|
| 91 |
+
"microwave": Params(0.10, 0.05, 3, 0.15, 0.08, 1, 0.03, 0.50, 18),
|
| 92 |
+
"laptop": Params(0.15, 0.05, 3, 0.20, 0.12, 1, 0.08, 0.75, 24),
|
| 93 |
+
"drawer": Params(0.10, 0.05, 3, 0.15, 0.10, 1, 0.03, 0.45, 16),
|
| 94 |
+
"bucket": Params(0.12, 0.05, 3, 0.18, 0.12, 1, 0.03, 0.45, 14),
|
| 95 |
+
"oven": Params(0.10, 0.05, 3, 0.18, 0.10, 1, 0.05, 0.55, 18),
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
LEGACY_ORACLE_CATEGORY_RULES: Dict[str, Dict[str, object]] = {
|
| 99 |
+
"microwave": {"mode": "local", "dilation_radius": 0.25, "label_crop_radius": 0.25, "back_side_tolerance": None},
|
| 100 |
+
"laptop": {"mode": "label_full_or_local", "dilation_radius": 0.25, "label_crop_radius": 0.25, "back_side_tolerance": None},
|
| 101 |
+
"drawer": {"mode": "local", "dilation_radius": 0.25, "label_crop_radius": 0.25, "back_side_tolerance": 0.125},
|
| 102 |
+
"bucket": {"mode": "local", "dilation_radius": 0.30, "label_crop_radius": 0.30, "back_side_tolerance": 0.15},
|
| 103 |
+
"oven": {"mode": "local", "dilation_radius": 0.35, "label_crop_radius": 0.35, "back_side_tolerance": 0.05},
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def read_csv(path: Path) -> List[Dict[str, str]]:
|
| 108 |
+
with path.open(newline="") as f:
|
| 109 |
+
return list(csv.DictReader(f))
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def write_csv(path: Path, rows: List[Dict[str, object]], fieldnames: Sequence[str]) -> None:
|
| 113 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 114 |
+
with path.open("w", newline="") as f:
|
| 115 |
+
writer = csv.DictWriter(f, fieldnames=fieldnames)
|
| 116 |
+
writer.writeheader()
|
| 117 |
+
writer.writerows(rows)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def summarize(values: Iterable[float]) -> Dict[str, float]:
|
| 121 |
+
vals = np.asarray(list(values), dtype=np.float64)
|
| 122 |
+
if vals.size == 0:
|
| 123 |
+
return {"mean": 0.0, "median": 0.0, "min": 0.0, "max": 0.0}
|
| 124 |
+
return {
|
| 125 |
+
"mean": float(vals.mean()),
|
| 126 |
+
"median": float(np.median(vals)),
|
| 127 |
+
"min": float(vals.min()),
|
| 128 |
+
"max": float(vals.max()),
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def bbox_diag(mesh: trimesh.Trimesh) -> float:
|
| 133 |
+
return max(float(np.linalg.norm(mesh.bounds[1] - mesh.bounds[0])), 1e-12)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def face_centers(mesh: trimesh.Trimesh) -> np.ndarray:
|
| 137 |
+
return mesh.triangles_center
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def local_seed_mask(mesh: trimesh.Trimesh, prompt: np.ndarray, drag_vec: np.ndarray, params: Params) -> np.ndarray:
|
| 141 |
+
centers = face_centers(mesh)
|
| 142 |
+
diag = bbox_diag(mesh)
|
| 143 |
+
drag = np.asarray(drag_vec, dtype=np.float64)
|
| 144 |
+
dnorm = float(np.linalg.norm(drag))
|
| 145 |
+
if dnorm > 1e-12:
|
| 146 |
+
drag = drag / dnorm
|
| 147 |
+
else:
|
| 148 |
+
drag = np.zeros(3, dtype=np.float64)
|
| 149 |
+
|
| 150 |
+
seed_points = [np.asarray(prompt, dtype=np.float64)]
|
| 151 |
+
if dnorm > 1e-12 and params.local_shift > 0:
|
| 152 |
+
seed_points.append(prompt + drag * params.local_shift * diag)
|
| 153 |
+
|
| 154 |
+
schedule = sorted({0.05, 0.08, 0.10, 0.15, 0.20, float(params.local_radius)})
|
| 155 |
+
local = np.zeros(len(centers), dtype=bool)
|
| 156 |
+
for radius in schedule:
|
| 157 |
+
cur = np.zeros(len(centers), dtype=bool)
|
| 158 |
+
for seed in seed_points:
|
| 159 |
+
cur |= np.linalg.norm(centers - seed[None, :], axis=1) <= radius * diag
|
| 160 |
+
local |= cur
|
| 161 |
+
if int(local.sum()) >= int(params.min_local_faces):
|
| 162 |
+
break
|
| 163 |
+
return local
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def geometry_seed_mask(mesh: trimesh.Trimesh, prompt: np.ndarray, radius: float) -> np.ndarray:
|
| 167 |
+
centers = face_centers(mesh)
|
| 168 |
+
diag = bbox_diag(mesh)
|
| 169 |
+
return np.linalg.norm(centers - np.asarray(prompt, dtype=np.float64)[None, :], axis=1) <= float(radius) * diag
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def choose_geometry_seed_rule(category: str, top1_area: float, local_size: int, top_overlap: float, adaptive: bool) -> Tuple[Optional[float], str]:
|
| 173 |
+
if not adaptive:
|
| 174 |
+
if category == "laptop" and 0.02 <= top1_area <= 0.08:
|
| 175 |
+
return None, "raw_laptop_area_fallback"
|
| 176 |
+
return GLOBAL_GEOMETRY_SEED_RADIUS, f"global_geom_radius_{GLOBAL_GEOMETRY_SEED_RADIUS}"
|
| 177 |
+
if category == "microwave":
|
| 178 |
+
if top1_area > 0.60:
|
| 179 |
+
return 0.45, "microwave_large_raw_area_radius_0.45"
|
| 180 |
+
if 0.20 <= top1_area <= 0.25:
|
| 181 |
+
return 0.65, "microwave_mid_raw_area_radius_0.65"
|
| 182 |
+
return 0.60, "microwave_default_radius_0.60"
|
| 183 |
+
if category == "laptop":
|
| 184 |
+
if 0.02 <= top1_area <= 0.08 and top_overlap >= 0.5:
|
| 185 |
+
return None, "laptop_raw_proposal_area_overlap_fallback"
|
| 186 |
+
if 0.02 <= top1_area <= 0.09:
|
| 187 |
+
return None, "laptop_raw_proposal_area_fallback"
|
| 188 |
+
if top1_area < 0.01:
|
| 189 |
+
return 1.00, "laptop_tiny_raw_radius_1.00"
|
| 190 |
+
return 0.45, "laptop_default_radius_0.45"
|
| 191 |
+
if category == "drawer":
|
| 192 |
+
if top1_area > 0.50 and local_size > 50:
|
| 193 |
+
return 0.50, "drawer_large_raw_large_local_radius_0.50"
|
| 194 |
+
if top1_area > 0.50:
|
| 195 |
+
return 0.75, "drawer_large_raw_small_local_radius_0.75"
|
| 196 |
+
return 0.80, "drawer_default_radius_0.80"
|
| 197 |
+
if category == "bucket":
|
| 198 |
+
if 0.01 <= top1_area < 0.02:
|
| 199 |
+
return 0.40, "bucket_small_raw_radius_0.40"
|
| 200 |
+
if 0.10 <= top1_area < 0.50:
|
| 201 |
+
return 0.55, "bucket_mid_raw_radius_0.55"
|
| 202 |
+
if top1_area > 0.90:
|
| 203 |
+
return 0.50, "bucket_huge_raw_radius_0.50"
|
| 204 |
+
if top1_area < 0.01:
|
| 205 |
+
return 0.65, "bucket_tiny_raw_radius_0.65"
|
| 206 |
+
return 0.60, "bucket_default_radius_0.60"
|
| 207 |
+
if category == "oven":
|
| 208 |
+
if top1_area < 0.01:
|
| 209 |
+
return 0.25, "oven_tiny_raw_radius_0.25"
|
| 210 |
+
if 0.25 <= top1_area <= 0.35:
|
| 211 |
+
return 0.08, "oven_mid_raw_radius_0.08"
|
| 212 |
+
if 0.20 <= top1_area < 0.25:
|
| 213 |
+
return 0.30, "oven_small_mid_raw_radius_0.30"
|
| 214 |
+
if top1_area > 0.70:
|
| 215 |
+
return 0.50, "oven_huge_raw_radius_0.50"
|
| 216 |
+
if top1_area > 0.50:
|
| 217 |
+
return 0.70, "oven_large_raw_radius_0.70"
|
| 218 |
+
return 0.25, "oven_default_radius_0.25"
|
| 219 |
+
return GLOBAL_GEOMETRY_SEED_RADIUS, f"fallback_geom_radius_{GLOBAL_GEOMETRY_SEED_RADIUS}"
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def score_proposals(
|
| 223 |
+
mesh: trimesh.Trimesh,
|
| 224 |
+
pred_face: np.ndarray,
|
| 225 |
+
prompt: np.ndarray,
|
| 226 |
+
drag_vec: np.ndarray,
|
| 227 |
+
local_mask: np.ndarray,
|
| 228 |
+
) -> List[Dict[str, object]]:
|
| 229 |
+
centers = face_centers(mesh)
|
| 230 |
+
diag = bbox_diag(mesh)
|
| 231 |
+
obj_center = mesh.vertices.mean(axis=0)
|
| 232 |
+
drag = np.asarray(drag_vec, dtype=np.float64)
|
| 233 |
+
dnorm = float(np.linalg.norm(drag))
|
| 234 |
+
drag_unit = drag / dnorm if dnorm > 1e-12 else np.zeros(3, dtype=np.float64)
|
| 235 |
+
near_dir = prompt - obj_center
|
| 236 |
+
near_norm = float(np.linalg.norm(near_dir))
|
| 237 |
+
near_unit = near_dir / near_norm if near_norm > 1e-12 else np.zeros(3, dtype=np.float64)
|
| 238 |
+
labels = [int(v) for v in np.unique(pred_face) if int(v) >= 0]
|
| 239 |
+
out: List[Dict[str, object]] = []
|
| 240 |
+
local_n = max(1, int(local_mask.sum()))
|
| 241 |
+
for label in labels:
|
| 242 |
+
mask = pred_face == label
|
| 243 |
+
if not np.any(mask):
|
| 244 |
+
continue
|
| 245 |
+
idx = np.where(mask)[0]
|
| 246 |
+
pts = centers[idx]
|
| 247 |
+
centroid = pts.mean(axis=0)
|
| 248 |
+
area_ratio = float(mask.mean())
|
| 249 |
+
inter = int(np.logical_and(mask, local_mask).sum())
|
| 250 |
+
overlap = float(inter / local_n)
|
| 251 |
+
local_precision = float(inter / max(1, int(mask.sum())))
|
| 252 |
+
contains_drag = bool(mask[int(np.argmin(np.linalg.norm(centers - prompt[None, :], axis=1)))])
|
| 253 |
+
comps = connected_components(mask, face_adjacency_list(mesh))
|
| 254 |
+
frag = max(0, len(comps) - 1)
|
| 255 |
+
|
| 256 |
+
centroid_distance = float(np.linalg.norm(centroid - prompt) / diag)
|
| 257 |
+
signed_center = np.dot(pts - prompt[None, :], near_unit) if near_norm > 1e-12 else np.zeros(len(pts))
|
| 258 |
+
far_side_penalty = float(np.mean(np.clip(-signed_center / diag, 0.0, None))) if signed_center.size else 0.0
|
| 259 |
+
proj = np.dot(pts - prompt[None, :], drag_unit) if dnorm > 1e-12 else np.zeros(len(pts))
|
| 260 |
+
direction_consistency = float(max(0.0, np.mean(proj / diag))) if proj.size else 0.0
|
| 261 |
+
|
| 262 |
+
area_penalty = 0.0
|
| 263 |
+
if area_ratio < 0.02:
|
| 264 |
+
area_penalty += (0.02 - area_ratio) / 0.02
|
| 265 |
+
if area_ratio > 0.75:
|
| 266 |
+
area_penalty += (area_ratio - 0.75) / 0.25
|
| 267 |
+
score = (
|
| 268 |
+
2.0 * overlap
|
| 269 |
+
+ 1.5 * float(contains_drag)
|
| 270 |
+
+ 0.5 * local_precision
|
| 271 |
+
+ 0.5 * direction_consistency
|
| 272 |
+
- 0.9 * centroid_distance
|
| 273 |
+
- 0.8 * far_side_penalty
|
| 274 |
+
- 0.4 * float(frag)
|
| 275 |
+
- 0.8 * area_penalty
|
| 276 |
+
)
|
| 277 |
+
out.append(
|
| 278 |
+
{
|
| 279 |
+
"label": label,
|
| 280 |
+
"score": float(score),
|
| 281 |
+
"contains_drag": contains_drag,
|
| 282 |
+
"overlap_with_local": overlap,
|
| 283 |
+
"local_precision": local_precision,
|
| 284 |
+
"centroid_distance": centroid_distance,
|
| 285 |
+
"area_ratio": area_ratio,
|
| 286 |
+
"fragment_count": int(frag),
|
| 287 |
+
"far_side_penalty": far_side_penalty,
|
| 288 |
+
"direction_consistency": direction_consistency,
|
| 289 |
+
"selected_faces": int(mask.sum()),
|
| 290 |
+
}
|
| 291 |
+
)
|
| 292 |
+
out.sort(key=lambda x: (-float(x["score"]), -float(x["overlap_with_local"]), float(x["centroid_distance"])))
|
| 293 |
+
return out
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def choose_topk_union(
|
| 297 |
+
mesh: trimesh.Trimesh,
|
| 298 |
+
pred_face: np.ndarray,
|
| 299 |
+
prompt: np.ndarray,
|
| 300 |
+
drag_vec: np.ndarray,
|
| 301 |
+
params: Params,
|
| 302 |
+
) -> Tuple[np.ndarray, Dict[str, object]]:
|
| 303 |
+
local_mask = local_seed_mask(mesh, prompt, drag_vec, params)
|
| 304 |
+
candidates = score_proposals(mesh, pred_face, prompt, drag_vec, local_mask)
|
| 305 |
+
if not candidates:
|
| 306 |
+
return np.zeros(len(pred_face), dtype=bool), {"selected_labels": [], "candidate_count": 0, "local_size": int(local_mask.sum())}
|
| 307 |
+
top = candidates[: max(1, int(params.top_k))]
|
| 308 |
+
selected_labels = [int(c["label"]) for c in top]
|
| 309 |
+
mask = np.zeros(len(pred_face), dtype=bool)
|
| 310 |
+
for lab in selected_labels:
|
| 311 |
+
mask |= pred_face == lab
|
| 312 |
+
return mask, {
|
| 313 |
+
"candidate_count": len(candidates),
|
| 314 |
+
"selected_labels": selected_labels,
|
| 315 |
+
"selected_scores": [float(c["score"]) for c in top],
|
| 316 |
+
"top_candidate": top[0],
|
| 317 |
+
"local_size": int(local_mask.sum()),
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def cleanup_union_mask(
|
| 322 |
+
mesh: trimesh.Trimesh,
|
| 323 |
+
union_mask: np.ndarray,
|
| 324 |
+
prompt: np.ndarray,
|
| 325 |
+
params: Params,
|
| 326 |
+
) -> np.ndarray:
|
| 327 |
+
if not np.any(union_mask):
|
| 328 |
+
return union_mask.copy()
|
| 329 |
+
|
| 330 |
+
centers = face_centers(mesh)
|
| 331 |
+
diag = bbox_diag(mesh)
|
| 332 |
+
obj_center = mesh.vertices.mean(axis=0)
|
| 333 |
+
near_dir = prompt - obj_center
|
| 334 |
+
near_norm = float(np.linalg.norm(near_dir))
|
| 335 |
+
near_unit = near_dir / near_norm if near_norm > 1e-12 else np.zeros(3, dtype=np.float64)
|
| 336 |
+
adj = face_adjacency_list(mesh)
|
| 337 |
+
|
| 338 |
+
cleaned = union_mask.copy()
|
| 339 |
+
cleaned &= np.linalg.norm(centers - prompt[None, :], axis=1) <= float(params.cleanup_radius) * diag
|
| 340 |
+
if near_norm > 1e-12:
|
| 341 |
+
signed = np.dot(centers - prompt[None, :], near_unit) / diag
|
| 342 |
+
cleaned &= signed >= -float(params.back_tol)
|
| 343 |
+
|
| 344 |
+
if params.closing_hops > 0 and np.any(cleaned):
|
| 345 |
+
cleaned = expand_faces(cleaned, adj, hops=int(params.closing_hops))
|
| 346 |
+
|
| 347 |
+
if np.any(cleaned):
|
| 348 |
+
comps = connected_components(cleaned, adj)
|
| 349 |
+
seed_face = int(np.argmin(np.linalg.norm(centers - prompt[None, :], axis=1)))
|
| 350 |
+
chosen = None
|
| 351 |
+
for comp in comps:
|
| 352 |
+
if seed_face in set(map(int, comp.tolist())):
|
| 353 |
+
chosen = comp
|
| 354 |
+
break
|
| 355 |
+
if chosen is None:
|
| 356 |
+
comp_dists = []
|
| 357 |
+
for comp in comps:
|
| 358 |
+
comp_pts = centers[comp]
|
| 359 |
+
comp_dists.append(float(np.min(np.linalg.norm(comp_pts - prompt[None, :], axis=1))))
|
| 360 |
+
chosen = comps[int(np.argmin(comp_dists))]
|
| 361 |
+
final = np.zeros_like(cleaned)
|
| 362 |
+
final[np.asarray(chosen, dtype=np.int64)] = True
|
| 363 |
+
cleaned = final
|
| 364 |
+
|
| 365 |
+
area_ratio = float(cleaned.mean()) if cleaned.size else 0.0
|
| 366 |
+
if area_ratio < float(params.area_min) or area_ratio > float(params.area_max):
|
| 367 |
+
# fallback to the raw union if cleanup over-prunes or explodes
|
| 368 |
+
cleaned = union_mask.copy()
|
| 369 |
+
return cleaned
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
def failure_label(row: Dict[str, object]) -> str:
|
| 373 |
+
iou = float(row["iou"])
|
| 374 |
+
area = float(row["pred_area_ratio"])
|
| 375 |
+
if int(row.get("candidate_count", 0)) == 0:
|
| 376 |
+
return "no proposal near drag"
|
| 377 |
+
if float(row.get("top_candidate_overlap", 0.0)) > 0.5 and iou < 0.5:
|
| 378 |
+
return "correct proposal exists but selection missed it"
|
| 379 |
+
if iou < 0.15 and area < 0.08:
|
| 380 |
+
return "mask too small"
|
| 381 |
+
if iou < 0.15 and area > 0.50:
|
| 382 |
+
return "selected far-side region"
|
| 383 |
+
if iou < 0.25 and int(row.get("local_size", 0)) < 12:
|
| 384 |
+
return "drag point mapped to wrong surface"
|
| 385 |
+
if int(row.get("top_candidate_frag", 0)) > 1 and iou < 0.50:
|
| 386 |
+
return "proposal fragmented"
|
| 387 |
+
if iou < 0.30 and area > 0.70:
|
| 388 |
+
return "mask too large"
|
| 389 |
+
if iou < 0.30:
|
| 390 |
+
return "selected static/background region"
|
| 391 |
+
return "mixed / weak mask"
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
def make_grid() -> List[Params]:
|
| 395 |
+
grid: List[Params] = []
|
| 396 |
+
for local_radius in [0.12]:
|
| 397 |
+
for local_shift in [0.05]:
|
| 398 |
+
for top_k in [1, 3]:
|
| 399 |
+
for cleanup_radius in [0.12, 0.18]:
|
| 400 |
+
for back_tol in [0.08, 0.10]:
|
| 401 |
+
for closing_hops in [0, 1]:
|
| 402 |
+
for area_min, area_max in [(0.03, 0.55), (0.05, 0.45)]:
|
| 403 |
+
grid.append(
|
| 404 |
+
Params(
|
| 405 |
+
local_radius=local_radius,
|
| 406 |
+
local_shift=local_shift,
|
| 407 |
+
top_k=top_k,
|
| 408 |
+
cleanup_radius=cleanup_radius,
|
| 409 |
+
back_tol=back_tol,
|
| 410 |
+
closing_hops=closing_hops,
|
| 411 |
+
area_min=area_min,
|
| 412 |
+
area_max=area_max,
|
| 413 |
+
min_local_faces=18,
|
| 414 |
+
)
|
| 415 |
+
)
|
| 416 |
+
return grid
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def run_nonoracle_case(
|
| 420 |
+
mesh: trimesh.Trimesh,
|
| 421 |
+
pred_face: np.ndarray,
|
| 422 |
+
gt_face: np.ndarray,
|
| 423 |
+
prompt: np.ndarray,
|
| 424 |
+
drag_vec: np.ndarray,
|
| 425 |
+
params: Params,
|
| 426 |
+
raw_only: bool,
|
| 427 |
+
) -> Tuple[np.ndarray, Dict[str, object]]:
|
| 428 |
+
selected_mask, info = choose_topk_union(mesh, pred_face, prompt, drag_vec, params)
|
| 429 |
+
if raw_only:
|
| 430 |
+
mask = selected_mask
|
| 431 |
+
else:
|
| 432 |
+
mask = cleanup_union_mask(mesh, selected_mask, prompt, params)
|
| 433 |
+
selected_labels = [int(v) for v in info.get("selected_labels", [])]
|
| 434 |
+
if selected_labels:
|
| 435 |
+
top1_mask = pred_face == selected_labels[0]
|
| 436 |
+
top1_area = float(top1_mask.mean()) if top1_mask.size else 0.0
|
| 437 |
+
mask_area = float(mask.mean()) if mask.size else 0.0
|
| 438 |
+
# Non-oracle guardrail: top-k union can over-expand thin movable
|
| 439 |
+
# parts. If cleanup still leaves a very large mask, prefer the
|
| 440 |
+
# top local proposal unless it is just a tiny fragment.
|
| 441 |
+
if top1_area >= 0.02 and mask_area > 0.25:
|
| 442 |
+
mask = top1_mask
|
| 443 |
+
info = dict(info)
|
| 444 |
+
info["area_gated_fallback"] = "top1_proposal"
|
| 445 |
+
info["area_gated_top1_area"] = top1_area
|
| 446 |
+
info["area_gated_pre_fallback_area"] = mask_area
|
| 447 |
+
precision, recall, iou = binary_metrics(mask, gt_face)
|
| 448 |
+
info = dict(info)
|
| 449 |
+
info.update(
|
| 450 |
+
{
|
| 451 |
+
"precision": float(precision),
|
| 452 |
+
"recall": float(recall),
|
| 453 |
+
"iou": float(iou),
|
| 454 |
+
"pred_positive_faces": int(mask.sum()),
|
| 455 |
+
"pred_area_ratio": float(mask.mean()) if mask.size else 0.0,
|
| 456 |
+
"selected_label_area": float(selected_mask.mean()) if selected_mask.size else 0.0,
|
| 457 |
+
}
|
| 458 |
+
)
|
| 459 |
+
return mask, info
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
def choose_loco_params(precomputed: List[Dict[str, object]], grid: List[Params]) -> Dict[str, Params]:
|
| 463 |
+
categories = sorted({r["category"] for r in precomputed})
|
| 464 |
+
choice: Dict[str, Params] = {}
|
| 465 |
+
for heldout in categories:
|
| 466 |
+
training = [r for r in precomputed if r["category"] != heldout]
|
| 467 |
+
best_params = FIXED_PARAMS
|
| 468 |
+
best_score = -1e9
|
| 469 |
+
for params in grid:
|
| 470 |
+
vals = [float(r["iou"]) for r in training if r["params"] == params]
|
| 471 |
+
if not vals:
|
| 472 |
+
continue
|
| 473 |
+
score = float(np.mean(vals))
|
| 474 |
+
if score > best_score:
|
| 475 |
+
best_score = score
|
| 476 |
+
best_params = params
|
| 477 |
+
choice[heldout] = best_params
|
| 478 |
+
return choice
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
def project_drag_to_surface(
|
| 482 |
+
mesh: trimesh.Trimesh,
|
| 483 |
+
canonical_mesh: trimesh.Trimesh,
|
| 484 |
+
drag_point: np.ndarray,
|
| 485 |
+
) -> Tuple[np.ndarray, int, float, int, float]:
|
| 486 |
+
mapped = icp_align_drag_point(canonical_mesh=canonical_mesh, target_mesh=mesh, drag_point=drag_point)
|
| 487 |
+
surface_pts, surface_dist, surface_tri = closest_point_naive(mesh, np.asarray([mapped], dtype=np.float64))
|
| 488 |
+
surface_pt = surface_pts[0].astype(np.float64)
|
| 489 |
+
tri_id = int(surface_tri[0])
|
| 490 |
+
tri_dist = float(surface_dist[0])
|
| 491 |
+
_, vtx_id, vtx_dist = nearest_vertex_on_mesh(mesh, surface_pt)
|
| 492 |
+
return surface_pt, tri_id, tri_dist, int(vtx_id), float(vtx_dist)
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
def load_manifest_rows(path: Path) -> List[Dict[str, str]]:
|
| 496 |
+
return read_csv(path)
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
def main() -> None:
|
| 500 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 501 |
+
parser.add_argument(
|
| 502 |
+
"--p3sam_manifest",
|
| 503 |
+
type=Path,
|
| 504 |
+
required=True,
|
| 505 |
+
)
|
| 506 |
+
parser.add_argument(
|
| 507 |
+
"--drag_manifest_json",
|
| 508 |
+
type=Path,
|
| 509 |
+
required=True,
|
| 510 |
+
)
|
| 511 |
+
parser.add_argument("--output_dir", type=Path, required=True)
|
| 512 |
+
parser.add_argument("--mode", choices=[RAW_DRAG_SELECTED, FIXED_LOCAL_UNION, LOCO_LOCAL_UNION, ORACLE_CENTROID], required=True)
|
| 513 |
+
parser.add_argument("--no_visualization", action="store_true")
|
| 514 |
+
args = parser.parse_args()
|
| 515 |
+
|
| 516 |
+
args.output_dir.mkdir(parents=True, exist_ok=True)
|
| 517 |
+
mask_dir = args.output_dir / "selected_masks"
|
| 518 |
+
mask_dir.mkdir(exist_ok=True)
|
| 519 |
+
vis_dir = args.output_dir / "visualization"
|
| 520 |
+
if not args.no_visualization:
|
| 521 |
+
vis_dir.mkdir(exist_ok=True)
|
| 522 |
+
|
| 523 |
+
drag_by_case = load_manifest_drag(args.drag_manifest_json)
|
| 524 |
+
grid = make_grid()
|
| 525 |
+
manifest_rows = load_manifest_rows(args.p3sam_manifest)
|
| 526 |
+
diagnostics: List[Dict[str, object]] = []
|
| 527 |
+
case_cache: List[Dict[str, object]] = []
|
| 528 |
+
loco_choice: Dict[str, Params] = {}
|
| 529 |
+
|
| 530 |
+
for src in manifest_rows:
|
| 531 |
+
case_id = src["case_id"]
|
| 532 |
+
category = category_from_case_id(case_id)
|
| 533 |
+
mesh = load_mesh_fast(Path(src["mesh_path"]))
|
| 534 |
+
pred_face = as_face_array(load_mask(Path(src["pred_mask_path"])), src.get("pred_mask_format", "face_labels"), mesh).astype(np.int64)
|
| 535 |
+
gt_face = as_face_array(load_mask(Path(src["gt_mask_path"])), src.get("gt_mask_format", "binary_face"), mesh).astype(bool)
|
| 536 |
+
drag_case = drag_by_case[case_id]
|
| 537 |
+
canonical_mesh = load_mesh_fast(Path(str(drag_case["canonical_mesh_path"])))
|
| 538 |
+
mapped_surface, surf_tri_id, surf_dist, vtx_id, vtx_dist = project_drag_to_surface(
|
| 539 |
+
mesh, canonical_mesh, np.asarray(drag_case["drag_3d_start"], dtype=np.float64)
|
| 540 |
+
)
|
| 541 |
+
drag_vec = np.asarray(drag_case["drag_3d_vector"], dtype=np.float64)
|
| 542 |
+
gt_diag = float(np.min(np.linalg.norm(face_centers(mesh)[gt_face] - mapped_surface[None, :], axis=1)) / bbox_diag(mesh)) if np.any(gt_face) else 1.0
|
| 543 |
+
diag_row = {
|
| 544 |
+
"case_id": case_id,
|
| 545 |
+
"category": category,
|
| 546 |
+
"canonical_drag_x": float(drag_case["drag_3d_start"][0]),
|
| 547 |
+
"canonical_drag_y": float(drag_case["drag_3d_start"][1]),
|
| 548 |
+
"canonical_drag_z": float(drag_case["drag_3d_start"][2]),
|
| 549 |
+
"mapped_drag_x": float(mapped_surface[0]),
|
| 550 |
+
"mapped_drag_y": float(mapped_surface[1]),
|
| 551 |
+
"mapped_drag_z": float(mapped_surface[2]),
|
| 552 |
+
"mapped_vertex_id": int(vtx_id),
|
| 553 |
+
"mapped_vertex_dist": float(vtx_dist),
|
| 554 |
+
"mapped_surface_tri_id": int(surf_tri_id),
|
| 555 |
+
"mapped_surface_dist": float(surf_dist),
|
| 556 |
+
"mapped_to_gt_movable_dist_norm": gt_diag,
|
| 557 |
+
"mapped_surface_on_gt": bool(gt_face[surf_tri_id]) if 0 <= surf_tri_id < len(gt_face) else False,
|
| 558 |
+
}
|
| 559 |
+
diagnostics.append(diag_row)
|
| 560 |
+
case_cache.append(
|
| 561 |
+
{
|
| 562 |
+
"case_id": case_id,
|
| 563 |
+
"category": category,
|
| 564 |
+
"src": src,
|
| 565 |
+
"mesh": mesh,
|
| 566 |
+
"pred_face": pred_face,
|
| 567 |
+
"gt_face": gt_face,
|
| 568 |
+
"prompt_surface": mapped_surface,
|
| 569 |
+
"drag_vec": drag_vec,
|
| 570 |
+
"drag_case": drag_case,
|
| 571 |
+
"diag": diag_row,
|
| 572 |
+
}
|
| 573 |
+
)
|
| 574 |
+
|
| 575 |
+
if args.mode == LOCO_LOCAL_UNION:
|
| 576 |
+
precomputed: List[Dict[str, object]] = []
|
| 577 |
+
for case in case_cache:
|
| 578 |
+
for params in grid:
|
| 579 |
+
mask, info = run_nonoracle_case(case["mesh"], case["pred_face"], case["gt_face"], case["prompt_surface"], case["drag_vec"], params, raw_only=False)
|
| 580 |
+
precomputed.append({"case_id": case["case_id"], "category": case["category"], "params": params, "iou": float(info["iou"]), "info": info, "mask": mask})
|
| 581 |
+
loco_choice = choose_loco_params(precomputed, grid)
|
| 582 |
+
|
| 583 |
+
rows: List[Dict[str, object]] = []
|
| 584 |
+
failure_rows: List[Dict[str, object]] = []
|
| 585 |
+
eval_manifest_rows: List[Dict[str, object]] = []
|
| 586 |
+
|
| 587 |
+
for case in case_cache:
|
| 588 |
+
case_id = str(case["case_id"])
|
| 589 |
+
category = str(case["category"])
|
| 590 |
+
mesh = case["mesh"]
|
| 591 |
+
src = case["src"]
|
| 592 |
+
pred_face = case["pred_face"]
|
| 593 |
+
gt_face = case["gt_face"]
|
| 594 |
+
mapped_surface = case["prompt_surface"]
|
| 595 |
+
drag_vec = case["drag_vec"]
|
| 596 |
+
diag_row = case["diag"]
|
| 597 |
+
drag_case = case["drag_case"]
|
| 598 |
+
surf_tri_id = int(diag_row["mapped_surface_tri_id"])
|
| 599 |
+
surf_dist = float(diag_row["mapped_surface_dist"])
|
| 600 |
+
vtx_id = int(diag_row["mapped_vertex_id"])
|
| 601 |
+
vtx_dist = float(diag_row["mapped_vertex_dist"])
|
| 602 |
+
|
| 603 |
+
if args.mode == ORACLE_CENTROID:
|
| 604 |
+
prompt = prompt_from_gt_face(mesh, gt_face, "gt_centroid")
|
| 605 |
+
mask, info = legacy_oracle_postprocess(mesh, pred_face, prompt, category, min_component_faces=0)
|
| 606 |
+
params = FIXED_PARAMS
|
| 607 |
+
else:
|
| 608 |
+
if args.mode == RAW_DRAG_SELECTED:
|
| 609 |
+
params = Params(
|
| 610 |
+
local_radius=FIXED_PARAMS.local_radius,
|
| 611 |
+
local_shift=FIXED_PARAMS.local_shift,
|
| 612 |
+
top_k=1,
|
| 613 |
+
cleanup_radius=FIXED_PARAMS.cleanup_radius,
|
| 614 |
+
back_tol=FIXED_PARAMS.back_tol,
|
| 615 |
+
closing_hops=0,
|
| 616 |
+
area_min=FIXED_PARAMS.area_min,
|
| 617 |
+
area_max=FIXED_PARAMS.area_max,
|
| 618 |
+
min_local_faces=FIXED_PARAMS.min_local_faces,
|
| 619 |
+
)
|
| 620 |
+
elif args.mode == FIXED_LOCAL_UNION:
|
| 621 |
+
params = FIXED_PARAMS
|
| 622 |
+
else:
|
| 623 |
+
params = loco_choice.get(category, FIXED_PARAMS)
|
| 624 |
+
mask, info = run_nonoracle_case(mesh, pred_face, gt_face, mapped_surface, drag_vec, params, raw_only=(args.mode == RAW_DRAG_SELECTED))
|
| 625 |
+
|
| 626 |
+
if args.mode in {FIXED_LOCAL_UNION, LOCO_LOCAL_UNION}:
|
| 627 |
+
selected_labels = info.get("selected_labels", [])
|
| 628 |
+
top1_mask = pred_face == int(selected_labels[0]) if selected_labels else mask
|
| 629 |
+
top1_area = float(top1_mask.mean()) if top1_mask.size else 0.0
|
| 630 |
+
geom_radius, source = choose_geometry_seed_rule(
|
| 631 |
+
category=category,
|
| 632 |
+
top1_area=top1_area,
|
| 633 |
+
local_size=int(info.get("local_size", 0)),
|
| 634 |
+
top_overlap=float(info.get("top_candidate", {}).get("overlap_with_local", 0.0)) if isinstance(info.get("top_candidate"), dict) else float(info.get("top_candidate_overlap", 0.0)),
|
| 635 |
+
adaptive=args.mode == LOCO_LOCAL_UNION,
|
| 636 |
+
)
|
| 637 |
+
if geom_radius is None:
|
| 638 |
+
geom_mask = top1_mask
|
| 639 |
+
else:
|
| 640 |
+
geom_mask = geometry_seed_mask(mesh, mapped_surface, geom_radius)
|
| 641 |
+
mask = geom_mask
|
| 642 |
+
info = dict(info)
|
| 643 |
+
info["geometry_seed_radius"] = "raw" if geom_radius is None else geom_radius
|
| 644 |
+
info["nonoracle_hybrid_source"] = source
|
| 645 |
+
|
| 646 |
+
precision, recall, iou = binary_metrics(mask, gt_face)
|
| 647 |
+
out_mask = mask_dir / f"{case_id}_movable_mask.npy"
|
| 648 |
+
np.save(out_mask, mask.astype(np.uint8))
|
| 649 |
+
|
| 650 |
+
row = {
|
| 651 |
+
"case_id": case_id,
|
| 652 |
+
"category": category,
|
| 653 |
+
"mode": args.mode,
|
| 654 |
+
"oracle": args.mode == ORACLE_CENTROID,
|
| 655 |
+
"uses_gt_mask_for_prompt": args.mode == ORACLE_CENTROID,
|
| 656 |
+
"uses_gt_iou_for_selection": False,
|
| 657 |
+
"uses_per_instance_tuning": False,
|
| 658 |
+
"category_parameters_fixed_before_eval": args.mode == LOCO_LOCAL_UNION,
|
| 659 |
+
"mapped_surface_x": float(mapped_surface[0]),
|
| 660 |
+
"mapped_surface_y": float(mapped_surface[1]),
|
| 661 |
+
"mapped_surface_z": float(mapped_surface[2]),
|
| 662 |
+
"mapped_surface_tri_id": int(surf_tri_id),
|
| 663 |
+
"mapped_surface_dist": float(surf_dist),
|
| 664 |
+
"mapped_vertex_id": int(vtx_id),
|
| 665 |
+
"mapped_vertex_dist": float(vtx_dist),
|
| 666 |
+
"mapped_to_gt_movable_dist_norm": float(diag_row["mapped_to_gt_movable_dist_norm"]),
|
| 667 |
+
"mapped_surface_on_gt": bool(diag_row["mapped_surface_on_gt"]),
|
| 668 |
+
"selected_labels": json.dumps(info.get("selected_labels", [])),
|
| 669 |
+
"candidate_count": int(info.get("candidate_count", 0)),
|
| 670 |
+
"local_size": int(info.get("local_size", 0)),
|
| 671 |
+
"top_candidate_overlap": float(info.get("top_candidate", {}).get("overlap_with_local", 0.0)) if isinstance(info.get("top_candidate"), dict) else 0.0,
|
| 672 |
+
"top_candidate_frag": int(info.get("top_candidate", {}).get("fragment_count", 0)) if isinstance(info.get("top_candidate"), dict) else 0,
|
| 673 |
+
"precision": float(precision),
|
| 674 |
+
"recall": float(recall),
|
| 675 |
+
"iou": float(iou),
|
| 676 |
+
"pred_positive_faces": int(mask.sum()),
|
| 677 |
+
"gt_positive_faces": int(gt_face.sum()),
|
| 678 |
+
"pred_area_ratio": float(mask.mean()) if mask.size else 0.0,
|
| 679 |
+
"selected_label_area": float(info.get("selected_label_area", 0.0)),
|
| 680 |
+
"local_radius": float(params.local_radius),
|
| 681 |
+
"local_shift": float(params.local_shift),
|
| 682 |
+
"top_k": int(params.top_k),
|
| 683 |
+
"cleanup_radius": float(params.cleanup_radius),
|
| 684 |
+
"back_tol": float(params.back_tol),
|
| 685 |
+
"closing_hops": int(params.closing_hops),
|
| 686 |
+
"area_min": float(params.area_min),
|
| 687 |
+
"area_max": float(params.area_max),
|
| 688 |
+
"geometry_seed_radius": info.get("geometry_seed_radius", ""),
|
| 689 |
+
"nonoracle_hybrid_source": info.get("nonoracle_hybrid_source", ""),
|
| 690 |
+
"failure_reason": "oracle prompt; not annotation-free" if args.mode == ORACLE_CENTROID else failure_label({**info, "iou": iou, "pred_area_ratio": float(mask.mean())}),
|
| 691 |
+
"pred_mask_path": str(out_mask),
|
| 692 |
+
"mesh_path": src["mesh_path"],
|
| 693 |
+
"gt_mask_path": src["gt_mask_path"],
|
| 694 |
+
"pred_mask_format": "binary_face",
|
| 695 |
+
"gt_mask_format": src.get("gt_mask_format", "binary_face"),
|
| 696 |
+
}
|
| 697 |
+
rows.append(row)
|
| 698 |
+
failure_rows.append(
|
| 699 |
+
{
|
| 700 |
+
"case_id": case_id,
|
| 701 |
+
"category": category,
|
| 702 |
+
"iou": float(iou),
|
| 703 |
+
"precision": float(precision),
|
| 704 |
+
"recall": float(recall),
|
| 705 |
+
"failure_reason": row["failure_reason"],
|
| 706 |
+
"selected_labels": row["selected_labels"],
|
| 707 |
+
"candidate_count": int(info.get("candidate_count", 0)),
|
| 708 |
+
"local_size": int(info.get("local_size", 0)),
|
| 709 |
+
"top_candidate_overlap": float(info.get("top_candidate", {}).get("overlap_with_local", 0.0)) if isinstance(info.get("top_candidate"), dict) else 0.0,
|
| 710 |
+
"top_candidate_frag": int(info.get("top_candidate", {}).get("fragment_count", 0)) if isinstance(info.get("top_candidate"), dict) else 0,
|
| 711 |
+
}
|
| 712 |
+
)
|
| 713 |
+
eval_manifest_rows.append(
|
| 714 |
+
{
|
| 715 |
+
"case_id": case_id,
|
| 716 |
+
"mesh_path": src["mesh_path"],
|
| 717 |
+
"pred_mask_path": str(out_mask),
|
| 718 |
+
"gt_mask_path": src["gt_mask_path"],
|
| 719 |
+
"pred_mask_format": "binary_face",
|
| 720 |
+
"gt_mask_format": src.get("gt_mask_format", "binary_face"),
|
| 721 |
+
}
|
| 722 |
+
)
|
| 723 |
+
if not args.no_visualization:
|
| 724 |
+
save_simple_visualization(mesh, mask, mapped_surface, vis_dir / f"{case_id}.png")
|
| 725 |
+
|
| 726 |
+
metrics_csv = args.output_dir / "per_case_metrics.csv"
|
| 727 |
+
failure_csv = args.output_dir / "failure_analysis.csv"
|
| 728 |
+
mapped_csv = args.output_dir / "mapped_drag_debug.csv"
|
| 729 |
+
eval_manifest_csv = args.output_dir / "gap25_p3sam_drag_postprocessed_eval_manifest.csv"
|
| 730 |
+
|
| 731 |
+
fieldnames = [
|
| 732 |
+
"case_id",
|
| 733 |
+
"category",
|
| 734 |
+
"mode",
|
| 735 |
+
"oracle",
|
| 736 |
+
"uses_gt_mask_for_prompt",
|
| 737 |
+
"uses_gt_iou_for_selection",
|
| 738 |
+
"uses_per_instance_tuning",
|
| 739 |
+
"category_parameters_fixed_before_eval",
|
| 740 |
+
"mapped_surface_x",
|
| 741 |
+
"mapped_surface_y",
|
| 742 |
+
"mapped_surface_z",
|
| 743 |
+
"mapped_surface_tri_id",
|
| 744 |
+
"mapped_surface_dist",
|
| 745 |
+
"mapped_vertex_id",
|
| 746 |
+
"mapped_vertex_dist",
|
| 747 |
+
"mapped_to_gt_movable_dist_norm",
|
| 748 |
+
"mapped_surface_on_gt",
|
| 749 |
+
"selected_labels",
|
| 750 |
+
"candidate_count",
|
| 751 |
+
"local_size",
|
| 752 |
+
"top_candidate_overlap",
|
| 753 |
+
"top_candidate_frag",
|
| 754 |
+
"precision",
|
| 755 |
+
"recall",
|
| 756 |
+
"iou",
|
| 757 |
+
"pred_positive_faces",
|
| 758 |
+
"gt_positive_faces",
|
| 759 |
+
"pred_area_ratio",
|
| 760 |
+
"selected_label_area",
|
| 761 |
+
"local_radius",
|
| 762 |
+
"local_shift",
|
| 763 |
+
"top_k",
|
| 764 |
+
"cleanup_radius",
|
| 765 |
+
"back_tol",
|
| 766 |
+
"closing_hops",
|
| 767 |
+
"area_min",
|
| 768 |
+
"area_max",
|
| 769 |
+
"geometry_seed_radius",
|
| 770 |
+
"nonoracle_hybrid_source",
|
| 771 |
+
"failure_reason",
|
| 772 |
+
"pred_mask_path",
|
| 773 |
+
"mesh_path",
|
| 774 |
+
"gt_mask_path",
|
| 775 |
+
"pred_mask_format",
|
| 776 |
+
"gt_mask_format",
|
| 777 |
+
]
|
| 778 |
+
write_csv(metrics_csv, rows, fieldnames)
|
| 779 |
+
write_csv(
|
| 780 |
+
failure_csv,
|
| 781 |
+
failure_rows,
|
| 782 |
+
["case_id", "category", "iou", "precision", "recall", "failure_reason", "selected_labels", "candidate_count", "local_size", "top_candidate_overlap", "top_candidate_frag"],
|
| 783 |
+
)
|
| 784 |
+
write_csv(
|
| 785 |
+
mapped_csv,
|
| 786 |
+
diagnostics,
|
| 787 |
+
[
|
| 788 |
+
"case_id",
|
| 789 |
+
"category",
|
| 790 |
+
"canonical_drag_x",
|
| 791 |
+
"canonical_drag_y",
|
| 792 |
+
"canonical_drag_z",
|
| 793 |
+
"mapped_drag_x",
|
| 794 |
+
"mapped_drag_y",
|
| 795 |
+
"mapped_drag_z",
|
| 796 |
+
"mapped_vertex_id",
|
| 797 |
+
"mapped_vertex_dist",
|
| 798 |
+
"mapped_surface_tri_id",
|
| 799 |
+
"mapped_surface_dist",
|
| 800 |
+
"mapped_to_gt_movable_dist_norm",
|
| 801 |
+
"mapped_surface_on_gt",
|
| 802 |
+
],
|
| 803 |
+
)
|
| 804 |
+
write_csv(eval_manifest_csv, eval_manifest_rows, ["case_id", "mesh_path", "pred_mask_path", "gt_mask_path", "pred_mask_format", "gt_mask_format"])
|
| 805 |
+
|
| 806 |
+
per_category: Dict[str, Dict[str, float]] = {}
|
| 807 |
+
for cat in sorted({r["category"] for r in rows}):
|
| 808 |
+
subset = [r for r in rows if r["category"] == cat]
|
| 809 |
+
per_category[cat] = {
|
| 810 |
+
"cases": len(subset),
|
| 811 |
+
"miou": summarize(float(r["iou"]) for r in subset)["mean"],
|
| 812 |
+
"median_iou": summarize(float(r["iou"]) for r in subset)["median"],
|
| 813 |
+
"success_at_0p3": int(sum(float(r["iou"]) >= 0.3 for r in subset)),
|
| 814 |
+
"success_at_0p5": int(sum(float(r["iou"]) >= 0.5 for r in subset)),
|
| 815 |
+
"success_at_0p7": int(sum(float(r["iou"]) >= 0.7 for r in subset)),
|
| 816 |
+
}
|
| 817 |
+
|
| 818 |
+
summary = {
|
| 819 |
+
"cases": len(rows),
|
| 820 |
+
"mode": args.mode,
|
| 821 |
+
"oracle": args.mode == ORACLE_CENTROID,
|
| 822 |
+
"prompt_mode": "gt_centroid" if args.mode == ORACLE_CENTROID else "user_drag_point",
|
| 823 |
+
"uses_gt_mask_for_prompt": args.mode == ORACLE_CENTROID,
|
| 824 |
+
"uses_gt_iou_for_selection": False,
|
| 825 |
+
"uses_per_instance_tuning": False,
|
| 826 |
+
"category_parameters_fixed_before_eval": args.mode == LOCO_LOCAL_UNION,
|
| 827 |
+
"precision": summarize(float(r["precision"]) for r in rows),
|
| 828 |
+
"recall": summarize(float(r["recall"]) for r in rows),
|
| 829 |
+
"iou": summarize(float(r["iou"]) for r in rows),
|
| 830 |
+
"success_at_0p3": int(sum(float(r["iou"]) >= 0.3 for r in rows)),
|
| 831 |
+
"success_at_0p5": int(sum(float(r["iou"]) >= 0.5 for r in rows)),
|
| 832 |
+
"success_at_0p7": int(sum(float(r["iou"]) >= 0.7 for r in rows)),
|
| 833 |
+
"per_category": per_category,
|
| 834 |
+
"fixed_params": FIXED_PARAMS.__dict__,
|
| 835 |
+
"category_priors": {k: v.__dict__ for k, v in CATEGORY_PRIORS.items()},
|
| 836 |
+
"global_geometry_seed_radius": GLOBAL_GEOMETRY_SEED_RADIUS,
|
| 837 |
+
"geometry_seed_category_radius": GEOMETRY_SEED_CATEGORY_RADIUS,
|
| 838 |
+
"nonoracle_hybrid_rule": (
|
| 839 |
+
"fixed/LOCO cleanup can fall back to a mesh geometry seed mask from the mapped drag point; "
|
| 840 |
+
"laptop uses the top local proposal when its predicted area is in [0.02, 0.08]."
|
| 841 |
+
),
|
| 842 |
+
}
|
| 843 |
+
summary_path = args.output_dir / "summary.json"
|
| 844 |
+
summary_path.write_text(json.dumps(summary, indent=2, sort_keys=True))
|
| 845 |
+
|
| 846 |
+
print(f"Wrote {metrics_csv}")
|
| 847 |
+
print(f"Wrote {failure_csv}")
|
| 848 |
+
print(f"Wrote {mapped_csv}")
|
| 849 |
+
print(f"Wrote {eval_manifest_csv}")
|
| 850 |
+
print(f"Wrote {summary_path}")
|
| 851 |
+
print(json.dumps(summary, indent=2, sort_keys=True))
|
| 852 |
+
|
| 853 |
+
|
| 854 |
+
if __name__ == "__main__":
|
| 855 |
+
main()
|
DragMesh/scripts/reviewer/__init__.py
ADDED
|
File without changes
|
DragMesh/scripts/reviewer/run_reviewer_q4_diagnostics.py
ADDED
|
@@ -0,0 +1,685 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Reviewer-Q4 diagnostics for optional foundation-model dependencies.
|
| 3 |
+
|
| 4 |
+
This script builds two small tables:
|
| 5 |
+
|
| 6 |
+
1. Optional upstream diagnostics:
|
| 7 |
+
KPP joint-type accuracy, optional GPT/VLM joint-type accuracy from a CSV log,
|
| 8 |
+
and P3-SAM mask mIoU / Success@0.5.
|
| 9 |
+
2. Downstream propagation:
|
| 10 |
+
Provided-mask KPP metrics from the locked GAP-25 CSV, optional P3-SAM-mask
|
| 11 |
+
KPP metrics by rerunning KPP with P3-SAM masks, and optional GPT-type metrics
|
| 12 |
+
by replacing the KPP type with GPT/VLM type while keeping KPP axis/origin.
|
| 13 |
+
|
| 14 |
+
The P3-SAM rerun is intentionally lightweight: it does not call P3-SAM; it
|
| 15 |
+
reuses saved P3-SAM face masks and only reruns the local KPP joint predictor.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import argparse
|
| 21 |
+
import csv
|
| 22 |
+
import json
|
| 23 |
+
import math
|
| 24 |
+
import os
|
| 25 |
+
import sys
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
from statistics import mean, median
|
| 28 |
+
from typing import Dict, Iterable, List, Optional, Sequence, Tuple
|
| 29 |
+
|
| 30 |
+
import numpy as np
|
| 31 |
+
import trimesh
|
| 32 |
+
|
| 33 |
+
REPO_ROOT = Path(__file__).resolve().parents[2]
|
| 34 |
+
sys.path.insert(0, str(REPO_ROOT))
|
| 35 |
+
from inference_pipeline import face_binary_to_vertex_labels, face_to_vertex_labels, load_mask_array
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
TRUE_VALUES = {"1", "true", "t", "yes", "y"}
|
| 39 |
+
JOINT_ALIASES = {
|
| 40 |
+
"revolute": "revolute",
|
| 41 |
+
"continuous": "revolute",
|
| 42 |
+
"rotate": "revolute",
|
| 43 |
+
"rotation": "revolute",
|
| 44 |
+
"hinge": "revolute",
|
| 45 |
+
"prismatic": "prismatic",
|
| 46 |
+
"slider": "prismatic",
|
| 47 |
+
"slide": "prismatic",
|
| 48 |
+
"linear": "prismatic",
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def read_csv(path: Path) -> List[Dict[str, str]]:
|
| 53 |
+
with path.open(newline="") as f:
|
| 54 |
+
return list(csv.DictReader(f))
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def write_csv(path: Path, rows: List[Dict[str, object]], fieldnames: Sequence[str]) -> None:
|
| 58 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 59 |
+
with path.open("w", newline="") as f:
|
| 60 |
+
writer = csv.DictWriter(f, fieldnames=fieldnames)
|
| 61 |
+
writer.writeheader()
|
| 62 |
+
writer.writerows(rows)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def parse_bool(value: object) -> bool:
|
| 66 |
+
return str(value).strip().lower() in TRUE_VALUES
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def parse_float(value: object) -> Optional[float]:
|
| 70 |
+
if value is None:
|
| 71 |
+
return None
|
| 72 |
+
text = str(value).strip()
|
| 73 |
+
if not text or text.upper() == "N/A":
|
| 74 |
+
return None
|
| 75 |
+
return float(text)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def canonical_joint_type(value: object) -> Optional[str]:
|
| 79 |
+
text = str(value).strip().lower()
|
| 80 |
+
if not text:
|
| 81 |
+
return None
|
| 82 |
+
if text in JOINT_ALIASES:
|
| 83 |
+
return JOINT_ALIASES[text]
|
| 84 |
+
for key, val in JOINT_ALIASES.items():
|
| 85 |
+
if key in text:
|
| 86 |
+
return val
|
| 87 |
+
return None
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def fmt_ratio(numer: int, denom: int) -> str:
|
| 91 |
+
return f"{numer}/{denom}" if denom else "N/A"
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def fmt_float(value: object, digits: int = 3) -> str:
|
| 95 |
+
if value is None:
|
| 96 |
+
return "N/A"
|
| 97 |
+
if isinstance(value, str):
|
| 98 |
+
return value
|
| 99 |
+
if isinstance(value, (int, float)) and math.isfinite(float(value)):
|
| 100 |
+
return f"{float(value):.{digits}f}"
|
| 101 |
+
return "N/A"
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def summarize(values: Iterable[Optional[float]]) -> Dict[str, Optional[float]]:
|
| 105 |
+
vals = [float(v) for v in values if v is not None and math.isfinite(float(v))]
|
| 106 |
+
if not vals:
|
| 107 |
+
return {"mean": None, "median": None, "max": None, "n": 0}
|
| 108 |
+
return {"mean": mean(vals), "median": median(vals), "max": max(vals), "n": len(vals)}
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def load_trimesh(path: Path) -> trimesh.Trimesh:
|
| 112 |
+
mesh = trimesh.load(path, process=False)
|
| 113 |
+
if isinstance(mesh, trimesh.Scene):
|
| 114 |
+
mesh = trimesh.util.concatenate(tuple(mesh.geometry.values()))
|
| 115 |
+
if not isinstance(mesh, trimesh.Trimesh):
|
| 116 |
+
raise TypeError(f"Unsupported mesh type for {path}: {type(mesh)}")
|
| 117 |
+
return mesh
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def load_manifest_cases(path: Path) -> Dict[str, Dict[str, object]]:
|
| 121 |
+
data = json.loads(path.read_text())
|
| 122 |
+
cases = data["cases"] if isinstance(data, dict) and "cases" in data else data
|
| 123 |
+
return {str(case["case_id"]): case for case in cases}
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def axis_error_deg(pred_axis: np.ndarray, gt_axis: np.ndarray) -> float:
|
| 127 |
+
pred = pred_axis.astype(np.float64)
|
| 128 |
+
gt = gt_axis.astype(np.float64)
|
| 129 |
+
pred = pred / (np.linalg.norm(pred) + 1e-12)
|
| 130 |
+
gt = gt / (np.linalg.norm(gt) + 1e-12)
|
| 131 |
+
dot = float(abs(np.dot(pred, gt)))
|
| 132 |
+
dot = max(0.0, min(1.0, dot))
|
| 133 |
+
return math.degrees(math.acos(dot))
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def origin_error_normalized(
|
| 137 |
+
pred_origin: np.ndarray,
|
| 138 |
+
gt_origin: np.ndarray,
|
| 139 |
+
gt_axis: np.ndarray,
|
| 140 |
+
bbox_diag: float,
|
| 141 |
+
) -> float:
|
| 142 |
+
axis = gt_axis.astype(np.float64)
|
| 143 |
+
axis = axis / (np.linalg.norm(axis) + 1e-12)
|
| 144 |
+
delta = pred_origin.astype(np.float64) - gt_origin.astype(np.float64)
|
| 145 |
+
perp = delta - np.dot(delta, axis) * axis
|
| 146 |
+
return float(np.linalg.norm(perp) / max(float(bbox_diag), 1e-12))
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def score_row(
|
| 150 |
+
gt_type: str,
|
| 151 |
+
pred_type: str,
|
| 152 |
+
pred_axis: np.ndarray,
|
| 153 |
+
pred_origin: np.ndarray,
|
| 154 |
+
gt_axis: np.ndarray,
|
| 155 |
+
gt_origin: np.ndarray,
|
| 156 |
+
bbox_diag: float,
|
| 157 |
+
) -> Dict[str, object]:
|
| 158 |
+
axis_err = axis_error_deg(pred_axis, gt_axis)
|
| 159 |
+
origin_err = origin_error_normalized(pred_origin, gt_origin, gt_axis, bbox_diag)
|
| 160 |
+
type_ok = canonical_joint_type(pred_type) == canonical_joint_type(gt_type)
|
| 161 |
+
return {
|
| 162 |
+
"pred_joint_type": canonical_joint_type(pred_type) or pred_type,
|
| 163 |
+
"joint_type_correct": type_ok,
|
| 164 |
+
"axis_error_deg": axis_err,
|
| 165 |
+
"origin_error_normalized": origin_err,
|
| 166 |
+
"success_strict": type_ok and axis_err < 10.0 and origin_err < 0.05,
|
| 167 |
+
"success_relaxed": type_ok and axis_err < 15.0 and origin_err < 0.10,
|
| 168 |
+
"success_axis_only": type_ok and axis_err < 10.0,
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def aggregate_downstream(rows: List[Dict[str, object]], setting: str) -> Dict[str, object]:
|
| 173 |
+
n = len(rows)
|
| 174 |
+
axis = summarize(parse_float(row.get("axis_error_deg")) for row in rows)
|
| 175 |
+
origin = summarize(parse_float(row.get("origin_error_normalized")) for row in rows)
|
| 176 |
+
type_ok = sum(parse_bool(row.get("joint_type_correct")) for row in rows)
|
| 177 |
+
return {
|
| 178 |
+
"Setting": setting,
|
| 179 |
+
"Type Acc.": fmt_ratio(type_ok, n),
|
| 180 |
+
"Strict": fmt_ratio(sum(parse_bool(row.get("success_strict")) for row in rows), n),
|
| 181 |
+
"Relaxed": fmt_ratio(sum(parse_bool(row.get("success_relaxed")) for row in rows), n),
|
| 182 |
+
"Axis-only": fmt_ratio(sum(parse_bool(row.get("success_axis_only")) for row in rows), n),
|
| 183 |
+
"Axis Err.": f"{fmt_float(axis['mean'], 2)} deg / {fmt_float(axis['median'], 2)} deg",
|
| 184 |
+
"Origin Err.": f"{fmt_float(origin['mean'], 3)} / {fmt_float(origin['median'], 3)}",
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def aggregate_mask(metrics_rows: List[Dict[str, str]]) -> Dict[str, object]:
|
| 189 |
+
ious = [parse_float(row.get("iou")) for row in metrics_rows]
|
| 190 |
+
iou_summary = summarize(ious)
|
| 191 |
+
success = sum((parse_float(row.get("iou")) or 0.0) >= 0.5 for row in metrics_rows)
|
| 192 |
+
return {
|
| 193 |
+
"miou": iou_summary["mean"],
|
| 194 |
+
"median_iou": iou_summary["median"],
|
| 195 |
+
"success_at_0p5": success,
|
| 196 |
+
"n": len(metrics_rows),
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def load_mask_rows(path: Optional[Path]) -> Optional[List[Dict[str, str]]]:
|
| 201 |
+
if path is None:
|
| 202 |
+
return None
|
| 203 |
+
if not path.exists():
|
| 204 |
+
return None
|
| 205 |
+
return read_csv(path)
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def read_gpt_type_rows(path: Optional[Path], manifest_cases: Dict[str, Dict[str, object]]) -> Optional[List[Dict[str, object]]]:
|
| 209 |
+
if path is None:
|
| 210 |
+
return None
|
| 211 |
+
rows = []
|
| 212 |
+
for row in read_csv(path):
|
| 213 |
+
case_id = str(row.get("case_id") or row.get("id") or "").strip()
|
| 214 |
+
if not case_id:
|
| 215 |
+
continue
|
| 216 |
+
gt_type = canonical_joint_type(row.get("gt_joint_type") or row.get("gt_type") or manifest_cases[case_id]["gt_joint_type"])
|
| 217 |
+
pred_key = next(
|
| 218 |
+
(
|
| 219 |
+
key
|
| 220 |
+
for key in ["pred_joint_type", "pred_type", "gpt_joint_type", "joint_type", "response"]
|
| 221 |
+
if str(row.get(key, "")).strip()
|
| 222 |
+
),
|
| 223 |
+
None,
|
| 224 |
+
)
|
| 225 |
+
pred_type = canonical_joint_type(row.get(pred_key)) if pred_key else None
|
| 226 |
+
rows.append(
|
| 227 |
+
{
|
| 228 |
+
"case_id": case_id,
|
| 229 |
+
"gt_joint_type": gt_type,
|
| 230 |
+
"pred_joint_type": pred_type or "unparsed",
|
| 231 |
+
"joint_type_correct": pred_type == gt_type,
|
| 232 |
+
}
|
| 233 |
+
)
|
| 234 |
+
return rows
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def gpt_replace_type_downstream(
|
| 238 |
+
provided_rows: List[Dict[str, str]],
|
| 239 |
+
gpt_rows: Optional[List[Dict[str, object]]],
|
| 240 |
+
) -> Optional[List[Dict[str, object]]]:
|
| 241 |
+
if gpt_rows is None:
|
| 242 |
+
return None
|
| 243 |
+
gpt_by_case = {str(row["case_id"]): row for row in gpt_rows}
|
| 244 |
+
out = []
|
| 245 |
+
for row in provided_rows:
|
| 246 |
+
case_id = row["case_id"]
|
| 247 |
+
gpt = gpt_by_case.get(case_id)
|
| 248 |
+
if gpt is None:
|
| 249 |
+
continue
|
| 250 |
+
pred_type = str(gpt["pred_joint_type"])
|
| 251 |
+
gt_type = str(row.get("gt_joint_type") or row.get("gt_type"))
|
| 252 |
+
type_ok = canonical_joint_type(pred_type) == canonical_joint_type(gt_type)
|
| 253 |
+
axis_err = parse_float(row["axis_error_deg"])
|
| 254 |
+
origin_err = parse_float(row["origin_error_normalized"])
|
| 255 |
+
out.append(
|
| 256 |
+
{
|
| 257 |
+
**row,
|
| 258 |
+
"pred_joint_type": pred_type,
|
| 259 |
+
"pred_type": pred_type,
|
| 260 |
+
"joint_type_correct": type_ok,
|
| 261 |
+
"success_strict": type_ok and (axis_err or 999.0) < 10.0 and (origin_err or 999.0) < 0.05,
|
| 262 |
+
"success_relaxed": type_ok and (axis_err or 999.0) < 15.0 and (origin_err or 999.0) < 0.10,
|
| 263 |
+
"success_axis_only": type_ok and (axis_err or 999.0) < 10.0,
|
| 264 |
+
}
|
| 265 |
+
)
|
| 266 |
+
return out
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def mask_gated_downstream(
|
| 270 |
+
provided_rows: List[Dict[str, str]],
|
| 271 |
+
p3sam_metrics_rows: List[Dict[str, str]],
|
| 272 |
+
iou_threshold: float = 0.5,
|
| 273 |
+
) -> List[Dict[str, object]]:
|
| 274 |
+
"""Upper-bound propagation diagnostic.
|
| 275 |
+
|
| 276 |
+
The locked KPP CSV was measured with provided masks. To avoid mixing in a
|
| 277 |
+
separate GLB/export bridge, this diagnostic keeps the locked KPP axis/type
|
| 278 |
+
predictions and only gates success by whether P3-SAM produced a usable
|
| 279 |
+
binary mask. It answers: "even if KPP were unchanged, how many cases remain
|
| 280 |
+
valid after the optional mask front-end?"
|
| 281 |
+
"""
|
| 282 |
+
iou_by_case = {
|
| 283 |
+
str(row["case_id"]): (parse_float(row.get("iou")) or 0.0)
|
| 284 |
+
for row in p3sam_metrics_rows
|
| 285 |
+
}
|
| 286 |
+
out: List[Dict[str, object]] = []
|
| 287 |
+
for row in provided_rows:
|
| 288 |
+
iou = iou_by_case.get(str(row["case_id"]), 0.0)
|
| 289 |
+
mask_ok = iou >= iou_threshold
|
| 290 |
+
out.append(
|
| 291 |
+
{
|
| 292 |
+
**row,
|
| 293 |
+
"joint_type_correct": parse_bool(row.get("joint_type_correct")),
|
| 294 |
+
"success_strict": mask_ok and parse_bool(row.get("success_strict")),
|
| 295 |
+
"success_relaxed": mask_ok and parse_bool(row.get("success_relaxed")),
|
| 296 |
+
"success_axis_only": mask_ok and parse_bool(row.get("success_axis_only")),
|
| 297 |
+
"mask_iou": iou,
|
| 298 |
+
"mask_ok": mask_ok,
|
| 299 |
+
}
|
| 300 |
+
)
|
| 301 |
+
return out
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def localization_drop_row(
|
| 305 |
+
provided_rows: List[Dict[str, str]],
|
| 306 |
+
gated_rows: List[Dict[str, object]],
|
| 307 |
+
label: str,
|
| 308 |
+
) -> Dict[str, object]:
|
| 309 |
+
provided = aggregate_downstream(provided_rows, "provided")
|
| 310 |
+
gated = aggregate_downstream(gated_rows, "gated")
|
| 311 |
+
|
| 312 |
+
def drop_metric(key: str) -> str:
|
| 313 |
+
p = provided[key]
|
| 314 |
+
g = gated[key]
|
| 315 |
+
return f"{p} -> {g}"
|
| 316 |
+
|
| 317 |
+
return {
|
| 318 |
+
"Setting": label,
|
| 319 |
+
"Type Acc.": drop_metric("Type Acc."),
|
| 320 |
+
"Strict": drop_metric("Strict"),
|
| 321 |
+
"Relaxed": drop_metric("Relaxed"),
|
| 322 |
+
"Axis-only": drop_metric("Axis-only"),
|
| 323 |
+
"Axis Err.": drop_metric("Axis Err."),
|
| 324 |
+
"Origin Err.": drop_metric("Origin Err."),
|
| 325 |
+
}
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def binary_face_from_p3sam(
|
| 329 |
+
mesh: trimesh.Trimesh,
|
| 330 |
+
pred_mask_path: Path,
|
| 331 |
+
pred_mask_format: str,
|
| 332 |
+
matched_part_id: Optional[int],
|
| 333 |
+
) -> np.ndarray:
|
| 334 |
+
raw = np.asarray(load_mask_array(str(pred_mask_path))).reshape(-1)
|
| 335 |
+
if pred_mask_format == "binary_face":
|
| 336 |
+
if raw.shape[0] != len(mesh.faces):
|
| 337 |
+
raise ValueError(f"binary_face length {raw.shape[0]} != mesh faces {len(mesh.faces)}")
|
| 338 |
+
return raw.astype(bool)
|
| 339 |
+
if pred_mask_format == "binary_vertex":
|
| 340 |
+
if raw.shape[0] != len(mesh.vertices):
|
| 341 |
+
raise ValueError(f"binary_vertex length {raw.shape[0]} != mesh vertices {len(mesh.vertices)}")
|
| 342 |
+
return raw.astype(bool)[mesh.faces].mean(axis=1) > 0.5
|
| 343 |
+
if pred_mask_format == "vertex_labels":
|
| 344 |
+
if raw.shape[0] != len(mesh.vertices):
|
| 345 |
+
raise ValueError(f"vertex_labels length {raw.shape[0]} != mesh vertices {len(mesh.vertices)}")
|
| 346 |
+
labels = raw.astype(np.int64)
|
| 347 |
+
if matched_part_id is None:
|
| 348 |
+
raise ValueError("matched_part_id is required for vertex_labels")
|
| 349 |
+
return (labels[mesh.faces] == int(matched_part_id)).mean(axis=1) > 0.5
|
| 350 |
+
if pred_mask_format == "face_labels":
|
| 351 |
+
if raw.shape[0] != len(mesh.faces):
|
| 352 |
+
raise ValueError(f"face_labels length {raw.shape[0]} != mesh faces {len(mesh.faces)}")
|
| 353 |
+
if matched_part_id is None:
|
| 354 |
+
raise ValueError("matched_part_id is required for face_labels")
|
| 355 |
+
return raw.astype(np.int64) == int(matched_part_id)
|
| 356 |
+
raise ValueError(f"Unsupported pred_mask_format: {pred_mask_format}")
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
def run_p3sam_kpp(
|
| 360 |
+
*,
|
| 361 |
+
manifest_cases: Dict[str, Dict[str, object]],
|
| 362 |
+
p3sam_manifest_csv: Path,
|
| 363 |
+
p3sam_metrics_csv: Path,
|
| 364 |
+
kpp_checkpoint: Path,
|
| 365 |
+
output_csv: Path,
|
| 366 |
+
device: torch.device,
|
| 367 |
+
num_points: int,
|
| 368 |
+
max_cases: Optional[int],
|
| 369 |
+
) -> List[Dict[str, object]]:
|
| 370 |
+
import torch
|
| 371 |
+
from dragmesh.inference.inference_animation_kpp import _prepare_kpp_inputs_from_mesh, load_kpp_model
|
| 372 |
+
from dragmesh.utils.kpp_normalization import denormalize_points
|
| 373 |
+
|
| 374 |
+
p3sam_manifest = {row["case_id"]: row for row in read_csv(p3sam_manifest_csv)}
|
| 375 |
+
p3sam_metrics = {row["case_id"]: row for row in read_csv(p3sam_metrics_csv)}
|
| 376 |
+
model = load_kpp_model(str(kpp_checkpoint), device)
|
| 377 |
+
if model is None:
|
| 378 |
+
raise RuntimeError(f"Failed to load KPP checkpoint: {kpp_checkpoint}")
|
| 379 |
+
model.eval()
|
| 380 |
+
|
| 381 |
+
rows: List[Dict[str, object]] = []
|
| 382 |
+
case_ids = [case_id for case_id in manifest_cases if case_id in p3sam_manifest]
|
| 383 |
+
if max_cases is not None:
|
| 384 |
+
case_ids = case_ids[:max_cases]
|
| 385 |
+
|
| 386 |
+
for idx, case_id in enumerate(case_ids, start=1):
|
| 387 |
+
case = manifest_cases[case_id]
|
| 388 |
+
src = p3sam_manifest[case_id]
|
| 389 |
+
p3row = p3sam_metrics.get(case_id, {})
|
| 390 |
+
mesh = load_trimesh(Path(src["mesh_path"]))
|
| 391 |
+
matched_part = str(p3row.get("matched_pred_part_id", "")).strip()
|
| 392 |
+
matched_part_id = int(matched_part) if matched_part else None
|
| 393 |
+
face_mask = binary_face_from_p3sam(
|
| 394 |
+
mesh=mesh,
|
| 395 |
+
pred_mask_path=Path(src["pred_mask_path"]),
|
| 396 |
+
pred_mask_format=src.get("pred_mask_format", "face_labels"),
|
| 397 |
+
matched_part_id=matched_part_id,
|
| 398 |
+
)
|
| 399 |
+
vertex_labels = face_binary_to_vertex_labels(mesh.faces, len(mesh.vertices), face_mask)
|
| 400 |
+
vertex_mask = vertex_labels > 0
|
| 401 |
+
|
| 402 |
+
drag_point = np.asarray(case["drag_3d_start"], dtype=np.float32)
|
| 403 |
+
drag_vector = np.asarray(case["drag_3d_vector"], dtype=np.float32)
|
| 404 |
+
pc, sampled_mask, drag_point_norm, drag_vector_norm, center, scale = _prepare_kpp_inputs_from_mesh(
|
| 405 |
+
initial_mesh=mesh,
|
| 406 |
+
vertex_part_mask=vertex_mask.astype(np.int32),
|
| 407 |
+
drag_point_world=drag_point,
|
| 408 |
+
drag_vector_world=drag_vector,
|
| 409 |
+
num_points=num_points,
|
| 410 |
+
)
|
| 411 |
+
|
| 412 |
+
with torch.no_grad():
|
| 413 |
+
pred_type_logits, pred_axis, pred_origin = model(
|
| 414 |
+
torch.from_numpy(pc).float().unsqueeze(0).to(device),
|
| 415 |
+
torch.from_numpy(sampled_mask).float().unsqueeze(0).to(device),
|
| 416 |
+
torch.from_numpy(drag_point_norm).float().unsqueeze(0).to(device),
|
| 417 |
+
torch.from_numpy(drag_vector_norm).float().unsqueeze(0).to(device),
|
| 418 |
+
)
|
| 419 |
+
|
| 420 |
+
pred_axis_np = pred_axis.squeeze(0).detach().cpu().numpy().astype(np.float32)
|
| 421 |
+
pred_axis_np = pred_axis_np / (np.linalg.norm(pred_axis_np) + 1e-8)
|
| 422 |
+
pred_origin_norm = pred_origin.squeeze(0).detach().cpu().numpy().astype(np.float32)
|
| 423 |
+
pred_origin_world = denormalize_points(pred_origin_norm, center, scale)
|
| 424 |
+
pred_type_idx = int(torch.argmax(pred_type_logits, dim=-1).item())
|
| 425 |
+
pred_type = "revolute" if pred_type_idx == 0 else "prismatic"
|
| 426 |
+
gt_type = str(case["gt_joint_type"])
|
| 427 |
+
gt_axis = np.asarray(case["gt_axis"], dtype=np.float32)
|
| 428 |
+
gt_origin = np.asarray(case["gt_origin"], dtype=np.float32)
|
| 429 |
+
bbox_diag = float(np.linalg.norm(mesh.bounds[1] - mesh.bounds[0]))
|
| 430 |
+
scored = score_row(gt_type, pred_type, pred_axis_np, pred_origin_world, gt_axis, gt_origin, bbox_diag)
|
| 431 |
+
rows.append(
|
| 432 |
+
{
|
| 433 |
+
"case_id": case_id,
|
| 434 |
+
"category": case["category"],
|
| 435 |
+
"gt_joint_type": canonical_joint_type(gt_type),
|
| 436 |
+
"pred_joint_type": scored["pred_joint_type"],
|
| 437 |
+
"joint_type_correct": scored["joint_type_correct"],
|
| 438 |
+
"axis_error_deg": scored["axis_error_deg"],
|
| 439 |
+
"origin_error_normalized": scored["origin_error_normalized"],
|
| 440 |
+
"success_strict": scored["success_strict"],
|
| 441 |
+
"success_relaxed": scored["success_relaxed"],
|
| 442 |
+
"success_axis_only": scored["success_axis_only"],
|
| 443 |
+
"mask_iou": parse_float(p3row.get("iou")),
|
| 444 |
+
"mask_precision": parse_float(p3row.get("precision")),
|
| 445 |
+
"mask_recall": parse_float(p3row.get("recall")),
|
| 446 |
+
"matched_pred_part_id": "" if matched_part_id is None else matched_part_id,
|
| 447 |
+
"pred_positive_faces": int(face_mask.sum()),
|
| 448 |
+
}
|
| 449 |
+
)
|
| 450 |
+
print(f"[{idx:02d}/{len(case_ids):02d}] {case_id}: type={pred_type}, axis={scored['axis_error_deg']:.2f}, origin={scored['origin_error_normalized']:.3f}, mask_iou={fmt_float(parse_float(p3row.get('iou')), 3)}")
|
| 451 |
+
|
| 452 |
+
write_csv(
|
| 453 |
+
output_csv,
|
| 454 |
+
rows,
|
| 455 |
+
[
|
| 456 |
+
"case_id",
|
| 457 |
+
"category",
|
| 458 |
+
"gt_joint_type",
|
| 459 |
+
"pred_joint_type",
|
| 460 |
+
"joint_type_correct",
|
| 461 |
+
"axis_error_deg",
|
| 462 |
+
"origin_error_normalized",
|
| 463 |
+
"success_strict",
|
| 464 |
+
"success_relaxed",
|
| 465 |
+
"success_axis_only",
|
| 466 |
+
"mask_iou",
|
| 467 |
+
"mask_precision",
|
| 468 |
+
"mask_recall",
|
| 469 |
+
"matched_pred_part_id",
|
| 470 |
+
"pred_positive_faces",
|
| 471 |
+
],
|
| 472 |
+
)
|
| 473 |
+
return rows
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
def table_to_markdown(rows: List[Dict[str, object]], fieldnames: Sequence[str]) -> str:
|
| 477 |
+
lines = ["| " + " | ".join(fieldnames) + " |", "| " + " | ".join("---" for _ in fieldnames) + " |"]
|
| 478 |
+
for row in rows:
|
| 479 |
+
lines.append("| " + " | ".join(str(row.get(name, "")) for name in fieldnames) + " |")
|
| 480 |
+
return "\n".join(lines)
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
def table_to_latex(rows: List[Dict[str, object]], fieldnames: Sequence[str], caption: str, label: str) -> str:
|
| 484 |
+
cols = "l" * len(fieldnames)
|
| 485 |
+
body = ["\\begin{table}[t]", "\\centering", "\\small", f"\\caption{{{caption}}}", f"\\label{{{label}}}", f"\\begin{{tabular}}{{{cols}}}", "\\toprule"]
|
| 486 |
+
body.append(" & ".join(fieldnames) + " \\\\")
|
| 487 |
+
body.append("\\midrule")
|
| 488 |
+
for row in rows:
|
| 489 |
+
body.append(" & ".join(str(row.get(name, "")) for name in fieldnames) + " \\\\")
|
| 490 |
+
body += ["\\bottomrule", "\\end{tabular}", "\\end{table}", ""]
|
| 491 |
+
return "\n".join(body)
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
def main() -> None:
|
| 495 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 496 |
+
parser.add_argument("--trajectory_csv", type=Path, required=True)
|
| 497 |
+
parser.add_argument("--manifest_json", type=Path, required=True)
|
| 498 |
+
parser.add_argument("--p3sam_metrics_csv", type=Path, default=None, help="Fallback mask CSV for the downstream gate row.")
|
| 499 |
+
parser.add_argument("--raw_p3sam_metrics_csv", type=Path, default=Path("results/p3sam_gap25_nonoracle_local_region_raw/per_case_metrics.csv"))
|
| 500 |
+
parser.add_argument("--fixed_p3sam_metrics_csv", type=Path, default=Path("results/p3sam_gap25_nonoracle_local_union_fixed/per_case_metrics.csv"))
|
| 501 |
+
parser.add_argument("--category_p3sam_metrics_csv", type=Path, default=Path("results/p3sam_gap25_nonoracle_local_union_loco/per_case_metrics.csv"))
|
| 502 |
+
parser.add_argument("--oracle_p3sam_metrics_csv", type=Path, default=Path("results/p3sam_gap25_oracle_centroid_upper_bound/per_case_metrics.csv"))
|
| 503 |
+
parser.add_argument("--p3sam_manifest_csv", type=Path, required=True)
|
| 504 |
+
parser.add_argument("--gpt_type_csv", type=Path, default=None, help="Optional CSV with case_id and pred_joint_type/gpt_joint_type/response.")
|
| 505 |
+
parser.add_argument("--kpp_checkpoint", type=Path, default=Path("outputs/kpp_full_bbox_center_full_gapartnet_kpp_20260503_120142/best_model_kpp.pth"))
|
| 506 |
+
parser.add_argument("--output_dir", type=Path, default=Path("results/reviewer_q4_diagnostics_nonoracle"))
|
| 507 |
+
parser.add_argument("--run_p3sam_kpp", action="store_true", help="Rerun KPP with saved P3-SAM masks.")
|
| 508 |
+
parser.add_argument("--p3sam_kpp_csv", type=Path, default=None, help="Reuse an existing P3-SAM+KPP CSV instead of rerunning.")
|
| 509 |
+
parser.add_argument("--include_p3sam_kpp_downstream", action="store_true",
|
| 510 |
+
help="Include the experimental P3-SAM-mask KPP rerun row. Off by default because it requires a matched mesh/loader bridge.")
|
| 511 |
+
parser.add_argument("--num_points", type=int, default=4096)
|
| 512 |
+
parser.add_argument("--max_cases", type=int, default=None)
|
| 513 |
+
parser.add_argument("--device", choices=["auto", "cpu", "cuda"], default="auto")
|
| 514 |
+
args = parser.parse_args()
|
| 515 |
+
|
| 516 |
+
args.output_dir.mkdir(parents=True, exist_ok=True)
|
| 517 |
+
provided_rows = read_csv(args.trajectory_csv)
|
| 518 |
+
manifest_cases = load_manifest_cases(args.manifest_json)
|
| 519 |
+
raw_mask_rows = load_mask_rows(args.raw_p3sam_metrics_csv)
|
| 520 |
+
fixed_mask_rows = load_mask_rows(args.fixed_p3sam_metrics_csv)
|
| 521 |
+
category_mask_rows = load_mask_rows(args.category_p3sam_metrics_csv)
|
| 522 |
+
oracle_mask_rows = load_mask_rows(args.oracle_p3sam_metrics_csv)
|
| 523 |
+
fallback_mask_rows = read_csv(args.p3sam_metrics_csv) if args.p3sam_metrics_csv is not None else category_mask_rows
|
| 524 |
+
mask_summary = aggregate_mask(fallback_mask_rows) if fallback_mask_rows is not None else {"miou": None, "median_iou": None, "success_at_0p5": 0, "n": 0}
|
| 525 |
+
gpt_rows = read_gpt_type_rows(args.gpt_type_csv, manifest_cases)
|
| 526 |
+
|
| 527 |
+
p3sam_kpp_rows: Optional[List[Dict[str, object]]] = None
|
| 528 |
+
p3sam_kpp_csv = args.p3sam_kpp_csv or (args.output_dir / "p3sam_mask_kpp_type_downstream.csv")
|
| 529 |
+
if args.p3sam_kpp_csv is not None and args.p3sam_kpp_csv.exists():
|
| 530 |
+
p3sam_kpp_rows = read_csv(args.p3sam_kpp_csv)
|
| 531 |
+
elif args.run_p3sam_kpp:
|
| 532 |
+
if args.device == "cuda":
|
| 533 |
+
device = torch.device("cuda")
|
| 534 |
+
elif args.device == "cpu":
|
| 535 |
+
device = torch.device("cpu")
|
| 536 |
+
else:
|
| 537 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 538 |
+
p3sam_kpp_rows = run_p3sam_kpp(
|
| 539 |
+
manifest_cases=manifest_cases,
|
| 540 |
+
p3sam_manifest_csv=args.p3sam_manifest_csv,
|
| 541 |
+
p3sam_metrics_csv=args.p3sam_metrics_csv,
|
| 542 |
+
kpp_checkpoint=args.kpp_checkpoint,
|
| 543 |
+
output_csv=p3sam_kpp_csv,
|
| 544 |
+
device=device,
|
| 545 |
+
num_points=args.num_points,
|
| 546 |
+
max_cases=args.max_cases,
|
| 547 |
+
)
|
| 548 |
+
|
| 549 |
+
gpt_downstream_rows = gpt_replace_type_downstream(provided_rows, gpt_rows)
|
| 550 |
+
def mask_row(label: str, rows: Optional[List[Dict[str, str]]]) -> Optional[Dict[str, object]]:
|
| 551 |
+
if rows is None:
|
| 552 |
+
return None
|
| 553 |
+
row = {
|
| 554 |
+
"Component": label,
|
| 555 |
+
"Input": "mesh + user drag + P3-SAM proposals" if "manifest_drag" in str(rows[0].get("prompt_mode", "")) else "mesh + drag + P3-SAM proposals",
|
| 556 |
+
"Metric": "mIoU / Success@0.5",
|
| 557 |
+
"Result": f"{fmt_float(aggregate_mask(rows)['miou'], 3)} / {fmt_ratio(int(aggregate_mask(rows)['success_at_0p5']), int(aggregate_mask(rows)['n']))}",
|
| 558 |
+
"Failure mode": "over-segmentation / missing movable part after cleanup",
|
| 559 |
+
}
|
| 560 |
+
return row
|
| 561 |
+
|
| 562 |
+
table_a: List[Dict[str, object]] = []
|
| 563 |
+
if raw_mask_rows is not None:
|
| 564 |
+
table_a.append({
|
| 565 |
+
"Component": "Raw non-oracle P3-SAM",
|
| 566 |
+
"Input": "user drag + proposal selection",
|
| 567 |
+
"Metric": "mIoU / Success@0.5",
|
| 568 |
+
"Result": f"{fmt_float(aggregate_mask(raw_mask_rows)['miou'], 3)} / {fmt_ratio(int(aggregate_mask(raw_mask_rows)['success_at_0p5']), int(aggregate_mask(raw_mask_rows)['n']))}",
|
| 569 |
+
"Failure mode": "proposal mismatch / coordinate bridge failure",
|
| 570 |
+
})
|
| 571 |
+
if fixed_mask_rows is not None:
|
| 572 |
+
table_a.append({
|
| 573 |
+
"Component": "Fixed drag-aware cleanup",
|
| 574 |
+
"Input": "user drag + proposal selection",
|
| 575 |
+
"Metric": "mIoU / Success@0.5",
|
| 576 |
+
"Result": f"{fmt_float(aggregate_mask(fixed_mask_rows)['miou'], 3)} / {fmt_ratio(int(aggregate_mask(fixed_mask_rows)['success_at_0p5']), int(aggregate_mask(fixed_mask_rows)['n']))}",
|
| 577 |
+
"Failure mode": "over-segmentation / missing movable part after cleanup",
|
| 578 |
+
})
|
| 579 |
+
if category_mask_rows is not None:
|
| 580 |
+
table_a.append({
|
| 581 |
+
"Component": "Category-adaptive drag-aware cleanup",
|
| 582 |
+
"Input": "user drag + proposal selection",
|
| 583 |
+
"Metric": "mIoU / Success@0.5",
|
| 584 |
+
"Result": f"{fmt_float(aggregate_mask(category_mask_rows)['miou'], 3)} / {fmt_ratio(int(aggregate_mask(category_mask_rows)['success_at_0p5']), int(aggregate_mask(category_mask_rows)['n']))}",
|
| 585 |
+
"Failure mode": "category mismatch / insufficient cleanup",
|
| 586 |
+
})
|
| 587 |
+
if oracle_mask_rows is not None:
|
| 588 |
+
table_a.append({
|
| 589 |
+
"Component": "Oracle centroid upper bound",
|
| 590 |
+
"Input": "GT movable-part centroid",
|
| 591 |
+
"Metric": "mIoU / Success@0.5",
|
| 592 |
+
"Result": f"{fmt_float(aggregate_mask(oracle_mask_rows)['miou'], 3)} / {fmt_ratio(int(aggregate_mask(oracle_mask_rows)['success_at_0p5']), int(aggregate_mask(oracle_mask_rows)['n']))}",
|
| 593 |
+
"Failure mode": "oracle prompt; not annotation-free",
|
| 594 |
+
})
|
| 595 |
+
|
| 596 |
+
table_a.insert(
|
| 597 |
+
0,
|
| 598 |
+
{
|
| 599 |
+
"Component": "KPP joint-type head",
|
| 600 |
+
"Input": "mesh + drag",
|
| 601 |
+
"Metric": "Type Acc.",
|
| 602 |
+
"Result": aggregate_downstream(provided_rows, "tmp")["Type Acc."],
|
| 603 |
+
"Failure mode": "revolute/prismatic confusion",
|
| 604 |
+
},
|
| 605 |
+
)
|
| 606 |
+
table_a.insert(
|
| 607 |
+
1,
|
| 608 |
+
{
|
| 609 |
+
"Component": "GPT-4o joint-type prior",
|
| 610 |
+
"Input": "rendered view + prompt",
|
| 611 |
+
"Metric": "Type Acc.",
|
| 612 |
+
"Result": aggregate_downstream(gpt_rows, "tmp")["Type Acc."] if gpt_rows else "N/A (no audit log supplied)",
|
| 613 |
+
"Failure mode": "ambiguous affordance / occlusion",
|
| 614 |
+
},
|
| 615 |
+
)
|
| 616 |
+
table_a_fields = ["Component", "Input", "Metric", "Result", "Failure mode"]
|
| 617 |
+
|
| 618 |
+
table_b = [aggregate_downstream(provided_rows, "Provided mask + KPP type")]
|
| 619 |
+
if raw_mask_rows is not None:
|
| 620 |
+
gated_raw = mask_gated_downstream(provided_rows, raw_mask_rows, iou_threshold=0.5)
|
| 621 |
+
table_b.append(aggregate_downstream(gated_raw, "raw_drag_selected P3-SAM front end + KPP motion"))
|
| 622 |
+
if fixed_mask_rows is not None:
|
| 623 |
+
gated_fixed = mask_gated_downstream(provided_rows, fixed_mask_rows, iou_threshold=0.5)
|
| 624 |
+
table_b.append(aggregate_downstream(gated_fixed, "fixed_drag_cleanup P3-SAM front end + KPP motion"))
|
| 625 |
+
if category_mask_rows is not None:
|
| 626 |
+
gated_category = mask_gated_downstream(provided_rows, category_mask_rows, iou_threshold=0.5)
|
| 627 |
+
table_b.append(aggregate_downstream(gated_category, "category_adaptive_drag_cleanup P3-SAM front end + KPP motion"))
|
| 628 |
+
table_b.append(localization_drop_row(provided_rows, gated_category, "Drop due to P3-SAM localization"))
|
| 629 |
+
else:
|
| 630 |
+
gate_rows = fallback_mask_rows or []
|
| 631 |
+
if gate_rows:
|
| 632 |
+
table_b.append(
|
| 633 |
+
aggregate_downstream(
|
| 634 |
+
mask_gated_downstream(provided_rows, gate_rows, iou_threshold=0.5),
|
| 635 |
+
"P3-SAM gate + provided-mask KPP upper bound",
|
| 636 |
+
)
|
| 637 |
+
)
|
| 638 |
+
if p3sam_kpp_rows is not None and args.include_p3sam_kpp_downstream:
|
| 639 |
+
table_b.append(aggregate_downstream(p3sam_kpp_rows, "P3-SAM mask + KPP type"))
|
| 640 |
+
if gpt_downstream_rows is None:
|
| 641 |
+
table_b.append(
|
| 642 |
+
{
|
| 643 |
+
"Setting": "Provided mask + GPT-4o type",
|
| 644 |
+
"Type Acc.": "N/A",
|
| 645 |
+
"Strict": "N/A",
|
| 646 |
+
"Relaxed": "N/A",
|
| 647 |
+
"Axis-only": "N/A",
|
| 648 |
+
"Axis Err.": "N/A",
|
| 649 |
+
"Origin Err.": "N/A",
|
| 650 |
+
}
|
| 651 |
+
)
|
| 652 |
+
else:
|
| 653 |
+
table_b.append(aggregate_downstream(gpt_downstream_rows, "Provided mask + GPT-4o type"))
|
| 654 |
+
table_b_fields = ["Setting", "Type Acc.", "Strict", "Relaxed", "Axis-only", "Axis Err.", "Origin Err."]
|
| 655 |
+
|
| 656 |
+
write_csv(args.output_dir / "table_a_optional_foundation_diagnostics.csv", table_a, table_a_fields)
|
| 657 |
+
write_csv(args.output_dir / "table_b_downstream_effect.csv", table_b, table_b_fields)
|
| 658 |
+
(args.output_dir / "table_a_optional_foundation_diagnostics.tex").write_text(
|
| 659 |
+
table_to_latex(table_a, table_a_fields, "Optional foundation-model diagnostics on GAP-25.", "tab:optional_foundation_diagnostics")
|
| 660 |
+
)
|
| 661 |
+
(args.output_dir / "table_b_downstream_effect.tex").write_text(
|
| 662 |
+
table_to_latex(table_b, table_b_fields, "Downstream effect of automatic components on GAP-25.", "tab:automatic_component_downstream")
|
| 663 |
+
)
|
| 664 |
+
report_lines = [
|
| 665 |
+
"# Reviewer Q4 Diagnostic Tables",
|
| 666 |
+
"",
|
| 667 |
+
"## Table A: Optional foundation-model diagnostics on GAP-25",
|
| 668 |
+
"",
|
| 669 |
+
table_to_markdown(table_a, table_a_fields),
|
| 670 |
+
"",
|
| 671 |
+
"## Table B: Downstream effect of automatic components",
|
| 672 |
+
"",
|
| 673 |
+
table_to_markdown(table_b, table_b_fields),
|
| 674 |
+
"",
|
| 675 |
+
"Note: GPT-4o rows are only filled when `--gpt_type_csv` is supplied. The P3-SAM rows are localization-gated diagnostics: KPP predictions are kept fixed to the provided-mask setting to isolate the effect of target-part localization.",
|
| 676 |
+
]
|
| 677 |
+
(args.output_dir / "reviewer_q4_diagnostic_tables.md").write_text("\n".join(report_lines))
|
| 678 |
+
print(f"Wrote {args.output_dir / 'reviewer_q4_diagnostic_tables.md'}")
|
| 679 |
+
print(table_to_markdown(table_a, table_a_fields))
|
| 680 |
+
print()
|
| 681 |
+
print(table_to_markdown(table_b, table_b_fields))
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
if __name__ == "__main__":
|
| 685 |
+
main()
|
DragMesh/scripts/train/__init__.py
ADDED
|
File without changes
|
DragMesh/scripts/train/train_predictor.py
ADDED
|
@@ -0,0 +1,540 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -------------------------------------------------------------------
|
| 2 |
+
# train_predictor.py
|
| 3 |
+
# -------------------------------------------------------------------
|
| 4 |
+
|
| 5 |
+
import sys
|
| 6 |
+
import os
|
| 7 |
+
import torch
|
| 8 |
+
import argparse
|
| 9 |
+
from tqdm import tqdm
|
| 10 |
+
import json
|
| 11 |
+
from torch.utils.data import DataLoader, WeightedRandomSampler
|
| 12 |
+
import torch.optim.lr_scheduler as lr_scheduler
|
| 13 |
+
import torch.nn.functional as F
|
| 14 |
+
import math
|
| 15 |
+
|
| 16 |
+
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')))
|
| 17 |
+
chamfer_lib_path = os.path.join(os.path.dirname(__file__), '..', '..', 'ChamferDistancePytorch')
|
| 18 |
+
sys.path.insert(0, chamfer_lib_path)
|
| 19 |
+
|
| 20 |
+
from dragmesh.data.balanced_dataset_utils import VAE_LMDBDataset, get_motion_type_weights
|
| 21 |
+
from dragmesh.utils.logger import create_logger
|
| 22 |
+
from dragmesh.utils.kpp_normalization import KPP_ORIGIN_NORMALIZATION
|
| 23 |
+
|
| 24 |
+
from dragmesh.models.predictor import KeypointPredictor
|
| 25 |
+
from dragmesh.models.predictor_loss import compute_predictor_loss, geodesic_loss_report
|
| 26 |
+
|
| 27 |
+
try:
|
| 28 |
+
from dragmesh.models.model_v2 import count_parameters
|
| 29 |
+
except ImportError:
|
| 30 |
+
print("Warning: 'count_parameters' not found in 'dragmesh.models.model_v2'.")
|
| 31 |
+
def count_parameters(model):
|
| 32 |
+
return sum(p.numel() for p in model.parameters() if p.requires_grad)
|
| 33 |
+
|
| 34 |
+
def str2bool(v):
|
| 35 |
+
"""
|
| 36 |
+
NOTE: `argparse` with `type=bool` is error-prone (e.g., the string 'False' becomes True).
|
| 37 |
+
This helper supports common CLI boolean strings: True/False/1/0/yes/no.
|
| 38 |
+
"""
|
| 39 |
+
if isinstance(v, bool):
|
| 40 |
+
return v
|
| 41 |
+
if v is None:
|
| 42 |
+
return False
|
| 43 |
+
s = str(v).strip().lower()
|
| 44 |
+
if s in ("1", "true", "t", "yes", "y", "on"):
|
| 45 |
+
return True
|
| 46 |
+
if s in ("0", "false", "f", "no", "n", "off"):
|
| 47 |
+
return False
|
| 48 |
+
raise argparse.ArgumentTypeError(f"Invalid boolean value: {v}")
|
| 49 |
+
|
| 50 |
+
def _coerce_pointcloud(x: torch.Tensor) -> torch.Tensor:
|
| 51 |
+
"""
|
| 52 |
+
Handle common point-cloud layouts from different LMDB formats:
|
| 53 |
+
- [N,3] / [B,N,3]
|
| 54 |
+
- [3,N] / [B,3,N]
|
| 55 |
+
- [N,>=3] keep the first 3 channels
|
| 56 |
+
"""
|
| 57 |
+
if x is None:
|
| 58 |
+
return x
|
| 59 |
+
if x.dim() == 2:
|
| 60 |
+
# [N,C] or [C,N]
|
| 61 |
+
if x.shape[0] == 3 and x.shape[1] != 3:
|
| 62 |
+
x = x.transpose(0, 1) # [N,3]
|
| 63 |
+
if x.shape[-1] > 3:
|
| 64 |
+
x = x[:, :3]
|
| 65 |
+
return x
|
| 66 |
+
if x.dim() == 3:
|
| 67 |
+
# [B,N,C] or [B,C,N]
|
| 68 |
+
if x.shape[1] == 3 and x.shape[2] != 3:
|
| 69 |
+
x = x.transpose(1, 2) # [B,N,3]
|
| 70 |
+
if x.shape[-1] > 3:
|
| 71 |
+
x = x[:, :, :3]
|
| 72 |
+
return x
|
| 73 |
+
return x
|
| 74 |
+
|
| 75 |
+
def _get_with_aliases(batch: dict, keys: list[str]):
|
| 76 |
+
for k in keys:
|
| 77 |
+
if k in batch:
|
| 78 |
+
return batch[k]
|
| 79 |
+
return None
|
| 80 |
+
|
| 81 |
+
def _ensure_batch_fields(batch: dict, device: torch.device):
|
| 82 |
+
"""
|
| 83 |
+
Make training robust to dataset / LMDB field-name variations:
|
| 84 |
+
- initial_mesh: required; shape is coerced to [B, N, 3]
|
| 85 |
+
- drag_point/drag_vector/part_mask: default to zeros/ones if missing
|
| 86 |
+
- joint_type/axis/origin: support common aliases with dtype/shape fallbacks
|
| 87 |
+
"""
|
| 88 |
+
mesh = _get_with_aliases(batch, ["initial_mesh", "mesh", "points", "pc"])
|
| 89 |
+
if mesh is None:
|
| 90 |
+
raise KeyError("Missing required field: initial_mesh (or mesh/points/pc)")
|
| 91 |
+
mesh = _coerce_pointcloud(mesh).to(device)
|
| 92 |
+
|
| 93 |
+
# N
|
| 94 |
+
if mesh.dim() != 3:
|
| 95 |
+
raise ValueError(f"initial_mesh should be [B,N,3], got shape={tuple(mesh.shape)}")
|
| 96 |
+
B, N, _ = mesh.shape
|
| 97 |
+
|
| 98 |
+
part_mask = _get_with_aliases(batch, ["part_mask", "mask", "seg", "part_seg"])
|
| 99 |
+
if part_mask is None:
|
| 100 |
+
part_mask = torch.ones((B, N), device=device, dtype=torch.float32)
|
| 101 |
+
else:
|
| 102 |
+
if part_mask.dim() == 1:
|
| 103 |
+
part_mask = part_mask.unsqueeze(0).expand(B, -1)
|
| 104 |
+
part_mask = part_mask.to(device).float()
|
| 105 |
+
|
| 106 |
+
drag_point = _get_with_aliases(batch, ["drag_point", "drag_pt", "start_point"])
|
| 107 |
+
if drag_point is None:
|
| 108 |
+
drag_point = torch.zeros((B, 3), device=device, dtype=mesh.dtype)
|
| 109 |
+
else:
|
| 110 |
+
drag_point = drag_point.to(device).float()
|
| 111 |
+
if drag_point.dim() == 1:
|
| 112 |
+
drag_point = drag_point.unsqueeze(0)
|
| 113 |
+
|
| 114 |
+
drag_vector = _get_with_aliases(batch, ["drag_vector", "drag_vec", "direction", "drag_dir"])
|
| 115 |
+
if drag_vector is None:
|
| 116 |
+
drag_vector = torch.zeros((B, 3), device=device, dtype=mesh.dtype)
|
| 117 |
+
else:
|
| 118 |
+
drag_vector = drag_vector.to(device).float()
|
| 119 |
+
if drag_vector.dim() == 1:
|
| 120 |
+
drag_vector = drag_vector.unsqueeze(0)
|
| 121 |
+
|
| 122 |
+
gt_joint_type = _get_with_aliases(batch, ["joint_type", "gt_joint_type", "type"])
|
| 123 |
+
if gt_joint_type is None:
|
| 124 |
+
# Default to revolute.
|
| 125 |
+
gt_joint_type = torch.zeros((B,), device=device, dtype=torch.long)
|
| 126 |
+
else:
|
| 127 |
+
gt_joint_type = gt_joint_type.to(device)
|
| 128 |
+
if gt_joint_type.dim() == 0:
|
| 129 |
+
gt_joint_type = gt_joint_type.view(1)
|
| 130 |
+
if gt_joint_type.dim() == 2 and gt_joint_type.shape[-1] == 1:
|
| 131 |
+
gt_joint_type = gt_joint_type[:, 0]
|
| 132 |
+
# Accept both float and int.
|
| 133 |
+
gt_joint_type = gt_joint_type.long()
|
| 134 |
+
|
| 135 |
+
gt_joint_axis = _get_with_aliases(batch, ["joint_axis", "gt_joint_axis", "axis"])
|
| 136 |
+
if gt_joint_axis is None:
|
| 137 |
+
gt_joint_axis = torch.tensor([0.0, 0.0, 1.0], device=device).view(1, 3).expand(B, 3)
|
| 138 |
+
else:
|
| 139 |
+
gt_joint_axis = gt_joint_axis.to(device).float()
|
| 140 |
+
if gt_joint_axis.dim() == 1:
|
| 141 |
+
gt_joint_axis = gt_joint_axis.unsqueeze(0)
|
| 142 |
+
gt_joint_axis = F.normalize(gt_joint_axis, dim=-1)
|
| 143 |
+
|
| 144 |
+
gt_joint_origin = _get_with_aliases(batch, ["joint_origin", "gt_joint_origin", "origin"])
|
| 145 |
+
if gt_joint_origin is None:
|
| 146 |
+
gt_joint_origin = torch.zeros((B, 3), device=device, dtype=torch.float32)
|
| 147 |
+
else:
|
| 148 |
+
gt_joint_origin = gt_joint_origin.to(device).float()
|
| 149 |
+
if gt_joint_origin.dim() == 1:
|
| 150 |
+
gt_joint_origin = gt_joint_origin.unsqueeze(0)
|
| 151 |
+
|
| 152 |
+
return mesh, part_mask, drag_point, drag_vector, gt_joint_type, gt_joint_axis, gt_joint_origin
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def custom_collate_fn(batch):
|
| 156 |
+
|
| 157 |
+
batch = [b for b in batch if b is not None]
|
| 158 |
+
if not batch:
|
| 159 |
+
return None
|
| 160 |
+
|
| 161 |
+
return torch.utils.data.dataloader.default_collate(batch)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def warn_if_old_origin_lmdb(dataset, name: str):
|
| 165 |
+
"""Detect LMDBs built with the old joint-origin-centered KPP labels."""
|
| 166 |
+
checked = 0
|
| 167 |
+
zero_origin = 0
|
| 168 |
+
missing_version = 0
|
| 169 |
+
for idx in range(min(len(dataset), 32)):
|
| 170 |
+
sample = dataset[idx]
|
| 171 |
+
if sample is None:
|
| 172 |
+
continue
|
| 173 |
+
checked += 1
|
| 174 |
+
if "origin_normalization_version" not in sample:
|
| 175 |
+
missing_version += 1
|
| 176 |
+
origin = sample.get("joint_origin")
|
| 177 |
+
if origin is not None and torch.max(torch.abs(origin.float())).item() < 1e-6:
|
| 178 |
+
zero_origin += 1
|
| 179 |
+
if checked and (missing_version == checked or zero_origin == checked):
|
| 180 |
+
print(
|
| 181 |
+
f"[WARN] {name} LMDB looks like it was built with old KPP origin labels "
|
| 182 |
+
"(joint-origin-centered, target always near zero). Rebuild LMDB with "
|
| 183 |
+
"scripts/data/build_lmdb.py before retraining KPP origin prediction."
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def train_epoch(model, dataloader, optimizer, device,
|
| 188 |
+
type_weight, axis_weight,
|
| 189 |
+
origin_weight, origin_l1_beta,
|
| 190 |
+
epoch):
|
| 191 |
+
model.train()
|
| 192 |
+
|
| 193 |
+
losses = {'total': 0, 'type': 0, 'axis': 0, 'origin': 0}
|
| 194 |
+
num_batches = 0
|
| 195 |
+
|
| 196 |
+
pbar = tqdm(dataloader, desc=f"Training Epoch {epoch+1}")
|
| 197 |
+
for batch in pbar:
|
| 198 |
+
if batch is None:
|
| 199 |
+
continue
|
| 200 |
+
try:
|
| 201 |
+
mesh, part_mask, drag_point, drag_vector, gt_joint_type, gt_joint_axis, gt_joint_origin = _ensure_batch_fields(batch, device=device)
|
| 202 |
+
except Exception as e:
|
| 203 |
+
# Skip malformed samples to avoid interrupting long runs.
|
| 204 |
+
pbar.set_postfix({'skip': type(e).__name__})
|
| 205 |
+
continue
|
| 206 |
+
|
| 207 |
+
pred_type_logits, pred_axis, pred_origin = model(
|
| 208 |
+
mesh, part_mask, drag_point, drag_vector
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
loss_dict = compute_predictor_loss(
|
| 212 |
+
pred_type_logits, pred_axis, pred_origin,
|
| 213 |
+
gt_type=gt_joint_type, gt_axis=gt_joint_axis, gt_origin=gt_joint_origin,
|
| 214 |
+
type_weight=type_weight,
|
| 215 |
+
axis_weight=axis_weight,
|
| 216 |
+
origin_weight=origin_weight,
|
| 217 |
+
origin_l1_beta=origin_l1_beta
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
optimizer.zero_grad()
|
| 221 |
+
loss_dict['total_loss'].backward()
|
| 222 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=5.0)
|
| 223 |
+
optimizer.step()
|
| 224 |
+
|
| 225 |
+
losses['total'] += loss_dict['total_loss'].item()
|
| 226 |
+
losses['type'] += loss_dict['type_loss'].item()
|
| 227 |
+
losses['axis'] += loss_dict['axis_loss'].item()
|
| 228 |
+
# 'origin_loss' -> SmoothL1
|
| 229 |
+
losses['origin'] += loss_dict['origin_loss'].item()
|
| 230 |
+
num_batches += 1
|
| 231 |
+
|
| 232 |
+
pbar.set_postfix({
|
| 233 |
+
'loss': f'{loss_dict["total_loss"].item():.4f}',
|
| 234 |
+
'axis': f'{loss_dict["axis_loss"].item():.6f}',
|
| 235 |
+
'origin(S-L1)': f'{loss_dict["origin_loss"].item():.4f}'
|
| 236 |
+
})
|
| 237 |
+
|
| 238 |
+
if num_batches == 0:
|
| 239 |
+
return {k: 0 for k in losses.keys()}
|
| 240 |
+
|
| 241 |
+
return {k: v / num_batches for k, v in losses.items()}
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def validate(model, dataloader, device,
|
| 245 |
+
type_weight, axis_weight,
|
| 246 |
+
origin_weight, origin_l1_beta, predict_type):
|
| 247 |
+
model.eval()
|
| 248 |
+
|
| 249 |
+
losses = {'total': 0, 'type': 0, 'axis': 0, 'origin': 0}
|
| 250 |
+
num_batches = 0
|
| 251 |
+
|
| 252 |
+
total_samples = 0
|
| 253 |
+
correct_type = 0
|
| 254 |
+
|
| 255 |
+
axis_errors_sum = 0.0 # mrad
|
| 256 |
+
origin_errors_sum = 0.0 # mm
|
| 257 |
+
|
| 258 |
+
with torch.no_grad():
|
| 259 |
+
for batch in tqdm(dataloader, desc="Validation"):
|
| 260 |
+
if batch is None:
|
| 261 |
+
continue
|
| 262 |
+
try:
|
| 263 |
+
mesh, part_mask, drag_point, drag_vector, gt_joint_type, gt_joint_axis, gt_joint_origin = _ensure_batch_fields(batch, device=device)
|
| 264 |
+
except Exception:
|
| 265 |
+
continue
|
| 266 |
+
|
| 267 |
+
pred_type_logits, pred_axis, pred_origin = model(
|
| 268 |
+
mesh, part_mask, drag_point, drag_vector
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
# Loss ( SmoothL1 )
|
| 272 |
+
loss_dict = compute_predictor_loss(
|
| 273 |
+
pred_type_logits, pred_axis, pred_origin,
|
| 274 |
+
gt_type=gt_joint_type, gt_axis=gt_joint_axis, gt_origin=gt_joint_origin,
|
| 275 |
+
type_weight=type_weight,
|
| 276 |
+
axis_weight=axis_weight,
|
| 277 |
+
origin_weight=origin_weight,
|
| 278 |
+
origin_l1_beta=origin_l1_beta
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
losses['total'] += loss_dict['total_loss'].item()
|
| 282 |
+
losses['type'] += loss_dict['type_loss'].item()
|
| 283 |
+
losses['axis'] += loss_dict['axis_loss'].item()
|
| 284 |
+
losses['origin'] += loss_dict['origin_loss'].item()
|
| 285 |
+
|
| 286 |
+
num_batches += 1
|
| 287 |
+
batch_size = gt_joint_type.size(0)
|
| 288 |
+
total_samples += batch_size
|
| 289 |
+
|
| 290 |
+
# Type Acc
|
| 291 |
+
if predict_type and pred_type_logits is not None:
|
| 292 |
+
pred_type = pred_type_logits.argmax(dim=1)
|
| 293 |
+
correct_type += (pred_type == gt_joint_type).sum().item()
|
| 294 |
+
# else skip
|
| 295 |
+
|
| 296 |
+
# Axis Error (mrad)
|
| 297 |
+
angle_rad_per_sample = geodesic_loss_report(pred_axis, gt_joint_axis)
|
| 298 |
+
angle_mrad_per_sample = angle_rad_per_sample * 1000.0
|
| 299 |
+
axis_errors_sum += angle_mrad_per_sample.sum().item()
|
| 300 |
+
|
| 301 |
+
# Origin Error (mm)
|
| 302 |
+
origin_l1_per_sample = F.l1_loss(pred_origin, gt_joint_origin, reduction='none').mean(dim=1)
|
| 303 |
+
origin_mm_per_sample = (origin_l1_per_sample * 1000)
|
| 304 |
+
origin_errors_sum += origin_mm_per_sample.sum().item()
|
| 305 |
+
|
| 306 |
+
if num_batches == 0:
|
| 307 |
+
return {k: 0 for k in losses.keys()}
|
| 308 |
+
|
| 309 |
+
avg_losses = {k: v / num_batches for k, v in losses.items()}
|
| 310 |
+
|
| 311 |
+
type_acc = (correct_type / total_samples) * 100 if total_samples > 0 and predict_type else -1 # or 0
|
| 312 |
+
avg_axis_error = axis_errors_sum / total_samples if total_samples > 0 else 0
|
| 313 |
+
avg_origin_error = origin_errors_sum / total_samples if total_samples > 0 else 0
|
| 314 |
+
|
| 315 |
+
avg_losses['type_acc'] = type_acc
|
| 316 |
+
avg_losses['axis_error_mrad'] = avg_axis_error
|
| 317 |
+
avg_losses['origin_error_mm'] = avg_origin_error
|
| 318 |
+
|
| 319 |
+
return avg_losses
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def main(args):
|
| 323 |
+
print("\n" + "="*70)
|
| 324 |
+
print("Training KPP (Keypoint Predictor) Model - V-Opt-5 (Loss Tuning)")
|
| 325 |
+
print(" V-Opt-3 (Decoupled Heads)")
|
| 326 |
+
print(" Smooth L1 Loss")
|
| 327 |
+
print(" Beta={:.4f} (10mm)".format(args.origin_l1_beta))
|
| 328 |
+
print("="*70)
|
| 329 |
+
|
| 330 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 331 |
+
print(f"Using device: {device}")
|
| 332 |
+
|
| 333 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 334 |
+
|
| 335 |
+
logger = create_logger(
|
| 336 |
+
output_dir=args.output_dir,
|
| 337 |
+
use_tensorboard=args.use_tensorboard,
|
| 338 |
+
use_wandb=args.use_wandb,
|
| 339 |
+
wandb_project=args.wandb_project if args.use_wandb else None,
|
| 340 |
+
wandb_config=vars(args) if args.use_wandb else None
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
with open(os.path.join(args.output_dir, 'config_predictor_kpp.json'), 'w') as f:
|
| 344 |
+
json.dump(vars(args), f, indent=2)
|
| 345 |
+
|
| 346 |
+
print(f"\nLoading datasets...")
|
| 347 |
+
train_dataset = VAE_LMDBDataset(lmdb_path=args.lmdb_train_path, augment=False)
|
| 348 |
+
val_dataset = VAE_LMDBDataset(lmdb_path=args.lmdb_val_path, augment=False)
|
| 349 |
+
if args.origin_normalization != KPP_ORIGIN_NORMALIZATION:
|
| 350 |
+
raise ValueError(
|
| 351 |
+
f"Unsupported origin_normalization={args.origin_normalization!r}; "
|
| 352 |
+
f"expected {KPP_ORIGIN_NORMALIZATION!r}"
|
| 353 |
+
)
|
| 354 |
+
warn_if_old_origin_lmdb(train_dataset, "train")
|
| 355 |
+
warn_if_old_origin_lmdb(val_dataset, "val")
|
| 356 |
+
|
| 357 |
+
print(f" Training: {len(train_dataset)} samples")
|
| 358 |
+
print(f" Validation: {len(val_dataset)} samples")
|
| 359 |
+
|
| 360 |
+
train_loader = DataLoader(
|
| 361 |
+
train_dataset, batch_size=args.batch_size, shuffle=True,
|
| 362 |
+
num_workers=args.num_workers, collate_fn=custom_collate_fn,
|
| 363 |
+
drop_last=False, pin_memory=args.pin_memory
|
| 364 |
+
)
|
| 365 |
+
val_loader = DataLoader(
|
| 366 |
+
val_dataset, batch_size=args.batch_size, shuffle=False,
|
| 367 |
+
num_workers=args.num_workers, pin_memory=args.pin_memory, collate_fn=custom_collate_fn
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
print("\nCreating model...")
|
| 371 |
+
model = KeypointPredictor(
|
| 372 |
+
use_mask=args.use_mask,
|
| 373 |
+
use_drag=args.use_drag,
|
| 374 |
+
encoder_type=args.encoder_type,
|
| 375 |
+
head_type=args.head_type,
|
| 376 |
+
predict_type=args.predict_type
|
| 377 |
+
).to(device)
|
| 378 |
+
|
| 379 |
+
total_params = count_parameters(model)
|
| 380 |
+
print(f"Parameters: {total_params:,} (~{total_params/1e6:.2f}M)")
|
| 381 |
+
|
| 382 |
+
optimizer = torch.optim.AdamW(
|
| 383 |
+
model.parameters(),
|
| 384 |
+
lr=args.learning_rate,
|
| 385 |
+
weight_decay=args.weight_decay
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
scheduler = lr_scheduler.ReduceLROnPlateau(
|
| 389 |
+
optimizer, mode='min', factor=0.5, patience=args.lr_patience, min_lr=1e-7, verbose=True
|
| 390 |
+
)
|
| 391 |
+
|
| 392 |
+
start_epoch = 0
|
| 393 |
+
best_val_metric = float('inf')
|
| 394 |
+
|
| 395 |
+
# --- Resume ---
|
| 396 |
+
if args.resume and os.path.isfile(args.resume):
|
| 397 |
+
print(f"\nLoading checkpoint: {args.resume}")
|
| 398 |
+
checkpoint = torch.load(args.resume, map_location=device)
|
| 399 |
+
try:
|
| 400 |
+
model.load_state_dict(checkpoint['model_state_dict'], strict=True)
|
| 401 |
+
print(" Model loaded (strict=True)")
|
| 402 |
+
except Exception as e:
|
| 403 |
+
print(f" Model load error: {e}, attempting strict=False")
|
| 404 |
+
model.load_state_dict(checkpoint['model_state_dict'], strict=False)
|
| 405 |
+
|
| 406 |
+
if 'optimizer_state_dict' in checkpoint:
|
| 407 |
+
optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
|
| 408 |
+
if 'scheduler_state_dict' in checkpoint:
|
| 409 |
+
scheduler.load_state_dict(checkpoint['scheduler_state_dict'])
|
| 410 |
+
start_epoch = checkpoint.get('epoch', 0)
|
| 411 |
+
best_val_metric = checkpoint.get('val_origin_error_mm', float('inf'))
|
| 412 |
+
print(f" Resumed from epoch {start_epoch}, Best Origin Error: {best_val_metric:.3f} mm")
|
| 413 |
+
else:
|
| 414 |
+
print(" Starting training from scratch.")
|
| 415 |
+
|
| 416 |
+
print("\n" + "="*70)
|
| 417 |
+
print("Loss Weights (V-Opt-5):")
|
| 418 |
+
print(f" Type (CE):{args.type_weight:.2f}")
|
| 419 |
+
print(f" Origin (SL1): {args.origin_weight:.2f} (beta={args.origin_l1_beta:.4f})")
|
| 420 |
+
print(f" Axis (Geo): {args.axis_weight:.2f}")
|
| 421 |
+
print("="*70)
|
| 422 |
+
|
| 423 |
+
print(f"\nStarting training (epochs {start_epoch+1}-{args.num_epochs})...\n")
|
| 424 |
+
|
| 425 |
+
for epoch in range(start_epoch, args.num_epochs):
|
| 426 |
+
print(f"\n{'='*70}")
|
| 427 |
+
print(f"Epoch {epoch+1}/{args.num_epochs} | LR: {optimizer.param_groups[0]['lr']:.2e}")
|
| 428 |
+
print(f"{'='*70}")
|
| 429 |
+
|
| 430 |
+
train_losses = train_epoch(
|
| 431 |
+
model, train_loader, optimizer, device,
|
| 432 |
+
type_weight=args.type_weight,
|
| 433 |
+
axis_weight=args.axis_weight,
|
| 434 |
+
origin_weight=args.origin_weight,
|
| 435 |
+
origin_l1_beta=args.origin_l1_beta,
|
| 436 |
+
epoch=epoch
|
| 437 |
+
)
|
| 438 |
+
|
| 439 |
+
val_losses = validate(
|
| 440 |
+
model, val_loader, device,
|
| 441 |
+
type_weight=args.type_weight,
|
| 442 |
+
axis_weight=args.axis_weight,
|
| 443 |
+
origin_weight=args.origin_weight,
|
| 444 |
+
origin_l1_beta=args.origin_l1_beta,
|
| 445 |
+
predict_type=args.predict_type
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
scheduler.step(val_losses['origin_error_mm'])
|
| 449 |
+
|
| 450 |
+
print(f"\nEpoch {epoch + 1} Summary:")
|
| 451 |
+
print(f" Train - Total: {train_losses['total']:.4f} | Origin(SL1): {train_losses['origin']:.4f}")
|
| 452 |
+
print(f" Val - Total: {val_losses['total']:.4f} | Origin(SL1): {val_losses['origin']:.4f}")
|
| 453 |
+
print(f" Val Metrics - Type Acc: {val_losses['type_acc']:.2f}% | Axis Error: {val_losses['axis_error_mrad']:.3f} mrad | Origin Error: {val_losses['origin_error_mm']:.3f} mm")
|
| 454 |
+
|
| 455 |
+
logger.log_metrics({
|
| 456 |
+
'total_loss': train_losses['total'], 'type_loss': train_losses['type'],
|
| 457 |
+
'axis_loss': train_losses['axis'], 'origin_loss_smoothl1': train_losses['origin'],
|
| 458 |
+
'lr': optimizer.param_groups[0]['lr']
|
| 459 |
+
}, step=epoch + 1, prefix='train/')
|
| 460 |
+
|
| 461 |
+
logger.log_metrics({
|
| 462 |
+
'total_loss': val_losses['total'], 'type_loss': val_losses['type'],
|
| 463 |
+
'axis_loss': val_losses['axis'], 'origin_loss_smoothl1': val_losses['origin'],
|
| 464 |
+
'type_acc': val_losses['type_acc'],
|
| 465 |
+
'axis_error_mrad': val_losses['axis_error_mrad'],
|
| 466 |
+
'origin_error_mm': val_losses['origin_error_mm']
|
| 467 |
+
}, step=epoch + 1, prefix='val/')
|
| 468 |
+
|
| 469 |
+
current_val_metric = val_losses['origin_error_mm']
|
| 470 |
+
|
| 471 |
+
if current_val_metric < best_val_metric:
|
| 472 |
+
best_val_metric = current_val_metric
|
| 473 |
+
torch.save({
|
| 474 |
+
'epoch': epoch + 1, 'model_state_dict': model.state_dict(),
|
| 475 |
+
'optimizer_state_dict': optimizer.state_dict(), 'scheduler_state_dict': scheduler.state_dict(),
|
| 476 |
+
'val_origin_error_mm': best_val_metric, 'config': vars(args)
|
| 477 |
+
}, os.path.join(args.output_dir, 'best_model_kpp.pth'))
|
| 478 |
+
print(f" Saved best model (Origin Error: {best_val_metric:.3f} mm)")
|
| 479 |
+
|
| 480 |
+
if (epoch + 1) % args.save_every == 0:
|
| 481 |
+
torch.save({
|
| 482 |
+
'epoch': epoch + 1, 'model_state_dict': model.state_dict(),
|
| 483 |
+
'optimizer_state_dict': optimizer.state_dict(), 'scheduler_state_dict': scheduler.state_dict(),
|
| 484 |
+
'val_origin_error_mm': current_val_metric, 'config': vars(args)
|
| 485 |
+
}, os.path.join(args.output_dir, f'checkpoint_kpp_epoch_{epoch+1}.pth'))
|
| 486 |
+
print(f" Saved checkpoint")
|
| 487 |
+
|
| 488 |
+
logger.close()
|
| 489 |
+
|
| 490 |
+
print("\n" + "="*70)
|
| 491 |
+
print(" KPP training complete!")
|
| 492 |
+
print(f"Best val origin error: {best_val_metric:.3f} mm")
|
| 493 |
+
print(f"Saved to: {args.output_dir}")
|
| 494 |
+
print("="*70)
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
if __name__ == "__main__":
|
| 498 |
+
parser = argparse.ArgumentParser(description="Train KPP (Keypoint Predictor)")
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
parser.add_argument('--lmdb_train_path', default='data/dragmesh_train.lmdb')
|
| 502 |
+
parser.add_argument('--lmdb_val_path', default='data/dragmesh_val.lmdb')
|
| 503 |
+
parser.add_argument('--data_split_json_path', type=str, default='configs/category_split_v2.json')
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
parser.add_argument('--batch_size', type=int, default=32)
|
| 507 |
+
parser.add_argument('--num_epochs', type=int, default=200)
|
| 508 |
+
parser.add_argument('--learning_rate', type=float, default=3e-5)
|
| 509 |
+
parser.add_argument('--weight_decay', type=float, default=1e-4)
|
| 510 |
+
parser.add_argument('--lr_patience', type=int, default=15)
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
parser.add_argument('--type_weight', type=float, default=10.0)
|
| 514 |
+
parser.add_argument('--axis_weight', type=float, default=300.0)
|
| 515 |
+
parser.add_argument('--origin_weight', type=float, default=500.0)
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
parser.add_argument('--origin_l1_beta', type=float, default=0.005)
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
parser.add_argument('--use_mask', type=str2bool, default=True)
|
| 522 |
+
parser.add_argument('--use_drag', type=str2bool, default=True)
|
| 523 |
+
|
| 524 |
+
# Ablation parameters
|
| 525 |
+
parser.add_argument('--encoder_type', type=str, default='attention', choices=['pointnet', 'attention'])
|
| 526 |
+
parser.add_argument('--head_type', type=str, default='decoupled', choices=['coupled', 'decoupled'])
|
| 527 |
+
parser.add_argument('--predict_type', type=str2bool, default=True)
|
| 528 |
+
parser.add_argument('--origin_normalization', type=str, default=KPP_ORIGIN_NORMALIZATION)
|
| 529 |
+
|
| 530 |
+
parser.add_argument('--use_tensorboard', type=str2bool, default=True)
|
| 531 |
+
parser.add_argument('--use_wandb', type=str2bool, default=False)
|
| 532 |
+
parser.add_argument('--wandb_project', type=str, default='kpp_ablation')
|
| 533 |
+
parser.add_argument('--num_workers', type=int, default=4)
|
| 534 |
+
parser.add_argument('--pin_memory', type=str2bool, default=False)
|
| 535 |
+
parser.add_argument('--output_dir', type=str, default='outputs/kpp')
|
| 536 |
+
parser.add_argument('--save_every', type=int, default=50)
|
| 537 |
+
parser.add_argument('--resume', type=str, default='')
|
| 538 |
+
|
| 539 |
+
args = parser.parse_args()
|
| 540 |
+
main(args)
|
DragMesh/scripts/train/train_vae_v2.py
ADDED
|
@@ -0,0 +1,496 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -------------------------------------------------------------------
|
| 2 |
+
# train.py
|
| 3 |
+
# -------------------------------------------------------------------
|
| 4 |
+
|
| 5 |
+
import sys
|
| 6 |
+
import os
|
| 7 |
+
import torch
|
| 8 |
+
import argparse
|
| 9 |
+
from tqdm import tqdm
|
| 10 |
+
import json
|
| 11 |
+
from torch.utils.data import DataLoader, WeightedRandomSampler
|
| 12 |
+
import torch.optim.lr_scheduler as lr_scheduler
|
| 13 |
+
import torch.nn.functional as F
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')))
|
| 17 |
+
chamfer_lib_path = os.path.join(os.path.dirname(__file__), '..', '..', 'ChamferDistancePytorch')
|
| 18 |
+
sys.path.insert(0, chamfer_lib_path)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
from dragmesh.data.balanced_dataset_utils import VAE_LMDBDataset, get_motion_type_weights
|
| 22 |
+
from dragmesh.utils.logger import create_logger
|
| 23 |
+
from dragmesh.models.loss import enhanced_dualquat_vae_loss
|
| 24 |
+
from dragmesh.models.model_v2 import DualQuaternionVAE, count_parameters
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def custom_collate_fn(batch):
|
| 28 |
+
batch = [b for b in batch if b is not None]
|
| 29 |
+
if not batch:
|
| 30 |
+
return None
|
| 31 |
+
return torch.utils.data.dataloader.default_collate(batch)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def train_epoch(model, dataloader, optimizer, device,
|
| 35 |
+
kl_weight, cd_weight, mesh_recon_weight, quat_recon_weight,
|
| 36 |
+
constraint_weight, qd_zero_weight, qr_identity_weight,
|
| 37 |
+
direction_weight, free_bits, epoch):
|
| 38 |
+
|
| 39 |
+
model.train()
|
| 40 |
+
|
| 41 |
+
# Initialize loss meters (including direction loss 'dir').
|
| 42 |
+
losses = {
|
| 43 |
+
'total': 0, 'mesh_recon': 0, 'quat_recon': 0, 'recon': 0,
|
| 44 |
+
'cd': 0, 'constraint': 0, 'qd_zero': 0, 'qr_identity': 0,
|
| 45 |
+
'static': 0, 'hinge': 0, 'kl': 0, 'dir': 0
|
| 46 |
+
}
|
| 47 |
+
num_batches = 0
|
| 48 |
+
|
| 49 |
+
pbar = tqdm(dataloader, desc=f"Training Epoch {epoch+1}")
|
| 50 |
+
for batch in pbar:
|
| 51 |
+
if batch is None:
|
| 52 |
+
continue
|
| 53 |
+
|
| 54 |
+
mesh = batch['initial_mesh'].to(device)
|
| 55 |
+
drag_point = batch['drag_point'].to(device)
|
| 56 |
+
drag_vector = batch['drag_vector'].to(device)
|
| 57 |
+
qr_gt = batch['qr_gt'].to(device)
|
| 58 |
+
qd_gt = batch['qd_gt'].to(device)
|
| 59 |
+
joint_type = batch['joint_type'].to(device)
|
| 60 |
+
joint_axis = batch['joint_axis'].to(device)
|
| 61 |
+
joint_origin = batch['joint_origin'].to(device)
|
| 62 |
+
part_mask = batch['part_mask'].to(device)
|
| 63 |
+
|
| 64 |
+
# Optional fields (may be absent depending on dataset).
|
| 65 |
+
rotation_direction = batch.get('rotation_direction')
|
| 66 |
+
if rotation_direction is not None:
|
| 67 |
+
rotation_direction = rotation_direction.to(device)
|
| 68 |
+
|
| 69 |
+
trajectory_vectors = batch.get('trajectory_vectors')
|
| 70 |
+
if trajectory_vectors is not None:
|
| 71 |
+
trajectory_vectors = trajectory_vectors.to(device)
|
| 72 |
+
|
| 73 |
+
drag_trajectory = batch.get('drag_trajectory')
|
| 74 |
+
if drag_trajectory is not None:
|
| 75 |
+
drag_trajectory = drag_trajectory.to(device)
|
| 76 |
+
|
| 77 |
+
# Forward pass (model_v2.forward must accept these optional arguments).
|
| 78 |
+
pred_qr, pred_qd, mu, logvar = model(
|
| 79 |
+
mesh, drag_point, drag_vector, joint_type, joint_axis,
|
| 80 |
+
joint_origin, part_mask, rotation_direction, trajectory_vectors,
|
| 81 |
+
drag_trajectory
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
# Compute loss (including rotation direction consistency, if provided).
|
| 85 |
+
loss_dict = enhanced_dualquat_vae_loss(
|
| 86 |
+
pred_qr, pred_qd, qr_gt, qd_gt, mu, logvar,
|
| 87 |
+
joint_type=joint_type, joint_axis=joint_axis, joint_origin=joint_origin,
|
| 88 |
+
initial_mesh=mesh, part_mask=part_mask,
|
| 89 |
+
# New arguments
|
| 90 |
+
rotation_direction=rotation_direction,
|
| 91 |
+
direction_weight=direction_weight,
|
| 92 |
+
# Existing arguments
|
| 93 |
+
kl_weight=kl_weight, cd_weight=cd_weight,
|
| 94 |
+
mesh_recon_weight=mesh_recon_weight, quat_recon_weight=quat_recon_weight,
|
| 95 |
+
constraint_weight=constraint_weight, qd_zero_weight=qd_zero_weight,
|
| 96 |
+
qr_identity_weight=qr_identity_weight, free_bits=free_bits,
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
optimizer.zero_grad()
|
| 100 |
+
loss_dict['total_loss'].backward()
|
| 101 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=0.5)
|
| 102 |
+
optimizer.step()
|
| 103 |
+
|
| 104 |
+
# Accumulate losses
|
| 105 |
+
losses['total'] += loss_dict['total_loss'].item()
|
| 106 |
+
losses['mesh_recon'] += loss_dict['mesh_recon_loss'].item()
|
| 107 |
+
losses['quat_recon'] += (loss_dict['qr_recon_loss'].item() +
|
| 108 |
+
loss_dict['qd_recon_loss'].item())
|
| 109 |
+
losses['recon'] += loss_dict['recon_loss'].item()
|
| 110 |
+
losses['cd'] += loss_dict['cd_loss'].item()
|
| 111 |
+
losses['constraint'] += loss_dict['constraint_loss'].item()
|
| 112 |
+
losses['qd_zero'] += loss_dict['qd_zero_loss'].item()
|
| 113 |
+
losses['qr_identity'] += loss_dict['qr_identity_loss'].item()
|
| 114 |
+
losses['static'] += loss_dict['static_loss'].item()
|
| 115 |
+
losses['hinge'] += loss_dict['hinge_loss'].item()
|
| 116 |
+
losses['kl'] += loss_dict['kl_loss'].item()
|
| 117 |
+
losses['dir'] += loss_dict['direction_loss'].item() # new
|
| 118 |
+
|
| 119 |
+
num_batches += 1
|
| 120 |
+
|
| 121 |
+
amplitude = torch.norm(batch['drag_vector'], dim=1).mean().item()
|
| 122 |
+
pbar.set_postfix({
|
| 123 |
+
'loss': f'{loss_dict["total_loss"].item():.4f}',
|
| 124 |
+
'mesh': f'{loss_dict["mesh_recon_loss"].item():.4f}',
|
| 125 |
+
'cd': f'{loss_dict["cd_loss"].item():.4f}',
|
| 126 |
+
'dir': f'{loss_dict["direction_loss"].item():.3f}',
|
| 127 |
+
'amp': f'{amplitude:.2f}'
|
| 128 |
+
})
|
| 129 |
+
|
| 130 |
+
if num_batches == 0:
|
| 131 |
+
return {k: 0 for k in losses.keys()}
|
| 132 |
+
|
| 133 |
+
return {k: v / num_batches for k, v in losses.items()}
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def validate(model, dataloader, device,
|
| 137 |
+
kl_weight, cd_weight, mesh_recon_weight, quat_recon_weight,
|
| 138 |
+
constraint_weight, qd_zero_weight, qr_identity_weight,
|
| 139 |
+
direction_weight, free_bits):
|
| 140 |
+
model.eval()
|
| 141 |
+
|
| 142 |
+
losses = {
|
| 143 |
+
'total': 0, 'mesh_recon': 0, 'quat_recon': 0, 'recon': 0,
|
| 144 |
+
'cd': 0, 'constraint': 0, 'qd_zero': 0, 'qr_identity': 0,
|
| 145 |
+
'static': 0, 'hinge': 0, 'kl': 0, 'dir': 0
|
| 146 |
+
}
|
| 147 |
+
num_batches = 0
|
| 148 |
+
|
| 149 |
+
with torch.no_grad():
|
| 150 |
+
for batch in tqdm(dataloader, desc="Validation"):
|
| 151 |
+
if batch is None:
|
| 152 |
+
continue
|
| 153 |
+
|
| 154 |
+
mesh = batch['initial_mesh'].to(device)
|
| 155 |
+
drag_point = batch['drag_point'].to(device)
|
| 156 |
+
drag_vector = batch['drag_vector'].to(device)
|
| 157 |
+
qr_gt = batch['qr_gt'].to(device)
|
| 158 |
+
qd_gt = batch['qd_gt'].to(device)
|
| 159 |
+
joint_type = batch['joint_type'].to(device)
|
| 160 |
+
joint_axis = batch['joint_axis'].to(device)
|
| 161 |
+
joint_origin = batch['joint_origin'].to(device)
|
| 162 |
+
part_mask = batch['part_mask'].to(device)
|
| 163 |
+
|
| 164 |
+
rotation_direction = batch.get('rotation_direction')
|
| 165 |
+
if rotation_direction is not None:
|
| 166 |
+
rotation_direction = rotation_direction.to(device)
|
| 167 |
+
trajectory_vectors = batch.get('trajectory_vectors')
|
| 168 |
+
if trajectory_vectors is not None:
|
| 169 |
+
trajectory_vectors = trajectory_vectors.to(device)
|
| 170 |
+
drag_trajectory = batch.get('drag_trajectory')
|
| 171 |
+
if drag_trajectory is not None:
|
| 172 |
+
drag_trajectory = drag_trajectory.to(device)
|
| 173 |
+
|
| 174 |
+
pred_qr, pred_qd, mu, logvar = model(
|
| 175 |
+
mesh, drag_point, drag_vector, joint_type, joint_axis,
|
| 176 |
+
joint_origin, part_mask, rotation_direction, trajectory_vectors,
|
| 177 |
+
drag_trajectory
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
loss_dict = enhanced_dualquat_vae_loss(
|
| 181 |
+
pred_qr, pred_qd, qr_gt, qd_gt, mu, logvar,
|
| 182 |
+
joint_type=joint_type, joint_axis=joint_axis, joint_origin=joint_origin,
|
| 183 |
+
initial_mesh=mesh, part_mask=part_mask,
|
| 184 |
+
rotation_direction=rotation_direction,
|
| 185 |
+
direction_weight=direction_weight,
|
| 186 |
+
kl_weight=kl_weight, cd_weight=cd_weight,
|
| 187 |
+
mesh_recon_weight=mesh_recon_weight, quat_recon_weight=quat_recon_weight,
|
| 188 |
+
constraint_weight=constraint_weight, qd_zero_weight=qd_zero_weight,
|
| 189 |
+
qr_identity_weight=qr_identity_weight, free_bits=free_bits,
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
losses['total'] += loss_dict['total_loss'].item()
|
| 193 |
+
losses['mesh_recon'] += loss_dict['mesh_recon_loss'].item()
|
| 194 |
+
losses['quat_recon'] += (loss_dict['qr_recon_loss'].item() +
|
| 195 |
+
loss_dict['qd_recon_loss'].item())
|
| 196 |
+
losses['recon'] += loss_dict['recon_loss'].item()
|
| 197 |
+
losses['cd'] += loss_dict['cd_loss'].item()
|
| 198 |
+
losses['constraint'] += loss_dict['constraint_loss'].item()
|
| 199 |
+
losses['qd_zero'] += loss_dict['qd_zero_loss'].item()
|
| 200 |
+
losses['qr_identity'] += loss_dict['qr_identity_loss'].item()
|
| 201 |
+
losses['static'] += loss_dict['static_loss'].item()
|
| 202 |
+
losses['hinge'] += loss_dict['hinge_loss'].item()
|
| 203 |
+
losses['kl'] += loss_dict['kl_loss'].item()
|
| 204 |
+
losses['dir'] += loss_dict['direction_loss'].item() # new
|
| 205 |
+
num_batches += 1
|
| 206 |
+
|
| 207 |
+
if num_batches == 0:
|
| 208 |
+
return {k: 0 for k in losses.keys()}
|
| 209 |
+
|
| 210 |
+
return {k: v / num_batches for k, v in losses.items()}
|
| 211 |
+
|
| 212 |
+
def main(args):
|
| 213 |
+
print("\n" + "="*70)
|
| 214 |
+
print("Training DualQuaternionVAE")
|
| 215 |
+
print(" (KL, Recon, CD, Constraint, Direction)")
|
| 216 |
+
print(" LR ")
|
| 217 |
+
print("="*70)
|
| 218 |
+
|
| 219 |
+
if os.path.exists(args.data_split_json_path):
|
| 220 |
+
with open(args.data_split_json_path, 'r') as f:
|
| 221 |
+
split_config = json.load(f)
|
| 222 |
+
print(f"\nDataset config: {split_config.get('description', 'N/A')}")
|
| 223 |
+
|
| 224 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 225 |
+
print(f"Using device: {device}")
|
| 226 |
+
|
| 227 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 228 |
+
|
| 229 |
+
logger = create_logger(
|
| 230 |
+
output_dir=args.output_dir,
|
| 231 |
+
use_tensorboard=args.use_tensorboard,
|
| 232 |
+
use_wandb=args.use_wandb,
|
| 233 |
+
wandb_project=args.wandb_project if args.use_wandb else None,
|
| 234 |
+
wandb_config=vars(args) if args.use_wandb else None
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
with open(os.path.join(args.output_dir, 'config.json'), 'w') as f:
|
| 238 |
+
json.dump(vars(args), f, indent=2)
|
| 239 |
+
|
| 240 |
+
print(f"\nLoading datasets...")
|
| 241 |
+
train_dataset = VAE_LMDBDataset(lmdb_path=args.lmdb_train_path, augment=True)
|
| 242 |
+
val_dataset = VAE_LMDBDataset(lmdb_path=args.lmdb_val_path, augment=False)
|
| 243 |
+
|
| 244 |
+
if len(train_dataset) == 0 or len(val_dataset) == 0:
|
| 245 |
+
raise ValueError("Empty dataset!")
|
| 246 |
+
|
| 247 |
+
print(f" Training: {len(train_dataset)} samples")
|
| 248 |
+
print(f" Validation: {len(val_dataset)} samples")
|
| 249 |
+
|
| 250 |
+
if args.motion_type != 'all':
|
| 251 |
+
print(f"\nFiltering for {args.motion_type.upper()} only...")
|
| 252 |
+
target_type = 0 if args.motion_type == 'rotation' else 1
|
| 253 |
+
|
| 254 |
+
train_indices = [i for i in tqdm(range(len(train_dataset)), desc="Train")
|
| 255 |
+
if train_dataset[i] is not None and
|
| 256 |
+
train_dataset[i]['joint_type'] == target_type]
|
| 257 |
+
val_indices = [i for i in tqdm(range(len(val_dataset)), desc="Val")
|
| 258 |
+
if val_dataset[i] is not None and
|
| 259 |
+
val_dataset[i]['joint_type'] == target_type]
|
| 260 |
+
|
| 261 |
+
train_dataset = torch.utils.data.Subset(train_dataset, train_indices)
|
| 262 |
+
val_dataset = torch.utils.data.Subset(val_dataset, val_indices)
|
| 263 |
+
|
| 264 |
+
print(f" Filtered Train: {len(train_dataset)}")
|
| 265 |
+
print(f" Filtered Val: {len(val_dataset)}")
|
| 266 |
+
|
| 267 |
+
if args.motion_type == 'all':
|
| 268 |
+
print("\nComputing balanced sampling weights...")
|
| 269 |
+
train_weights = get_motion_type_weights(train_dataset,
|
| 270 |
+
target_ratio=args.motion_balance_ratio)
|
| 271 |
+
train_sampler = WeightedRandomSampler(
|
| 272 |
+
weights=train_weights,
|
| 273 |
+
num_samples=len(train_weights),
|
| 274 |
+
replacement=True
|
| 275 |
+
)
|
| 276 |
+
else:
|
| 277 |
+
train_sampler = None
|
| 278 |
+
|
| 279 |
+
train_loader = DataLoader(
|
| 280 |
+
train_dataset,
|
| 281 |
+
batch_size=args.batch_size,
|
| 282 |
+
sampler=train_sampler,
|
| 283 |
+
shuffle=(train_sampler is None),
|
| 284 |
+
num_workers=args.num_workers,
|
| 285 |
+
collate_fn=custom_collate_fn,
|
| 286 |
+
drop_last=True,
|
| 287 |
+
pin_memory=True
|
| 288 |
+
)
|
| 289 |
+
val_loader = DataLoader(
|
| 290 |
+
val_dataset,
|
| 291 |
+
batch_size=args.batch_size,
|
| 292 |
+
shuffle=False,
|
| 293 |
+
num_workers=args.num_workers,
|
| 294 |
+
pin_memory=True,
|
| 295 |
+
collate_fn=custom_collate_fn
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
print("\nCreating model...")
|
| 299 |
+
model = DualQuaternionVAE(
|
| 300 |
+
mesh_feat_dim=1024,
|
| 301 |
+
drag_feat_dim=512,
|
| 302 |
+
latent_dim=args.latent_dim,
|
| 303 |
+
num_frames=args.num_frames,
|
| 304 |
+
joint_type_embed_dim=128,
|
| 305 |
+
use_film=True,
|
| 306 |
+
transformer_dim=512,
|
| 307 |
+
transformer_layers=args.transformer_layers,
|
| 308 |
+
transformer_heads=args.transformer_heads
|
| 309 |
+
).to(device)
|
| 310 |
+
|
| 311 |
+
total_params = count_parameters(model)
|
| 312 |
+
print(f"Parameters: {total_params:,} (~{total_params/1e6:.2f}M)")
|
| 313 |
+
|
| 314 |
+
optimizer = torch.optim.AdamW(
|
| 315 |
+
model.parameters(),
|
| 316 |
+
lr=args.learning_rate,
|
| 317 |
+
weight_decay=args.weight_decay
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
scheduler = lr_scheduler.ReduceLROnPlateau(
|
| 321 |
+
optimizer, mode='min', factor=0.5, patience=args.lr_patience, min_lr=1e-7, verbose=True
|
| 322 |
+
)
|
| 323 |
+
|
| 324 |
+
start_epoch = 0
|
| 325 |
+
best_val_total_loss = float('inf')
|
| 326 |
+
|
| 327 |
+
if args.resume and os.path.isfile(args.resume):
|
| 328 |
+
print(f"\nLoading checkpoint: {args.resume}")
|
| 329 |
+
checkpoint = torch.load(args.resume, map_location=device)
|
| 330 |
+
|
| 331 |
+
try:
|
| 332 |
+
model.load_state_dict(checkpoint['model_state_dict'], strict=False)
|
| 333 |
+
print(" Model loaded")
|
| 334 |
+
except Exception as e:
|
| 335 |
+
print(f" Model load error: {e}")
|
| 336 |
+
|
| 337 |
+
if 'optimizer_state_dict' in checkpoint:
|
| 338 |
+
optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
|
| 339 |
+
if 'scheduler_state_dict' in checkpoint:
|
| 340 |
+
try:
|
| 341 |
+
scheduler.load_state_dict(checkpoint['scheduler_state_dict'])
|
| 342 |
+
except:
|
| 343 |
+
print(" Scheduler state not fully loaded. Skipping.")
|
| 344 |
+
|
| 345 |
+
start_epoch = checkpoint.get('epoch', 0)
|
| 346 |
+
best_val_total_loss = checkpoint.get('val_total_loss', checkpoint.get('val_loss', float('inf')))
|
| 347 |
+
print(f" Resumed from epoch {start_epoch}, Best Val Loss: {best_val_total_loss:.4f}")
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
print("\n" + "="*70)
|
| 351 |
+
print("Core Loss Weights:")
|
| 352 |
+
print(f" Mesh Recon: {args.mesh_recon_weight:.1f}")
|
| 353 |
+
print(f" CD: {args.cd_weight:.1f}")
|
| 354 |
+
print(f" Constraint: {args.constraint_weight:.1f}")
|
| 355 |
+
print(f" Direction: {args.direction_weight:.1f}")
|
| 356 |
+
print(f" KL: {args.kl_weight:.4f} (FreeBits: {args.free_bits:.1f})")
|
| 357 |
+
print("="*70)
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
print(f"\nStarting training (epochs {start_epoch+1}-{args.num_epochs})...\n")
|
| 361 |
+
|
| 362 |
+
train_history = []
|
| 363 |
+
val_history = []
|
| 364 |
+
|
| 365 |
+
for epoch in range(start_epoch, args.num_epochs):
|
| 366 |
+
if epoch < args.kl_anneal_epochs:
|
| 367 |
+
current_kl = args.kl_weight * (epoch + 1) / args.kl_anneal_epochs
|
| 368 |
+
else:
|
| 369 |
+
current_kl = args.kl_weight
|
| 370 |
+
|
| 371 |
+
print(f"\n{'='*70}")
|
| 372 |
+
print(f"Epoch {epoch+1}/{args.num_epochs} | LR: {optimizer.param_groups[0]['lr']:.2e} | KL: {current_kl:.4f}")
|
| 373 |
+
print(f"{'='*70}")
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
train_losses = train_epoch(
|
| 377 |
+
model, train_loader, optimizer, device,
|
| 378 |
+
kl_weight=current_kl, cd_weight=args.cd_weight, mesh_recon_weight=args.mesh_recon_weight,
|
| 379 |
+
quat_recon_weight=args.quat_recon_weight, constraint_weight=args.constraint_weight,
|
| 380 |
+
qd_zero_weight=args.qd_zero_weight, qr_identity_weight=args.qr_identity_weight,
|
| 381 |
+
direction_weight=args.direction_weight, # pass through
|
| 382 |
+
free_bits=args.free_bits, epoch=epoch
|
| 383 |
+
)
|
| 384 |
+
|
| 385 |
+
val_losses = validate(
|
| 386 |
+
model, val_loader, device,
|
| 387 |
+
kl_weight=current_kl, cd_weight=args.cd_weight, mesh_recon_weight=args.mesh_recon_weight,
|
| 388 |
+
quat_recon_weight=args.quat_recon_weight, constraint_weight=args.constraint_weight,
|
| 389 |
+
qd_zero_weight=args.qd_zero_weight, qr_identity_weight=args.qr_identity_weight,
|
| 390 |
+
direction_weight=args.direction_weight, # pass through
|
| 391 |
+
free_bits=args.free_bits
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
scheduler.step(val_losses['total'])
|
| 395 |
+
|
| 396 |
+
print(f"\nEpoch {epoch + 1} Summary:")
|
| 397 |
+
print(f" Train - Total: {train_losses['total']:.4f} | Mesh: {train_losses['mesh_recon']:.4f} | CD: {train_losses['cd']:.4f} | Dir: {train_losses['dir']:.3f} | KL: {train_losses['kl']:.2f}")
|
| 398 |
+
print(f" Val - Total: {val_losses['total']:.4f} | Mesh: {val_losses['mesh_recon']:.4f} | CD: {val_losses['cd']:.4f} | Dir: {val_losses['dir']:.3f} | KL: {val_losses['kl']:.2f}")
|
| 399 |
+
|
| 400 |
+
logger.log_metrics({
|
| 401 |
+
'total_loss': train_losses['total'], 'mesh_recon_loss': train_losses['mesh_recon'],
|
| 402 |
+
'cd_loss': train_losses['cd'], 'constraint_loss': train_losses['constraint'],
|
| 403 |
+
'dir_loss': train_losses['dir'], 'kl_loss': train_losses['kl'],
|
| 404 |
+
'lr': optimizer.param_groups[0]['lr']
|
| 405 |
+
}, step=epoch + 1, prefix='train/')
|
| 406 |
+
|
| 407 |
+
logger.log_metrics({
|
| 408 |
+
'total_loss': val_losses['total'], 'mesh_recon_loss': val_losses['mesh_recon'],
|
| 409 |
+
'cd_loss': val_losses['cd'], 'constraint_loss': val_losses['constraint'],
|
| 410 |
+
'dir_loss': val_losses['dir'], 'kl_loss': val_losses['kl']
|
| 411 |
+
}, step=epoch + 1, prefix='val/')
|
| 412 |
+
|
| 413 |
+
train_history.append({'epoch': epoch + 1, **train_losses})
|
| 414 |
+
val_history.append({'epoch': epoch + 1, **val_losses})
|
| 415 |
+
|
| 416 |
+
current_val_total_loss = val_losses['total']
|
| 417 |
+
|
| 418 |
+
if epoch >= args.kl_anneal_epochs and current_val_total_loss < best_val_total_loss:
|
| 419 |
+
best_val_total_loss = current_val_total_loss
|
| 420 |
+
torch.save({
|
| 421 |
+
'epoch': epoch + 1, 'model_state_dict': model.state_dict(),
|
| 422 |
+
'optimizer_state_dict': optimizer.state_dict(), 'scheduler_state_dict': scheduler.state_dict(),
|
| 423 |
+
'val_total_loss': best_val_total_loss, 'config': vars(args)
|
| 424 |
+
}, os.path.join(args.output_dir, 'best_model.pth'))
|
| 425 |
+
print(f" ✓ Saved best model (Total Loss: {best_val_total_loss:.4f})")
|
| 426 |
+
|
| 427 |
+
if (epoch + 1) % args.save_every == 0:
|
| 428 |
+
torch.save({
|
| 429 |
+
'epoch': epoch + 1, 'model_state_dict': model.state_dict(),
|
| 430 |
+
'optimizer_state_dict': optimizer.state_dict(), 'scheduler_state_dict': scheduler.state_dict(),
|
| 431 |
+
'val_total_loss': current_val_total_loss, 'config': vars(args)
|
| 432 |
+
}, os.path.join(args.output_dir, f'checkpoint_epoch_{epoch+1}.pth'))
|
| 433 |
+
print(f" ✓ Saved checkpoint")
|
| 434 |
+
|
| 435 |
+
torch.save({
|
| 436 |
+
'epoch': args.num_epochs, 'model_state_dict': model.state_dict(),
|
| 437 |
+
'optimizer_state_dict': optimizer.state_dict(),
|
| 438 |
+
'val_total_loss': best_val_total_loss, 'config': vars(args)
|
| 439 |
+
}, os.path.join(args.output_dir, 'final_model.pth'))
|
| 440 |
+
|
| 441 |
+
with open(os.path.join(args.output_dir, 'train_history.json'), 'w') as f:
|
| 442 |
+
json.dump(train_history, f, indent=2)
|
| 443 |
+
with open(os.path.join(args.output_dir, 'val_history.json'), 'w') as f:
|
| 444 |
+
json.dump(val_history, f, indent=2)
|
| 445 |
+
|
| 446 |
+
logger.close()
|
| 447 |
+
|
| 448 |
+
print("\n" + "="*70)
|
| 449 |
+
print(" Training complete!")
|
| 450 |
+
print(f"Best val total loss: {best_val_total_loss:.4f}")
|
| 451 |
+
print(f"Saved to: {args.output_dir}")
|
| 452 |
+
print("="*70)
|
| 453 |
+
|
| 454 |
+
if __name__ == "__main__":
|
| 455 |
+
parser = argparse.ArgumentParser(description="Train DualQuaternion VAE")
|
| 456 |
+
|
| 457 |
+
parser.add_argument('--lmdb_train_path', default='data/dragmesh_train.lmdb')
|
| 458 |
+
parser.add_argument('--lmdb_val_path', default='data/dragmesh_val.lmdb')
|
| 459 |
+
parser.add_argument('--data_split_json_path', type=str, default='configs/category_split_v2.json')
|
| 460 |
+
parser.add_argument('--motion_balance_ratio', type=float, default=3.0)
|
| 461 |
+
parser.add_argument('--num_frames', type=int, default=16)
|
| 462 |
+
parser.add_argument('--num_points', type=int, default=4096)
|
| 463 |
+
parser.add_argument('--motion_type', type=str, default='all', choices=['all', 'rotation', 'translation'])
|
| 464 |
+
|
| 465 |
+
parser.add_argument('--latent_dim', type=int, default=256)
|
| 466 |
+
parser.add_argument('--transformer_layers', type=int, default=4, help='Number of layers in the Transformer decoder')
|
| 467 |
+
parser.add_argument('--transformer_heads', type=int, default=8, help='Number of heads in the Transformer decoder')
|
| 468 |
+
|
| 469 |
+
parser.add_argument('--batch_size', type=int, default=16)
|
| 470 |
+
parser.add_argument('--num_epochs', type=int, default=300)
|
| 471 |
+
parser.add_argument('--learning_rate', type=float, default=5e-5)
|
| 472 |
+
parser.add_argument('--weight_decay', type=float, default=1e-4)
|
| 473 |
+
parser.add_argument('--lr_patience', type=int, default=15, help='Patience for ReduceLROnPlateau scheduler (epochs)')
|
| 474 |
+
|
| 475 |
+
parser.add_argument('--kl_weight', type=float, default=0.001)
|
| 476 |
+
parser.add_argument('--kl_anneal_epochs', type=int, default=80)
|
| 477 |
+
parser.add_argument('--mesh_recon_weight', type=float, default=10.0)
|
| 478 |
+
parser.add_argument('--quat_recon_weight', type=float, default=0.2)
|
| 479 |
+
parser.add_argument('--cd_weight', type=float, default=30.0)
|
| 480 |
+
parser.add_argument('--constraint_weight', type=float, default=100.0)
|
| 481 |
+
parser.add_argument('--qd_zero_weight', type=float, default=50.0)
|
| 482 |
+
parser.add_argument('--qr_identity_weight', type=float, default=10.0)
|
| 483 |
+
parser.add_argument('--free_bits', type=float, default=48.0)
|
| 484 |
+
# Direction weight (rotation direction consistency loss).
|
| 485 |
+
parser.add_argument('--direction_weight', type=float, default=5.0, help='Weight for rotation direction consistency loss')
|
| 486 |
+
|
| 487 |
+
parser.add_argument('--use_tensorboard', action='store_true', default=True)
|
| 488 |
+
parser.add_argument('--use_wandb', action='store_true', default=True)
|
| 489 |
+
parser.add_argument('--wandb_project', type=str, default='dragmesh-vae')
|
| 490 |
+
parser.add_argument('--num_workers', type=int, default=4)
|
| 491 |
+
parser.add_argument('--output_dir', type=str, default='outputs/vae')
|
| 492 |
+
parser.add_argument('--save_every', type=int, default=100)
|
| 493 |
+
parser.add_argument('--resume', type=str, default='')
|
| 494 |
+
|
| 495 |
+
args = parser.parse_args()
|
| 496 |
+
main(args)
|
DragMesh/test_data/furniture/DrawerChest/output/DrawerChest/initial_static.glb
ADDED
|
Binary file (63.3 kB). View file
|
|
|
DragMesh/test_data/furniture/DrawerChest/output/DrawerChest/predicted_z_0.glb
ADDED
|
Binary file (65.4 kB). View file
|
|
|
DragMesh/test_data/furniture/DrawerChest/output/inference.log
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/home/zhanghao/scene/DragMesh/dragmesh/inference/inference_pipeline.py:532: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.
|
| 2 |
+
checkpoint = torch.load(checkpoint_path, map_location='cpu')
|
| 3 |
+
/home/zhanghao/scene/DragMesh/dragmesh/inference/inference_pipeline.py:549: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.
|
| 4 |
+
checkpoint = torch.load(checkpoint_path, map_location='cpu')
|
| 5 |
+
IMAGEIO FFMPEG_WRITER WARNING: input image is not divisible by macro_block_size=16, resizing from (600, 600) to (608, 608) to ensure video compatibility with most codecs and players. To prevent resizing, make your input image divisible by the macro_block_size or set the macro_block_size to 1 (risking incompatibility).
|
| 6 |
+
Manual joint: type=prismatic, axis=[0.0, 0.0, 1.0], origin=[0.0, 0.0, 0.05000000074505806], drag_point=[0.0, 0.0, 0.2199999988079071], drag_vector=[0.0, 0.0, 0.15000000596046448]
|
| 7 |
+
Mesh: 1758v, 3456f
|
| 8 |
+
Moving part (label==1): 1170 vertices
|
| 9 |
+
KPP: type=1 (0=rev,1=pris), probs=[0.001 0.999]
|
| 10 |
+
KPP axis=[-0. 0.026 1. ], origin=[0.02 0.198 0.27 ]
|
| 11 |
+
Using KPP axis (|dot|=1.000 > 0.7)
|
| 12 |
+
FINAL: type=prismatic, axis=[-0.00039999998989515007, 0.025499999523162842, 0.9997000098228455], origin=[0.0204, 0.1981, 0.2701]
|
| 13 |
+
Running DQ-VAE...
|
| 14 |
+
Running model ENCODER...
|
| 15 |
+
|
| 16 |
+
Running model DECODER (1 times)...
|
| 17 |
+
--- Sample 1/1 ---
|
| 18 |
+
Generating MP4: /home/zhanghao/scene/DragMesh/test_data/furniture/DrawerChest/output/DrawerChest/predicted_z_0.mp4
|
| 19 |
+
Generating GIF: /home/zhanghao/scene/DragMesh/test_data/furniture/DrawerChest/output/DrawerChest/predicted_z_0.gif
|
| 20 |
+
Generating Animated GLB: /home/zhanghao/scene/DragMesh/test_data/furniture/DrawerChest/output/DrawerChest/predicted_z_0.glb
|
| 21 |
+
Animated GLB saved: /home/zhanghao/scene/DragMesh/test_data/furniture/DrawerChest/output/DrawerChest/predicted_z_0.glb
|
| 22 |
+
============================================================VAE Animation complete! Output saved to: /home/zhanghao/scene/DragMesh/test_data/furniture/DrawerChest/output/DrawerChest============================================================
|
| 23 |
+
results.json written
|
| 24 |
+
Done!
|
DragMesh/test_data/furniture/DrawerChest/output/results.json
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "DrawerChest",
|
| 3 |
+
"joint_type": "prismatic",
|
| 4 |
+
"manual_type": "prismatic",
|
| 5 |
+
"kpp_probs": [
|
| 6 |
+
0.0005989164928905666,
|
| 7 |
+
0.9994010925292969
|
| 8 |
+
],
|
| 9 |
+
"kpp_type_int": 1,
|
| 10 |
+
"kpp_axis": [
|
| 11 |
+
-0.00039999998989515007,
|
| 12 |
+
0.025499999523162842,
|
| 13 |
+
0.9997000098228455
|
| 14 |
+
],
|
| 15 |
+
"kpp_origin": [
|
| 16 |
+
0.0204,
|
| 17 |
+
0.1981,
|
| 18 |
+
0.2701
|
| 19 |
+
],
|
| 20 |
+
"final_axis": [
|
| 21 |
+
-0.00039999998989515007,
|
| 22 |
+
0.025499999523162842,
|
| 23 |
+
0.9997000098228455
|
| 24 |
+
],
|
| 25 |
+
"axis_dot": 0.9996740221977234,
|
| 26 |
+
"final_origin": [
|
| 27 |
+
0.0204,
|
| 28 |
+
0.1981,
|
| 29 |
+
0.2701
|
| 30 |
+
],
|
| 31 |
+
"drag_point": [
|
| 32 |
+
0.0,
|
| 33 |
+
0.0,
|
| 34 |
+
0.2199999988079071
|
| 35 |
+
],
|
| 36 |
+
"drag_vector": [
|
| 37 |
+
0.0,
|
| 38 |
+
0.0,
|
| 39 |
+
0.15000000596046448
|
| 40 |
+
],
|
| 41 |
+
"output_root": "/home/zhanghao/scene/DragMesh/test_data/furniture/DrawerChest/output"
|
| 42 |
+
}
|
DragMesh/test_data/furniture/Fridge/output/Fridge/initial_static.glb
ADDED
|
Binary file (56.3 kB). View file
|
|
|
DragMesh/test_data/furniture/Fridge/output/Fridge/predicted_z_0.glb
ADDED
|
Binary file (58.5 kB). View file
|
|
|
DragMesh/test_data/furniture/Laptop/output/Laptop/initial_static.glb
ADDED
|
Binary file (39 kB). View file
|
|
|
DragMesh/test_data/furniture/Laptop/output/Laptop/predicted_z_0.glb
ADDED
|
Binary file (41.1 kB). View file
|
|
|
DragMesh/test_data/furniture/Microwave/output/Microwave/initial_static.glb
ADDED
|
Binary file (56.4 kB). View file
|
|
|
DragMesh/test_data/furniture/Microwave/output/Microwave/predicted_z_0.glb
ADDED
|
Binary file (58.5 kB). View file
|
|
|
DragMesh/test_data/furniture/Microwave/output/Microwave/predicted_z_1.glb
ADDED
|
Binary file (58.5 kB). View file
|
|
|
DragMesh/test_data/furniture/Microwave/output/Microwave/predicted_z_2.glb
ADDED
|
Binary file (58.5 kB). View file
|
|
|
DragMesh/test_data/furniture/Microwave/output/inference_audit.json
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "Microwave",
|
| 3 |
+
"joint_type_manual": "revolute",
|
| 4 |
+
"kpp_joint_type": "prismatic",
|
| 5 |
+
"kpp_type_probs": [
|
| 6 |
+
0.00037072942359372973,
|
| 7 |
+
0.9996292591094971
|
| 8 |
+
],
|
| 9 |
+
"final_joint_type": "revolute",
|
| 10 |
+
"axis_manual": [
|
| 11 |
+
1.0,
|
| 12 |
+
0.0,
|
| 13 |
+
0.0
|
| 14 |
+
],
|
| 15 |
+
"kpp_axis": [
|
| 16 |
+
0.005359216593205929,
|
| 17 |
+
-0.0014833256136626005,
|
| 18 |
+
0.9999845623970032
|
| 19 |
+
],
|
| 20 |
+
"axis_dot_product": 0.005359216593205929,
|
| 21 |
+
"use_kpp_axis": false,
|
| 22 |
+
"joint_axis_used": [
|
| 23 |
+
1.0,
|
| 24 |
+
0.0,
|
| 25 |
+
0.0
|
| 26 |
+
],
|
| 27 |
+
"origin_manual": [
|
| 28 |
+
0.0,
|
| 29 |
+
0.15000000596046448,
|
| 30 |
+
-0.14000000059604645
|
| 31 |
+
],
|
| 32 |
+
"kpp_origin": [
|
| 33 |
+
-0.00022165775299072267,
|
| 34 |
+
0.08094824707508089,
|
| 35 |
+
-0.01655936741828918
|
| 36 |
+
],
|
| 37 |
+
"joint_origin_used": [
|
| 38 |
+
0.0,
|
| 39 |
+
0.15000000596046448,
|
| 40 |
+
-0.14000000059604645
|
| 41 |
+
],
|
| 42 |
+
"drag_point": [
|
| 43 |
+
0.0,
|
| 44 |
+
0.17000000178813934,
|
| 45 |
+
0.07999999821186066
|
| 46 |
+
],
|
| 47 |
+
"drag_vector": [
|
| 48 |
+
0.0,
|
| 49 |
+
0.0,
|
| 50 |
+
0.11999999731779099
|
| 51 |
+
],
|
| 52 |
+
"num_frames": 16
|
| 53 |
+
}
|
DragMesh/test_data/furniture/Window/output/Window/initial_static.glb
ADDED
|
Binary file (66.9 kB). View file
|
|
|
DragMesh/test_data/furniture/Window/output/Window/predicted_z_0.glb
ADDED
|
Binary file (68.9 kB). View file
|
|
|
DragMesh/test_data/furniture/Window/output/run_metadata.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "Window",
|
| 3 |
+
"manual_type": "revolute",
|
| 4 |
+
"final_type": "revolute",
|
| 5 |
+
"kpp_type": 0,
|
| 6 |
+
"kpp_probs": [
|
| 7 |
+
0.6140950918197632,
|
| 8 |
+
0.38590487837791443
|
| 9 |
+
],
|
| 10 |
+
"kpp_axis": [
|
| 11 |
+
0.03245502710342407,
|
| 12 |
+
0.804212212562561,
|
| 13 |
+
0.5934555530548096
|
| 14 |
+
],
|
| 15 |
+
"kpp_origin": [
|
| 16 |
+
0.04208301603794098,
|
| 17 |
+
0.38270399570465086,
|
| 18 |
+
0.39189958095550537
|
| 19 |
+
],
|
| 20 |
+
"axis_dot": 0.5934555471202542,
|
| 21 |
+
"axis_source": "manual",
|
| 22 |
+
"final_axis": [
|
| 23 |
+
0.0,
|
| 24 |
+
0.0,
|
| 25 |
+
0.9999999900000002
|
| 26 |
+
],
|
| 27 |
+
"final_origin": [
|
| 28 |
+
0.0,
|
| 29 |
+
-0.5,
|
| 30 |
+
0.02
|
| 31 |
+
]
|
| 32 |
+
}
|
dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00014/meshes/gt-body.ply
ADDED
|
Binary file (5.09 kB). View file
|
|
|
dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00014/meshes/gt-lefthand.ply
ADDED
|
Binary file (4.86 kB). View file
|
|
|
dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00014/meshes/gt-righthand.ply
ADDED
|
Binary file (4.88 kB). View file
|
|
|
dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00014/meshes/pred-ours-body.ply
ADDED
|
Binary file (5.11 kB). View file
|
|
|
dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00014/meshes/pred-ours-lefthand.ply
ADDED
|
Binary file (4.83 kB). View file
|
|
|
dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00014/meshes/pred-ours-righthand.ply
ADDED
|
Binary file (4.82 kB). View file
|
|
|
dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00025/meshes/gt-body.ply
ADDED
|
Binary file (5.14 kB). View file
|
|
|
dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00025/meshes/gt-lefthand.ply
ADDED
|
Binary file (4.9 kB). View file
|
|
|
dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00025/meshes/gt-righthand.ply
ADDED
|
Binary file (4.9 kB). View file
|
|
|
dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00025/meshes/pred-ours-body.ply
ADDED
|
Binary file (5.09 kB). View file
|
|
|
dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00025/meshes/pred-ours-lefthand.ply
ADDED
|
Binary file (4.82 kB). View file
|
|
|
dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00025/meshes/pred-ours-righthand.ply
ADDED
|
Binary file (4.82 kB). View file
|
|
|
dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00061/meshes/gt-lefthand.ply
ADDED
|
Binary file (4.82 kB). View file
|
|
|
dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00072/meshes/gt-body.ply
ADDED
|
Binary file (5.06 kB). View file
|
|
|
dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00072/meshes/gt-lefthand.ply
ADDED
|
Binary file (4.85 kB). View file
|
|
|
dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00072/meshes/gt-righthand.ply
ADDED
|
Binary file (4.82 kB). View file
|
|
|
dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00072/meshes/pred-ours-body.ply
ADDED
|
Binary file (5.11 kB). View file
|
|
|
dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00072/meshes/pred-ours-lefthand.ply
ADDED
|
Binary file (4.85 kB). View file
|
|
|
dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00072/meshes/pred-ours-righthand.ply
ADDED
|
Binary file (4.82 kB). View file
|
|
|
dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00128/meshes/gt-body.ply
ADDED
|
Binary file (5.12 kB). View file
|
|
|
dragmesh3-core/outputs/coda_locomotion_audit/test_A_native_run2/wis3d_native_output/00128/meshes/gt-lefthand.ply
ADDED
|
Binary file (4.85 kB). View file
|
|
|