Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- atec_robot_model/objects/task_e/KLT_Bin/.thumbs/256x256/.small_KLT.usd.last_generated +1 -0
- atec_robot_model/objects/task_e/KLT_Bin/.thumbs/256x256/.small_KLT_visual.usd.last_generated +1 -0
- atec_robot_model/objects/task_e/KLT_Bin/.thumbs/256x256/.small_KLT_visual_collision.usd.last_generated +1 -0
- atec_robot_model/objects/task_e/KLT_Bin/.thumbs/small_KLT.thumb.usd +0 -0
- atec_robot_model/objects/task_e/KLT_Bin/.thumbs/small_KLT_visual.thumb.usd +0 -0
- atec_robot_model/objects/task_e/KLT_Bin/.thumbs/small_KLT_visual_collision.thumb.usd +0 -0
- atec_robot_model/objects/task_e/KLT_Bin/small_KLT.usd +0 -0
- atec_robot_model/objects/task_e/shop_table/.collect.mapping.json +77 -0
- demo/act/detr/backbone.py +126 -0
- demo/act/detr/detr_vae.py +137 -0
- demo/act/detr/position_encoding.py +90 -0
- demo/act/detr/transformer.py +455 -0
- demo/act/detr/utils.py +161 -0
- scripts/act/baseline.sh +27 -0
- scripts/act/cli_args.py +48 -0
- scripts/act/collect_demos_task_e.py +229 -0
- scripts/act/eval_task_e_act.py +191 -0
- scripts/act/filter_demos.py +99 -0
- scripts/act/run_task_e_pipeline.sh +83 -0
- scripts/act/search_task_e_grasps.py +761 -0
- scripts/act/task_e/__init__.py +0 -0
- scripts/act/task_e/collector.py +399 -0
- scripts/act/task_e/config.py +295 -0
- scripts/act/task_e/state_machine.py +439 -0
- scripts/act/trace_task_e_policy.py +84 -0
- scripts/act/train_task_e.py +442 -0
- scripts/graspnet_task_e/__init__.py +2 -0
- scripts/graspnet_task_e/anygrasp_adapter.py +228 -0
- scripts/graspnet_task_e/debug_solution_pca_execution.py +178 -0
- scripts/graspnet_task_e/debug_solution_pca_perception.py +84 -0
- scripts/graspnet_task_e/pca_aabb_adapter.py +114 -0
- scripts/graspnet_task_e/run_anygrasp_pick.sh +37 -0
- scripts/graspnet_task_e/run_graspnet_pick.py +844 -0
- scripts/graspnet_task_e/sam3_segment_image.py +109 -0
- scripts/graspnet_task_e/tuntun_adapter.py +388 -0
- scripts/pi05/compare_pi05_vs_act_baseline.py +94 -0
- scripts/pi05/convert_task_e_hdf5_to_lerobot.py +206 -0
- scripts/pi05/convert_task_e_hdf5_to_lerobot_native8.py +184 -0
- scripts/pi05/eval_task_e_pi05.py +183 -0
- scripts/pi05/run_pi05_20demos_after_convert.sh +42 -0
- scripts/pi05/run_pi05_eval_checkpoint.sh +84 -0
- scripts/pi05/run_pi05_native8_100demos_prepare.sh +30 -0
- scripts/pi05/run_pi05_native8_100demos_s2_gate.sh +47 -0
- scripts/pi05/run_pi05_native8_100demos_s2_lora_gate.sh +55 -0
- scripts/pi05/run_pi05_native8_20demos_s2_smoke.sh +45 -0
- scripts/pi05/run_pi05_native8_20demos_smoke.sh +34 -0
- scripts/pi05/run_pi05_native8_4demos_s2_sanity.sh +45 -0
- scripts/pi05/run_pi05_native8_eval_checkpoint.sh +87 -0
- scripts/pi05/run_pi05_native8_rawabs_1demo_s10_aefull_h10_10k_lr5.sh +31 -0
- scripts/pi05/run_pi05_native8_rawabs_1demo_s10_aefull_h10_2k.sh +31 -0
atec_robot_model/objects/task_e/KLT_Bin/.thumbs/256x256/.small_KLT.usd.last_generated
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
2025-01-15 22:28:57
|
atec_robot_model/objects/task_e/KLT_Bin/.thumbs/256x256/.small_KLT_visual.usd.last_generated
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
2025-01-15 22:29:04
|
atec_robot_model/objects/task_e/KLT_Bin/.thumbs/256x256/.small_KLT_visual_collision.usd.last_generated
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
2025-01-15 22:29:09
|
atec_robot_model/objects/task_e/KLT_Bin/.thumbs/small_KLT.thumb.usd
ADDED
|
Binary file (3.52 kB). View file
|
|
|
atec_robot_model/objects/task_e/KLT_Bin/.thumbs/small_KLT_visual.thumb.usd
ADDED
|
Binary file (3.33 kB). View file
|
|
|
atec_robot_model/objects/task_e/KLT_Bin/.thumbs/small_KLT_visual_collision.thumb.usd
ADDED
|
Binary file (3.34 kB). View file
|
|
|
atec_robot_model/objects/task_e/KLT_Bin/small_KLT.usd
ADDED
|
Binary file (6.65 kB). View file
|
|
|
atec_robot_model/objects/task_e/shop_table/.collect.mapping.json
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"version": "1.0",
|
| 3 |
+
"file_records": [
|
| 4 |
+
{
|
| 5 |
+
"source_url": "/home/wxm/VLA/IsaacSim/isaac-sim-asserts/isaac-sim-assets-1@4.5.0-rc.36+release.19112.f59b3005/Assets/Isaac/4.5/Isaac/Samples/Examples/FrankaNutBolt/SubUSDs/Shop_Table/textures/aluminum_feet_basecolor.png",
|
| 6 |
+
"source_hash": "f57c28888268a580c183fdeb41f7bb9e9eb0b134",
|
| 7 |
+
"target_url": "./textures/aluminum_feet_basecolor.png",
|
| 8 |
+
"target_hash": "8ceaebf96f29d4ca23d43b0b35a4a9d7d591b9a2"
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"source_url": "/home/wxm/VLA/IsaacSim/isaac-sim-asserts/isaac-sim-assets-1@4.5.0-rc.36+release.19112.f59b3005/Assets/Isaac/4.5/Isaac/Samples/Examples/FrankaNutBolt/SubUSDs/Shop_Table/textures/aluminum_feet_normal.png",
|
| 12 |
+
"source_hash": "90799c1ef386f466fd2fc4ec065edd8c0d6c4a7e",
|
| 13 |
+
"target_url": "./textures/aluminum_feet_normal.png",
|
| 14 |
+
"target_hash": "782bdfd98942e2e209de7ad9685ed07fe221d45c"
|
| 15 |
+
},
|
| 16 |
+
{
|
| 17 |
+
"source_url": "/home/wxm/VLA/IsaacSim/isaac-sim-asserts/isaac-sim-assets-1@4.5.0-rc.36+release.19112.f59b3005/Assets/Isaac/4.5/Isaac/Samples/Examples/FrankaNutBolt/SubUSDs/Shop_Table/textures/aluminum_feet_roughness.png",
|
| 18 |
+
"source_hash": "2b7a4d8487620024cc43a6e796b52a3a92b566e5",
|
| 19 |
+
"target_url": "./textures/aluminum_feet_roughness.png",
|
| 20 |
+
"target_hash": "ff5571089243d1d75b7509293beabe4f24f973ea"
|
| 21 |
+
},
|
| 22 |
+
{
|
| 23 |
+
"source_url": "/home/wxm/VLA/IsaacSim/isaac-sim-asserts/isaac-sim-assets-1@4.5.0-rc.36+release.19112.f59b3005/Assets/Isaac/4.5/Isaac/Samples/Examples/FrankaNutBolt/SubUSDs/Shop_Table/textures/metal_tabletop_basecolor.png",
|
| 24 |
+
"source_hash": "e70234bdc6a607996b395667c8a1dee815703a4a",
|
| 25 |
+
"target_url": "./textures/metal_tabletop_basecolor.png",
|
| 26 |
+
"target_hash": "f07f6619e46cc26545f5061bec0cbdb94e37c922"
|
| 27 |
+
},
|
| 28 |
+
{
|
| 29 |
+
"source_url": "/home/wxm/VLA/IsaacSim/isaac-sim-asserts/isaac-sim-assets-1@4.5.0-rc.36+release.19112.f59b3005/Assets/Isaac/4.5/Isaac/Samples/Examples/FrankaNutBolt/SubUSDs/Shop_Table/textures/metal_tabletop_metallic.png",
|
| 30 |
+
"source_hash": "d21eeeb9e675f4203387875b1d690151cb574c74",
|
| 31 |
+
"target_url": "./textures/metal_tabletop_metallic.png",
|
| 32 |
+
"target_hash": "2c6266f3ab51d0537ad38b54df02007eb9111803"
|
| 33 |
+
},
|
| 34 |
+
{
|
| 35 |
+
"source_url": "/home/wxm/VLA/IsaacSim/isaac-sim-asserts/isaac-sim-assets-1@4.5.0-rc.36+release.19112.f59b3005/Assets/Isaac/4.5/Isaac/Samples/Examples/FrankaNutBolt/SubUSDs/Shop_Table/textures/metal_tabletop_normal.png",
|
| 36 |
+
"source_hash": "330003f7b33e37a63ff1547d603c9f54ecac6f1c",
|
| 37 |
+
"target_url": "./textures/metal_tabletop_normal.png",
|
| 38 |
+
"target_hash": "ce62d74aa3f6a05b8662b1a8f938a6421a9819aa"
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"source_url": "/home/wxm/VLA/IsaacSim/isaac-sim-asserts/isaac-sim-assets-1@4.5.0-rc.36+release.19112.f59b3005/Assets/Isaac/4.5/Isaac/Samples/Examples/FrankaNutBolt/SubUSDs/Shop_Table/textures/metal_tabletop_roughness.png",
|
| 42 |
+
"source_hash": "679380766abf4ca418c1d1681dec38a96f74d24e",
|
| 43 |
+
"target_url": "./textures/metal_tabletop_roughness.png",
|
| 44 |
+
"target_hash": "e4e2dc752544d7a9d0919520a33f084adff9cf50"
|
| 45 |
+
},
|
| 46 |
+
{
|
| 47 |
+
"source_url": "/home/wxm/VLA/IsaacSim/isaac-sim-asserts/isaac-sim-assets-1@4.5.0-rc.36+release.19112.f59b3005/Assets/Isaac/4.5/Isaac/Samples/Examples/FrankaNutBolt/SubUSDs/Shop_Table/textures/steel_orange_basecolor.png",
|
| 48 |
+
"source_hash": "19de24af03b4a0a2a9fb1213e72b8dbb9fe43446",
|
| 49 |
+
"target_url": "./textures/steel_orange_basecolor.png",
|
| 50 |
+
"target_hash": "ada63e416ff77d9579ddb44bf24069b4d7393e84"
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"source_url": "/home/wxm/VLA/IsaacSim/isaac-sim-asserts/isaac-sim-assets-1@4.5.0-rc.36+release.19112.f59b3005/Assets/Isaac/4.5/Isaac/Samples/Examples/FrankaNutBolt/SubUSDs/Shop_Table/textures/steel_orange_metallic.png",
|
| 54 |
+
"source_hash": "a3b4c3c79ac1f820465b66078faf40131e83deb1",
|
| 55 |
+
"target_url": "./textures/steel_orange_metallic.png",
|
| 56 |
+
"target_hash": "6ef5e8a42ce00c27e79275c54258d9f99fe09ca7"
|
| 57 |
+
},
|
| 58 |
+
{
|
| 59 |
+
"source_url": "/home/wxm/VLA/IsaacSim/isaac-sim-asserts/isaac-sim-assets-1@4.5.0-rc.36+release.19112.f59b3005/Assets/Isaac/4.5/Isaac/Samples/Examples/FrankaNutBolt/SubUSDs/Shop_Table/textures/steel_orange_normal.png",
|
| 60 |
+
"source_hash": "2024c4b6f6a2bed8812d854df83e115f15b132df",
|
| 61 |
+
"target_url": "./textures/steel_orange_normal.png",
|
| 62 |
+
"target_hash": "6c49a1bdb10f7b66c8e4028988fa6bafd416ab5b"
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"source_url": "/home/wxm/VLA/IsaacSim/isaac-sim-asserts/isaac-sim-assets-1@4.5.0-rc.36+release.19112.f59b3005/Assets/Isaac/4.5/Isaac/Samples/Examples/FrankaNutBolt/SubUSDs/Shop_Table/textures/steel_orange_roughness.png",
|
| 66 |
+
"source_hash": "529db0802c83a483c28e235ff6c706b99159d778",
|
| 67 |
+
"target_url": "./textures/steel_orange_roughness.png",
|
| 68 |
+
"target_hash": "fd92178c5427e9a2728bb4f866827724cb0025a5"
|
| 69 |
+
},
|
| 70 |
+
{
|
| 71 |
+
"source_url": "/home/wxm/VLA/IsaacSim/isaac-sim-asserts/isaac-sim-assets-1@4.5.0-rc.36+release.19112.f59b3005/Assets/Isaac/4.5/Isaac/Samples/Examples/FrankaNutBolt/SubUSDs/Shop_Table/textures/vibrationtable_base_basecolor.png",
|
| 72 |
+
"source_hash": "c526c43071d2aa9dd4399e7682390774d84a9ee5",
|
| 73 |
+
"target_url": "./textures/vibrationtable_base_basecolor.png",
|
| 74 |
+
"target_hash": "933a0ca8cf7d13fbae9a8980a58798842625483a"
|
| 75 |
+
}
|
| 76 |
+
]
|
| 77 |
+
}
|
demo/act/detr/backbone.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
|
| 2 |
+
"""
|
| 3 |
+
Backbone modules.
|
| 4 |
+
"""
|
| 5 |
+
from collections import OrderedDict
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
import torchvision
|
| 10 |
+
from torch import nn
|
| 11 |
+
from torchvision.models._utils import IntermediateLayerGetter
|
| 12 |
+
from typing import Dict, List
|
| 13 |
+
|
| 14 |
+
from .utils import NestedTensor
|
| 15 |
+
from .position_encoding import build_position_encoding
|
| 16 |
+
|
| 17 |
+
class FrozenBatchNorm2d(torch.nn.Module):
|
| 18 |
+
"""
|
| 19 |
+
BatchNorm2d where the batch statistics and the affine parameters are fixed.
|
| 20 |
+
|
| 21 |
+
Copy-paste from torchvision.misc.ops with added eps before rqsrt,
|
| 22 |
+
without which any other policy_models than torchvision.policy_models.resnet[18,34,50,101]
|
| 23 |
+
produce nans.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
def __init__(self, n):
|
| 27 |
+
super(FrozenBatchNorm2d, self).__init__()
|
| 28 |
+
self.register_buffer("weight", torch.ones(n))
|
| 29 |
+
self.register_buffer("bias", torch.zeros(n))
|
| 30 |
+
self.register_buffer("running_mean", torch.zeros(n))
|
| 31 |
+
self.register_buffer("running_var", torch.ones(n))
|
| 32 |
+
|
| 33 |
+
def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict,
|
| 34 |
+
missing_keys, unexpected_keys, error_msgs):
|
| 35 |
+
num_batches_tracked_key = prefix + 'num_batches_tracked'
|
| 36 |
+
if num_batches_tracked_key in state_dict:
|
| 37 |
+
del state_dict[num_batches_tracked_key]
|
| 38 |
+
|
| 39 |
+
super(FrozenBatchNorm2d, self)._load_from_state_dict(
|
| 40 |
+
state_dict, prefix, local_metadata, strict,
|
| 41 |
+
missing_keys, unexpected_keys, error_msgs)
|
| 42 |
+
|
| 43 |
+
def forward(self, x):
|
| 44 |
+
# move reshapes to the beginning
|
| 45 |
+
# to make it fuser-friendly
|
| 46 |
+
w = self.weight.reshape(1, -1, 1, 1)
|
| 47 |
+
b = self.bias.reshape(1, -1, 1, 1)
|
| 48 |
+
rv = self.running_var.reshape(1, -1, 1, 1)
|
| 49 |
+
rm = self.running_mean.reshape(1, -1, 1, 1)
|
| 50 |
+
eps = 1e-5
|
| 51 |
+
scale = w * (rv + eps).rsqrt()
|
| 52 |
+
bias = b - rm * scale
|
| 53 |
+
return x * scale + bias
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class BackboneBase(nn.Module):
|
| 57 |
+
|
| 58 |
+
def __init__(self, backbone: nn.Module, train_backbone: bool, num_channels: int, return_interm_layers: bool):
|
| 59 |
+
super().__init__()
|
| 60 |
+
# for name, parameter in backbone.named_parameters(): # only train later layers # TODO do we want this?
|
| 61 |
+
# if not train_backbone or 'layer2' not in name and 'layer3' not in name and 'layer4' not in name:
|
| 62 |
+
# parameter.requires_grad_(False)
|
| 63 |
+
if return_interm_layers:
|
| 64 |
+
return_layers = {"layer1": "0", "layer2": "1", "layer3": "2", "layer4": "3"}
|
| 65 |
+
else:
|
| 66 |
+
return_layers = {'layer4': "0"}
|
| 67 |
+
self.body = IntermediateLayerGetter(backbone, return_layers=return_layers)
|
| 68 |
+
self.num_channels = num_channels
|
| 69 |
+
|
| 70 |
+
def forward(self, tensor):
|
| 71 |
+
xs = self.body(tensor)
|
| 72 |
+
return xs
|
| 73 |
+
# out: Dict[str, NestedTensor] = {}
|
| 74 |
+
# for name, x in xs.items():
|
| 75 |
+
# m = tensor_list.mask
|
| 76 |
+
# assert m is not None
|
| 77 |
+
# mask = F.interpolate(m[None].float(), size=x.shape[-2:]).to(torch.bool)[0]
|
| 78 |
+
# out[name] = NestedTensor(x, mask)
|
| 79 |
+
# return out
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class Backbone(BackboneBase):
|
| 83 |
+
"""ResNet backbone with frozen BatchNorm."""
|
| 84 |
+
def __init__(self, name: str,
|
| 85 |
+
train_backbone: bool,
|
| 86 |
+
return_interm_layers: bool,
|
| 87 |
+
dilation: bool,
|
| 88 |
+
include_depth: bool):
|
| 89 |
+
backbone = getattr(torchvision.models, name)(
|
| 90 |
+
replace_stride_with_dilation=[False, False, dilation],
|
| 91 |
+
pretrained=False, norm_layer=FrozenBatchNorm2d) # pretrained # TODO do we want frozen batch_norm??
|
| 92 |
+
|
| 93 |
+
# for rgbd data
|
| 94 |
+
if include_depth:
|
| 95 |
+
w = backbone.conv1.weight
|
| 96 |
+
w = torch.cat([w, torch.full((64, 1, 7, 7), 0)], dim=1)
|
| 97 |
+
backbone.conv1.weight = nn.Parameter(w)
|
| 98 |
+
|
| 99 |
+
num_channels = 512 if name in ('resnet18', 'resnet34') else 2048
|
| 100 |
+
super().__init__(backbone, train_backbone, num_channels, return_interm_layers)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class Joiner(nn.Sequential):
|
| 104 |
+
def __init__(self, backbone, position_embedding):
|
| 105 |
+
super().__init__(backbone, position_embedding)
|
| 106 |
+
|
| 107 |
+
def forward(self, tensor_list: NestedTensor):
|
| 108 |
+
xs = self[0](tensor_list)
|
| 109 |
+
out: List[NestedTensor] = []
|
| 110 |
+
pos = []
|
| 111 |
+
for name, x in xs.items():
|
| 112 |
+
out.append(x)
|
| 113 |
+
# position encoding
|
| 114 |
+
pos.append(self[1](x).to(x.dtype))
|
| 115 |
+
|
| 116 |
+
return out, pos
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def build_backbone(args):
|
| 120 |
+
position_embedding = build_position_encoding(args)
|
| 121 |
+
train_backbone = args.lr_backbone > 0
|
| 122 |
+
return_interm_layers = args.masks
|
| 123 |
+
backbone = Backbone(args.backbone, train_backbone, return_interm_layers, args.dilation, args.include_depth)
|
| 124 |
+
model = Joiner(backbone, position_embedding)
|
| 125 |
+
model.num_channels = backbone.num_channels
|
| 126 |
+
return model
|
demo/act/detr/detr_vae.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
|
| 2 |
+
"""
|
| 3 |
+
DETR model and criterion classes.
|
| 4 |
+
"""
|
| 5 |
+
import torch
|
| 6 |
+
from torch import nn
|
| 7 |
+
from torch.autograd import Variable
|
| 8 |
+
from .transformer import build_transformer, TransformerEncoder, TransformerEncoderLayer
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
|
| 12 |
+
def reparametrize(mu, logvar):
|
| 13 |
+
std = logvar.div(2).exp()
|
| 14 |
+
eps = Variable(std.data.new(std.size()).normal_())
|
| 15 |
+
return mu + std * eps
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def get_sinusoid_encoding_table(n_position, d_hid):
|
| 19 |
+
def get_position_angle_vec(position):
|
| 20 |
+
return [position / np.power(10000, 2 * (hid_j // 2) / d_hid) for hid_j in range(d_hid)]
|
| 21 |
+
|
| 22 |
+
sinusoid_table = np.array([get_position_angle_vec(pos_i) for pos_i in range(n_position)])
|
| 23 |
+
sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i
|
| 24 |
+
sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1
|
| 25 |
+
|
| 26 |
+
return torch.FloatTensor(sinusoid_table).unsqueeze(0)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class DETRVAE(nn.Module):
|
| 30 |
+
""" This is the DETR module that performs object detection """
|
| 31 |
+
def __init__(self, backbones, transformer, encoder, state_dim, action_dim, num_queries):
|
| 32 |
+
super().__init__()
|
| 33 |
+
self.num_queries = num_queries
|
| 34 |
+
self.transformer = transformer
|
| 35 |
+
self.encoder = encoder
|
| 36 |
+
hidden_dim = transformer.d_model
|
| 37 |
+
self.action_head = nn.Linear(hidden_dim, action_dim)
|
| 38 |
+
self.query_embed = nn.Embedding(num_queries, hidden_dim)
|
| 39 |
+
if backbones is not None:
|
| 40 |
+
self.input_proj = nn.Conv2d(backbones[0].num_channels, hidden_dim, kernel_size=1)
|
| 41 |
+
self.backbones = nn.ModuleList(backbones)
|
| 42 |
+
self.input_proj_robot_state = nn.Linear(state_dim, hidden_dim)
|
| 43 |
+
else:
|
| 44 |
+
self.input_proj_robot_state = nn.Linear(state_dim, hidden_dim)
|
| 45 |
+
self.backbones = None
|
| 46 |
+
|
| 47 |
+
# encoder extra parameters
|
| 48 |
+
self.latent_dim = 32 # size of latent z
|
| 49 |
+
self.cls_embed = nn.Embedding(1, hidden_dim) # extra cls token embedding
|
| 50 |
+
self.encoder_state_proj = nn.Linear(state_dim, hidden_dim) # project state to embedding
|
| 51 |
+
self.encoder_action_proj = nn.Linear(action_dim, hidden_dim) # project action to embedding
|
| 52 |
+
self.latent_proj = nn.Linear(hidden_dim, self.latent_dim*2) # project hidden state to latent std, var
|
| 53 |
+
self.register_buffer('pos_table', get_sinusoid_encoding_table(1+1+num_queries, hidden_dim)) # [CLS], state, actions
|
| 54 |
+
|
| 55 |
+
# decoder extra parameters
|
| 56 |
+
self.latent_out_proj = nn.Linear(self.latent_dim, hidden_dim) # project latent sample to embedding
|
| 57 |
+
self.additional_pos_embed = nn.Embedding(2, hidden_dim) # learned position embedding for state and proprio
|
| 58 |
+
|
| 59 |
+
def forward(self, obs, actions=None):
|
| 60 |
+
is_training = actions is not None
|
| 61 |
+
state = obs['state'] if self.backbones is not None else obs
|
| 62 |
+
bs = state.shape[0]
|
| 63 |
+
|
| 64 |
+
if is_training:
|
| 65 |
+
# project CLS token, state sequence, and action sequence to embedding dim
|
| 66 |
+
cls_embed = self.cls_embed.weight # (1, hidden_dim)
|
| 67 |
+
cls_embed = torch.unsqueeze(cls_embed, axis=0).repeat(bs, 1, 1) # (bs, 1, hidden_dim)
|
| 68 |
+
state_embed = self.encoder_state_proj(state) # (bs, hidden_dim)
|
| 69 |
+
state_embed = torch.unsqueeze(state_embed, axis=1) # (bs, 1, hidden_dim)
|
| 70 |
+
action_embed = self.encoder_action_proj(actions) # (bs, seq, hidden_dim)
|
| 71 |
+
# concat them together to form an input to the CVAE encoder
|
| 72 |
+
encoder_input = torch.cat([cls_embed, state_embed, action_embed], axis=1) # (bs, seq+2, hidden_dim)
|
| 73 |
+
encoder_input = encoder_input.permute(1, 0, 2) # (seq+2, bs, hidden_dim)
|
| 74 |
+
# no masking is applied to all parts of the CVAE encoder input
|
| 75 |
+
is_pad = torch.full((bs, encoder_input.shape[0]), False).to(state.device) # False: not a padding
|
| 76 |
+
# obtain position embedding
|
| 77 |
+
pos_embed = self.pos_table.clone().detach()
|
| 78 |
+
pos_embed = pos_embed.permute(1, 0, 2) # (seq+2, 1, hidden_dim)
|
| 79 |
+
# query CVAE encoder
|
| 80 |
+
encoder_output = self.encoder(encoder_input, pos=pos_embed, src_key_padding_mask=is_pad)
|
| 81 |
+
encoder_output = encoder_output[0] # take cls output only
|
| 82 |
+
latent_info = self.latent_proj(encoder_output)
|
| 83 |
+
mu = latent_info[:, :self.latent_dim]
|
| 84 |
+
logvar = latent_info[:, self.latent_dim:]
|
| 85 |
+
latent_sample = reparametrize(mu, logvar)
|
| 86 |
+
latent_input = self.latent_out_proj(latent_sample)
|
| 87 |
+
else:
|
| 88 |
+
mu = logvar = None
|
| 89 |
+
latent_sample = torch.zeros([bs, self.latent_dim], dtype=torch.float32).to(state.device)
|
| 90 |
+
latent_input = self.latent_out_proj(latent_sample)
|
| 91 |
+
|
| 92 |
+
# CVAE decoder
|
| 93 |
+
if self.backbones is not None:
|
| 94 |
+
vis_data = obs['rgb']
|
| 95 |
+
if "depth" in obs:
|
| 96 |
+
vis_data = torch.cat([vis_data, obs['depth']], dim=2)
|
| 97 |
+
num_cams = vis_data.shape[1]
|
| 98 |
+
|
| 99 |
+
# Image observation features and position embeddings
|
| 100 |
+
all_cam_features = []
|
| 101 |
+
all_cam_pos = []
|
| 102 |
+
for cam_id in range(num_cams):
|
| 103 |
+
features, pos = self.backbones[0](vis_data[:, cam_id]) # HARDCODED
|
| 104 |
+
features = features[0] # take the last layer feature # (batch, hidden_dim, H, W)
|
| 105 |
+
pos = pos[0] # (1, hidden_dim, H, W)
|
| 106 |
+
all_cam_features.append(self.input_proj(features))
|
| 107 |
+
all_cam_pos.append(pos)
|
| 108 |
+
|
| 109 |
+
# proprioception features (state)
|
| 110 |
+
proprio_input = self.input_proj_robot_state(state)
|
| 111 |
+
# fold camera dimension into width dimension
|
| 112 |
+
src = torch.cat(all_cam_features, axis=3) # (batch, hidden_dim, 4, 8)
|
| 113 |
+
pos = torch.cat(all_cam_pos, axis=3) # (batch, hidden_dim, 4, 8)
|
| 114 |
+
hs = self.transformer(src, None, self.query_embed.weight, pos, latent_input, proprio_input, self.additional_pos_embed.weight)[0] # (batch, num_queries, hidden_dim)
|
| 115 |
+
else:
|
| 116 |
+
state = self.input_proj_robot_state(state)
|
| 117 |
+
hs = self.transformer(None, None, self.query_embed.weight, None, latent_input, state, self.additional_pos_embed.weight)[0]
|
| 118 |
+
|
| 119 |
+
a_hat = self.action_head(hs)
|
| 120 |
+
return a_hat, [mu, logvar]
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def build_encoder(args):
|
| 124 |
+
d_model = args.hidden_dim # 256
|
| 125 |
+
dropout = args.dropout # 0.1
|
| 126 |
+
nhead = args.nheads # 8
|
| 127 |
+
dim_feedforward = args.dim_feedforward # 2048
|
| 128 |
+
num_encoder_layers = args.enc_layers # 4 # TODO shared with VAE decoder
|
| 129 |
+
normalize_before = args.pre_norm # False
|
| 130 |
+
activation = "relu"
|
| 131 |
+
|
| 132 |
+
encoder_layer = TransformerEncoderLayer(d_model, nhead, dim_feedforward,
|
| 133 |
+
dropout, activation, normalize_before)
|
| 134 |
+
encoder_norm = nn.LayerNorm(d_model) if normalize_before else None
|
| 135 |
+
encoder = TransformerEncoder(encoder_layer, num_encoder_layers, encoder_norm)
|
| 136 |
+
|
| 137 |
+
return encoder
|
demo/act/detr/position_encoding.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
|
| 2 |
+
"""
|
| 3 |
+
Various positional encodings for the transformer.
|
| 4 |
+
"""
|
| 5 |
+
import math
|
| 6 |
+
import torch
|
| 7 |
+
from torch import nn
|
| 8 |
+
|
| 9 |
+
from .utils import NestedTensor
|
| 10 |
+
|
| 11 |
+
class PositionEmbeddingSine(nn.Module):
|
| 12 |
+
"""
|
| 13 |
+
This is a more standard version of the position embedding, very similar to the one
|
| 14 |
+
used by the Attention is all you need paper, generalized to work on images.
|
| 15 |
+
"""
|
| 16 |
+
def __init__(self, num_pos_feats=64, temperature=10000, normalize=False, scale=None):
|
| 17 |
+
super().__init__()
|
| 18 |
+
self.num_pos_feats = num_pos_feats
|
| 19 |
+
self.temperature = temperature
|
| 20 |
+
self.normalize = normalize
|
| 21 |
+
if scale is not None and normalize is False:
|
| 22 |
+
raise ValueError("normalize should be True if scale is passed")
|
| 23 |
+
if scale is None:
|
| 24 |
+
scale = 2 * math.pi
|
| 25 |
+
self.scale = scale
|
| 26 |
+
|
| 27 |
+
def forward(self, tensor):
|
| 28 |
+
x = tensor
|
| 29 |
+
# mask = tensor_list.mask
|
| 30 |
+
# assert mask is not None
|
| 31 |
+
# not_mask = ~mask
|
| 32 |
+
|
| 33 |
+
not_mask = torch.ones_like(x[0, [0]])
|
| 34 |
+
y_embed = not_mask.cumsum(1, dtype=torch.float32)
|
| 35 |
+
x_embed = not_mask.cumsum(2, dtype=torch.float32)
|
| 36 |
+
if self.normalize:
|
| 37 |
+
eps = 1e-6
|
| 38 |
+
y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale
|
| 39 |
+
x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale
|
| 40 |
+
|
| 41 |
+
dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device)
|
| 42 |
+
dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats)
|
| 43 |
+
|
| 44 |
+
pos_x = x_embed[:, :, :, None] / dim_t
|
| 45 |
+
pos_y = y_embed[:, :, :, None] / dim_t
|
| 46 |
+
pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3)
|
| 47 |
+
pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3)
|
| 48 |
+
pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
|
| 49 |
+
return pos
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class PositionEmbeddingLearned(nn.Module):
|
| 53 |
+
"""
|
| 54 |
+
Absolute pos embedding, learned.
|
| 55 |
+
"""
|
| 56 |
+
def __init__(self, num_pos_feats=256):
|
| 57 |
+
super().__init__()
|
| 58 |
+
self.row_embed = nn.Embedding(50, num_pos_feats)
|
| 59 |
+
self.col_embed = nn.Embedding(50, num_pos_feats)
|
| 60 |
+
self.reset_parameters()
|
| 61 |
+
|
| 62 |
+
def reset_parameters(self):
|
| 63 |
+
nn.init.uniform_(self.row_embed.weight)
|
| 64 |
+
nn.init.uniform_(self.col_embed.weight)
|
| 65 |
+
|
| 66 |
+
def forward(self, tensor_list: NestedTensor):
|
| 67 |
+
x = tensor_list.tensors
|
| 68 |
+
h, w = x.shape[-2:]
|
| 69 |
+
i = torch.arange(w, device=x.device)
|
| 70 |
+
j = torch.arange(h, device=x.device)
|
| 71 |
+
x_emb = self.col_embed(i)
|
| 72 |
+
y_emb = self.row_embed(j)
|
| 73 |
+
pos = torch.cat([
|
| 74 |
+
x_emb.unsqueeze(0).repeat(h, 1, 1),
|
| 75 |
+
y_emb.unsqueeze(1).repeat(1, w, 1),
|
| 76 |
+
], dim=-1).permute(2, 0, 1).unsqueeze(0).repeat(x.shape[0], 1, 1, 1)
|
| 77 |
+
return pos
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def build_position_encoding(args):
|
| 81 |
+
N_steps = args.hidden_dim // 2
|
| 82 |
+
if args.position_embedding in ('v2', 'sine'):
|
| 83 |
+
# TODO find a better way of exposing other arguments
|
| 84 |
+
position_embedding = PositionEmbeddingSine(N_steps, normalize=True)
|
| 85 |
+
elif args.position_embedding in ('v3', 'learned'):
|
| 86 |
+
position_embedding = PositionEmbeddingLearned(N_steps)
|
| 87 |
+
else:
|
| 88 |
+
raise ValueError(f"not supported {args.position_embedding}")
|
| 89 |
+
|
| 90 |
+
return position_embedding
|
demo/act/detr/transformer.py
ADDED
|
@@ -0,0 +1,455 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
|
| 2 |
+
"""
|
| 3 |
+
DETR Transformer class.
|
| 4 |
+
|
| 5 |
+
Copy-paste from torch.nn.Transformer with modifications:
|
| 6 |
+
* positional encodings are passed in MHattention
|
| 7 |
+
* extra LN at the end of encoder is removed
|
| 8 |
+
* decoder returns a stack of activations from all decoding layers
|
| 9 |
+
"""
|
| 10 |
+
import copy
|
| 11 |
+
from typing import Optional, List
|
| 12 |
+
|
| 13 |
+
import torch
|
| 14 |
+
import torch.nn.functional as F
|
| 15 |
+
from torch import nn, Tensor
|
| 16 |
+
|
| 17 |
+
class Transformer(nn.Module):
|
| 18 |
+
|
| 19 |
+
def __init__(self, d_model=512, nhead=8, num_encoder_layers=6,
|
| 20 |
+
num_decoder_layers=6, dim_feedforward=2048, dropout=0.1,
|
| 21 |
+
activation="relu", normalize_before=False,
|
| 22 |
+
return_intermediate_dec=False, use_xsa=False):
|
| 23 |
+
super().__init__()
|
| 24 |
+
|
| 25 |
+
encoder_cls = XSATransformerEncoderLayer if use_xsa else TransformerEncoderLayer
|
| 26 |
+
decoder_cls = XSATransformerDecoderLayer if use_xsa else TransformerDecoderLayer
|
| 27 |
+
|
| 28 |
+
encoder_layer = encoder_cls(d_model, nhead, dim_feedforward,
|
| 29 |
+
dropout, activation, normalize_before)
|
| 30 |
+
encoder_norm = nn.LayerNorm(d_model) if normalize_before else None
|
| 31 |
+
self.encoder = TransformerEncoder(encoder_layer, num_encoder_layers, encoder_norm)
|
| 32 |
+
|
| 33 |
+
decoder_layer = decoder_cls(d_model, nhead, dim_feedforward,
|
| 34 |
+
dropout, activation, normalize_before)
|
| 35 |
+
decoder_norm = nn.LayerNorm(d_model)
|
| 36 |
+
self.decoder = TransformerDecoder(decoder_layer, num_decoder_layers, decoder_norm,
|
| 37 |
+
return_intermediate=return_intermediate_dec)
|
| 38 |
+
|
| 39 |
+
self._reset_parameters()
|
| 40 |
+
|
| 41 |
+
self.d_model = d_model
|
| 42 |
+
self.nhead = nhead
|
| 43 |
+
|
| 44 |
+
def _reset_parameters(self):
|
| 45 |
+
for p in self.parameters():
|
| 46 |
+
if p.dim() > 1:
|
| 47 |
+
nn.init.xavier_uniform_(p)
|
| 48 |
+
|
| 49 |
+
def forward(self, src, mask, query_embed, pos_embed, latent_input=None, proprio_input=None, additional_pos_embed=None):
|
| 50 |
+
if src is None:
|
| 51 |
+
bs = proprio_input.shape[0]
|
| 52 |
+
query_embed = query_embed.unsqueeze(1).repeat(1, bs, 1)
|
| 53 |
+
pos_embed = additional_pos_embed.unsqueeze(1).repeat(1, bs, 1) # seq, bs, dim
|
| 54 |
+
src = torch.stack([latent_input, proprio_input], axis=0)
|
| 55 |
+
# TODO flatten only when input has H and W
|
| 56 |
+
elif len(src.shape) == 4: # has H and W
|
| 57 |
+
# flatten NxCxHxW to HWxNxC
|
| 58 |
+
bs, c, h, w = src.shape
|
| 59 |
+
src = src.flatten(2).permute(2, 0, 1)
|
| 60 |
+
pos_embed = pos_embed.flatten(2).permute(2, 0, 1).repeat(1, bs, 1)
|
| 61 |
+
query_embed = query_embed.unsqueeze(1).repeat(1, bs, 1)
|
| 62 |
+
# mask = mask.flatten(1)
|
| 63 |
+
|
| 64 |
+
additional_pos_embed = additional_pos_embed.unsqueeze(1).repeat(1, bs, 1) # seq, bs, dim
|
| 65 |
+
pos_embed = torch.cat([additional_pos_embed, pos_embed], axis=0)
|
| 66 |
+
|
| 67 |
+
addition_input = torch.stack([latent_input, proprio_input], axis=0)
|
| 68 |
+
src = torch.cat([addition_input, src], axis=0)
|
| 69 |
+
|
| 70 |
+
tgt = torch.zeros_like(query_embed)
|
| 71 |
+
memory = self.encoder(src, src_key_padding_mask=mask, pos=pos_embed)
|
| 72 |
+
hs = self.decoder(tgt, memory, memory_key_padding_mask=mask,
|
| 73 |
+
pos=pos_embed, query_pos=query_embed)
|
| 74 |
+
hs = hs.transpose(1, 2)
|
| 75 |
+
return hs
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class TransformerEncoder(nn.Module):
|
| 79 |
+
|
| 80 |
+
def __init__(self, encoder_layer, num_layers, norm=None):
|
| 81 |
+
super().__init__()
|
| 82 |
+
self.layers = _get_clones(encoder_layer, num_layers)
|
| 83 |
+
self.num_layers = num_layers
|
| 84 |
+
self.norm = norm
|
| 85 |
+
|
| 86 |
+
def forward(self, src,
|
| 87 |
+
mask: Optional[Tensor] = None,
|
| 88 |
+
src_key_padding_mask: Optional[Tensor] = None,
|
| 89 |
+
pos: Optional[Tensor] = None):
|
| 90 |
+
output = src
|
| 91 |
+
|
| 92 |
+
for layer in self.layers:
|
| 93 |
+
output = layer(output, src_mask=mask,
|
| 94 |
+
src_key_padding_mask=src_key_padding_mask, pos=pos)
|
| 95 |
+
|
| 96 |
+
if self.norm is not None:
|
| 97 |
+
output = self.norm(output)
|
| 98 |
+
|
| 99 |
+
return output
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class TransformerDecoder(nn.Module):
|
| 103 |
+
|
| 104 |
+
def __init__(self, decoder_layer, num_layers, norm=None, return_intermediate=False):
|
| 105 |
+
super().__init__()
|
| 106 |
+
self.layers = _get_clones(decoder_layer, num_layers)
|
| 107 |
+
self.num_layers = num_layers
|
| 108 |
+
self.norm = norm
|
| 109 |
+
self.return_intermediate = return_intermediate
|
| 110 |
+
|
| 111 |
+
def forward(self, tgt, memory,
|
| 112 |
+
tgt_mask: Optional[Tensor] = None,
|
| 113 |
+
memory_mask: Optional[Tensor] = None,
|
| 114 |
+
tgt_key_padding_mask: Optional[Tensor] = None,
|
| 115 |
+
memory_key_padding_mask: Optional[Tensor] = None,
|
| 116 |
+
pos: Optional[Tensor] = None,
|
| 117 |
+
query_pos: Optional[Tensor] = None):
|
| 118 |
+
output = tgt
|
| 119 |
+
|
| 120 |
+
intermediate = []
|
| 121 |
+
|
| 122 |
+
for layer in self.layers:
|
| 123 |
+
output = layer(output, memory, tgt_mask=tgt_mask,
|
| 124 |
+
memory_mask=memory_mask,
|
| 125 |
+
tgt_key_padding_mask=tgt_key_padding_mask,
|
| 126 |
+
memory_key_padding_mask=memory_key_padding_mask,
|
| 127 |
+
pos=pos, query_pos=query_pos)
|
| 128 |
+
if self.return_intermediate:
|
| 129 |
+
intermediate.append(self.norm(output))
|
| 130 |
+
|
| 131 |
+
if self.norm is not None:
|
| 132 |
+
output = self.norm(output)
|
| 133 |
+
if self.return_intermediate:
|
| 134 |
+
intermediate.pop()
|
| 135 |
+
intermediate.append(output)
|
| 136 |
+
|
| 137 |
+
if self.return_intermediate:
|
| 138 |
+
return torch.stack(intermediate)
|
| 139 |
+
|
| 140 |
+
return output.unsqueeze(0)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
class TransformerEncoderLayer(nn.Module):
|
| 144 |
+
|
| 145 |
+
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1,
|
| 146 |
+
activation="relu", normalize_before=False):
|
| 147 |
+
super().__init__()
|
| 148 |
+
self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
|
| 149 |
+
# Implementation of Feedforward model
|
| 150 |
+
self.linear1 = nn.Linear(d_model, dim_feedforward)
|
| 151 |
+
self.dropout = nn.Dropout(dropout)
|
| 152 |
+
self.linear2 = nn.Linear(dim_feedforward, d_model)
|
| 153 |
+
|
| 154 |
+
self.norm1 = nn.LayerNorm(d_model)
|
| 155 |
+
self.norm2 = nn.LayerNorm(d_model)
|
| 156 |
+
self.dropout1 = nn.Dropout(dropout)
|
| 157 |
+
self.dropout2 = nn.Dropout(dropout)
|
| 158 |
+
|
| 159 |
+
self.activation = _get_activation_fn(activation)
|
| 160 |
+
self.normalize_before = normalize_before
|
| 161 |
+
|
| 162 |
+
def with_pos_embed(self, tensor, pos: Optional[Tensor]):
|
| 163 |
+
return tensor if pos is None else tensor + pos
|
| 164 |
+
|
| 165 |
+
def forward_post(self,
|
| 166 |
+
src,
|
| 167 |
+
src_mask: Optional[Tensor] = None,
|
| 168 |
+
src_key_padding_mask: Optional[Tensor] = None,
|
| 169 |
+
pos: Optional[Tensor] = None):
|
| 170 |
+
q = k = self.with_pos_embed(src, pos)
|
| 171 |
+
src2 = self.self_attn(q, k, value=src, attn_mask=src_mask,
|
| 172 |
+
key_padding_mask=src_key_padding_mask)[0]
|
| 173 |
+
src = src + self.dropout1(src2)
|
| 174 |
+
src = self.norm1(src)
|
| 175 |
+
src2 = self.linear2(self.dropout(self.activation(self.linear1(src))))
|
| 176 |
+
src = src + self.dropout2(src2)
|
| 177 |
+
src = self.norm2(src)
|
| 178 |
+
return src
|
| 179 |
+
|
| 180 |
+
def forward_pre(self, src,
|
| 181 |
+
src_mask: Optional[Tensor] = None,
|
| 182 |
+
src_key_padding_mask: Optional[Tensor] = None,
|
| 183 |
+
pos: Optional[Tensor] = None):
|
| 184 |
+
src2 = self.norm1(src)
|
| 185 |
+
q = k = self.with_pos_embed(src2, pos)
|
| 186 |
+
src2 = self.self_attn(q, k, value=src2, attn_mask=src_mask,
|
| 187 |
+
key_padding_mask=src_key_padding_mask)[0]
|
| 188 |
+
src = src + self.dropout1(src2)
|
| 189 |
+
src2 = self.norm2(src)
|
| 190 |
+
src2 = self.linear2(self.dropout(self.activation(self.linear1(src2))))
|
| 191 |
+
src = src + self.dropout2(src2)
|
| 192 |
+
return src
|
| 193 |
+
|
| 194 |
+
def forward(self, src,
|
| 195 |
+
src_mask: Optional[Tensor] = None,
|
| 196 |
+
src_key_padding_mask: Optional[Tensor] = None,
|
| 197 |
+
pos: Optional[Tensor] = None):
|
| 198 |
+
if self.normalize_before:
|
| 199 |
+
return self.forward_pre(src, src_mask, src_key_padding_mask, pos)
|
| 200 |
+
return self.forward_post(src, src_mask, src_key_padding_mask, pos)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
class TransformerDecoderLayer(nn.Module):
|
| 204 |
+
|
| 205 |
+
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1,
|
| 206 |
+
activation="relu", normalize_before=False):
|
| 207 |
+
super().__init__()
|
| 208 |
+
self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
|
| 209 |
+
self.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
|
| 210 |
+
# Implementation of Feedforward model
|
| 211 |
+
self.linear1 = nn.Linear(d_model, dim_feedforward)
|
| 212 |
+
self.dropout = nn.Dropout(dropout)
|
| 213 |
+
self.linear2 = nn.Linear(dim_feedforward, d_model)
|
| 214 |
+
|
| 215 |
+
self.norm1 = nn.LayerNorm(d_model)
|
| 216 |
+
self.norm2 = nn.LayerNorm(d_model)
|
| 217 |
+
self.norm3 = nn.LayerNorm(d_model)
|
| 218 |
+
self.dropout1 = nn.Dropout(dropout)
|
| 219 |
+
self.dropout2 = nn.Dropout(dropout)
|
| 220 |
+
self.dropout3 = nn.Dropout(dropout)
|
| 221 |
+
|
| 222 |
+
self.activation = _get_activation_fn(activation)
|
| 223 |
+
self.normalize_before = normalize_before
|
| 224 |
+
|
| 225 |
+
def with_pos_embed(self, tensor, pos: Optional[Tensor]):
|
| 226 |
+
return tensor if pos is None else tensor + pos
|
| 227 |
+
|
| 228 |
+
def forward_post(self, tgt, memory,
|
| 229 |
+
tgt_mask: Optional[Tensor] = None,
|
| 230 |
+
memory_mask: Optional[Tensor] = None,
|
| 231 |
+
tgt_key_padding_mask: Optional[Tensor] = None,
|
| 232 |
+
memory_key_padding_mask: Optional[Tensor] = None,
|
| 233 |
+
pos: Optional[Tensor] = None,
|
| 234 |
+
query_pos: Optional[Tensor] = None):
|
| 235 |
+
q = k = self.with_pos_embed(tgt, query_pos)
|
| 236 |
+
tgt2 = self.self_attn(q, k, value=tgt, attn_mask=tgt_mask,
|
| 237 |
+
key_padding_mask=tgt_key_padding_mask)[0]
|
| 238 |
+
tgt = tgt + self.dropout1(tgt2)
|
| 239 |
+
tgt = self.norm1(tgt)
|
| 240 |
+
tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt, query_pos),
|
| 241 |
+
key=self.with_pos_embed(memory, pos),
|
| 242 |
+
value=memory, attn_mask=memory_mask,
|
| 243 |
+
key_padding_mask=memory_key_padding_mask)[0]
|
| 244 |
+
tgt = tgt + self.dropout2(tgt2)
|
| 245 |
+
tgt = self.norm2(tgt)
|
| 246 |
+
tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt))))
|
| 247 |
+
tgt = tgt + self.dropout3(tgt2)
|
| 248 |
+
tgt = self.norm3(tgt)
|
| 249 |
+
return tgt
|
| 250 |
+
|
| 251 |
+
def forward_pre(self, tgt, memory,
|
| 252 |
+
tgt_mask: Optional[Tensor] = None,
|
| 253 |
+
memory_mask: Optional[Tensor] = None,
|
| 254 |
+
tgt_key_padding_mask: Optional[Tensor] = None,
|
| 255 |
+
memory_key_padding_mask: Optional[Tensor] = None,
|
| 256 |
+
pos: Optional[Tensor] = None,
|
| 257 |
+
query_pos: Optional[Tensor] = None):
|
| 258 |
+
tgt2 = self.norm1(tgt)
|
| 259 |
+
q = k = self.with_pos_embed(tgt2, query_pos)
|
| 260 |
+
tgt2 = self.self_attn(q, k, value=tgt2, attn_mask=tgt_mask,
|
| 261 |
+
key_padding_mask=tgt_key_padding_mask)[0]
|
| 262 |
+
tgt = tgt + self.dropout1(tgt2)
|
| 263 |
+
tgt2 = self.norm2(tgt)
|
| 264 |
+
tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt2, query_pos),
|
| 265 |
+
key=self.with_pos_embed(memory, pos),
|
| 266 |
+
value=memory, attn_mask=memory_mask,
|
| 267 |
+
key_padding_mask=memory_key_padding_mask)[0]
|
| 268 |
+
tgt = tgt + self.dropout2(tgt2)
|
| 269 |
+
tgt2 = self.norm3(tgt)
|
| 270 |
+
tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2))))
|
| 271 |
+
tgt = tgt + self.dropout3(tgt2)
|
| 272 |
+
return tgt
|
| 273 |
+
|
| 274 |
+
def forward(self, tgt, memory,
|
| 275 |
+
tgt_mask: Optional[Tensor] = None,
|
| 276 |
+
memory_mask: Optional[Tensor] = None,
|
| 277 |
+
tgt_key_padding_mask: Optional[Tensor] = None,
|
| 278 |
+
memory_key_padding_mask: Optional[Tensor] = None,
|
| 279 |
+
pos: Optional[Tensor] = None,
|
| 280 |
+
query_pos: Optional[Tensor] = None):
|
| 281 |
+
if self.normalize_before:
|
| 282 |
+
return self.forward_pre(tgt, memory, tgt_mask, memory_mask,
|
| 283 |
+
tgt_key_padding_mask, memory_key_padding_mask, pos, query_pos)
|
| 284 |
+
return self.forward_post(tgt, memory, tgt_mask, memory_mask,
|
| 285 |
+
tgt_key_padding_mask, memory_key_padding_mask, pos, query_pos)
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
class _XSAAttention(nn.Module):
|
| 289 |
+
"""XSA self-attention block adapted from the local LeRobot act_xsa plugin."""
|
| 290 |
+
|
| 291 |
+
def __init__(self, d_model, nhead, dropout=0.1):
|
| 292 |
+
super().__init__()
|
| 293 |
+
if d_model % nhead != 0:
|
| 294 |
+
raise ValueError(f"d_model={d_model} must be divisible by nhead={nhead}")
|
| 295 |
+
self.nhead = nhead
|
| 296 |
+
self.head_dim = d_model // nhead
|
| 297 |
+
self.scale = self.head_dim ** -0.5
|
| 298 |
+
|
| 299 |
+
self.q_proj = nn.Linear(d_model, d_model)
|
| 300 |
+
self.k_proj = nn.Linear(d_model, d_model)
|
| 301 |
+
self.v_proj = nn.Linear(d_model, d_model)
|
| 302 |
+
self.out_proj = nn.Linear(d_model, d_model)
|
| 303 |
+
self.gate_proj = nn.Linear(d_model, nhead)
|
| 304 |
+
self.q_norm = nn.RMSNorm(self.head_dim)
|
| 305 |
+
self.k_norm = nn.RMSNorm(self.head_dim)
|
| 306 |
+
self.dropout = nn.Dropout(dropout)
|
| 307 |
+
|
| 308 |
+
@staticmethod
|
| 309 |
+
def with_pos_embed(tensor, pos: Optional[Tensor]):
|
| 310 |
+
return tensor if pos is None else tensor + pos
|
| 311 |
+
|
| 312 |
+
def forward(self, x, pos: Optional[Tensor] = None,
|
| 313 |
+
attn_mask: Optional[Tensor] = None,
|
| 314 |
+
key_padding_mask: Optional[Tensor] = None):
|
| 315 |
+
q = k = self.with_pos_embed(x, pos)
|
| 316 |
+
q = self.q_proj(q)
|
| 317 |
+
k = self.k_proj(k)
|
| 318 |
+
v = self.v_proj(x)
|
| 319 |
+
|
| 320 |
+
seq_len, batch_size, _ = q.shape
|
| 321 |
+
q = q.view(seq_len, batch_size, self.nhead, self.head_dim).permute(1, 2, 0, 3)
|
| 322 |
+
k = k.view(seq_len, batch_size, self.nhead, self.head_dim).permute(1, 2, 0, 3)
|
| 323 |
+
v = v.view(seq_len, batch_size, self.nhead, self.head_dim).permute(1, 2, 0, 3)
|
| 324 |
+
|
| 325 |
+
q = self.q_norm(q)
|
| 326 |
+
k = self.k_norm(k)
|
| 327 |
+
attn_weights = torch.matmul(q, k.transpose(-2, -1)) * self.scale
|
| 328 |
+
if attn_mask is not None:
|
| 329 |
+
attn_weights = attn_weights + attn_mask
|
| 330 |
+
if key_padding_mask is not None:
|
| 331 |
+
attn_weights = attn_weights.masked_fill(
|
| 332 |
+
key_padding_mask.unsqueeze(1).unsqueeze(2), float("-inf")
|
| 333 |
+
)
|
| 334 |
+
attn_weights = F.softmax(attn_weights, dim=-1)
|
| 335 |
+
attn_weights = self.dropout(attn_weights)
|
| 336 |
+
|
| 337 |
+
y = torch.matmul(attn_weights, v)
|
| 338 |
+
v_norm = F.normalize(v, dim=-1)
|
| 339 |
+
projection = (y * v_norm).sum(dim=-1, keepdim=True)
|
| 340 |
+
y = y - projection * v_norm
|
| 341 |
+
|
| 342 |
+
gate = self.gate_proj(x).sigmoid().permute(1, 2, 0).unsqueeze(-1)
|
| 343 |
+
y = y * gate
|
| 344 |
+
y = y.permute(2, 0, 1, 3).contiguous().view(seq_len, batch_size, -1)
|
| 345 |
+
return self.out_proj(y)
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
class XSATransformerEncoderLayer(nn.Module):
|
| 349 |
+
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1,
|
| 350 |
+
activation="relu", normalize_before=False):
|
| 351 |
+
super().__init__()
|
| 352 |
+
self.self_attn = _XSAAttention(d_model, nhead, dropout=dropout)
|
| 353 |
+
self.linear1 = nn.Linear(d_model, dim_feedforward * 2)
|
| 354 |
+
self.dropout = nn.Dropout(dropout)
|
| 355 |
+
self.linear2 = nn.Linear(dim_feedforward, d_model)
|
| 356 |
+
self.norm1 = nn.RMSNorm(d_model)
|
| 357 |
+
self.norm2 = nn.RMSNorm(d_model)
|
| 358 |
+
self.dropout1 = nn.Dropout(dropout)
|
| 359 |
+
self.dropout2 = nn.Dropout(dropout)
|
| 360 |
+
|
| 361 |
+
def forward(self, src,
|
| 362 |
+
src_mask: Optional[Tensor] = None,
|
| 363 |
+
src_key_padding_mask: Optional[Tensor] = None,
|
| 364 |
+
pos: Optional[Tensor] = None):
|
| 365 |
+
skip = src
|
| 366 |
+
src2 = self.norm1(src)
|
| 367 |
+
src = skip + self.dropout1(
|
| 368 |
+
self.self_attn(src2, pos=pos, attn_mask=src_mask,
|
| 369 |
+
key_padding_mask=src_key_padding_mask)
|
| 370 |
+
)
|
| 371 |
+
skip = src
|
| 372 |
+
src2 = self.norm2(src)
|
| 373 |
+
gate, value = self.linear1(src2).chunk(2, dim=-1)
|
| 374 |
+
src2 = self.linear2(self.dropout(F.silu(gate) * value))
|
| 375 |
+
src = skip + self.dropout2(src2)
|
| 376 |
+
return src
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
class XSATransformerDecoderLayer(nn.Module):
|
| 380 |
+
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1,
|
| 381 |
+
activation="relu", normalize_before=False):
|
| 382 |
+
super().__init__()
|
| 383 |
+
self.self_attn = _XSAAttention(d_model, nhead, dropout=dropout)
|
| 384 |
+
self.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
|
| 385 |
+
self.linear1 = nn.Linear(d_model, dim_feedforward * 2)
|
| 386 |
+
self.dropout = nn.Dropout(dropout)
|
| 387 |
+
self.linear2 = nn.Linear(dim_feedforward, d_model)
|
| 388 |
+
self.norm1 = nn.RMSNorm(d_model)
|
| 389 |
+
self.norm2 = nn.RMSNorm(d_model)
|
| 390 |
+
self.norm3 = nn.RMSNorm(d_model)
|
| 391 |
+
self.dropout1 = nn.Dropout(dropout)
|
| 392 |
+
self.dropout2 = nn.Dropout(dropout)
|
| 393 |
+
self.dropout3 = nn.Dropout(dropout)
|
| 394 |
+
|
| 395 |
+
@staticmethod
|
| 396 |
+
def with_pos_embed(tensor, pos: Optional[Tensor]):
|
| 397 |
+
return tensor if pos is None else tensor + pos
|
| 398 |
+
|
| 399 |
+
def forward(self, tgt, memory,
|
| 400 |
+
tgt_mask: Optional[Tensor] = None,
|
| 401 |
+
memory_mask: Optional[Tensor] = None,
|
| 402 |
+
tgt_key_padding_mask: Optional[Tensor] = None,
|
| 403 |
+
memory_key_padding_mask: Optional[Tensor] = None,
|
| 404 |
+
pos: Optional[Tensor] = None,
|
| 405 |
+
query_pos: Optional[Tensor] = None):
|
| 406 |
+
skip = tgt
|
| 407 |
+
tgt2 = self.norm1(tgt)
|
| 408 |
+
tgt = skip + self.dropout1(
|
| 409 |
+
self.self_attn(tgt2, pos=query_pos, attn_mask=tgt_mask,
|
| 410 |
+
key_padding_mask=tgt_key_padding_mask)
|
| 411 |
+
)
|
| 412 |
+
|
| 413 |
+
skip = tgt
|
| 414 |
+
tgt2 = self.norm2(tgt)
|
| 415 |
+
tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt2, query_pos),
|
| 416 |
+
key=self.with_pos_embed(memory, pos),
|
| 417 |
+
value=memory, attn_mask=memory_mask,
|
| 418 |
+
key_padding_mask=memory_key_padding_mask)[0]
|
| 419 |
+
tgt = skip + self.dropout2(tgt2)
|
| 420 |
+
|
| 421 |
+
skip = tgt
|
| 422 |
+
tgt2 = self.norm3(tgt)
|
| 423 |
+
gate, value = self.linear1(tgt2).chunk(2, dim=-1)
|
| 424 |
+
tgt2 = self.linear2(self.dropout(F.silu(gate) * value))
|
| 425 |
+
tgt = skip + self.dropout3(tgt2)
|
| 426 |
+
return tgt
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
def _get_clones(module, N):
|
| 430 |
+
return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
def build_transformer(args):
|
| 434 |
+
return Transformer(
|
| 435 |
+
d_model=args.hidden_dim,
|
| 436 |
+
dropout=args.dropout,
|
| 437 |
+
nhead=args.nheads,
|
| 438 |
+
dim_feedforward=args.dim_feedforward,
|
| 439 |
+
num_encoder_layers=args.enc_layers,
|
| 440 |
+
num_decoder_layers=args.dec_layers,
|
| 441 |
+
normalize_before=args.pre_norm,
|
| 442 |
+
return_intermediate_dec=True,
|
| 443 |
+
use_xsa=getattr(args, "use_xsa", False),
|
| 444 |
+
)
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def _get_activation_fn(activation):
|
| 448 |
+
"""Return an activation function given a string"""
|
| 449 |
+
if activation == "relu":
|
| 450 |
+
return F.relu
|
| 451 |
+
if activation == "gelu":
|
| 452 |
+
return F.gelu
|
| 453 |
+
if activation == "glu":
|
| 454 |
+
return F.glu
|
| 455 |
+
raise RuntimeError(F"activation should be relu/gelu, not {activation}.")
|
demo/act/detr/utils.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from torch.utils.data.sampler import Sampler
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch
|
| 4 |
+
import torch.distributed as dist
|
| 5 |
+
from torch import Tensor
|
| 6 |
+
from h5py import File, Group, Dataset
|
| 7 |
+
from typing import Optional
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class NestedTensor(object):
|
| 11 |
+
def __init__(self, tensors, mask: Optional[Tensor]):
|
| 12 |
+
self.tensors = tensors
|
| 13 |
+
self.mask = mask
|
| 14 |
+
|
| 15 |
+
def to(self, device):
|
| 16 |
+
# type: (Device) -> NestedTensor # noqa
|
| 17 |
+
cast_tensor = self.tensors.to(device)
|
| 18 |
+
mask = self.mask
|
| 19 |
+
if mask is not None:
|
| 20 |
+
assert mask is not None
|
| 21 |
+
cast_mask = mask.to(device)
|
| 22 |
+
else:
|
| 23 |
+
cast_mask = None
|
| 24 |
+
return NestedTensor(cast_tensor, cast_mask)
|
| 25 |
+
|
| 26 |
+
def decompose(self):
|
| 27 |
+
return self.tensors, self.mask
|
| 28 |
+
|
| 29 |
+
def __repr__(self):
|
| 30 |
+
return str(self.tensors)
|
| 31 |
+
|
| 32 |
+
def is_dist_avail_and_initialized():
|
| 33 |
+
if not dist.is_available():
|
| 34 |
+
return False
|
| 35 |
+
if not dist.is_initialized():
|
| 36 |
+
return False
|
| 37 |
+
return True
|
| 38 |
+
|
| 39 |
+
def get_rank():
|
| 40 |
+
if not is_dist_avail_and_initialized():
|
| 41 |
+
return 0
|
| 42 |
+
return dist.get_rank()
|
| 43 |
+
|
| 44 |
+
def is_main_process():
|
| 45 |
+
return get_rank() == 0
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class IterationBasedBatchSampler(Sampler):
|
| 49 |
+
"""Wraps a BatchSampler.
|
| 50 |
+
Resampling from it until a specified number of iterations have been sampled
|
| 51 |
+
References:
|
| 52 |
+
https://github.com/facebookresearch/maskrcnn-benchmark/blob/master/maskrcnn_benchmark/data/samplers/iteration_based_batch_sampler.py
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
def __init__(self, batch_sampler, num_iterations, start_iter=0):
|
| 56 |
+
self.batch_sampler = batch_sampler
|
| 57 |
+
self.num_iterations = num_iterations
|
| 58 |
+
self.start_iter = start_iter
|
| 59 |
+
|
| 60 |
+
def __iter__(self):
|
| 61 |
+
iteration = self.start_iter
|
| 62 |
+
while iteration < self.num_iterations:
|
| 63 |
+
# if the underlying sampler has a set_epoch method, like
|
| 64 |
+
# DistributedSampler, used for making each process see
|
| 65 |
+
# a different split of the dataset, then set it
|
| 66 |
+
if hasattr(self.batch_sampler.sampler, "set_epoch"):
|
| 67 |
+
self.batch_sampler.sampler.set_epoch(iteration)
|
| 68 |
+
for batch in self.batch_sampler:
|
| 69 |
+
yield batch
|
| 70 |
+
iteration += 1
|
| 71 |
+
if iteration >= self.num_iterations:
|
| 72 |
+
break
|
| 73 |
+
|
| 74 |
+
def __len__(self):
|
| 75 |
+
return self.num_iterations - self.start_iter
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def worker_init_fn(worker_id, base_seed=None):
|
| 79 |
+
"""The function is designed for pytorch multi-process dataloader.
|
| 80 |
+
Note that we use the pytorch random generator to generate a base_seed.
|
| 81 |
+
Please try to be consistent.
|
| 82 |
+
References:
|
| 83 |
+
https://pytorch.org/docs/stable/notes/faq.html#dataloader-workers-random-seed
|
| 84 |
+
"""
|
| 85 |
+
if base_seed is None:
|
| 86 |
+
base_seed = torch.IntTensor(1).random_().item()
|
| 87 |
+
# print(worker_id, base_seed)
|
| 88 |
+
np.random.seed(base_seed + worker_id)
|
| 89 |
+
|
| 90 |
+
TARGET_KEY_TO_SOURCE_KEY = {
|
| 91 |
+
'states': 'env_states',
|
| 92 |
+
'observations': 'obs',
|
| 93 |
+
'success': 'success',
|
| 94 |
+
'next_observations': 'obs',
|
| 95 |
+
# 'dones': 'dones',
|
| 96 |
+
# 'rewards': 'rewards',
|
| 97 |
+
'actions': 'actions',
|
| 98 |
+
}
|
| 99 |
+
def load_content_from_h5_file(file):
|
| 100 |
+
if isinstance(file, (File, Group)):
|
| 101 |
+
return {key: load_content_from_h5_file(file[key]) for key in list(file.keys())}
|
| 102 |
+
elif isinstance(file, Dataset):
|
| 103 |
+
return file[()]
|
| 104 |
+
else:
|
| 105 |
+
raise NotImplementedError(f"Unspported h5 file type: {type(file)}")
|
| 106 |
+
|
| 107 |
+
def load_hdf5(path, ):
|
| 108 |
+
print('Loading HDF5 file', path)
|
| 109 |
+
file = File(path, 'r')
|
| 110 |
+
ret = load_content_from_h5_file(file)
|
| 111 |
+
file.close()
|
| 112 |
+
print('Loaded')
|
| 113 |
+
return ret
|
| 114 |
+
|
| 115 |
+
def load_traj_hdf5(path, num_traj=None):
|
| 116 |
+
print('Loading HDF5 file', path)
|
| 117 |
+
file = File(path, 'r')
|
| 118 |
+
keys = list(file.keys())
|
| 119 |
+
if num_traj is not None:
|
| 120 |
+
assert num_traj <= len(keys), f"num_traj: {num_traj} > len(keys): {len(keys)}"
|
| 121 |
+
keys = sorted(keys, key=lambda x: int(x.split('_')[-1]))
|
| 122 |
+
keys = keys[:num_traj]
|
| 123 |
+
ret = {
|
| 124 |
+
key: load_content_from_h5_file(file[key]) for key in keys
|
| 125 |
+
}
|
| 126 |
+
file.close()
|
| 127 |
+
print('Loaded')
|
| 128 |
+
return ret
|
| 129 |
+
def load_demo_dataset(path, keys=['observations', 'actions'], num_traj=None, concat=True):
|
| 130 |
+
# assert num_traj is None
|
| 131 |
+
raw_data = load_traj_hdf5(path, num_traj)
|
| 132 |
+
# raw_data has keys like: ['traj_0', 'traj_1', ...]
|
| 133 |
+
# raw_data['traj_0'] has keys like: ['actions', 'dones', 'env_states', 'infos', ...]
|
| 134 |
+
_traj = raw_data['traj_0']
|
| 135 |
+
for key in keys:
|
| 136 |
+
source_key = TARGET_KEY_TO_SOURCE_KEY[key]
|
| 137 |
+
assert source_key in _traj, f"key: {source_key} not in traj_0: {_traj.keys()}"
|
| 138 |
+
dataset = {}
|
| 139 |
+
for target_key in keys:
|
| 140 |
+
# if 'next' in target_key:
|
| 141 |
+
# raise NotImplementedError('Please carefully deal with the length of trajectory')
|
| 142 |
+
source_key = TARGET_KEY_TO_SOURCE_KEY[target_key]
|
| 143 |
+
dataset[target_key] = [ raw_data[idx][source_key] for idx in raw_data ]
|
| 144 |
+
if isinstance(dataset[target_key][0], np.ndarray) and concat:
|
| 145 |
+
if target_key in ['observations', 'states'] and \
|
| 146 |
+
len(dataset[target_key][0]) > len(raw_data['traj_0']['actions']):
|
| 147 |
+
dataset[target_key] = np.concatenate([
|
| 148 |
+
t[:-1] for t in dataset[target_key]
|
| 149 |
+
], axis=0)
|
| 150 |
+
elif target_key in ['next_observations', 'next_states'] and \
|
| 151 |
+
len(dataset[target_key][0]) > len(raw_data['traj_0']['actions']):
|
| 152 |
+
dataset[target_key] = np.concatenate([
|
| 153 |
+
t[1:] for t in dataset[target_key]
|
| 154 |
+
], axis=0)
|
| 155 |
+
else:
|
| 156 |
+
dataset[target_key] = np.concatenate(dataset[target_key], axis=0)
|
| 157 |
+
|
| 158 |
+
print('Load', target_key, dataset[target_key].shape)
|
| 159 |
+
else:
|
| 160 |
+
print('Load', target_key, len(dataset[target_key]), type(dataset[target_key][0]))
|
| 161 |
+
return dataset
|
scripts/act/baseline.sh
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
seed=1
|
| 2 |
+
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
| 3 |
+
demo_path="$SCRIPT_DIR/../../datasets/atec_task_e/trajectory_filtered.hdf5"
|
| 4 |
+
|
| 5 |
+
echo "$demo_path"
|
| 6 |
+
total_iters=100000
|
| 7 |
+
batch_size=256
|
| 8 |
+
log_freq=1000
|
| 9 |
+
save_freq=10000
|
| 10 |
+
wandb_entity=""
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
# RGB based
|
| 14 |
+
for demos in 100; do
|
| 15 |
+
python train_task_e.py \
|
| 16 |
+
--demo_path $demo_path \
|
| 17 |
+
--num_demos $demos \
|
| 18 |
+
--include_rgb \
|
| 19 |
+
--total_iters $total_iters \
|
| 20 |
+
--batch_size $batch_size \
|
| 21 |
+
--log_freq $log_freq \
|
| 22 |
+
--save_freq $save_freq \
|
| 23 |
+
--seed $seed \
|
| 24 |
+
--exp_name act-task-e-rgb-${demos}demos-seed${seed} \
|
| 25 |
+
--wandb_entity $wandb_entity \
|
| 26 |
+
--track
|
| 27 |
+
done
|
scripts/act/cli_args.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CLI argument definitions for Task E demo collection.
|
| 2 |
+
"""
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def add_collect_demo_args(parser) -> None:
|
| 6 |
+
parser.add_argument(
|
| 7 |
+
"--num_demos", type=int, default=50,
|
| 8 |
+
help="Number of successful demos to collect.",
|
| 9 |
+
)
|
| 10 |
+
parser.add_argument(
|
| 11 |
+
"--output_dir", type=str, default="./datasets/atec_task_e",
|
| 12 |
+
help="Directory to save trajectory.hdf5 and trajectory.json.",
|
| 13 |
+
)
|
| 14 |
+
parser.add_argument(
|
| 15 |
+
"--pick_objects", type=int, nargs="+", default=[3, 2, 1],
|
| 16 |
+
metavar="N",
|
| 17 |
+
help="Which objects to pick, in execution order. Default clears near-to-far: 3 2 1.",
|
| 18 |
+
)
|
| 19 |
+
parser.add_argument(
|
| 20 |
+
"--save_video", action="store_true", default=False,
|
| 21 |
+
help="Save an MP4 per demo for visualization "
|
| 22 |
+
"(requires: pip install imageio imageio-ffmpeg).",
|
| 23 |
+
)
|
| 24 |
+
parser.add_argument(
|
| 25 |
+
"--video_dir", type=str, default=None,
|
| 26 |
+
help="Output directory for MP4 files. Defaults to <output_dir>/videos/.",
|
| 27 |
+
)
|
| 28 |
+
parser.add_argument(
|
| 29 |
+
"--save_images", action="store_true", default=False,
|
| 30 |
+
help="Save raw RGB frames into HDF5 under traj_N/images/rgb (T,H,W,3) "
|
| 31 |
+
"for ACT RGBD training. Shares the camera with --save_video.",
|
| 32 |
+
)
|
| 33 |
+
parser.add_argument(
|
| 34 |
+
"--only_success", action="store_true", default=False,
|
| 35 |
+
help="Discard demos where not all picked objects ended up in the basket.",
|
| 36 |
+
)
|
| 37 |
+
parser.add_argument(
|
| 38 |
+
"--max_attempts", type=int, default=0,
|
| 39 |
+
help="Stop after this many attempts even if num_demos is not reached. 0 means unlimited.",
|
| 40 |
+
)
|
| 41 |
+
parser.add_argument(
|
| 42 |
+
"--trace", action="store_true", default=False,
|
| 43 |
+
help="Print compact grasp/basket diagnostics for failed scripted demos.",
|
| 44 |
+
)
|
| 45 |
+
parser.add_argument(
|
| 46 |
+
"--abort_failed_lift", action="store_true", default=False,
|
| 47 |
+
help="Abort an attempt as soon as the current object fails the post-LIFT height gate.",
|
| 48 |
+
)
|
scripts/act/collect_demos_task_e.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Scripted oracle data collection for Task E (pick-and-place).
|
| 2 |
+
|
| 3 |
+
Usage
|
| 4 |
+
-----
|
| 5 |
+
# NOTE: only for object 3 now, if you want to pick objects 1 and 2, please modify the distance accordingly.
|
| 6 |
+
python scripts/act/collect_demos_task_e.py --pick_objects 3 --num_demos 50 --headless
|
| 7 |
+
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import argparse
|
| 11 |
+
import os
|
| 12 |
+
import sys
|
| 13 |
+
|
| 14 |
+
# sys.path.insert(0, os.path.dirname(__file__))
|
| 15 |
+
|
| 16 |
+
from isaaclab.app import AppLauncher
|
| 17 |
+
from cli_args import add_collect_demo_args
|
| 18 |
+
|
| 19 |
+
parser = argparse.ArgumentParser(description="Collect Task E demonstrations for ACT.")
|
| 20 |
+
add_collect_demo_args(parser)
|
| 21 |
+
AppLauncher.add_app_launcher_args(parser)
|
| 22 |
+
args_cli = parser.parse_args()
|
| 23 |
+
|
| 24 |
+
if args_cli.save_video or args_cli.save_images:
|
| 25 |
+
args_cli.enable_cameras = True
|
| 26 |
+
|
| 27 |
+
app_launcher = AppLauncher(args_cli)
|
| 28 |
+
simulation_app = app_launcher.app
|
| 29 |
+
|
| 30 |
+
import h5py
|
| 31 |
+
import json
|
| 32 |
+
import numpy as np
|
| 33 |
+
|
| 34 |
+
from isaaclab.actuators import ImplicitActuatorCfg
|
| 35 |
+
from isaaclab.envs import ManagerBasedRLEnv
|
| 36 |
+
from isaaclab.sensors import CameraCfg
|
| 37 |
+
import isaaclab.sim as sim_utils
|
| 38 |
+
|
| 39 |
+
from atec_rl_lab.tasks.task_e.env_cfg import TaskEEnvPiperCfg
|
| 40 |
+
from atec_rl_lab.utils import CartesianController
|
| 41 |
+
|
| 42 |
+
from task_e.config import (
|
| 43 |
+
EE_BODY_NAME, ARM_JOINT_NAMES, GRIPPER_JOINT_NAMES,
|
| 44 |
+
ACT_STIFFNESS, ACT_DAMPING, ACT_EFFORT_LIMIT, ACT_VEL_LIMIT,
|
| 45 |
+
CAM_H, CAM_W, CAM_POS, CAM_ROT,
|
| 46 |
+
)
|
| 47 |
+
from task_e.collector import basket_status_lines, check_objects_in_basket, collect_one_demo
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _trace_lines(data: dict | None, pick_objects: list[int]) -> list[str]:
|
| 51 |
+
if data is None or "trace" not in data:
|
| 52 |
+
return []
|
| 53 |
+
lines = []
|
| 54 |
+
for obj_idx in pick_objects:
|
| 55 |
+
tr = data["trace"].get(f"object_{obj_idx}", {})
|
| 56 |
+
if not tr:
|
| 57 |
+
continue
|
| 58 |
+
states = tr.get("states", {})
|
| 59 |
+
close = states.get("CLOSE", {})
|
| 60 |
+
lift = states.get("LIFT", {})
|
| 61 |
+
transport = states.get("TRANSPORT", {})
|
| 62 |
+
def _vec(value):
|
| 63 |
+
if value is None:
|
| 64 |
+
return "none"
|
| 65 |
+
return "(" + ",".join(f"{float(v):+.3f}" for v in value[:3]) + ")"
|
| 66 |
+
lines.append(
|
| 67 |
+
f"object_{obj_idx}: z_gain={float(tr.get('z_gain', 0.0)):.3f} "
|
| 68 |
+
f"lifted={tr.get('lifted')} reward_lifted={tr.get('reward_lifted')} "
|
| 69 |
+
f"gap_close={float(close.get('min_gripper_gap', 999.0)):.3f} "
|
| 70 |
+
f"finger_close={float(close.get('min_finger_center_dist', 999.0)):.3f} "
|
| 71 |
+
f"finger_vec_close={_vec(close.get('min_finger_center_vec'))} "
|
| 72 |
+
f"gap_lift={float(lift.get('min_gripper_gap', 999.0)):.3f} "
|
| 73 |
+
f"finger_gap={float(lift.get('min_finger_body_gap', 999.0)):.3f} "
|
| 74 |
+
f"finger_lift={float(lift.get('min_finger_center_dist', 999.0)):.3f} "
|
| 75 |
+
f"finger_vec_lift={_vec(lift.get('min_finger_center_vec'))} "
|
| 76 |
+
f"finger_transport={float(transport.get('min_finger_center_dist', 999.0)):.3f} "
|
| 77 |
+
f"ee_vec_lift={_vec(lift.get('min_ee_vec'))} "
|
| 78 |
+
f"basket_inside={tr.get('basket_inside')}"
|
| 79 |
+
)
|
| 80 |
+
return lines
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def build_env(pick_objects: list[int], need_camera: bool) -> ManagerBasedRLEnv:
|
| 84 |
+
import time
|
| 85 |
+
cfg = TaskEEnvPiperCfg()
|
| 86 |
+
cfg.seed = int(time.time_ns() % (2**31)) # random seed each call
|
| 87 |
+
cfg.scene.num_envs = 1
|
| 88 |
+
cfg.episode_length_s = 80.0 * len(pick_objects) + 30.0
|
| 89 |
+
if not need_camera:
|
| 90 |
+
cfg.scene.video_cam = None
|
| 91 |
+
cfg.scene.ee_camera = None
|
| 92 |
+
cfg.scene.ee_dual_camera = None
|
| 93 |
+
cfg.scene.head_camera = None
|
| 94 |
+
cfg.observations.image = None
|
| 95 |
+
cfg.scene.robot.actuators["default"] = ImplicitActuatorCfg(
|
| 96 |
+
joint_names_expr=[".*"],
|
| 97 |
+
effort_limit=ACT_EFFORT_LIMIT,
|
| 98 |
+
velocity_limit=ACT_VEL_LIMIT,
|
| 99 |
+
stiffness=ACT_STIFFNESS,
|
| 100 |
+
damping=ACT_DAMPING,
|
| 101 |
+
)
|
| 102 |
+
# if need_camera:
|
| 103 |
+
# cfg.scene.video_cam = CameraCfg(
|
| 104 |
+
# prim_path="{ENV_REGEX_NS}/video_cam",
|
| 105 |
+
# update_period=0.0,
|
| 106 |
+
# height=CAM_H, width=CAM_W,
|
| 107 |
+
# data_types=["rgb"],
|
| 108 |
+
# spawn=sim_utils.PinholeCameraCfg(
|
| 109 |
+
# focal_length=24.0, focus_distance=400.0,
|
| 110 |
+
# horizontal_aperture=20.955, clipping_range=(0.1, 100.0),
|
| 111 |
+
# ),
|
| 112 |
+
# offset=CameraCfg.OffsetCfg(pos=CAM_POS, rot=CAM_ROT, convention="world"),
|
| 113 |
+
# )
|
| 114 |
+
return ManagerBasedRLEnv(cfg)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def init_output(output_dir: str) -> tuple[str, str]:
|
| 118 |
+
"""Create output directory, wipe any existing trajectory.hdf5, write JSON metadata."""
|
| 119 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 120 |
+
traj_path = os.path.join(output_dir, "trajectory.hdf5")
|
| 121 |
+
json_path = os.path.join(output_dir, "trajectory.json")
|
| 122 |
+
with h5py.File(traj_path, "w"): # truncate / create fresh
|
| 123 |
+
pass
|
| 124 |
+
with open(json_path, "w") as fh:
|
| 125 |
+
json.dump({"env_info": {"env_kwargs": {"control_mode": "pd_joint_pos"}}}, fh)
|
| 126 |
+
return traj_path, json_path
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def save_traj(traj_path: str, traj_idx: int, data: dict,
|
| 130 |
+
save_images: bool) -> None:
|
| 131 |
+
"""Append one trajectory group to the consolidated HDF5."""
|
| 132 |
+
with h5py.File(traj_path, "a") as f:
|
| 133 |
+
grp = f.create_group(f"traj_{traj_idx}")
|
| 134 |
+
grp.create_dataset("obs", data=data["qpos"], compression="gzip")
|
| 135 |
+
grp.create_dataset("actions", data=data["action"], compression="gzip")
|
| 136 |
+
grp.create_dataset("qvel", data=data["qvel"], compression="gzip")
|
| 137 |
+
grp.create_dataset("ee_pos", data=data["ee_pos"], compression="gzip")
|
| 138 |
+
grp.create_dataset("ee_quat", data=data["ee_quat"], compression="gzip")
|
| 139 |
+
if save_images and "frames" in data:
|
| 140 |
+
grp.create_group("images").create_dataset(
|
| 141 |
+
"rgb", data=data["frames"], compression="gzip"
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def main() -> None:
|
| 146 |
+
pick_objects = list(dict.fromkeys(args_cli.pick_objects))
|
| 147 |
+
need_camera = args_cli.save_video or args_cli.save_images
|
| 148 |
+
|
| 149 |
+
env = build_env(pick_objects, need_camera)
|
| 150 |
+
dev = env.unwrapped.device
|
| 151 |
+
camera = env.unwrapped.scene["video_cam"] if need_camera else None
|
| 152 |
+
|
| 153 |
+
robot = env.unwrapped.scene.articulations["robot"]
|
| 154 |
+
arm_ids, _ = robot.find_joints(ARM_JOINT_NAMES)
|
| 155 |
+
gripper_ids, _ = robot.find_joints(GRIPPER_JOINT_NAMES)
|
| 156 |
+
ik_ctrl = CartesianController(
|
| 157 |
+
robot=robot, ee_body_name=EE_BODY_NAME,
|
| 158 |
+
arm_joint_names=ARM_JOINT_NAMES,
|
| 159 |
+
num_envs=1, device=dev,
|
| 160 |
+
command_type="pose",
|
| 161 |
+
lambda_val=0.05,
|
| 162 |
+
max_joint_delta=0.2,
|
| 163 |
+
)
|
| 164 |
+
default_jpos = robot.data.default_joint_pos.clone()
|
| 165 |
+
|
| 166 |
+
video_dir = None
|
| 167 |
+
imageio = None
|
| 168 |
+
if args_cli.save_video:
|
| 169 |
+
video_dir = args_cli.video_dir or os.path.join(args_cli.output_dir, "videos")
|
| 170 |
+
os.makedirs(video_dir, exist_ok=True)
|
| 171 |
+
import imageio as _io
|
| 172 |
+
imageio = _io
|
| 173 |
+
|
| 174 |
+
traj_path, _ = init_output(args_cli.output_dir)
|
| 175 |
+
rng = np.random.default_rng() # unseeded → different positions every run
|
| 176 |
+
|
| 177 |
+
n_ok = 0
|
| 178 |
+
attempt = 0
|
| 179 |
+
while n_ok < args_cli.num_demos:
|
| 180 |
+
attempt += 1
|
| 181 |
+
if args_cli.max_attempts and attempt > args_cli.max_attempts:
|
| 182 |
+
print(f"\n[WARN] Reached --max_attempts={args_cli.max_attempts}; collected {n_ok} demos.")
|
| 183 |
+
break
|
| 184 |
+
print(f"\n[INFO] Demo {n_ok + 1}/{args_cli.num_demos} (attempt {attempt})")
|
| 185 |
+
|
| 186 |
+
data = collect_one_demo(
|
| 187 |
+
env, robot, ik_ctrl,
|
| 188 |
+
arm_ids, gripper_ids,
|
| 189 |
+
pick_objects, dev,
|
| 190 |
+
default_jpos=default_jpos,
|
| 191 |
+
rng=rng,
|
| 192 |
+
camera=camera,
|
| 193 |
+
trace=args_cli.trace,
|
| 194 |
+
abort_failed_lift=args_cli.abort_failed_lift,
|
| 195 |
+
)
|
| 196 |
+
if data is None:
|
| 197 |
+
print("[WARN] Early termination — skipping.")
|
| 198 |
+
continue
|
| 199 |
+
|
| 200 |
+
if args_cli.only_success and not check_objects_in_basket(env, pick_objects):
|
| 201 |
+
print("[WARN] Objects not in basket — skipping (--only_success).")
|
| 202 |
+
for line in basket_status_lines(env, pick_objects):
|
| 203 |
+
print(f"[WARN] {line}")
|
| 204 |
+
for line in _trace_lines(data, pick_objects):
|
| 205 |
+
print(f"[TRACE] {line}")
|
| 206 |
+
continue
|
| 207 |
+
|
| 208 |
+
for line in _trace_lines(data, pick_objects):
|
| 209 |
+
print(f"[TRACE] {line}")
|
| 210 |
+
save_traj(traj_path, n_ok, data, args_cli.save_images)
|
| 211 |
+
|
| 212 |
+
T = len(data["qpos"])
|
| 213 |
+
notes = [f"{T} steps"]
|
| 214 |
+
if args_cli.save_video and "frames" in data:
|
| 215 |
+
vp = os.path.join(video_dir, f"demo_{n_ok:04d}.mp4")
|
| 216 |
+
imageio.mimwrite(vp, data["frames"], fps=50, quality=7)
|
| 217 |
+
notes.append(f"video → {vp}")
|
| 218 |
+
if args_cli.save_images and "frames" in data:
|
| 219 |
+
notes.append("images saved")
|
| 220 |
+
print(f"[INFO] traj_{n_ok}: {', '.join(notes)}")
|
| 221 |
+
n_ok += 1
|
| 222 |
+
|
| 223 |
+
print(f"\n[INFO] Collected {n_ok} demos → {traj_path}")
|
| 224 |
+
env.close()
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
if __name__ == "__main__":
|
| 228 |
+
main()
|
| 229 |
+
simulation_app.close()
|
scripts/act/eval_task_e_act.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Rollout evaluation for the Task-E ACT policy checkpoint."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
import time
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
|
| 9 |
+
from isaaclab.app import AppLauncher
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
parser = argparse.ArgumentParser(description="Evaluate ACT checkpoint on ATEC Task E.")
|
| 13 |
+
parser.add_argument(
|
| 14 |
+
"--checkpoint",
|
| 15 |
+
type=str,
|
| 16 |
+
default="runs/act-task-e-rgb-100demos-seed1/checkpoints/best_loss.pt",
|
| 17 |
+
help="ACT checkpoint path.",
|
| 18 |
+
)
|
| 19 |
+
parser.add_argument("--task", type=str, default="ATEC-TaskE-Piper")
|
| 20 |
+
parser.add_argument("--episodes", type=int, default=3)
|
| 21 |
+
parser.add_argument("--max_steps", type=int, default=1500)
|
| 22 |
+
parser.add_argument("--video_path", type=str, default=None, help="Optional MP4 output path for episode 1.")
|
| 23 |
+
parser.add_argument("--video_interval", type=int, default=2, help="Record every N env steps.")
|
| 24 |
+
parser.add_argument("--video_fps", type=int, default=25)
|
| 25 |
+
parser.add_argument("--seed", type=int, default=None)
|
| 26 |
+
parser.add_argument("--disable_fabric", action="store_true", default=False)
|
| 27 |
+
parser.add_argument("--debug", action="store_true", default=False)
|
| 28 |
+
parser.add_argument(
|
| 29 |
+
"--solution_module",
|
| 30 |
+
type=str,
|
| 31 |
+
default="solution_act",
|
| 32 |
+
help="Module under demo/ that provides AlgSolution, e.g. solution_act or solution_pca.",
|
| 33 |
+
)
|
| 34 |
+
AppLauncher.add_app_launcher_args(parser)
|
| 35 |
+
args_cli = parser.parse_args()
|
| 36 |
+
args_cli.enable_cameras = True
|
| 37 |
+
|
| 38 |
+
repo_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
|
| 39 |
+
checkpoint = os.path.abspath(args_cli.checkpoint)
|
| 40 |
+
os.environ["ATEC_ACT_POLICY_PATH"] = checkpoint
|
| 41 |
+
|
| 42 |
+
app_launcher = AppLauncher(args_cli)
|
| 43 |
+
simulation_app = app_launcher.app
|
| 44 |
+
|
| 45 |
+
import gymnasium as gym # noqa: E402
|
| 46 |
+
import torch # noqa: E402
|
| 47 |
+
|
| 48 |
+
from isaaclab.envs import DirectMARLEnv, multi_agent_to_single_agent # noqa: E402
|
| 49 |
+
from isaaclab_tasks.utils import parse_env_cfg # noqa: E402
|
| 50 |
+
|
| 51 |
+
import atec_rl_lab.tasks # noqa: F401, E402
|
| 52 |
+
|
| 53 |
+
demo_dir = os.path.join(repo_root, "demo")
|
| 54 |
+
if repo_root not in sys.path:
|
| 55 |
+
sys.path.insert(0, repo_root)
|
| 56 |
+
if demo_dir not in sys.path:
|
| 57 |
+
sys.path.insert(0, demo_dir)
|
| 58 |
+
from scripts.act.task_e.collector import basket_status_lines # noqa: E402
|
| 59 |
+
import importlib # noqa: E402
|
| 60 |
+
|
| 61 |
+
AlgSolution = importlib.import_module(args_cli.solution_module).AlgSolution
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _frame_from_obs(obs) -> object:
|
| 65 |
+
rgb = obs["image"]["video_rgb"]
|
| 66 |
+
if isinstance(rgb, torch.Tensor):
|
| 67 |
+
frame = rgb[0].detach().cpu()
|
| 68 |
+
if frame.ndim == 3 and frame.shape[0] in (3, 4):
|
| 69 |
+
frame = frame.permute(1, 2, 0)
|
| 70 |
+
if frame.shape[-1] == 4:
|
| 71 |
+
frame = frame[..., :3]
|
| 72 |
+
if frame.dtype != torch.uint8:
|
| 73 |
+
frame = (frame.float() * 255.0).clamp(0, 255).to(torch.uint8)
|
| 74 |
+
return frame.numpy()
|
| 75 |
+
return rgb[0]
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _resolve_video_path() -> str | None:
|
| 79 |
+
if args_cli.video_path is None:
|
| 80 |
+
return None
|
| 81 |
+
if args_cli.video_path:
|
| 82 |
+
return os.path.abspath(args_cli.video_path)
|
| 83 |
+
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 84 |
+
return os.path.join(repo_root, "logs", "videos", "task_e_act_eval", f"eval_{stamp}.mp4")
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def evaluate() -> list[dict[str, float]]:
|
| 88 |
+
if not os.path.exists(checkpoint):
|
| 89 |
+
raise FileNotFoundError(f"Checkpoint not found: {checkpoint}")
|
| 90 |
+
|
| 91 |
+
env_cfg = parse_env_cfg(
|
| 92 |
+
args_cli.task,
|
| 93 |
+
device=args_cli.device,
|
| 94 |
+
num_envs=1,
|
| 95 |
+
use_fabric=not args_cli.disable_fabric,
|
| 96 |
+
)
|
| 97 |
+
if args_cli.seed is not None:
|
| 98 |
+
env_cfg.seed = args_cli.seed
|
| 99 |
+
env = gym.make(args_cli.task, cfg=env_cfg)
|
| 100 |
+
if isinstance(env.unwrapped, DirectMARLEnv):
|
| 101 |
+
env = multi_agent_to_single_agent(env)
|
| 102 |
+
|
| 103 |
+
policy = AlgSolution()
|
| 104 |
+
video_path = _resolve_video_path()
|
| 105 |
+
writer = None
|
| 106 |
+
if video_path is not None:
|
| 107 |
+
import imageio.v2 as imageio
|
| 108 |
+
|
| 109 |
+
os.makedirs(os.path.dirname(video_path), exist_ok=True)
|
| 110 |
+
writer = imageio.get_writer(video_path, fps=args_cli.video_fps, quality=7)
|
| 111 |
+
print(f"[INFO] Recording episode 1 video to: {video_path}")
|
| 112 |
+
|
| 113 |
+
results = []
|
| 114 |
+
try:
|
| 115 |
+
for episode in range(args_cli.episodes):
|
| 116 |
+
reset_kwargs = {"seed": args_cli.seed + episode} if args_cli.seed is not None else {}
|
| 117 |
+
obs, _ = env.reset(**reset_kwargs)
|
| 118 |
+
policy.reset_episode()
|
| 119 |
+
total_reward = 0.0
|
| 120 |
+
elapsed_time = 0.0
|
| 121 |
+
steps = 0
|
| 122 |
+
done = False
|
| 123 |
+
start_wall = time.time()
|
| 124 |
+
if writer is not None and episode == 0:
|
| 125 |
+
writer.append_data(_frame_from_obs(obs))
|
| 126 |
+
|
| 127 |
+
while simulation_app.is_running() and steps < args_cli.max_steps:
|
| 128 |
+
with torch.inference_mode():
|
| 129 |
+
resp = policy.predicts(obs, total_reward)
|
| 130 |
+
if resp["giveup"]:
|
| 131 |
+
break
|
| 132 |
+
action = torch.as_tensor(resp["action"], dtype=torch.float32, device=args_cli.device).view(1, -1)
|
| 133 |
+
obs, reward, terminated, truncated, info = env.step(action)
|
| 134 |
+
|
| 135 |
+
sim_dt = info["Step_dt"]
|
| 136 |
+
total_reward += reward.mean().item() / sim_dt if isinstance(reward, torch.Tensor) else float(reward) / sim_dt
|
| 137 |
+
if isinstance(info, dict) and "Elapsed_Time" in info:
|
| 138 |
+
elapsed = info["Elapsed_Time"]
|
| 139 |
+
elapsed_time = elapsed.item() if hasattr(elapsed, "item") else float(elapsed)
|
| 140 |
+
else:
|
| 141 |
+
elapsed_time += env.unwrapped.step_dt
|
| 142 |
+
|
| 143 |
+
done = bool(terminated.item() or truncated.item())
|
| 144 |
+
steps += 1
|
| 145 |
+
if writer is not None and episode == 0 and steps % max(1, args_cli.video_interval) == 0:
|
| 146 |
+
writer.append_data(_frame_from_obs(obs))
|
| 147 |
+
if args_cli.debug and steps % 100 == 0:
|
| 148 |
+
print(f"[DEBUG] episode={episode + 1} step={steps} score={total_reward:.2f}")
|
| 149 |
+
if done:
|
| 150 |
+
break
|
| 151 |
+
|
| 152 |
+
result = {
|
| 153 |
+
"episode": episode + 1,
|
| 154 |
+
"score": float(total_reward),
|
| 155 |
+
"elapsed_time": float(elapsed_time),
|
| 156 |
+
"steps": float(steps),
|
| 157 |
+
"done": float(done),
|
| 158 |
+
"wall_time": time.time() - start_wall,
|
| 159 |
+
}
|
| 160 |
+
results.append(result)
|
| 161 |
+
try:
|
| 162 |
+
for line in basket_status_lines(env, [1, 2, 3]):
|
| 163 |
+
print(f"[BASKET] episode={episode + 1} {line}")
|
| 164 |
+
except Exception as exc:
|
| 165 |
+
if args_cli.debug:
|
| 166 |
+
print(f"[DEBUG] basket status unavailable: {exc}")
|
| 167 |
+
print(
|
| 168 |
+
"[RESULT] "
|
| 169 |
+
f"episode={result['episode']:.0f} "
|
| 170 |
+
f"score={result['score']:.2f} "
|
| 171 |
+
f"elapsed_time={result['elapsed_time']:.2f} "
|
| 172 |
+
f"steps={result['steps']:.0f} "
|
| 173 |
+
f"done={bool(result['done'])} "
|
| 174 |
+
f"wall_time={result['wall_time']:.1f}s"
|
| 175 |
+
)
|
| 176 |
+
finally:
|
| 177 |
+
if writer is not None:
|
| 178 |
+
writer.close()
|
| 179 |
+
env.close()
|
| 180 |
+
|
| 181 |
+
return results
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
if __name__ == "__main__":
|
| 185 |
+
try:
|
| 186 |
+
results = evaluate()
|
| 187 |
+
if results:
|
| 188 |
+
scores = torch.tensor([r["score"] for r in results], dtype=torch.float32)
|
| 189 |
+
print(f"[SUMMARY] episodes={len(results)} mean_score={scores.mean().item():.2f} best_score={scores.max().item():.2f}")
|
| 190 |
+
finally:
|
| 191 |
+
simulation_app.close()
|
scripts/act/filter_demos.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Filter HDF5 trajectory data: remove timesteps where the robot is not moving.
|
| 2 |
+
|
| 3 |
+
Uses consecutive action differences: steps where max|action[t] - action[t-1]| < threshold
|
| 4 |
+
are considered stationary and removed.
|
| 5 |
+
|
| 6 |
+
Usage:
|
| 7 |
+
python scripts/act/filter_demos.py \
|
| 8 |
+
--input datasets/atec_task_e/trajectory.hdf5 \
|
| 9 |
+
--output datasets/atec_task_e/trajectory_filtered.hdf5 \
|
| 10 |
+
--threshold 0.001
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import argparse
|
| 14 |
+
import h5py
|
| 15 |
+
import numpy as np
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def compute_moving_mask(actions, threshold):
|
| 19 |
+
"""Return a boolean mask (length T) marking steps where the robot is moving.
|
| 20 |
+
|
| 21 |
+
A step is 'moving' if max|action[t] - action[t-1]| >= threshold.
|
| 22 |
+
"""
|
| 23 |
+
delta = np.zeros_like(actions)
|
| 24 |
+
delta[1:] = np.abs(actions[1:] - actions[:-1])
|
| 25 |
+
return delta.max(axis=1) >= threshold
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def main():
|
| 29 |
+
parser = argparse.ArgumentParser(description="Filter stationary steps from demo HDF5.")
|
| 30 |
+
parser.add_argument("--input", type=str, required=True, help="Input HDF5 path")
|
| 31 |
+
parser.add_argument("--output", type=str, required=True, help="Output HDF5 path")
|
| 32 |
+
parser.add_argument("--threshold", type=float, default=0.001,
|
| 33 |
+
help="Steps with max|action_delta| < threshold are removed (default: 0.001)")
|
| 34 |
+
parser.add_argument("--dry_run", action="store_true",
|
| 35 |
+
help="Only print statistics, don't write output")
|
| 36 |
+
args = parser.parse_args()
|
| 37 |
+
|
| 38 |
+
total_before = 0
|
| 39 |
+
total_after = 0
|
| 40 |
+
|
| 41 |
+
with h5py.File(args.input, "r") as fin:
|
| 42 |
+
traj_keys = sorted(fin.keys(), key=lambda k: int(k.split("_")[1]))
|
| 43 |
+
|
| 44 |
+
if args.dry_run:
|
| 45 |
+
print(f"{'traj':>10s} {'before':>7s} {'after':>7s} {'removed':>7s} {'removed%':>8s}")
|
| 46 |
+
for key in traj_keys:
|
| 47 |
+
actions = fin[key]["actions"][:]
|
| 48 |
+
mask = compute_moving_mask(actions, args.threshold)
|
| 49 |
+
n_before = len(actions)
|
| 50 |
+
n_after = mask.sum()
|
| 51 |
+
total_before += n_before
|
| 52 |
+
total_after += n_after
|
| 53 |
+
print(f"{key:>10s} {n_before:7d} {n_after:7d} "
|
| 54 |
+
f"{n_before - n_after:7d} {(1 - n_after/n_before)*100:7.1f}%")
|
| 55 |
+
print(f"\nTotal: {total_before} → {total_after} "
|
| 56 |
+
f"(removed {total_before - total_after}, "
|
| 57 |
+
f"{(1 - total_after/total_before)*100:.1f}%)")
|
| 58 |
+
return
|
| 59 |
+
|
| 60 |
+
with h5py.File(args.output, "w") as fout:
|
| 61 |
+
for key in traj_keys:
|
| 62 |
+
grp_in = fin[key]
|
| 63 |
+
actions = grp_in["actions"][:]
|
| 64 |
+
mask = compute_moving_mask(actions, args.threshold)
|
| 65 |
+
|
| 66 |
+
n_before = len(actions)
|
| 67 |
+
n_after = mask.sum()
|
| 68 |
+
total_before += n_before
|
| 69 |
+
total_after += n_after
|
| 70 |
+
|
| 71 |
+
grp_out = fout.create_group(key)
|
| 72 |
+
|
| 73 |
+
# Filter all (T, ...) datasets with the same mask
|
| 74 |
+
for ds_name in grp_in.keys():
|
| 75 |
+
if ds_name == "images":
|
| 76 |
+
# Handle nested image group
|
| 77 |
+
img_grp = grp_out.create_group("images")
|
| 78 |
+
for img_key in grp_in["images"].keys():
|
| 79 |
+
data = grp_in[f"images/{img_key}"][:]
|
| 80 |
+
img_grp.create_dataset(img_key, data=data[mask], compression="gzip")
|
| 81 |
+
elif isinstance(grp_in[ds_name], h5py.Dataset):
|
| 82 |
+
data = grp_in[ds_name][:]
|
| 83 |
+
if data.shape[0] == n_before:
|
| 84 |
+
grp_out.create_dataset(ds_name, data=data[mask], compression="gzip")
|
| 85 |
+
else:
|
| 86 |
+
# Non-temporal dataset, copy as-is
|
| 87 |
+
grp_out.create_dataset(ds_name, data=data, compression="gzip")
|
| 88 |
+
|
| 89 |
+
print(f" {key}: {n_before} → {n_after} steps "
|
| 90 |
+
f"(removed {n_before - n_after})")
|
| 91 |
+
|
| 92 |
+
print(f"\nTotal: {total_before} → {total_after} "
|
| 93 |
+
f"(removed {total_before - total_after}, "
|
| 94 |
+
f"{(1 - total_after/total_before)*100:.1f}%)")
|
| 95 |
+
print(f"Saved to: {args.output}")
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
if __name__ == "__main__":
|
| 99 |
+
main()
|
scripts/act/run_task_e_pipeline.sh
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
| 5 |
+
PYTHON="${PYTHON:-/home/ubuntu/envs/genmanip-isaac5-py311/bin/python}"
|
| 6 |
+
ISAACLAB_SITE="/home/ubuntu/envs/genmanip-isaac5-py311/lib/python3.11/site-packages/isaaclab/source"
|
| 7 |
+
|
| 8 |
+
export OMNI_KIT_ACCEPT_EULA=YES
|
| 9 |
+
export PYTHONUNBUFFERED=1
|
| 10 |
+
export CUDA_VISIBLE_DEVICES="${CUDA_VISIBLE_DEVICES:-0}"
|
| 11 |
+
export PYTHONPATH="${ISAACLAB_SITE}/isaaclab:${ISAACLAB_SITE}/isaaclab_tasks:${ISAACLAB_SITE}/isaaclab_assets:${ISAACLAB_SITE}/isaaclab_rl:${ISAACLAB_SITE}/isaaclab_mimic:${ROOT_DIR}/source/atec_rl_lab:${ROOT_DIR}/scripts/act:${PYTHONPATH:-}"
|
| 12 |
+
|
| 13 |
+
cd "$ROOT_DIR"
|
| 14 |
+
|
| 15 |
+
DATA_DIR="${DATA_DIR:-datasets/atec_task_e}"
|
| 16 |
+
NUM_DEMOS="${NUM_DEMOS:-100}"
|
| 17 |
+
PICK_OBJECTS="${PICK_OBJECTS:-3 2 1}"
|
| 18 |
+
read -r -a PICK_OBJECTS_ARGS <<< "$PICK_OBJECTS"
|
| 19 |
+
MAX_ATTEMPTS="${MAX_ATTEMPTS:-0}"
|
| 20 |
+
TOTAL_ITERS="${TOTAL_ITERS:-100000}"
|
| 21 |
+
BATCH_SIZE="${BATCH_SIZE:-512}"
|
| 22 |
+
SEED="${SEED:-1}"
|
| 23 |
+
LOG_FREQ="${LOG_FREQ:-100}"
|
| 24 |
+
SAVE_FREQ="${SAVE_FREQ:-5000}"
|
| 25 |
+
RUN_NAME="${RUN_NAME:-act-task-e-rgb-${NUM_DEMOS}demos-seed${SEED}}"
|
| 26 |
+
RESUME_CHECKPOINT="${RESUME_CHECKPOINT:-}"
|
| 27 |
+
RESUME_ITER="${RESUME_ITER:-}"
|
| 28 |
+
|
| 29 |
+
RAW_DATA="${DATA_DIR}/trajectory.hdf5"
|
| 30 |
+
FILTERED_DATA="${DATA_DIR}/trajectory_filtered.hdf5"
|
| 31 |
+
|
| 32 |
+
mkdir -p "$DATA_DIR" logs
|
| 33 |
+
|
| 34 |
+
echo "[ATEC Task E] root: $ROOT_DIR"
|
| 35 |
+
echo "[ATEC Task E] python: $PYTHON"
|
| 36 |
+
echo "[ATEC Task E] data: $DATA_DIR"
|
| 37 |
+
echo "[ATEC Task E] demos: $NUM_DEMOS, pick_objects: ${PICK_OBJECTS_ARGS[*]}, batch: $BATCH_SIZE, iters: $TOTAL_ITERS"
|
| 38 |
+
|
| 39 |
+
if [[ ! -f "$RAW_DATA" ]]; then
|
| 40 |
+
"$PYTHON" -u scripts/act/collect_demos_task_e.py \
|
| 41 |
+
--pick_objects "${PICK_OBJECTS_ARGS[@]}" \
|
| 42 |
+
--num_demos "$NUM_DEMOS" \
|
| 43 |
+
--headless \
|
| 44 |
+
--enable_cameras \
|
| 45 |
+
--save_images \
|
| 46 |
+
--only_success \
|
| 47 |
+
--trace \
|
| 48 |
+
--abort_failed_lift \
|
| 49 |
+
--max_attempts "$MAX_ATTEMPTS" \
|
| 50 |
+
--output_dir "$DATA_DIR"
|
| 51 |
+
else
|
| 52 |
+
echo "[ATEC Task E] Found $RAW_DATA, skip collection."
|
| 53 |
+
fi
|
| 54 |
+
|
| 55 |
+
if [[ ! -f "$FILTERED_DATA" ]]; then
|
| 56 |
+
"$PYTHON" -u scripts/act/filter_demos.py \
|
| 57 |
+
--input "$RAW_DATA" \
|
| 58 |
+
--output "$FILTERED_DATA" \
|
| 59 |
+
--threshold 0.001
|
| 60 |
+
else
|
| 61 |
+
echo "[ATEC Task E] Found $FILTERED_DATA, skip filtering."
|
| 62 |
+
fi
|
| 63 |
+
|
| 64 |
+
TRAIN_ARGS=(
|
| 65 |
+
--demo_path "$FILTERED_DATA"
|
| 66 |
+
--num_demos "$NUM_DEMOS"
|
| 67 |
+
--include_rgb
|
| 68 |
+
--total_iters "$TOTAL_ITERS"
|
| 69 |
+
--batch_size "$BATCH_SIZE"
|
| 70 |
+
--log_freq "$LOG_FREQ"
|
| 71 |
+
--save_freq "$SAVE_FREQ"
|
| 72 |
+
--seed "$SEED"
|
| 73 |
+
--exp_name "$RUN_NAME"
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
if [[ -n "$RESUME_CHECKPOINT" ]]; then
|
| 77 |
+
TRAIN_ARGS+=(--resume_checkpoint "$RESUME_CHECKPOINT")
|
| 78 |
+
fi
|
| 79 |
+
if [[ -n "$RESUME_ITER" ]]; then
|
| 80 |
+
TRAIN_ARGS+=(--resume_iter "$RESUME_ITER")
|
| 81 |
+
fi
|
| 82 |
+
|
| 83 |
+
"$PYTHON" -u scripts/act/train_task_e.py "${TRAIN_ARGS[@]}"
|
scripts/act/search_task_e_grasps.py
ADDED
|
@@ -0,0 +1,761 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Search per-object scripted grasp parameters for Task E.
|
| 2 |
+
|
| 3 |
+
This is a fast physics-only diagnostic: it disables cameras, runs candidate
|
| 4 |
+
grasp offsets/heights/yaw corrections in one Isaac process, and reports the
|
| 5 |
+
first successful candidates.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
import math
|
| 10 |
+
import os
|
| 11 |
+
|
| 12 |
+
from isaaclab.app import AppLauncher
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
parser = argparse.ArgumentParser(description="Search Task-E grasp candidates.")
|
| 16 |
+
parser.add_argument("--objects", type=int, nargs="+", default=[1, 2])
|
| 17 |
+
parser.add_argument("--trials", type=int, default=1)
|
| 18 |
+
parser.add_argument("--max_candidates", type=int, default=40)
|
| 19 |
+
parser.add_argument("--start_candidate", type=int, default=1,
|
| 20 |
+
help="1-based candidate index to start from; useful for resuming long searches.")
|
| 21 |
+
parser.add_argument("--max_joint_delta", type=float, default=0.2,
|
| 22 |
+
help="Per-step IK joint target limit. Lower values make contact pushes gentler.")
|
| 23 |
+
AppLauncher.add_app_launcher_args(parser)
|
| 24 |
+
args_cli = parser.parse_args()
|
| 25 |
+
|
| 26 |
+
app_launcher = AppLauncher(args_cli)
|
| 27 |
+
simulation_app = app_launcher.app
|
| 28 |
+
|
| 29 |
+
import numpy as np
|
| 30 |
+
import torch
|
| 31 |
+
from isaaclab.actuators import ImplicitActuatorCfg
|
| 32 |
+
from isaaclab.envs import ManagerBasedRLEnv
|
| 33 |
+
|
| 34 |
+
from atec_rl_lab.tasks.task_e.env_cfg import TaskEEnvPiperCfg
|
| 35 |
+
from atec_rl_lab.utils import CartesianController
|
| 36 |
+
|
| 37 |
+
from task_e import config as grasp_cfg
|
| 38 |
+
from task_e.collector import (
|
| 39 |
+
basket_status_lines,
|
| 40 |
+
check_objects_in_basket,
|
| 41 |
+
collect_one_demo,
|
| 42 |
+
)
|
| 43 |
+
from task_e.config import (
|
| 44 |
+
ACT_DAMPING,
|
| 45 |
+
ACT_EFFORT_LIMIT,
|
| 46 |
+
ACT_STIFFNESS,
|
| 47 |
+
ACT_VEL_LIMIT,
|
| 48 |
+
ARM_JOINT_NAMES,
|
| 49 |
+
EE_BODY_NAME,
|
| 50 |
+
GRIPPER_JOINT_NAMES,
|
| 51 |
+
STEPS,
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
BASE_STATE_STEP_OVERRIDES = {
|
| 55 |
+
obj_idx: steps.copy()
|
| 56 |
+
for obj_idx, steps in grasp_cfg.OBJ_STATE_STEP_OVERRIDES.items()
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _candidate_dict(
|
| 61 |
+
dx: float,
|
| 62 |
+
dy: float,
|
| 63 |
+
z: float,
|
| 64 |
+
carry_z: float,
|
| 65 |
+
target_x: float,
|
| 66 |
+
target_y: float,
|
| 67 |
+
transport_gripper: str,
|
| 68 |
+
yaw: float,
|
| 69 |
+
push_y: float | None = None,
|
| 70 |
+
*,
|
| 71 |
+
push_x: float = 0.0,
|
| 72 |
+
push_z: float = 0.0,
|
| 73 |
+
transport_steps: int | None = None,
|
| 74 |
+
place_steps: int | None = None,
|
| 75 |
+
open_steps: int | None = None,
|
| 76 |
+
close_steps: int | None = None,
|
| 77 |
+
lift_steps: int | None = None,
|
| 78 |
+
close_z: float | None = None,
|
| 79 |
+
finger_target_z: float | None = None,
|
| 80 |
+
finger_max_z: float | None = None,
|
| 81 |
+
mode: str = "pick",
|
| 82 |
+
push_x_gain: float | None = None,
|
| 83 |
+
push_max_x: float | None = None,
|
| 84 |
+
push_min_behind: float | None = None,
|
| 85 |
+
) -> dict[str, float]:
|
| 86 |
+
return {
|
| 87 |
+
"mode": mode,
|
| 88 |
+
"dx": dx,
|
| 89 |
+
"dy": dy,
|
| 90 |
+
"z": z,
|
| 91 |
+
"carry_z": carry_z,
|
| 92 |
+
"place_z": min(carry_z, grasp_cfg.TABLE_TOP_Z + 0.15),
|
| 93 |
+
"target_x": target_x,
|
| 94 |
+
"target_y": target_y,
|
| 95 |
+
"transport_gripper": transport_gripper,
|
| 96 |
+
"yaw": yaw,
|
| 97 |
+
"push_x": push_x,
|
| 98 |
+
"push_y": push_y,
|
| 99 |
+
"push_z": push_z,
|
| 100 |
+
"transport_steps": transport_steps,
|
| 101 |
+
"place_steps": place_steps,
|
| 102 |
+
"open_steps": open_steps,
|
| 103 |
+
"close_steps": close_steps,
|
| 104 |
+
"lift_steps": lift_steps,
|
| 105 |
+
"close_z": close_z,
|
| 106 |
+
"finger_target_z": finger_target_z,
|
| 107 |
+
"finger_max_z": finger_max_z,
|
| 108 |
+
"push_x_gain": push_x_gain,
|
| 109 |
+
"push_max_x": push_max_x,
|
| 110 |
+
"push_min_behind": push_min_behind,
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _normalize_candidate(item: tuple | dict) -> dict[str, float]:
|
| 115 |
+
if isinstance(item, dict):
|
| 116 |
+
cand = item.copy()
|
| 117 |
+
cand.setdefault("mode", "pick")
|
| 118 |
+
cand.setdefault("place_z", min(cand["carry_z"], grasp_cfg.TABLE_TOP_Z + 0.15))
|
| 119 |
+
cand.setdefault("push_x", 0.0)
|
| 120 |
+
cand.setdefault("push_y", None)
|
| 121 |
+
cand.setdefault("push_z", 0.0)
|
| 122 |
+
cand.setdefault("transport_steps", None)
|
| 123 |
+
cand.setdefault("place_steps", None)
|
| 124 |
+
cand.setdefault("open_steps", None)
|
| 125 |
+
cand.setdefault("close_steps", None)
|
| 126 |
+
cand.setdefault("lift_steps", None)
|
| 127 |
+
cand.setdefault("close_z", None)
|
| 128 |
+
cand.setdefault("finger_target_z", None)
|
| 129 |
+
cand.setdefault("finger_max_z", None)
|
| 130 |
+
cand.setdefault("push_x_gain", None)
|
| 131 |
+
cand.setdefault("push_max_x", None)
|
| 132 |
+
cand.setdefault("push_min_behind", None)
|
| 133 |
+
return cand
|
| 134 |
+
if len(item) == 8:
|
| 135 |
+
dx, dy, z, carry_z, target_x, target_y, transport_gripper, yaw = item
|
| 136 |
+
return _candidate_dict(dx, dy, z, carry_z, target_x, target_y, transport_gripper, yaw)
|
| 137 |
+
dx, dy, z, carry_z, target_x, target_y, transport_gripper, yaw, push_y = item
|
| 138 |
+
return _candidate_dict(dx, dy, z, carry_z, target_x, target_y, transport_gripper, yaw, push_y)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def build_env() -> ManagerBasedRLEnv:
|
| 142 |
+
cfg = TaskEEnvPiperCfg()
|
| 143 |
+
cfg.seed = 123
|
| 144 |
+
cfg.scene.num_envs = 1
|
| 145 |
+
cfg.scene.video_cam = None
|
| 146 |
+
cfg.scene.ee_camera = None
|
| 147 |
+
cfg.scene.ee_dual_camera = None
|
| 148 |
+
cfg.scene.head_camera = None
|
| 149 |
+
cfg.observations.image = None
|
| 150 |
+
cfg.scene.robot.actuators["default"] = ImplicitActuatorCfg(
|
| 151 |
+
joint_names_expr=[".*"],
|
| 152 |
+
effort_limit=ACT_EFFORT_LIMIT,
|
| 153 |
+
velocity_limit=ACT_VEL_LIMIT,
|
| 154 |
+
stiffness=ACT_STIFFNESS,
|
| 155 |
+
damping=ACT_DAMPING,
|
| 156 |
+
)
|
| 157 |
+
return ManagerBasedRLEnv(cfg)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def candidates_for(obj_idx: int) -> list[dict[str, float]]:
|
| 161 |
+
priority = []
|
| 162 |
+
if obj_idx == 1:
|
| 163 |
+
# Sugar box has an off-centre USD root. Try real top-down pinch
|
| 164 |
+
# grasps around the measured visible bbox centre first; keep push-like
|
| 165 |
+
# sweeps only as a fallback diagnostic.
|
| 166 |
+
priority = [
|
| 167 |
+
_candidate_dict(0.025, 0.000, 0.072, grasp_cfg.CARRY_Z,
|
| 168 |
+
0.00, 0.000, "close", 0.0,
|
| 169 |
+
close_z=0.020, finger_target_z=-0.025, finger_max_z=0.050,
|
| 170 |
+
transport_steps=2200, place_steps=300, open_steps=80),
|
| 171 |
+
_candidate_dict(0.025, 0.000, 0.072, grasp_cfg.CARRY_Z,
|
| 172 |
+
0.00, 0.000, "close", 0.0,
|
| 173 |
+
close_z=0.015, finger_target_z=-0.030, finger_max_z=0.060,
|
| 174 |
+
transport_steps=2200, place_steps=300, open_steps=80),
|
| 175 |
+
_candidate_dict(0.025, 0.000, 0.072, grasp_cfg.CARRY_Z,
|
| 176 |
+
0.00, 0.000, "close", 0.0,
|
| 177 |
+
close_z=0.025, finger_target_z=-0.020, finger_max_z=0.045,
|
| 178 |
+
transport_steps=2200, place_steps=300, open_steps=80),
|
| 179 |
+
_candidate_dict(0.015, 0.000, 0.072, grasp_cfg.CARRY_Z,
|
| 180 |
+
0.00, 0.000, "close", 0.0,
|
| 181 |
+
close_z=0.020, finger_target_z=-0.025, finger_max_z=0.050,
|
| 182 |
+
transport_steps=2200, place_steps=300, open_steps=80),
|
| 183 |
+
_candidate_dict(0.035, 0.000, 0.072, grasp_cfg.CARRY_Z,
|
| 184 |
+
0.00, 0.000, "close", 0.0,
|
| 185 |
+
close_z=0.020, finger_target_z=-0.025, finger_max_z=0.050,
|
| 186 |
+
transport_steps=2200, place_steps=300, open_steps=80),
|
| 187 |
+
_candidate_dict(0.025, 0.010, 0.072, grasp_cfg.CARRY_Z,
|
| 188 |
+
0.00, 0.000, "close", 0.0,
|
| 189 |
+
close_z=0.020, finger_target_z=-0.025, finger_max_z=0.050,
|
| 190 |
+
transport_steps=2200, place_steps=300, open_steps=80),
|
| 191 |
+
_candidate_dict(0.025, -0.010, 0.072, grasp_cfg.CARRY_Z,
|
| 192 |
+
0.00, 0.000, "close", 0.0,
|
| 193 |
+
close_z=0.020, finger_target_z=-0.025, finger_max_z=0.050,
|
| 194 |
+
transport_steps=2200, place_steps=300, open_steps=80),
|
| 195 |
+
_candidate_dict(0.040, 0.180, 0.000, grasp_cfg.TABLE_TOP_Z + 0.055,
|
| 196 |
+
0.00, 0.000, "close", 0.0,
|
| 197 |
+
transport_steps=1450, place_steps=320, open_steps=80,
|
| 198 |
+
mode="push", push_x_gain=0.55, push_max_x=0.12,
|
| 199 |
+
push_min_behind=0.035),
|
| 200 |
+
_candidate_dict(0.000, 0.180, 0.000, grasp_cfg.TABLE_TOP_Z + 0.055,
|
| 201 |
+
0.00, 0.000, "close", 0.0,
|
| 202 |
+
transport_steps=1450, place_steps=320, open_steps=80,
|
| 203 |
+
mode="push", push_x_gain=0.55, push_max_x=0.12,
|
| 204 |
+
push_min_behind=0.035),
|
| 205 |
+
_candidate_dict(-0.040, 0.180, 0.000, grasp_cfg.TABLE_TOP_Z + 0.055,
|
| 206 |
+
0.00, 0.000, "close", 0.0,
|
| 207 |
+
transport_steps=1450, place_steps=320, open_steps=80,
|
| 208 |
+
mode="push", push_x_gain=0.60, push_max_x=0.14,
|
| 209 |
+
push_min_behind=0.035),
|
| 210 |
+
_candidate_dict(0.040, 0.220, 0.000, grasp_cfg.TABLE_TOP_Z + 0.055,
|
| 211 |
+
0.00, 0.000, "close", 0.0,
|
| 212 |
+
transport_steps=1550, place_steps=360, open_steps=80,
|
| 213 |
+
mode="push", push_x_gain=0.55, push_max_x=0.12,
|
| 214 |
+
push_min_behind=0.040),
|
| 215 |
+
_candidate_dict(0.000, 0.220, 0.000, grasp_cfg.TABLE_TOP_Z + 0.055,
|
| 216 |
+
0.00, 0.000, "close", 0.0,
|
| 217 |
+
transport_steps=1550, place_steps=360, open_steps=80,
|
| 218 |
+
mode="push", push_x_gain=0.55, push_max_x=0.12,
|
| 219 |
+
push_min_behind=0.040),
|
| 220 |
+
# Push-slide primitive: approach from +Y and drive the object
|
| 221 |
+
# centre into the basket. This tests the contact-rich route
|
| 222 |
+
# before more top-down pinch candidates.
|
| 223 |
+
_candidate_dict(0.040, 0.150, 0.000, grasp_cfg.TABLE_TOP_Z + 0.060,
|
| 224 |
+
0.00, 0.000, "close", 0.0,
|
| 225 |
+
transport_steps=850, place_steps=140, open_steps=80,
|
| 226 |
+
mode="push", push_x_gain=0.65, push_max_x=0.10),
|
| 227 |
+
_candidate_dict(0.000, 0.150, 0.000, grasp_cfg.TABLE_TOP_Z + 0.060,
|
| 228 |
+
0.00, 0.000, "close", 0.0,
|
| 229 |
+
transport_steps=850, place_steps=140, open_steps=80,
|
| 230 |
+
mode="push", push_x_gain=0.65, push_max_x=0.10),
|
| 231 |
+
_candidate_dict(-0.040, 0.150, 0.000, grasp_cfg.TABLE_TOP_Z + 0.060,
|
| 232 |
+
0.00, 0.000, "close", 0.0,
|
| 233 |
+
transport_steps=850, place_steps=140, open_steps=80,
|
| 234 |
+
mode="push", push_x_gain=0.70, push_max_x=0.12),
|
| 235 |
+
_candidate_dict(0.040, 0.190, 0.000, grasp_cfg.TABLE_TOP_Z + 0.060,
|
| 236 |
+
0.00, 0.000, "close", 0.0,
|
| 237 |
+
transport_steps=950, place_steps=140, open_steps=80,
|
| 238 |
+
mode="push", push_x_gain=0.65, push_max_x=0.10),
|
| 239 |
+
_candidate_dict(0.000, 0.190, 0.000, grasp_cfg.TABLE_TOP_Z + 0.060,
|
| 240 |
+
0.00, 0.000, "close", 0.0,
|
| 241 |
+
transport_steps=950, place_steps=140, open_steps=80,
|
| 242 |
+
mode="push", push_x_gain=0.65, push_max_x=0.10),
|
| 243 |
+
_candidate_dict(0.040, 0.150, 0.000, grasp_cfg.TABLE_TOP_Z + 0.050,
|
| 244 |
+
0.00, 0.000, "open", 0.0,
|
| 245 |
+
transport_steps=950, place_steps=140, open_steps=80,
|
| 246 |
+
mode="push", push_x_gain=0.65, push_max_x=0.10),
|
| 247 |
+
_candidate_dict(0.040, 0.150, 0.000, grasp_cfg.TABLE_TOP_Z + 0.070,
|
| 248 |
+
0.00, 0.000, "close", math.pi / 2,
|
| 249 |
+
transport_steps=850, place_steps=140, open_steps=80,
|
| 250 |
+
mode="push", push_x_gain=0.65, push_max_x=0.10),
|
| 251 |
+
_candidate_dict(0.040, 0.150, 0.000, grasp_cfg.TABLE_TOP_Z + 0.070,
|
| 252 |
+
0.00, 0.000, "close", -math.pi / 2,
|
| 253 |
+
transport_steps=850, place_steps=140, open_steps=80,
|
| 254 |
+
mode="push", push_x_gain=0.65, push_max_x=0.10),
|
| 255 |
+
# Focused timing sweep after candidates 025-034 proved real
|
| 256 |
+
# contact/lift but missed the basket. Keep the end effector low,
|
| 257 |
+
# hold contact longer, then release near the basket plane.
|
| 258 |
+
_candidate_dict(0.040, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.025,
|
| 259 |
+
-0.17, 0.000, "close", 0.0, -0.160,
|
| 260 |
+
transport_steps=1000, place_steps=30, open_steps=80),
|
| 261 |
+
_candidate_dict(0.040, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.025,
|
| 262 |
+
-0.17, 0.000, "close", 0.0, -0.180,
|
| 263 |
+
transport_steps=900, place_steps=30, open_steps=80),
|
| 264 |
+
_candidate_dict(0.040, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.025,
|
| 265 |
+
-0.17, 0.000, "close", 0.0, -0.140,
|
| 266 |
+
transport_steps=1200, place_steps=30, open_steps=80),
|
| 267 |
+
_candidate_dict(0.040, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.025,
|
| 268 |
+
-0.17, 0.000, "close", 0.0, -0.200,
|
| 269 |
+
transport_steps=750, place_steps=30, open_steps=80),
|
| 270 |
+
_candidate_dict(0.040, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.015,
|
| 271 |
+
-0.17, 0.000, "close", 0.0, -0.180,
|
| 272 |
+
transport_steps=900, place_steps=30, open_steps=80),
|
| 273 |
+
_candidate_dict(0.040, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.025,
|
| 274 |
+
-0.17, 0.000, "open", 0.0, -0.180,
|
| 275 |
+
transport_steps=1000, place_steps=30, open_steps=80),
|
| 276 |
+
_candidate_dict(0.040, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.025,
|
| 277 |
+
-0.17, 0.000, "open", 0.0, -0.250,
|
| 278 |
+
transport_steps=850, place_steps=30, open_steps=80),
|
| 279 |
+
_candidate_dict(0.040, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.025,
|
| 280 |
+
-0.17, 0.000, "close", 0.0, -0.180,
|
| 281 |
+
push_x=-0.040, transport_steps=900, place_steps=30, open_steps=80),
|
| 282 |
+
_candidate_dict(0.040, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.025,
|
| 283 |
+
-0.17, 0.000, "close", 0.0, -0.180,
|
| 284 |
+
push_x=0.040, transport_steps=900, place_steps=30, open_steps=80),
|
| 285 |
+
_candidate_dict(0.040, 0.160, -0.020, grasp_cfg.TABLE_TOP_Z + 0.025,
|
| 286 |
+
-0.17, 0.000, "close", 0.0, -0.180,
|
| 287 |
+
transport_steps=900, place_steps=30, open_steps=80),
|
| 288 |
+
(-0.205, 0.104, 0.025, grasp_cfg.TABLE_TOP_Z + 0.140, 0.00, -0.240, "close", 0.0),
|
| 289 |
+
(-0.205, 0.104, 0.045, grasp_cfg.TABLE_TOP_Z + 0.160, 0.00, -0.240, "close", 0.0),
|
| 290 |
+
(-0.205, 0.104, 0.065, grasp_cfg.TABLE_TOP_Z + 0.180, 0.00, -0.240, "close", 0.0),
|
| 291 |
+
(-0.205, 0.104, 0.045, grasp_cfg.TABLE_TOP_Z + 0.160, 0.00, -0.240, "close", math.pi / 2),
|
| 292 |
+
(-0.205, 0.104, 0.045, grasp_cfg.TABLE_TOP_Z + 0.160, 0.00, -0.240, "close", -math.pi / 2),
|
| 293 |
+
(-0.180, 0.104, 0.045, grasp_cfg.TABLE_TOP_Z + 0.160, 0.00, -0.240, "close", 0.0),
|
| 294 |
+
(-0.230, 0.104, 0.045, grasp_cfg.TABLE_TOP_Z + 0.160, 0.00, -0.240, "close", 0.0),
|
| 295 |
+
(-0.205, 0.084, 0.045, grasp_cfg.TABLE_TOP_Z + 0.160, 0.00, -0.240, "close", 0.0),
|
| 296 |
+
(-0.205, 0.124, 0.045, grasp_cfg.TABLE_TOP_Z + 0.160, 0.00, -0.240, "close", 0.0),
|
| 297 |
+
(-0.180, 0.084, 0.045, grasp_cfg.TABLE_TOP_Z + 0.160, 0.00, -0.240, "close", 0.0),
|
| 298 |
+
(-0.230, 0.124, 0.045, grasp_cfg.TABLE_TOP_Z + 0.160, 0.00, -0.240, "close", 0.0),
|
| 299 |
+
(-0.205, 0.104, 0.085, grasp_cfg.TABLE_TOP_Z + 0.200, 0.00, -0.240, "close", 0.0),
|
| 300 |
+
(0.040, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, 0.00, -0.240, "close", 0.0, -0.100),
|
| 301 |
+
(0.040, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, 0.00, -0.240, "close", 0.0, -0.120),
|
| 302 |
+
(0.040, 0.120, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, 0.00, -0.240, "close", 0.0, -0.100),
|
| 303 |
+
(0.040, 0.160, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, 0.00, -0.240, "close", 0.0, -0.100),
|
| 304 |
+
(0.040, 0.140, 0.000, grasp_cfg.TABLE_TOP_Z + 0.050, 0.00, -0.240, "close", 0.0, -0.100),
|
| 305 |
+
(0.040, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, 0.00, -0.240, "close", 0.0, -0.140),
|
| 306 |
+
(0.040, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, 0.00, -0.240, "close", 0.0, -0.180),
|
| 307 |
+
(0.040, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, 0.00, -0.240, "close", 0.0, -0.220),
|
| 308 |
+
(0.040, 0.120, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, 0.00, -0.240, "close", 0.0, -0.160),
|
| 309 |
+
(0.040, 0.160, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, 0.00, -0.240, "close", 0.0, -0.160),
|
| 310 |
+
(0.020, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, 0.00, -0.240, "close", 0.0, -0.160),
|
| 311 |
+
(0.060, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, 0.00, -0.240, "close", 0.0, -0.160),
|
| 312 |
+
# Focused refinement around candidate 019: it made real contact
|
| 313 |
+
# and lifted object_1, but released high and too far +X/+Y.
|
| 314 |
+
# Lower the sweep height and bias release toward basket centre/left.
|
| 315 |
+
(0.040, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.025, -0.17, 0.000, "close", 0.0, -0.160),
|
| 316 |
+
(0.040, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.025, -0.17, 0.000, "close", 0.0, -0.180),
|
| 317 |
+
(0.040, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.025, -0.10, 0.000, "close", 0.0, -0.160),
|
| 318 |
+
(0.040, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.025, -0.10, 0.000, "close", 0.0, -0.180),
|
| 319 |
+
(0.040, 0.160, -0.020, grasp_cfg.TABLE_TOP_Z + 0.025, -0.17, 0.000, "close", 0.0, -0.160),
|
| 320 |
+
(0.040, 0.160, -0.020, grasp_cfg.TABLE_TOP_Z + 0.025, -0.17, 0.000, "close", 0.0, -0.180),
|
| 321 |
+
(0.040, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.025, -0.17, -0.100, "close", 0.0, -0.160),
|
| 322 |
+
(0.040, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.025, -0.17, -0.100, "close", 0.0, -0.180),
|
| 323 |
+
(0.040, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, -0.17, 0.000, "close", 0.0, -0.160),
|
| 324 |
+
(0.040, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, -0.17, 0.000, "close", 0.0, -0.180),
|
| 325 |
+
(0.040, 0.140, 0.000, grasp_cfg.TABLE_TOP_Z + 0.050, 0.00, -0.240, "close", 0.0, -0.160),
|
| 326 |
+
(0.040, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, 0.00, -0.300, "close", 0.0, -0.160),
|
| 327 |
+
(0.040, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, 0.08, -0.240, "close", 0.0, -0.160),
|
| 328 |
+
(0.040, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, 0.00, -0.240, "close", 0.0, -0.060),
|
| 329 |
+
(0.040, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, 0.00, -0.240, "close", 0.0, -0.100),
|
| 330 |
+
(0.040, 0.160, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, 0.00, -0.240, "close", 0.0, -0.060),
|
| 331 |
+
(0.040, 0.160, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, 0.00, -0.240, "close", 0.0, -0.100),
|
| 332 |
+
(0.020, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, 0.00, -0.240, "close", 0.0, -0.080),
|
| 333 |
+
(0.060, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, 0.00, -0.240, "close", 0.0, -0.080),
|
| 334 |
+
(0.040, 0.120, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, 0.00, -0.240, "close", 0.0, -0.080),
|
| 335 |
+
(0.040, 0.180, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, 0.00, -0.240, "close", 0.0, -0.080),
|
| 336 |
+
(0.040, 0.140, 0.000, grasp_cfg.TABLE_TOP_Z + 0.050, 0.00, -0.240, "close", 0.0, -0.080),
|
| 337 |
+
(0.040, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, 0.00, -0.300, "close", 0.0, -0.080),
|
| 338 |
+
(0.040, 0.160, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, 0.00, -0.750, "close", 0.0),
|
| 339 |
+
(0.040, 0.160, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, 0.08, -0.750, "close", 0.0),
|
| 340 |
+
(0.040, 0.160, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, 0.00, -0.600, "close", 0.0),
|
| 341 |
+
(0.040, 0.140, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, 0.00, -0.750, "close", 0.0),
|
| 342 |
+
(0.040, 0.120, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, 0.00, -0.750, "close", 0.0),
|
| 343 |
+
(0.060, 0.160, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, 0.00, -0.750, "close", 0.0),
|
| 344 |
+
(0.020, 0.160, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, 0.00, -0.750, "close", 0.0),
|
| 345 |
+
(0.040, 0.160, 0.000, grasp_cfg.TABLE_TOP_Z + 0.050, 0.00, -0.750, "close", 0.0),
|
| 346 |
+
(0.040, 0.140, 0.000, grasp_cfg.TABLE_TOP_Z + 0.050, 0.00, -0.750, "close", 0.0),
|
| 347 |
+
(0.040, 0.160, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, 0.00, -0.750, "open", 0.0),
|
| 348 |
+
(-0.205, 0.104, 0.045, grasp_cfg.TABLE_TOP_Z + 0.120, 0.00, -0.240, "close", 0.0),
|
| 349 |
+
(-0.205, 0.104, 0.045, grasp_cfg.TABLE_TOP_Z + 0.120, 0.00, -0.240, "close", math.pi / 2),
|
| 350 |
+
(-0.205, 0.104, 0.045, grasp_cfg.TABLE_TOP_Z + 0.120, 0.00, -0.240, "close", -math.pi / 2),
|
| 351 |
+
(-0.205, 0.084, 0.045, grasp_cfg.TABLE_TOP_Z + 0.120, 0.00, -0.240, "close", 0.0),
|
| 352 |
+
(-0.180, 0.104, 0.045, grasp_cfg.TABLE_TOP_Z + 0.120, 0.00, -0.240, "close", 0.0),
|
| 353 |
+
(-0.230, 0.104, 0.045, grasp_cfg.TABLE_TOP_Z + 0.120, 0.00, -0.240, "close", 0.0),
|
| 354 |
+
(-0.205, 0.124, 0.045, grasp_cfg.TABLE_TOP_Z + 0.120, 0.00, -0.240, "close", 0.0),
|
| 355 |
+
(-0.205, 0.104, 0.065, grasp_cfg.TABLE_TOP_Z + 0.140, 0.00, -0.240, "close", 0.0),
|
| 356 |
+
(-0.205, 0.104, 0.025, grasp_cfg.TABLE_TOP_Z + 0.100, 0.00, -0.240, "close", 0.0),
|
| 357 |
+
(-0.205, 0.104, 0.045, grasp_cfg.TABLE_TOP_Z + 0.180, 0.00, -0.240, "close", 0.0),
|
| 358 |
+
(-0.205, 0.104, 0.045, grasp_cfg.TABLE_TOP_Z + 0.120, -0.10, -0.240, "close", 0.0),
|
| 359 |
+
(-0.205, 0.104, 0.045, grasp_cfg.TABLE_TOP_Z + 0.120, 0.00, -0.300, "close", 0.0),
|
| 360 |
+
(0.040, 0.200, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, -0.17, -0.60, "close", 0.0),
|
| 361 |
+
(0.040, 0.200, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, -0.10, -0.60, "close", 0.0),
|
| 362 |
+
(0.040, 0.160, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, -0.17, -0.60, "close", 0.0),
|
| 363 |
+
(0.080, 0.200, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, -0.17, -0.60, "close", 0.0),
|
| 364 |
+
(-0.040, 0.200, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, -0.17, -0.60, "close", 0.0),
|
| 365 |
+
(-0.096, 0.200, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, -0.17, -0.60, "close", 0.0),
|
| 366 |
+
(0.040, 0.240, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, -0.17, -0.60, "close", 0.0),
|
| 367 |
+
(0.040, 0.200, 0.000, grasp_cfg.TABLE_TOP_Z + 0.035, -0.17, -0.60, "close", 0.0),
|
| 368 |
+
(0.040, 0.200, -0.020, grasp_cfg.TABLE_TOP_Z + 0.050, -0.17, -0.60, "close", 0.0),
|
| 369 |
+
(0.040, 0.200, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, -0.17, -0.45, "close", 0.0),
|
| 370 |
+
(0.040, 0.200, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, -0.17, -0.75, "close", 0.0),
|
| 371 |
+
(0.040, 0.200, -0.020, grasp_cfg.TABLE_TOP_Z + 0.035, -0.17, -0.60, "open", 0.0),
|
| 372 |
+
]
|
| 373 |
+
base_offsets = [
|
| 374 |
+
(0.040, 0.140),
|
| 375 |
+
(0.040, 0.180),
|
| 376 |
+
(0.040, 0.220),
|
| 377 |
+
(0.080, 0.180),
|
| 378 |
+
(0.080, 0.220),
|
| 379 |
+
(-0.096, 0.140),
|
| 380 |
+
(-0.096, 0.180),
|
| 381 |
+
(-0.096, 0.220),
|
| 382 |
+
(-0.040, 0.140),
|
| 383 |
+
(-0.040, 0.180),
|
| 384 |
+
(-0.040, 0.220),
|
| 385 |
+
(0.000, 0.140),
|
| 386 |
+
(0.000, 0.180),
|
| 387 |
+
(0.000, 0.220),
|
| 388 |
+
(-0.160, 0.140),
|
| 389 |
+
(-0.200, 0.140),
|
| 390 |
+
(-0.117, -0.025),
|
| 391 |
+
(-0.096, 0.084),
|
| 392 |
+
(-0.096, 0.000),
|
| 393 |
+
(-0.060, 0.060),
|
| 394 |
+
(-0.040, 0.020),
|
| 395 |
+
(0.000, 0.040),
|
| 396 |
+
(-0.140, 0.040),
|
| 397 |
+
(-0.100, 0.000),
|
| 398 |
+
(-0.020, 0.080),
|
| 399 |
+
]
|
| 400 |
+
z_values = [-0.020, -0.010, 0.000, 0.015, 0.025, 0.040, 0.060, 0.080, 0.110]
|
| 401 |
+
carry_values = [
|
| 402 |
+
grasp_cfg.TABLE_TOP_Z + 0.025,
|
| 403 |
+
grasp_cfg.TABLE_TOP_Z + 0.035,
|
| 404 |
+
grasp_cfg.TABLE_TOP_Z + 0.050,
|
| 405 |
+
grasp_cfg.TABLE_TOP_Z + 0.075,
|
| 406 |
+
grasp_cfg.TABLE_TOP_Z + 0.10,
|
| 407 |
+
grasp_cfg.TABLE_TOP_Z + 0.12,
|
| 408 |
+
grasp_cfg.TABLE_TOP_Z + 0.16,
|
| 409 |
+
grasp_cfg.TABLE_TOP_Z + 0.22,
|
| 410 |
+
grasp_cfg.CARRY_Z,
|
| 411 |
+
]
|
| 412 |
+
target_x_offsets = [-0.17, -0.10, 0.0, 0.08]
|
| 413 |
+
target_y_offsets = [-0.60, -0.45, -0.75, -0.36, -0.30, -0.24, -0.18, 0.0]
|
| 414 |
+
transport_gripper_cmds = ["close", "open"]
|
| 415 |
+
yaws = [0.0, math.pi / 2, -math.pi / 2]
|
| 416 |
+
elif obj_idx == 2:
|
| 417 |
+
priority = [
|
| 418 |
+
_candidate_dict(0.000, 0.045, 0.000, grasp_cfg.TABLE_TOP_Z + 0.045,
|
| 419 |
+
0.00, -0.140, "close", 0.0,
|
| 420 |
+
transport_steps=1500, place_steps=420, open_steps=80,
|
| 421 |
+
mode="push", push_x_gain=0.50, push_max_x=0.10,
|
| 422 |
+
push_min_behind=-0.015),
|
| 423 |
+
_candidate_dict(0.020, 0.045, 0.000, grasp_cfg.TABLE_TOP_Z + 0.045,
|
| 424 |
+
0.00, -0.140, "close", 0.0,
|
| 425 |
+
transport_steps=1500, place_steps=420, open_steps=80,
|
| 426 |
+
mode="push", push_x_gain=0.50, push_max_x=0.10,
|
| 427 |
+
push_min_behind=-0.015),
|
| 428 |
+
_candidate_dict(-0.020, 0.045, 0.000, grasp_cfg.TABLE_TOP_Z + 0.045,
|
| 429 |
+
0.00, -0.140, "close", 0.0,
|
| 430 |
+
transport_steps=1500, place_steps=420, open_steps=80,
|
| 431 |
+
mode="push", push_x_gain=0.55, push_max_x=0.12,
|
| 432 |
+
push_min_behind=-0.015),
|
| 433 |
+
_candidate_dict(0.000, 0.060, 0.000, grasp_cfg.TABLE_TOP_Z + 0.040,
|
| 434 |
+
0.00, -0.180, "close", 0.0,
|
| 435 |
+
transport_steps=1600, place_steps=460, open_steps=80,
|
| 436 |
+
mode="push", push_x_gain=0.50, push_max_x=0.10,
|
| 437 |
+
push_min_behind=-0.020),
|
| 438 |
+
_candidate_dict(0.020, 0.060, 0.000, grasp_cfg.TABLE_TOP_Z + 0.040,
|
| 439 |
+
0.00, -0.180, "close", 0.0,
|
| 440 |
+
transport_steps=1600, place_steps=460, open_steps=80,
|
| 441 |
+
mode="push", push_x_gain=0.50, push_max_x=0.10,
|
| 442 |
+
push_min_behind=-0.020),
|
| 443 |
+
_candidate_dict(-0.020, 0.060, 0.000, grasp_cfg.TABLE_TOP_Z + 0.040,
|
| 444 |
+
0.00, -0.180, "close", 0.0,
|
| 445 |
+
transport_steps=1600, place_steps=460, open_steps=80,
|
| 446 |
+
mode="push", push_x_gain=0.55, push_max_x=0.12,
|
| 447 |
+
push_min_behind=-0.020),
|
| 448 |
+
_candidate_dict(0.000, 0.095, 0.000, grasp_cfg.TABLE_TOP_Z + 0.045,
|
| 449 |
+
0.00, 0.000, "close", 0.0,
|
| 450 |
+
transport_steps=1250, place_steps=260, open_steps=80,
|
| 451 |
+
mode="push", push_x_gain=0.55, push_max_x=0.10,
|
| 452 |
+
push_min_behind=0.025),
|
| 453 |
+
_candidate_dict(0.020, 0.095, 0.000, grasp_cfg.TABLE_TOP_Z + 0.045,
|
| 454 |
+
0.00, 0.000, "close", 0.0,
|
| 455 |
+
transport_steps=1250, place_steps=260, open_steps=80,
|
| 456 |
+
mode="push", push_x_gain=0.55, push_max_x=0.10,
|
| 457 |
+
push_min_behind=0.025),
|
| 458 |
+
_candidate_dict(-0.020, 0.095, 0.000, grasp_cfg.TABLE_TOP_Z + 0.045,
|
| 459 |
+
0.00, 0.000, "close", 0.0,
|
| 460 |
+
transport_steps=1250, place_steps=260, open_steps=80,
|
| 461 |
+
mode="push", push_x_gain=0.60, push_max_x=0.12,
|
| 462 |
+
push_min_behind=0.025),
|
| 463 |
+
_candidate_dict(0.000, 0.125, 0.000, grasp_cfg.TABLE_TOP_Z + 0.045,
|
| 464 |
+
0.00, 0.000, "close", 0.0,
|
| 465 |
+
transport_steps=1350, place_steps=300, open_steps=80,
|
| 466 |
+
mode="push", push_x_gain=0.55, push_max_x=0.10,
|
| 467 |
+
push_min_behind=0.030),
|
| 468 |
+
_candidate_dict(0.020, 0.125, 0.000, grasp_cfg.TABLE_TOP_Z + 0.045,
|
| 469 |
+
0.00, 0.000, "close", 0.0,
|
| 470 |
+
transport_steps=1350, place_steps=300, open_steps=80,
|
| 471 |
+
mode="push", push_x_gain=0.55, push_max_x=0.10,
|
| 472 |
+
push_min_behind=0.030),
|
| 473 |
+
_candidate_dict(0.000, 0.095, 0.000, grasp_cfg.TABLE_TOP_Z + 0.040,
|
| 474 |
+
0.00, 0.000, "close", 0.0,
|
| 475 |
+
transport_steps=1350, place_steps=300, open_steps=80,
|
| 476 |
+
mode="push", push_x_gain=0.55, push_max_x=0.10,
|
| 477 |
+
push_min_behind=0.020),
|
| 478 |
+
_candidate_dict(-0.040, 0.070, 0.000, grasp_cfg.TABLE_TOP_Z + 0.045,
|
| 479 |
+
0.00, -0.140, "close", 0.0,
|
| 480 |
+
transport_steps=1000, place_steps=160, open_steps=80,
|
| 481 |
+
mode="push", push_x_gain=0.75, push_max_x=0.14),
|
| 482 |
+
_candidate_dict(0.000, 0.070, 0.000, grasp_cfg.TABLE_TOP_Z + 0.045,
|
| 483 |
+
0.00, -0.140, "close", 0.0,
|
| 484 |
+
transport_steps=1000, place_steps=160, open_steps=80,
|
| 485 |
+
mode="push", push_x_gain=0.70, push_max_x=0.12),
|
| 486 |
+
_candidate_dict(0.040, 0.070, 0.000, grasp_cfg.TABLE_TOP_Z + 0.045,
|
| 487 |
+
0.00, -0.140, "close", 0.0,
|
| 488 |
+
transport_steps=1000, place_steps=160, open_steps=80,
|
| 489 |
+
mode="push", push_x_gain=0.70, push_max_x=0.12),
|
| 490 |
+
_candidate_dict(-0.040, 0.050, 0.000, grasp_cfg.TABLE_TOP_Z + 0.040,
|
| 491 |
+
0.00, -0.180, "close", 0.0,
|
| 492 |
+
transport_steps=1100, place_steps=180, open_steps=80,
|
| 493 |
+
mode="push", push_x_gain=0.75, push_max_x=0.14),
|
| 494 |
+
_candidate_dict(0.000, 0.050, 0.000, grasp_cfg.TABLE_TOP_Z + 0.040,
|
| 495 |
+
0.00, -0.180, "close", 0.0,
|
| 496 |
+
transport_steps=1100, place_steps=180, open_steps=80,
|
| 497 |
+
mode="push", push_x_gain=0.70, push_max_x=0.12),
|
| 498 |
+
_candidate_dict(-0.040, 0.090, 0.000, grasp_cfg.TABLE_TOP_Z + 0.050,
|
| 499 |
+
0.00, -0.220, "open", 0.0,
|
| 500 |
+
transport_steps=1100, place_steps=180, open_steps=80,
|
| 501 |
+
mode="push", push_x_gain=0.75, push_max_x=0.14),
|
| 502 |
+
_candidate_dict(0.000, 0.115, 0.000, grasp_cfg.TABLE_TOP_Z + 0.065,
|
| 503 |
+
0.00, 0.000, "close", 0.0,
|
| 504 |
+
transport_steps=700, place_steps=120, open_steps=80,
|
| 505 |
+
mode="push", push_x_gain=0.65, push_max_x=0.10),
|
| 506 |
+
_candidate_dict(0.040, 0.115, 0.000, grasp_cfg.TABLE_TOP_Z + 0.065,
|
| 507 |
+
0.00, 0.000, "close", 0.0,
|
| 508 |
+
transport_steps=700, place_steps=120, open_steps=80,
|
| 509 |
+
mode="push", push_x_gain=0.65, push_max_x=0.10),
|
| 510 |
+
_candidate_dict(-0.040, 0.115, 0.000, grasp_cfg.TABLE_TOP_Z + 0.065,
|
| 511 |
+
0.00, 0.000, "close", 0.0,
|
| 512 |
+
transport_steps=700, place_steps=120, open_steps=80,
|
| 513 |
+
mode="push", push_x_gain=0.70, push_max_x=0.12),
|
| 514 |
+
_candidate_dict(0.000, 0.150, 0.000, grasp_cfg.TABLE_TOP_Z + 0.065,
|
| 515 |
+
0.00, 0.000, "close", 0.0,
|
| 516 |
+
transport_steps=850, place_steps=120, open_steps=80,
|
| 517 |
+
mode="push", push_x_gain=0.65, push_max_x=0.10),
|
| 518 |
+
_candidate_dict(0.040, 0.150, 0.000, grasp_cfg.TABLE_TOP_Z + 0.065,
|
| 519 |
+
0.00, 0.000, "close", -math.pi / 2,
|
| 520 |
+
transport_steps=850, place_steps=120, open_steps=80,
|
| 521 |
+
mode="push", push_x_gain=0.65, push_max_x=0.10),
|
| 522 |
+
_candidate_dict(0.000, 0.115, 0.000, grasp_cfg.TABLE_TOP_Z + 0.055,
|
| 523 |
+
0.00, 0.000, "open", 0.0,
|
| 524 |
+
transport_steps=850, place_steps=120, open_steps=80,
|
| 525 |
+
mode="push", push_x_gain=0.65, push_max_x=0.10),
|
| 526 |
+
(0.006, 0.046, 0.045, grasp_cfg.TABLE_TOP_Z + 0.075, 0.00, -0.240, "close", -math.pi / 2),
|
| 527 |
+
]
|
| 528 |
+
base_offsets = [
|
| 529 |
+
(0.006, 0.046),
|
| 530 |
+
(0.030, 0.026),
|
| 531 |
+
(0.060, 0.000),
|
| 532 |
+
(0.100, 0.020),
|
| 533 |
+
(0.115, 0.026),
|
| 534 |
+
(-0.020, 0.050),
|
| 535 |
+
(0.040, 0.070),
|
| 536 |
+
(0.000, 0.000),
|
| 537 |
+
]
|
| 538 |
+
z_values = [0.045, 0.065, 0.085, 0.110, 0.135, 0.160]
|
| 539 |
+
carry_values = [
|
| 540 |
+
grasp_cfg.TABLE_TOP_Z + 0.075,
|
| 541 |
+
grasp_cfg.TABLE_TOP_Z + 0.10,
|
| 542 |
+
grasp_cfg.TABLE_TOP_Z + 0.12,
|
| 543 |
+
grasp_cfg.TABLE_TOP_Z + 0.14,
|
| 544 |
+
grasp_cfg.TABLE_TOP_Z + 0.18,
|
| 545 |
+
grasp_cfg.TABLE_TOP_Z + 0.24,
|
| 546 |
+
grasp_cfg.CARRY_Z,
|
| 547 |
+
]
|
| 548 |
+
target_x_offsets = [0.0]
|
| 549 |
+
target_y_offsets = [-0.24, -0.18, -0.30, -0.12, 0.0]
|
| 550 |
+
transport_gripper_cmds = ["close"]
|
| 551 |
+
yaws = [0.0, math.pi / 2, -math.pi / 2]
|
| 552 |
+
else:
|
| 553 |
+
base_offsets = [(0.0, 0.0)]
|
| 554 |
+
z_values = [grasp_cfg.GRASP_Z_OFFSET]
|
| 555 |
+
carry_values = [grasp_cfg.CARRY_Z]
|
| 556 |
+
target_x_offsets = [0.0]
|
| 557 |
+
target_y_offsets = [0.0]
|
| 558 |
+
transport_gripper_cmds = ["close"]
|
| 559 |
+
yaws = [0.0]
|
| 560 |
+
|
| 561 |
+
out = []
|
| 562 |
+
for item in priority:
|
| 563 |
+
out.append(_normalize_candidate(item))
|
| 564 |
+
for z in z_values:
|
| 565 |
+
for carry_z in carry_values:
|
| 566 |
+
for target_x in target_x_offsets:
|
| 567 |
+
for target_y in target_y_offsets:
|
| 568 |
+
for transport_gripper in transport_gripper_cmds:
|
| 569 |
+
for yaw in yaws:
|
| 570 |
+
for dx, dy in base_offsets:
|
| 571 |
+
out.append({
|
| 572 |
+
"dx": dx,
|
| 573 |
+
"dy": dy,
|
| 574 |
+
"z": z,
|
| 575 |
+
"carry_z": carry_z,
|
| 576 |
+
"place_z": min(carry_z, grasp_cfg.TABLE_TOP_Z + 0.15),
|
| 577 |
+
"target_x": target_x,
|
| 578 |
+
"target_y": target_y,
|
| 579 |
+
"transport_gripper": transport_gripper,
|
| 580 |
+
"yaw": yaw,
|
| 581 |
+
"push_y": None,
|
| 582 |
+
})
|
| 583 |
+
start = max(args_cli.start_candidate, 1) - 1
|
| 584 |
+
return out[start : start + args_cli.max_candidates]
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
def apply_candidate(obj_idx: int, cand: dict[str, float]) -> None:
|
| 588 |
+
grasp_cfg.OBJ_MANIPULATION_MODES[obj_idx] = cand.get("mode", "pick")
|
| 589 |
+
grasp_cfg.OBJ_GRASP_CENTER_OFFSETS[obj_idx] = (cand["dx"], cand["dy"], 0.0)
|
| 590 |
+
grasp_cfg.OBJ_GRASP_Z_OFFSETS[obj_idx] = cand["z"]
|
| 591 |
+
if cand.get("close_z") is not None:
|
| 592 |
+
grasp_cfg.OBJ_CLOSE_Z_OFFSETS[obj_idx] = float(cand["close_z"])
|
| 593 |
+
grasp_cfg.OBJ_GRASP_YAW_OFFSETS[obj_idx] = cand["yaw"]
|
| 594 |
+
grasp_cfg.OBJ_CARRY_Z[obj_idx] = cand["carry_z"]
|
| 595 |
+
grasp_cfg.OBJ_PLACE_HEIGHTS[obj_idx] = cand["place_z"]
|
| 596 |
+
grasp_cfg.OBJ_PLACE_XY_OFFSETS[obj_idx] = (cand["target_x"], cand["target_y"])
|
| 597 |
+
grasp_cfg.OBJ_TRANSPORT_GRIPPER_CMDS[obj_idx] = cand["transport_gripper"]
|
| 598 |
+
grasp_cfg.OBJ_PUSH_GRIPPER_CMDS[obj_idx] = cand["transport_gripper"]
|
| 599 |
+
if cand.get("finger_target_z") is not None:
|
| 600 |
+
grasp_cfg.OBJ_FINGER_CENTER_SERVO_TARGET_Z[obj_idx] = float(cand["finger_target_z"])
|
| 601 |
+
if cand.get("finger_max_z") is not None:
|
| 602 |
+
grasp_cfg.OBJ_FINGER_CENTER_SERVO_MAX_Z[obj_idx] = float(cand["finger_max_z"])
|
| 603 |
+
if cand.get("push_x_gain") is not None:
|
| 604 |
+
grasp_cfg.OBJ_PUSH_X_GAINS[obj_idx] = float(cand["push_x_gain"])
|
| 605 |
+
if cand.get("push_max_x") is not None:
|
| 606 |
+
grasp_cfg.OBJ_PUSH_MAX_X_CORRECTIONS[obj_idx] = float(cand["push_max_x"])
|
| 607 |
+
if cand.get("push_min_behind") is not None:
|
| 608 |
+
grasp_cfg.OBJ_PUSH_MIN_BEHIND[obj_idx] = float(cand["push_min_behind"])
|
| 609 |
+
grasp_cfg.OBJ_TRANSPORT_PUSH_BIASES[obj_idx] = (
|
| 610 |
+
None if cand.get("push_y") is None
|
| 611 |
+
else (cand.get("push_x", 0.0), cand["push_y"], cand.get("push_z", 0.0))
|
| 612 |
+
)
|
| 613 |
+
step_overrides = BASE_STATE_STEP_OVERRIDES.get(obj_idx, {}).copy()
|
| 614 |
+
for cand_key, state_key in (
|
| 615 |
+
("close_steps", "CLOSE"),
|
| 616 |
+
("lift_steps", "LIFT"),
|
| 617 |
+
("transport_steps", "TRANSPORT"),
|
| 618 |
+
("place_steps", "PLACE"),
|
| 619 |
+
("open_steps", "OPEN"),
|
| 620 |
+
):
|
| 621 |
+
if cand.get(cand_key) is not None:
|
| 622 |
+
step_overrides[state_key] = int(cand[cand_key])
|
| 623 |
+
if step_overrides:
|
| 624 |
+
grasp_cfg.OBJ_STATE_STEP_OVERRIDES[obj_idx] = step_overrides
|
| 625 |
+
else:
|
| 626 |
+
grasp_cfg.OBJ_STATE_STEP_OVERRIDES.pop(obj_idx, None)
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
def format_trace(data: dict | None, obj_idx: int) -> str:
|
| 630 |
+
if data is None or "trace" not in data:
|
| 631 |
+
return "trace=none"
|
| 632 |
+
tr = data["trace"].get(f"object_{obj_idx}", {})
|
| 633 |
+
states = tr.get("states", {})
|
| 634 |
+
close = states.get("CLOSE", {})
|
| 635 |
+
lift = states.get("LIFT", {})
|
| 636 |
+
transport = states.get("TRANSPORT", {})
|
| 637 |
+
def _fmt_vec(vec):
|
| 638 |
+
if vec is None:
|
| 639 |
+
return "none"
|
| 640 |
+
return "(" + ",".join(f"{float(v):+.3f}" for v in vec[:3]) + ")"
|
| 641 |
+
return (
|
| 642 |
+
f"lifted={tr.get('lifted')} "
|
| 643 |
+
f"reward_lifted={tr.get('reward_lifted')} "
|
| 644 |
+
f"z_gain={float(tr.get('z_gain', 0.0)):.3f} "
|
| 645 |
+
f"gap_close={float(close.get('min_gripper_gap', 999.0)):.3f} "
|
| 646 |
+
f"gap_lift={float(lift.get('min_gripper_gap', 999.0)):.3f} "
|
| 647 |
+
f"ee_lift={float(lift.get('min_ee_dist', 999.0)):.3f} "
|
| 648 |
+
f"ee_transport={float(transport.get('min_ee_dist', 999.0)):.3f} "
|
| 649 |
+
f"finger_lift={float(lift.get('min_finger_center_dist', 999.0)):.3f} "
|
| 650 |
+
f"finger_gap={float(lift.get('min_finger_body_gap', 999.0)):.3f} "
|
| 651 |
+
f"finger_vec_transport={_fmt_vec(transport.get('min_finger_center_vec'))} "
|
| 652 |
+
f"ee_vec_transport={_fmt_vec(transport.get('min_ee_vec'))}"
|
| 653 |
+
)
|
| 654 |
+
|
| 655 |
+
|
| 656 |
+
def score_candidate(env: ManagerBasedRLEnv, data: dict | None, obj_idx: int, ok: bool) -> float:
|
| 657 |
+
pos = env.unwrapped.scene.rigid_objects[f"object_{obj_idx}"].data.root_pos_w[0]
|
| 658 |
+
dx = abs(float(pos[0].item() - grasp_cfg.BASKET_CENTER_X))
|
| 659 |
+
dy = abs(float(pos[1].item() - grasp_cfg.BASKET_CENTER_Y))
|
| 660 |
+
xy_err = max(dx - grasp_cfg.BASKET_IN_X, 0.0) + max(dy - grasp_cfg.BASKET_IN_Y, 0.0)
|
| 661 |
+
z_gain = 0.0
|
| 662 |
+
if data is not None and "trace" in data:
|
| 663 |
+
z_gain = float(data["trace"].get(f"object_{obj_idx}", {}).get("z_gain", 0.0))
|
| 664 |
+
return (100.0 if ok else 0.0) + 2.0 * z_gain - xy_err
|
| 665 |
+
|
| 666 |
+
|
| 667 |
+
def main() -> None:
|
| 668 |
+
env = build_env()
|
| 669 |
+
dev = env.unwrapped.device
|
| 670 |
+
robot = env.unwrapped.scene.articulations["robot"]
|
| 671 |
+
arm_ids, _ = robot.find_joints(ARM_JOINT_NAMES)
|
| 672 |
+
gripper_ids, _ = robot.find_joints(GRIPPER_JOINT_NAMES)
|
| 673 |
+
ik_ctrl = CartesianController(
|
| 674 |
+
robot=robot,
|
| 675 |
+
ee_body_name=EE_BODY_NAME,
|
| 676 |
+
arm_joint_names=ARM_JOINT_NAMES,
|
| 677 |
+
num_envs=1,
|
| 678 |
+
device=dev,
|
| 679 |
+
command_type="pose",
|
| 680 |
+
lambda_val=0.05,
|
| 681 |
+
max_joint_delta=args_cli.max_joint_delta,
|
| 682 |
+
)
|
| 683 |
+
default_jpos = robot.data.default_joint_pos.clone()
|
| 684 |
+
original_close = STEPS["CLOSE"]
|
| 685 |
+
STEPS["CLOSE"] = max(original_close, 100)
|
| 686 |
+
|
| 687 |
+
try:
|
| 688 |
+
for obj_idx in args_cli.objects:
|
| 689 |
+
print(f"\n[SEARCH] object_{obj_idx}")
|
| 690 |
+
successes: list[dict[str, float]] = []
|
| 691 |
+
best: tuple[float, int, dict[str, float], str] | None = None
|
| 692 |
+
for cand_idx, cand in enumerate(candidates_for(obj_idx), start=max(args_cli.start_candidate, 1)):
|
| 693 |
+
apply_candidate(obj_idx, cand)
|
| 694 |
+
ok_count = 0
|
| 695 |
+
last_status = ""
|
| 696 |
+
last_score = -1e9
|
| 697 |
+
for trial in range(args_cli.trials):
|
| 698 |
+
# Keep trial seeds independent of candidate index so every
|
| 699 |
+
# candidate is evaluated on the same object placements.
|
| 700 |
+
rng = np.random.default_rng(1000 + obj_idx * 100 + trial)
|
| 701 |
+
data = collect_one_demo(
|
| 702 |
+
env,
|
| 703 |
+
robot,
|
| 704 |
+
ik_ctrl,
|
| 705 |
+
arm_ids,
|
| 706 |
+
gripper_ids,
|
| 707 |
+
[obj_idx],
|
| 708 |
+
dev,
|
| 709 |
+
default_jpos=default_jpos,
|
| 710 |
+
rng=rng,
|
| 711 |
+
camera=None,
|
| 712 |
+
trace=True,
|
| 713 |
+
)
|
| 714 |
+
ok = data is not None and check_objects_in_basket(env, [obj_idx])
|
| 715 |
+
ok_count += int(ok)
|
| 716 |
+
last_score = score_candidate(env, data, obj_idx, ok)
|
| 717 |
+
last_status = (
|
| 718 |
+
"; ".join(basket_status_lines(env, [obj_idx]))
|
| 719 |
+
+ " | "
|
| 720 |
+
+ format_trace(data, obj_idx)
|
| 721 |
+
)
|
| 722 |
+
if not ok:
|
| 723 |
+
break
|
| 724 |
+
if best is None or last_score > best[0]:
|
| 725 |
+
best = (last_score, cand_idx, cand.copy(), last_status)
|
| 726 |
+
result = f"{ok_count}/{args_cli.trials}"
|
| 727 |
+
print(
|
| 728 |
+
f"[CAND {cand_idx:03d}] mode={cand.get('mode', 'pick')} result={result} "
|
| 729 |
+
f"dx={cand['dx']:+.3f} dy={cand['dy']:+.3f} "
|
| 730 |
+
f"z={cand['z']:.3f} close_z={cand.get('close_z')} "
|
| 731 |
+
f"finger_z={cand.get('finger_target_z')} carry={cand['carry_z']:.3f} "
|
| 732 |
+
f"target_x={cand['target_x']:+.3f} "
|
| 733 |
+
f"target_y={cand['target_y']:+.3f} "
|
| 734 |
+
f"push=({cand.get('push_x', 0.0):+.3f},{cand.get('push_y')},{cand.get('push_z', 0.0):+.3f}) "
|
| 735 |
+
f"behind={cand.get('push_min_behind')} "
|
| 736 |
+
f"steps=({cand.get('transport_steps')},{cand.get('place_steps')},{cand.get('open_steps')}) "
|
| 737 |
+
f"transport_gripper={cand['transport_gripper']} "
|
| 738 |
+
f"yaw={cand['yaw']:+.3f} | {last_status}",
|
| 739 |
+
flush=True,
|
| 740 |
+
)
|
| 741 |
+
if ok_count == args_cli.trials:
|
| 742 |
+
successes.append(cand.copy())
|
| 743 |
+
print(f"[SUCCESS] object_{obj_idx}: {cand}", flush=True)
|
| 744 |
+
break
|
| 745 |
+
if not successes:
|
| 746 |
+
print(f"[FAIL] object_{obj_idx}: no successful candidate in first {args_cli.max_candidates}")
|
| 747 |
+
if best is not None:
|
| 748 |
+
best_score, best_idx, best_cand, best_status = best
|
| 749 |
+
print(
|
| 750 |
+
f"[BEST] object_{obj_idx}: cand={best_idx:03d} score={best_score:.3f} "
|
| 751 |
+
f"{best_cand} | {best_status}",
|
| 752 |
+
flush=True,
|
| 753 |
+
)
|
| 754 |
+
finally:
|
| 755 |
+
STEPS["CLOSE"] = original_close
|
| 756 |
+
env.close()
|
| 757 |
+
|
| 758 |
+
|
| 759 |
+
if __name__ == "__main__":
|
| 760 |
+
main()
|
| 761 |
+
simulation_app.close()
|
scripts/act/task_e/__init__.py
ADDED
|
File without changes
|
scripts/act/task_e/collector.py
ADDED
|
@@ -0,0 +1,399 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Single-episode demo collection and success checking for Task E."""
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
from isaaclab.envs import ManagerBasedRLEnv
|
| 6 |
+
from atec_rl_lab.utils import CartesianController
|
| 7 |
+
from atec_rl_lab.tasks.task_e.env_cfg import (
|
| 8 |
+
TABLE_CENTER_X, TABLE_CENTER_Y, TABLE_TOP_Z,
|
| 9 |
+
BASKET_CENTER_X, BASKET_CENTER_Y,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
from .config import (
|
| 13 |
+
ACTION_SCALE,
|
| 14 |
+
EE_BODY_NAME,
|
| 15 |
+
GRIPPER_OPEN_POS, GRIPPER_CLOSE_POS,
|
| 16 |
+
OBJ_GRIPPER_CLOSE_POS,
|
| 17 |
+
RETRACT_POS_X, RETRACT_POS_Y, CARRY_Z,
|
| 18 |
+
DEFAULT_PLACE_QUAT_W,
|
| 19 |
+
BASKET_IN_X, BASKET_IN_Y,
|
| 20 |
+
OBJ_SPAWN_X_MIN, OBJ_SPAWN_X_MAX, OBJ_SPAWN_Z, OBJ_SPAWN_Y_BANDS,
|
| 21 |
+
OBJ_HALF_EXTENTS, OBJ_BBOX_MARGIN, OBJ_GRASP_CENTER_OFFSETS,
|
| 22 |
+
OBJ_FINGER_CENTER_SERVO_STATES, OBJ_FINGER_CENTER_SERVO_GAIN,
|
| 23 |
+
OBJ_FINGER_CENTER_SERVO_MAX_XY, OBJ_FINGER_CENTER_SERVO_TARGET_Z,
|
| 24 |
+
OBJ_FINGER_CENTER_SERVO_MAX_Z,
|
| 25 |
+
WARMUP_STEPS, SETTLE_STEPS,
|
| 26 |
+
)
|
| 27 |
+
from .state_machine import PickPlaceStateMachine
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _rerandomize_objects(env: ManagerBasedRLEnv, rng: np.random.Generator) -> None:
|
| 31 |
+
"""Place each object randomly with AABB-based overlap rejection."""
|
| 32 |
+
placed: dict[int, tuple[float, float]] = {} # obj_idx -> (x, y)
|
| 33 |
+
|
| 34 |
+
for obj_idx in [1, 2, 3]:
|
| 35 |
+
obj = env.unwrapped.scene.rigid_objects[f"object_{obj_idx}"]
|
| 36 |
+
y_min, y_max = OBJ_SPAWN_Y_BANDS[obj_idx]
|
| 37 |
+
hx, hy = OBJ_HALF_EXTENTS[obj_idx]
|
| 38 |
+
|
| 39 |
+
x = y = None
|
| 40 |
+
for _ in range(200):
|
| 41 |
+
cx = float(rng.uniform(OBJ_SPAWN_X_MIN, OBJ_SPAWN_X_MAX))
|
| 42 |
+
cy = float(rng.uniform(y_min, y_max))
|
| 43 |
+
# AABB overlap check against all already-placed objects
|
| 44 |
+
ok = all(
|
| 45 |
+
abs(cx - px) >= hx + OBJ_HALF_EXTENTS[pi][0] + OBJ_BBOX_MARGIN or
|
| 46 |
+
abs(cy - py) >= hy + OBJ_HALF_EXTENTS[pi][1] + OBJ_BBOX_MARGIN
|
| 47 |
+
for pi, (px, py) in placed.items()
|
| 48 |
+
)
|
| 49 |
+
if ok:
|
| 50 |
+
x, y = cx, cy
|
| 51 |
+
break
|
| 52 |
+
|
| 53 |
+
if x is None: # fallback: band centre
|
| 54 |
+
x = (OBJ_SPAWN_X_MIN + OBJ_SPAWN_X_MAX) / 2.0
|
| 55 |
+
y = (y_min + y_max) / 2.0
|
| 56 |
+
|
| 57 |
+
placed[obj_idx] = (x, y)
|
| 58 |
+
state = obj.data.default_root_state[0:1].clone()
|
| 59 |
+
state[0, 0] = x
|
| 60 |
+
state[0, 1] = y
|
| 61 |
+
state[0, 2] = OBJ_SPAWN_Z
|
| 62 |
+
state[0, 7:] = 0.0 # zero velocities
|
| 63 |
+
obj.write_root_state_to_sim(state)
|
| 64 |
+
|
| 65 |
+
env.unwrapped.scene.write_data_to_sim()
|
| 66 |
+
env.unwrapped.sim.forward()
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
_BASKET_MAX_Z = TABLE_TOP_Z + 0.15 # keep aligned with Task-E reward/termination bounds
|
| 70 |
+
|
| 71 |
+
def check_objects_in_basket(env: ManagerBasedRLEnv, pick_objects: list[int]) -> bool:
|
| 72 |
+
"""Return True only if every picked object is inside the basket region and settled."""
|
| 73 |
+
for obj_idx in pick_objects:
|
| 74 |
+
pos = env.unwrapped.scene.rigid_objects[f"object_{obj_idx}"].data.root_pos_w[0]
|
| 75 |
+
if (abs(pos[0].item() - BASKET_CENTER_X) > BASKET_IN_X or
|
| 76 |
+
abs(pos[1].item() - BASKET_CENTER_Y) > BASKET_IN_Y or
|
| 77 |
+
pos[2].item() > _BASKET_MAX_Z):
|
| 78 |
+
return False
|
| 79 |
+
return True
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def basket_status_lines(env: ManagerBasedRLEnv, pick_objects: list[int]) -> list[str]:
|
| 83 |
+
"""Return compact debug lines for picked objects against basket bounds."""
|
| 84 |
+
lines = []
|
| 85 |
+
for obj_idx in pick_objects:
|
| 86 |
+
pos = env.unwrapped.scene.rigid_objects[f"object_{obj_idx}"].data.root_pos_w[0]
|
| 87 |
+
dx = pos[0].item() - BASKET_CENTER_X
|
| 88 |
+
dy = pos[1].item() - BASKET_CENTER_Y
|
| 89 |
+
z = pos[2].item()
|
| 90 |
+
inside = abs(dx) <= BASKET_IN_X and abs(dy) <= BASKET_IN_Y and TABLE_TOP_Z <= z <= _BASKET_MAX_Z
|
| 91 |
+
lines.append(
|
| 92 |
+
f"object_{obj_idx}: pos=({pos[0].item():.3f},{pos[1].item():.3f},{z:.3f}) "
|
| 93 |
+
f"d=({dx:+.3f},{dy:+.3f}) inside={inside}"
|
| 94 |
+
)
|
| 95 |
+
return lines
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def collect_one_demo(
|
| 99 |
+
env: ManagerBasedRLEnv,
|
| 100 |
+
robot,
|
| 101 |
+
ik_ctrl: CartesianController,
|
| 102 |
+
arm_ids: list[int],
|
| 103 |
+
gripper_ids: list[int],
|
| 104 |
+
pick_objects: list[int],
|
| 105 |
+
device: str,
|
| 106 |
+
default_jpos: torch.Tensor,
|
| 107 |
+
rng: np.random.Generator,
|
| 108 |
+
camera=None,
|
| 109 |
+
trace: bool = False,
|
| 110 |
+
abort_failed_lift: bool = False,
|
| 111 |
+
) -> dict | None:
|
| 112 |
+
"""Run one full episode and return recorded data, or None on early termination.
|
| 113 |
+
|
| 114 |
+
Returns a dict with keys:
|
| 115 |
+
qpos (T, 8) absolute joint positions
|
| 116 |
+
qvel (T, 8) joint velocities
|
| 117 |
+
ee_pos (T, 3) end-effector position (world frame)
|
| 118 |
+
ee_quat (T, 4) end-effector quaternion (w,x,y,z)
|
| 119 |
+
action (T, 8) env action = (joint_target - default_jpos) / ACTION_SCALE
|
| 120 |
+
frames (T, H, W, 3) RGB uint8 — only present when camera is given
|
| 121 |
+
"""
|
| 122 |
+
env.reset()
|
| 123 |
+
robot.write_joint_state_to_sim(
|
| 124 |
+
robot.data.default_joint_pos,
|
| 125 |
+
torch.zeros_like(robot.data.default_joint_vel),
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
_rerandomize_objects(env, rng) # write new object positions to sim + sim.forward()
|
| 129 |
+
default_jpos = robot.data.default_joint_pos.clone()
|
| 130 |
+
|
| 131 |
+
ee_home = torch.tensor([[RETRACT_POS_X, RETRACT_POS_Y, CARRY_Z]],
|
| 132 |
+
dtype=torch.float32, device=device)
|
| 133 |
+
eq_home = torch.tensor([DEFAULT_PLACE_QUAT_W], dtype=torch.float32, device=device)
|
| 134 |
+
g_open = torch.tensor([GRIPPER_OPEN_POS], dtype=torch.float32, device=device)
|
| 135 |
+
|
| 136 |
+
robot.update(dt=env.unwrapped.physics_dt)
|
| 137 |
+
ik_ctrl.reset()
|
| 138 |
+
|
| 139 |
+
# Warm-up: drive arm to HOME position (not recorded)
|
| 140 |
+
for _ in range(WARMUP_STEPS):
|
| 141 |
+
_step_to(env, robot, ik_ctrl, arm_ids, gripper_ids,
|
| 142 |
+
ee_home, eq_home, g_open, default_jpos)
|
| 143 |
+
|
| 144 |
+
# Pre-compute grasp quaternions from actual object orientations after reset
|
| 145 |
+
sm = PickPlaceStateMachine(pick_objects, device)
|
| 146 |
+
for obj_idx in pick_objects:
|
| 147 |
+
obj_quat = env.unwrapped.scene.rigid_objects[f"object_{obj_idx}"] \
|
| 148 |
+
.data.root_state_w[0, 3:7]
|
| 149 |
+
sm.set_grasp_quat(obj_idx, obj_quat)
|
| 150 |
+
|
| 151 |
+
# Settle
|
| 152 |
+
for _ in range(SETTLE_STEPS):
|
| 153 |
+
_step_to(env, robot, ik_ctrl, arm_ids, gripper_ids,
|
| 154 |
+
ee_home, eq_home, g_open, default_jpos)
|
| 155 |
+
|
| 156 |
+
ik_ctrl.reset()
|
| 157 |
+
|
| 158 |
+
# ---- Recording loop ---- #
|
| 159 |
+
qpos_buf, qvel_buf, ee_pos_buf, ee_quat_buf, action_buf = [], [], [], [], []
|
| 160 |
+
frames_buf = [] if camera is not None else None
|
| 161 |
+
trace_stats: dict[str, dict] | None = {} if trace else None
|
| 162 |
+
ee_body_idx = None
|
| 163 |
+
finger_body_indices: tuple[int, int] | None = None
|
| 164 |
+
ee_body_ids, _ = robot.find_bodies(EE_BODY_NAME)
|
| 165 |
+
if len(ee_body_ids) > 0:
|
| 166 |
+
ee_body_idx = int(ee_body_ids[0])
|
| 167 |
+
link7_ids, _ = robot.find_bodies("link7")
|
| 168 |
+
link8_ids, _ = robot.find_bodies("link8")
|
| 169 |
+
if len(link7_ids) > 0 and len(link8_ids) > 0:
|
| 170 |
+
finger_body_indices = (int(link7_ids[0]), int(link8_ids[0]))
|
| 171 |
+
|
| 172 |
+
def _finger_center() -> torch.Tensor | None:
|
| 173 |
+
if finger_body_indices is None:
|
| 174 |
+
return None
|
| 175 |
+
f0 = robot.data.body_pos_w[0, finger_body_indices[0], :3].detach()
|
| 176 |
+
f1 = robot.data.body_pos_w[0, finger_body_indices[1], :3].detach()
|
| 177 |
+
return 0.5 * (f0 + f1)
|
| 178 |
+
|
| 179 |
+
def _servo_target_to_fingers(
|
| 180 |
+
state_name: str,
|
| 181 |
+
obj_key: str,
|
| 182 |
+
obj_pos: torch.Tensor,
|
| 183 |
+
ee_pos_des: torch.Tensor,
|
| 184 |
+
) -> torch.Tensor:
|
| 185 |
+
obj_idx = int(obj_key.rsplit("_", 1)[1])
|
| 186 |
+
if state_name not in OBJ_FINGER_CENTER_SERVO_STATES.get(obj_idx, ()):
|
| 187 |
+
return ee_pos_des
|
| 188 |
+
finger_center = _finger_center()
|
| 189 |
+
if finger_center is None:
|
| 190 |
+
return ee_pos_des
|
| 191 |
+
grasp_offset = torch.tensor(
|
| 192 |
+
OBJ_GRASP_CENTER_OFFSETS.get(obj_idx, (0.0, 0.0, 0.0)),
|
| 193 |
+
dtype=torch.float32,
|
| 194 |
+
device=device,
|
| 195 |
+
)
|
| 196 |
+
grasp_center = obj_pos + grasp_offset if obj_idx == 1 else obj_pos
|
| 197 |
+
xy_error = finger_center[:2] - grasp_center[:2]
|
| 198 |
+
err_norm = torch.linalg.norm(xy_error)
|
| 199 |
+
if err_norm.item() > 0.18:
|
| 200 |
+
return ee_pos_des
|
| 201 |
+
gain = OBJ_FINGER_CENTER_SERVO_GAIN.get(obj_idx, 0.85)
|
| 202 |
+
correction = -xy_error * gain
|
| 203 |
+
max_xy = OBJ_FINGER_CENTER_SERVO_MAX_XY.get(obj_idx, 0.08)
|
| 204 |
+
corr_norm = torch.linalg.norm(correction).clamp(min=1e-6)
|
| 205 |
+
if corr_norm.item() > max_xy:
|
| 206 |
+
correction = correction / corr_norm * max_xy
|
| 207 |
+
ee_pos_des = ee_pos_des.clone()
|
| 208 |
+
ee_pos_des[:2] = ee_pos_des[:2] + correction
|
| 209 |
+
if state_name in ("REACH", "CLOSE") and obj_idx in OBJ_FINGER_CENTER_SERVO_TARGET_Z:
|
| 210 |
+
target_rel_z = OBJ_FINGER_CENTER_SERVO_TARGET_Z[obj_idx]
|
| 211 |
+
z_error = target_rel_z - float((finger_center[2] - obj_pos[2]).item())
|
| 212 |
+
max_z = OBJ_FINGER_CENTER_SERVO_MAX_Z.get(obj_idx, 0.02)
|
| 213 |
+
z_correction = min(0.0, max(-max_z, z_error * gain))
|
| 214 |
+
ee_pos_des[2] = ee_pos_des[2] + z_correction
|
| 215 |
+
return ee_pos_des
|
| 216 |
+
|
| 217 |
+
def _update_trace(state_name: str, obj_key: str, obj_pos: torch.Tensor) -> None:
|
| 218 |
+
if trace_stats is None:
|
| 219 |
+
return
|
| 220 |
+
obj_idx = int(obj_key.rsplit("_", 1)[1])
|
| 221 |
+
grasp_offset = torch.tensor(
|
| 222 |
+
OBJ_GRASP_CENTER_OFFSETS.get(obj_idx, (0.0, 0.0, 0.0)),
|
| 223 |
+
dtype=torch.float32,
|
| 224 |
+
device=device,
|
| 225 |
+
)
|
| 226 |
+
grasp_center = obj_pos + grasp_offset if obj_idx == 1 else obj_pos
|
| 227 |
+
if ee_body_idx is not None:
|
| 228 |
+
ee_pos = robot.data.body_pos_w[0, ee_body_idx, :3].detach()
|
| 229 |
+
else:
|
| 230 |
+
ee_pos = ik_ctrl.ee_pos_w[0].detach()
|
| 231 |
+
finger_center_dist = None
|
| 232 |
+
finger_body_gap = None
|
| 233 |
+
if finger_body_indices is not None:
|
| 234 |
+
f0 = robot.data.body_pos_w[0, finger_body_indices[0], :3].detach()
|
| 235 |
+
f1 = robot.data.body_pos_w[0, finger_body_indices[1], :3].detach()
|
| 236 |
+
finger_center = 0.5 * (f0 + f1)
|
| 237 |
+
finger_center_dist = float(torch.linalg.norm(grasp_center - finger_center).item())
|
| 238 |
+
finger_body_gap = float(torch.linalg.norm(f0 - f1).item())
|
| 239 |
+
finger_center_vec = [float(v) for v in (finger_center - grasp_center).detach().cpu().tolist()]
|
| 240 |
+
else:
|
| 241 |
+
finger_center_vec = None
|
| 242 |
+
gripper_jpos = robot.data.joint_pos[0, gripper_ids].detach()
|
| 243 |
+
gripper_gap = abs(float(gripper_jpos[0].item() - gripper_jpos[1].item()))
|
| 244 |
+
ee_dist = float(torch.linalg.norm(obj_pos - ee_pos).item())
|
| 245 |
+
ee_vec = [float(v) for v in (ee_pos - obj_pos).detach().cpu().tolist()]
|
| 246 |
+
obj_pos_cpu = [float(v) for v in obj_pos.detach().cpu().tolist()]
|
| 247 |
+
obj_stats = trace_stats.setdefault(
|
| 248 |
+
obj_key,
|
| 249 |
+
{
|
| 250 |
+
"initial_pos": obj_pos_cpu,
|
| 251 |
+
"final_pos": obj_pos_cpu,
|
| 252 |
+
"max_z": obj_pos_cpu[2],
|
| 253 |
+
"min_ee_dist": ee_dist,
|
| 254 |
+
"min_ee_vec": ee_vec,
|
| 255 |
+
"min_gripper_gap": gripper_gap,
|
| 256 |
+
"min_finger_center_dist": finger_center_dist if finger_center_dist is not None else 999.0,
|
| 257 |
+
"min_finger_center_vec": finger_center_vec if finger_center_vec is not None else None,
|
| 258 |
+
"min_finger_body_gap": finger_body_gap if finger_body_gap is not None else 999.0,
|
| 259 |
+
"states": {},
|
| 260 |
+
},
|
| 261 |
+
)
|
| 262 |
+
obj_stats["final_pos"] = obj_pos_cpu
|
| 263 |
+
obj_stats["max_z"] = max(float(obj_stats["max_z"]), obj_pos_cpu[2])
|
| 264 |
+
if ee_dist < float(obj_stats["min_ee_dist"]):
|
| 265 |
+
obj_stats["min_ee_dist"] = ee_dist
|
| 266 |
+
obj_stats["min_ee_vec"] = ee_vec
|
| 267 |
+
obj_stats["min_gripper_gap"] = min(float(obj_stats["min_gripper_gap"]), gripper_gap)
|
| 268 |
+
if finger_center_dist is not None:
|
| 269 |
+
if finger_center_dist < float(obj_stats["min_finger_center_dist"]):
|
| 270 |
+
obj_stats["min_finger_center_dist"] = finger_center_dist
|
| 271 |
+
obj_stats["min_finger_center_vec"] = finger_center_vec
|
| 272 |
+
if finger_body_gap is not None:
|
| 273 |
+
obj_stats["min_finger_body_gap"] = min(float(obj_stats["min_finger_body_gap"]), finger_body_gap)
|
| 274 |
+
st = obj_stats["states"].setdefault(
|
| 275 |
+
state_name,
|
| 276 |
+
{
|
| 277 |
+
"steps": 0,
|
| 278 |
+
"start_pos": obj_pos_cpu,
|
| 279 |
+
"end_pos": obj_pos_cpu,
|
| 280 |
+
"max_z": obj_pos_cpu[2],
|
| 281 |
+
"min_ee_dist": ee_dist,
|
| 282 |
+
"min_ee_vec": ee_vec,
|
| 283 |
+
"min_gripper_gap": gripper_gap,
|
| 284 |
+
"min_finger_center_dist": finger_center_dist if finger_center_dist is not None else 999.0,
|
| 285 |
+
"min_finger_center_vec": finger_center_vec if finger_center_vec is not None else None,
|
| 286 |
+
"min_finger_body_gap": finger_body_gap if finger_body_gap is not None else 999.0,
|
| 287 |
+
},
|
| 288 |
+
)
|
| 289 |
+
st["steps"] += 1
|
| 290 |
+
st["end_pos"] = obj_pos_cpu
|
| 291 |
+
st["max_z"] = max(float(st["max_z"]), obj_pos_cpu[2])
|
| 292 |
+
if ee_dist < float(st["min_ee_dist"]):
|
| 293 |
+
st["min_ee_dist"] = ee_dist
|
| 294 |
+
st["min_ee_vec"] = ee_vec
|
| 295 |
+
st["min_gripper_gap"] = min(float(st["min_gripper_gap"]), gripper_gap)
|
| 296 |
+
if finger_center_dist is not None:
|
| 297 |
+
if finger_center_dist < float(st["min_finger_center_dist"]):
|
| 298 |
+
st["min_finger_center_dist"] = finger_center_dist
|
| 299 |
+
st["min_finger_center_vec"] = finger_center_vec
|
| 300 |
+
if finger_body_gap is not None:
|
| 301 |
+
st["min_finger_body_gap"] = min(float(st["min_finger_body_gap"]), finger_body_gap)
|
| 302 |
+
|
| 303 |
+
def _gripper_target_values(obj_key: str, gripper_cmd: str) -> list[float]:
|
| 304 |
+
if gripper_cmd == "open":
|
| 305 |
+
return GRIPPER_OPEN_POS
|
| 306 |
+
obj_idx = int(obj_key.rsplit("_", 1)[1])
|
| 307 |
+
return OBJ_GRIPPER_CLOSE_POS.get(obj_idx, GRIPPER_CLOSE_POS)
|
| 308 |
+
|
| 309 |
+
while not sm.done:
|
| 310 |
+
state_name = sm.state
|
| 311 |
+
obj_key = sm.current_object_key
|
| 312 |
+
obj_pos_w = env.unwrapped.scene.rigid_objects[sm.current_object_key] \
|
| 313 |
+
.data.root_pos_w[0].clone()
|
| 314 |
+
ee_pos_des, ee_quat_des, gripper_cmd = sm.tick(obj_pos_w)
|
| 315 |
+
ee_pos_des = _servo_target_to_fingers(state_name, obj_key, obj_pos_w, ee_pos_des)
|
| 316 |
+
|
| 317 |
+
arm_jpos_des = ik_ctrl.compute(ee_pos_des.unsqueeze(0), ee_quat_des.unsqueeze(0))
|
| 318 |
+
gripper_vals = _gripper_target_values(obj_key, gripper_cmd)
|
| 319 |
+
gripper_target = torch.tensor([gripper_vals], dtype=torch.float32, device=device)
|
| 320 |
+
|
| 321 |
+
full_target = robot.data.joint_pos.clone()
|
| 322 |
+
full_target[:, arm_ids] = arm_jpos_des
|
| 323 |
+
full_target[:, gripper_ids] = gripper_target
|
| 324 |
+
env_action = (full_target - default_jpos) / ACTION_SCALE
|
| 325 |
+
|
| 326 |
+
# Record BEFORE stepping (obs at time t, action at time t)
|
| 327 |
+
qpos_buf.append(robot.data.joint_pos[0].cpu().numpy())
|
| 328 |
+
qvel_buf.append(robot.data.joint_vel[0].cpu().numpy())
|
| 329 |
+
ee_pos_buf.append(ik_ctrl.ee_pos_w[0].cpu().numpy())
|
| 330 |
+
ee_quat_buf.append(ik_ctrl.ee_quat_w[0].cpu().numpy())
|
| 331 |
+
action_buf.append(env_action[0].cpu().numpy())
|
| 332 |
+
if frames_buf is not None:
|
| 333 |
+
rgba = camera.data.output["rgb"][0].cpu().numpy()
|
| 334 |
+
frames_buf.append(rgba[:, :, :3])
|
| 335 |
+
|
| 336 |
+
_update_trace(state_name, obj_key, obj_pos_w)
|
| 337 |
+
_, _, terminated, truncated, _ = env.step(env_action)
|
| 338 |
+
|
| 339 |
+
if abort_failed_lift and state_name == "LIFT" and sm.state != "LIFT":
|
| 340 |
+
final_obj_pos = env.unwrapped.scene.rigid_objects[obj_key].data.root_pos_w[0]
|
| 341 |
+
lift_gain = float((final_obj_pos[2] - obj_pos_w[2]).item())
|
| 342 |
+
trace_gain = None
|
| 343 |
+
if trace_stats is not None and obj_key in trace_stats:
|
| 344 |
+
obj_stats = trace_stats[obj_key]
|
| 345 |
+
trace_gain = float(obj_stats["max_z"] - obj_stats["initial_pos"][2])
|
| 346 |
+
effective_gain = max(lift_gain, trace_gain if trace_gain is not None else lift_gain)
|
| 347 |
+
if effective_gain < 0.035:
|
| 348 |
+
print(
|
| 349 |
+
f"[WARN] {obj_key} failed lift gate "
|
| 350 |
+
f"(z_gain={effective_gain:.3f}) - aborting attempt."
|
| 351 |
+
)
|
| 352 |
+
return None
|
| 353 |
+
|
| 354 |
+
if terminated.any() or truncated.any():
|
| 355 |
+
if check_objects_in_basket(env, pick_objects):
|
| 356 |
+
print("[INFO] Episode ended after basket success; keeping demo.")
|
| 357 |
+
break
|
| 358 |
+
print("[WARN] Episode ended early — skipping demo.")
|
| 359 |
+
return None
|
| 360 |
+
|
| 361 |
+
result = {
|
| 362 |
+
"qpos": np.stack(qpos_buf),
|
| 363 |
+
"qvel": np.stack(qvel_buf),
|
| 364 |
+
"ee_pos": np.stack(ee_pos_buf),
|
| 365 |
+
"ee_quat": np.stack(ee_quat_buf),
|
| 366 |
+
"action": np.stack(action_buf),
|
| 367 |
+
}
|
| 368 |
+
if frames_buf is not None:
|
| 369 |
+
result["frames"] = np.stack(frames_buf)
|
| 370 |
+
if trace_stats is not None:
|
| 371 |
+
for obj_idx in pick_objects:
|
| 372 |
+
obj_key = f"object_{obj_idx}"
|
| 373 |
+
if obj_key not in trace_stats:
|
| 374 |
+
continue
|
| 375 |
+
final_pos = env.unwrapped.scene.rigid_objects[obj_key].data.root_pos_w[0]
|
| 376 |
+
final_pos_cpu = [float(v) for v in final_pos.detach().cpu().tolist()]
|
| 377 |
+
obj_stats = trace_stats[obj_key]
|
| 378 |
+
obj_stats["final_pos"] = final_pos_cpu
|
| 379 |
+
obj_stats["z_gain"] = float(obj_stats["max_z"] - obj_stats["initial_pos"][2])
|
| 380 |
+
obj_stats["lifted"] = bool(obj_stats["z_gain"] >= 0.035)
|
| 381 |
+
obj_stats["reward_lifted"] = bool(obj_stats["max_z"] >= TABLE_TOP_Z + 0.15)
|
| 382 |
+
obj_stats["basket_inside"] = check_objects_in_basket(env, [obj_idx])
|
| 383 |
+
result["trace"] = trace_stats
|
| 384 |
+
return result
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
# ------------------------------------------------------------------ #
|
| 388 |
+
# Internal helper
|
| 389 |
+
# ------------------------------------------------------------------ #
|
| 390 |
+
|
| 391 |
+
def _step_to(env, robot, ik_ctrl, arm_ids, gripper_ids,
|
| 392 |
+
ee_pos, ee_quat, gripper_target, default_jpos):
|
| 393 |
+
"""Single IK step toward a target pose (utility used during warm-up/settle)."""
|
| 394 |
+
arm_des = ik_ctrl.compute(ee_pos, ee_quat)
|
| 395 |
+
tgt = robot.data.joint_pos.clone()
|
| 396 |
+
tgt[:, arm_ids] = arm_des
|
| 397 |
+
tgt[:, gripper_ids] = gripper_target
|
| 398 |
+
env.step((tgt - default_jpos) / ACTION_SCALE)
|
| 399 |
+
robot.update(dt=env.unwrapped.physics_dt)
|
scripts/act/task_e/config.py
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Task E demo-collection constants.
|
| 2 |
+
"""
|
| 3 |
+
|
| 4 |
+
from atec_rl_lab.tasks.task_e.env_cfg import (
|
| 5 |
+
BASKET_CENTER_X, BASKET_CENTER_Y,
|
| 6 |
+
TABLE_CENTER_X, TABLE_CENTER_Y, TABLE_TOP_Z, TABLE_HALF_X,
|
| 7 |
+
BASKET_EXCL_HALF_X, BASKET_EXCL_HALF_Y,
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
__all__ = [
|
| 11 |
+
"BASKET_CENTER_X", "BASKET_CENTER_Y",
|
| 12 |
+
"TABLE_CENTER_X", "TABLE_CENTER_Y", "TABLE_TOP_Z", "TABLE_HALF_X",
|
| 13 |
+
"BASKET_EXCL_HALF_X", "BASKET_EXCL_HALF_Y",
|
| 14 |
+
# robot
|
| 15 |
+
"EE_BODY_NAME", "ARM_JOINT_NAMES", "GRIPPER_JOINT_NAMES",
|
| 16 |
+
"GRIPPER_OPEN_POS", "GRIPPER_CLOSE_POS", "OBJ_GRIPPER_CLOSE_POS",
|
| 17 |
+
"ACTION_SCALE",
|
| 18 |
+
# state machine
|
| 19 |
+
"STEPS", "STATE_ORDER", "OBJ_STATE_STEP_OVERRIDES",
|
| 20 |
+
# geometry
|
| 21 |
+
"PRE_GRASP_CLEARANCE", "GRASP_Z_OFFSET", "OBJ_GRASP_Z_OFFSETS",
|
| 22 |
+
"OBJ_CLOSE_Z_OFFSETS",
|
| 23 |
+
"OBJ_GRASP_YAW_OFFSETS", "OBJ_CARRY_Z", "OBJ_PLACE_HEIGHTS",
|
| 24 |
+
"OBJ_PLACE_XY_OFFSETS", "OBJ_TRANSPORT_GRIPPER_CMDS",
|
| 25 |
+
"OBJ_KEEP_GRASP_QUAT_STATES", "OBJ_TRANSPORT_PUSH_BIASES",
|
| 26 |
+
"OBJ_MANIPULATION_MODES", "OBJ_PUSH_GRIPPER_CMDS",
|
| 27 |
+
"OBJ_PUSH_APPROACH_CLEARANCE",
|
| 28 |
+
"OBJ_PUSH_X_GAINS", "OBJ_PUSH_MAX_X_CORRECTIONS",
|
| 29 |
+
"OBJ_PUSH_Y_GAINS", "OBJ_PUSH_MAX_Y_CORRECTIONS",
|
| 30 |
+
"OBJ_PUSH_MIN_BEHIND",
|
| 31 |
+
"OBJ_SERVO_TO_BASKET_STATES", "OBJ_SERVO_XY_GAINS", "OBJ_SERVO_MAX_XY",
|
| 32 |
+
"OBJ_SERVO_HOLD_STATES", "OBJ_SERVO_EXTRA_STEPS",
|
| 33 |
+
"OBJ_FINGER_CENTER_SERVO_STATES", "OBJ_FINGER_CENTER_SERVO_GAIN",
|
| 34 |
+
"OBJ_FINGER_CENTER_SERVO_MAX_XY", "OBJ_FINGER_CENTER_SERVO_TARGET_Z",
|
| 35 |
+
"OBJ_FINGER_CENTER_SERVO_MAX_Z",
|
| 36 |
+
"CARRY_Z", "PLACE_HEIGHT",
|
| 37 |
+
"RETRACT_POS_X", "RETRACT_POS_Y",
|
| 38 |
+
"DEFAULT_PLACE_QUAT_W",
|
| 39 |
+
# success check
|
| 40 |
+
"BASKET_IN_X", "BASKET_IN_Y",
|
| 41 |
+
# spawn regions
|
| 42 |
+
"OBJ_SPAWN_X_MIN", "OBJ_SPAWN_X_MAX", "OBJ_SPAWN_Z", "OBJ_SPAWN_Y_BANDS",
|
| 43 |
+
"OBJ_HALF_EXTENTS", "OBJ_BBOX_MARGIN", "OBJ_GRASP_CENTER_OFFSETS",
|
| 44 |
+
# camera
|
| 45 |
+
"CAM_POS", "CAM_ROT", "CAM_H", "CAM_W",
|
| 46 |
+
# actuator
|
| 47 |
+
"ACT_STIFFNESS", "ACT_DAMPING", "ACT_EFFORT_LIMIT", "ACT_VEL_LIMIT",
|
| 48 |
+
# warm-up
|
| 49 |
+
"WARMUP_STEPS", "SETTLE_STEPS",
|
| 50 |
+
]
|
| 51 |
+
|
| 52 |
+
# ------------------------------------------------------------------ #
|
| 53 |
+
# Robot
|
| 54 |
+
# ------------------------------------------------------------------ #
|
| 55 |
+
EE_BODY_NAME = "gripper_base"
|
| 56 |
+
ARM_JOINT_NAMES = ["joint1", "joint2", "joint3", "joint4", "joint5", "joint6"]
|
| 57 |
+
GRIPPER_JOINT_NAMES = ["joint7", "joint8"]
|
| 58 |
+
GRIPPER_OPEN_POS = [0.035, -0.035] # joint7, joint8
|
| 59 |
+
GRIPPER_CLOSE_POS = [0.0, 0.0] # joint limits: joint7 >= 0, joint8 <= 0
|
| 60 |
+
OBJ_GRIPPER_CLOSE_POS: dict[int, list[float]] = {}
|
| 61 |
+
|
| 62 |
+
# Must match ActionsCfg: scale=0.5, use_default_offset=True
|
| 63 |
+
# env_action = (joint_target - default_joint_pos) / ACTION_SCALE
|
| 64 |
+
ACTION_SCALE = 0.5
|
| 65 |
+
|
| 66 |
+
# ------------------------------------------------------------------ #
|
| 67 |
+
# State-machine
|
| 68 |
+
# ------------------------------------------------------------------ #
|
| 69 |
+
STEPS: dict[str, int] = {
|
| 70 |
+
"INIT": 100,
|
| 71 |
+
"PRE_GRASP": 220,
|
| 72 |
+
"REACH": 150,
|
| 73 |
+
"CLOSE": 80,
|
| 74 |
+
"LIFT": 170,
|
| 75 |
+
"TRANSPORT": 240,
|
| 76 |
+
"PLACE": 90,
|
| 77 |
+
"OPEN": 70,
|
| 78 |
+
"LIFT_RETRACT": 80,
|
| 79 |
+
"RETRACT": 80,
|
| 80 |
+
}
|
| 81 |
+
STATE_ORDER = ["INIT", "PRE_GRASP", "REACH", "CLOSE", "LIFT",
|
| 82 |
+
"TRANSPORT", "PLACE", "OPEN", "LIFT_RETRACT", "RETRACT"]
|
| 83 |
+
OBJ_STATE_STEP_OVERRIDES: dict[int, dict[str, int]] = {
|
| 84 |
+
1: {
|
| 85 |
+
"TRANSPORT": 2200,
|
| 86 |
+
"PLACE": 300,
|
| 87 |
+
},
|
| 88 |
+
2: {
|
| 89 |
+
"TRANSPORT": 2200,
|
| 90 |
+
"PLACE": 300,
|
| 91 |
+
},
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
# ------------------------------------------------------------------ #
|
| 95 |
+
# Geometry
|
| 96 |
+
# ------------------------------------------------------------------ #
|
| 97 |
+
PRE_GRASP_CLEARANCE = 0.12 # metres above object before descent
|
| 98 |
+
GRASP_Z_OFFSET = 0.09 # metres: gripper approach height above object centre
|
| 99 |
+
|
| 100 |
+
CARRY_Z = TABLE_TOP_Z + 0.40 # safe carry height
|
| 101 |
+
PLACE_HEIGHT = TABLE_TOP_Z + 0.15 # height at which to release into basket
|
| 102 |
+
|
| 103 |
+
RETRACT_POS_X = TABLE_CENTER_X + TABLE_HALF_X - 0.05
|
| 104 |
+
RETRACT_POS_Y = TABLE_CENTER_Y
|
| 105 |
+
DEFAULT_PLACE_QUAT_W = [0.0, 1.0, 0.0, 0.0] # top-down orientation (w,x,y,z)
|
| 106 |
+
|
| 107 |
+
# ------------------------------------------------------------------ #
|
| 108 |
+
# Object spawn regions
|
| 109 |
+
#
|
| 110 |
+
# object_1 Y ∈ [0.25, 0.29] (top band)
|
| 111 |
+
# object_2 Y ∈ [0.14, 0.20] (middle band)
|
| 112 |
+
# object_3 Y ∈ [0.03, 0.09] (bottom band, closest to basket)
|
| 113 |
+
# ------------------------------------------------------------------ #
|
| 114 |
+
OBJ_SPAWN_X_MIN = TABLE_CENTER_X - 0.10
|
| 115 |
+
OBJ_SPAWN_X_MAX = TABLE_CENTER_X + 0.10
|
| 116 |
+
OBJ_SPAWN_Z = TABLE_TOP_Z + 0.05
|
| 117 |
+
|
| 118 |
+
# Per-object Y-bands: {object_idx: (y_min, y_max)}
|
| 119 |
+
OBJ_SPAWN_Y_BANDS = {
|
| 120 |
+
1: (TABLE_CENTER_Y + 0.25, TABLE_CENTER_Y + 0.29),
|
| 121 |
+
2: (TABLE_CENTER_Y + 0.14, TABLE_CENTER_Y + 0.20),
|
| 122 |
+
3: (TABLE_CENTER_Y + 0.03, TABLE_CENTER_Y + 0.09),
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
# Per-object 2-D bounding-box half-extents (metres, world XY plane, scale=1).
|
| 126 |
+
# Used for AABB overlap rejection during randomisation.
|
| 127 |
+
OBJ_HALF_EXTENTS: dict[int, tuple[float, float]] = {
|
| 128 |
+
1: (0.050, 0.044), # Sugar box (half_x, half_y)
|
| 129 |
+
2: (0.050, 0.030), # Mustard bottle
|
| 130 |
+
3: (0.100, 0.040), # Banana
|
| 131 |
+
}
|
| 132 |
+
OBJ_BBOX_MARGIN = 0.015 # extra clearance between object bounding boxes
|
| 133 |
+
|
| 134 |
+
# The object USD roots are centered on the visible geometry. Keep the XY target
|
| 135 |
+
# on the root/contact point; compensate the Piper TCP primarily in Z through
|
| 136 |
+
# OBJ_GRASP_Z_OFFSETS.
|
| 137 |
+
OBJ_GRASP_CENTER_OFFSETS: dict[int, tuple[float, float, float]] = {
|
| 138 |
+
1: (0.025, 0.0, 0.0), # Sugar box: compensate Piper fingertip centre offset
|
| 139 |
+
2: (0.060, 0.0, 0.0), # Mustard bottle: grasp a narrower side section
|
| 140 |
+
3: (0.0, 0.0, 0.0), # Banana already works from its root pose
|
| 141 |
+
}
|
| 142 |
+
OBJ_GRASP_Z_OFFSETS: dict[int, float] = {
|
| 143 |
+
1: 0.072,
|
| 144 |
+
2: 0.135,
|
| 145 |
+
3: GRASP_Z_OFFSET,
|
| 146 |
+
}
|
| 147 |
+
OBJ_CLOSE_Z_OFFSETS: dict[int, float] = {
|
| 148 |
+
1: 0.020,
|
| 149 |
+
}
|
| 150 |
+
OBJ_GRASP_YAW_OFFSETS: dict[int, float] = {
|
| 151 |
+
1: 0.0,
|
| 152 |
+
2: 0.0,
|
| 153 |
+
3: 0.0,
|
| 154 |
+
}
|
| 155 |
+
OBJ_CARRY_Z: dict[int, float] = {
|
| 156 |
+
1: CARRY_Z,
|
| 157 |
+
2: CARRY_Z,
|
| 158 |
+
3: CARRY_Z,
|
| 159 |
+
}
|
| 160 |
+
OBJ_PLACE_HEIGHTS: dict[int, float] = {
|
| 161 |
+
1: PLACE_HEIGHT,
|
| 162 |
+
2: PLACE_HEIGHT,
|
| 163 |
+
3: PLACE_HEIGHT,
|
| 164 |
+
}
|
| 165 |
+
OBJ_PLACE_XY_OFFSETS: dict[int, tuple[float, float]] = {
|
| 166 |
+
1: (0.0, 0.0),
|
| 167 |
+
2: (0.0, 0.0),
|
| 168 |
+
3: (0.040, 0.050),
|
| 169 |
+
}
|
| 170 |
+
OBJ_TRANSPORT_GRIPPER_CMDS: dict[int, str] = {
|
| 171 |
+
1: "close",
|
| 172 |
+
2: "close",
|
| 173 |
+
3: "close",
|
| 174 |
+
}
|
| 175 |
+
OBJ_KEEP_GRASP_QUAT_STATES: dict[int, tuple[str, ...]] = {
|
| 176 |
+
1: ("REACH", "CLOSE", "LIFT", "TRANSPORT", "PLACE", "OPEN"),
|
| 177 |
+
2: ("REACH", "CLOSE", "LIFT", "TRANSPORT", "PLACE", "OPEN"),
|
| 178 |
+
3: ("REACH", "CLOSE", "LIFT"),
|
| 179 |
+
}
|
| 180 |
+
OBJ_TRANSPORT_PUSH_BIASES: dict[int, tuple[float, float, float] | None] = {
|
| 181 |
+
1: None,
|
| 182 |
+
2: None,
|
| 183 |
+
3: None,
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
# Optional manipulation mode used by the candidate search. "pick" keeps the
|
| 187 |
+
# normal top-down grasp. "push" turns the same state machine into a low,
|
| 188 |
+
# table-contact pusher that drives the object centre to the basket.
|
| 189 |
+
OBJ_MANIPULATION_MODES: dict[int, str] = {
|
| 190 |
+
1: "pick",
|
| 191 |
+
2: "pick",
|
| 192 |
+
3: "pick",
|
| 193 |
+
}
|
| 194 |
+
OBJ_PUSH_GRIPPER_CMDS: dict[int, str] = {
|
| 195 |
+
1: "close",
|
| 196 |
+
2: "close",
|
| 197 |
+
}
|
| 198 |
+
OBJ_PUSH_APPROACH_CLEARANCE: dict[int, float] = {
|
| 199 |
+
1: 0.14,
|
| 200 |
+
2: 0.14,
|
| 201 |
+
}
|
| 202 |
+
OBJ_PUSH_X_GAINS: dict[int, float] = {
|
| 203 |
+
1: 0.55,
|
| 204 |
+
2: 0.55,
|
| 205 |
+
}
|
| 206 |
+
OBJ_PUSH_MAX_X_CORRECTIONS: dict[int, float] = {
|
| 207 |
+
1: 0.08,
|
| 208 |
+
2: 0.08,
|
| 209 |
+
}
|
| 210 |
+
OBJ_PUSH_Y_GAINS: dict[int, float] = {
|
| 211 |
+
1: 0.85,
|
| 212 |
+
2: 0.85,
|
| 213 |
+
}
|
| 214 |
+
OBJ_PUSH_MAX_Y_CORRECTIONS: dict[int, float] = {
|
| 215 |
+
1: 0.22,
|
| 216 |
+
2: 0.22,
|
| 217 |
+
}
|
| 218 |
+
OBJ_PUSH_MIN_BEHIND: dict[int, float] = {
|
| 219 |
+
1: 0.035,
|
| 220 |
+
2: 0.030,
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
# For the hard objects, keep the arm target coupled to the measured object
|
| 224 |
+
# position during carry/release. This compensates for Piper gripper_base/TCP
|
| 225 |
+
# offsets and small slips: the EE target is nudged in the direction that would
|
| 226 |
+
# move the object centre into the basket.
|
| 227 |
+
OBJ_SERVO_TO_BASKET_STATES: dict[int, tuple[str, ...]] = {
|
| 228 |
+
1: ("TRANSPORT", "PLACE", "OPEN"),
|
| 229 |
+
2: (),
|
| 230 |
+
}
|
| 231 |
+
OBJ_SERVO_XY_GAINS: dict[int, float] = {
|
| 232 |
+
1: 0.85,
|
| 233 |
+
2: 0.85,
|
| 234 |
+
}
|
| 235 |
+
OBJ_SERVO_MAX_XY: dict[int, float] = {
|
| 236 |
+
1: 0.28,
|
| 237 |
+
2: 0.24,
|
| 238 |
+
}
|
| 239 |
+
OBJ_SERVO_HOLD_STATES: dict[int, tuple[str, ...]] = {
|
| 240 |
+
1: ("PLACE",),
|
| 241 |
+
2: ("PLACE",),
|
| 242 |
+
}
|
| 243 |
+
OBJ_SERVO_EXTRA_STEPS: dict[int, int] = {
|
| 244 |
+
1: 500,
|
| 245 |
+
2: 500,
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
# Closed-loop correction used during scripted data generation. The target pose
|
| 249 |
+
# is nudged so the measured finger centre stays on the selected object centre,
|
| 250 |
+
# which absorbs IK/tracking variation across random object positions.
|
| 251 |
+
OBJ_FINGER_CENTER_SERVO_STATES: dict[int, tuple[str, ...]] = {
|
| 252 |
+
1: ("REACH", "CLOSE", "LIFT", "TRANSPORT", "PLACE"),
|
| 253 |
+
2: ("REACH", "CLOSE", "LIFT", "TRANSPORT", "PLACE"),
|
| 254 |
+
}
|
| 255 |
+
OBJ_FINGER_CENTER_SERVO_GAIN: dict[int, float] = {
|
| 256 |
+
1: 1.0,
|
| 257 |
+
2: 1.0,
|
| 258 |
+
}
|
| 259 |
+
OBJ_FINGER_CENTER_SERVO_MAX_XY: dict[int, float] = {
|
| 260 |
+
1: 0.12,
|
| 261 |
+
2: 0.12,
|
| 262 |
+
}
|
| 263 |
+
OBJ_FINGER_CENTER_SERVO_TARGET_Z: dict[int, float] = {
|
| 264 |
+
1: -0.025,
|
| 265 |
+
}
|
| 266 |
+
OBJ_FINGER_CENTER_SERVO_MAX_Z: dict[int, float] = {
|
| 267 |
+
1: 0.050,
|
| 268 |
+
}
|
| 269 |
+
|
| 270 |
+
# ------------------------------------------------------------------ #
|
| 271 |
+
# Success / basket bounds
|
| 272 |
+
# ------------------------------------------------------------------ #
|
| 273 |
+
BASKET_IN_X = 0.20 # ± metres in X around BASKET_CENTER_X
|
| 274 |
+
BASKET_IN_Y = 0.11 # ± metres in Y around BASKET_CENTER_Y
|
| 275 |
+
|
| 276 |
+
# ------------------------------------------------------------------ #
|
| 277 |
+
# Camera (for --save_video / --save_images)
|
| 278 |
+
# ------------------------------------------------------------------ #
|
| 279 |
+
CAM_H, CAM_W = 480, 640
|
| 280 |
+
CAM_POS = (TABLE_CENTER_X - 1.2, TABLE_CENTER_Y, TABLE_TOP_Z + 0.8)
|
| 281 |
+
CAM_ROT = (0.957, 0.0, 0.290, 0.0) # ~34° around +Y → looks forward-down
|
| 282 |
+
|
| 283 |
+
# ------------------------------------------------------------------ #
|
| 284 |
+
# Actuator overrides for data collection (high stiffness for fast tracking)
|
| 285 |
+
# ------------------------------------------------------------------ #
|
| 286 |
+
ACT_STIFFNESS = 800.0
|
| 287 |
+
ACT_DAMPING = 80.0
|
| 288 |
+
ACT_EFFORT_LIMIT = 100.0
|
| 289 |
+
ACT_VEL_LIMIT = 100.0
|
| 290 |
+
|
| 291 |
+
# ------------------------------------------------------------------ #
|
| 292 |
+
# Warm-up / settle steps before recording starts
|
| 293 |
+
# ------------------------------------------------------------------ #
|
| 294 |
+
WARMUP_STEPS = 150
|
| 295 |
+
SETTLE_STEPS = 30
|
scripts/act/task_e/state_machine.py
ADDED
|
@@ -0,0 +1,439 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pick-place state machine and grasp-quaternion solver for Task E."""
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from isaaclab.utils.math import matrix_from_quat, quat_from_matrix
|
| 5 |
+
|
| 6 |
+
from .config import (
|
| 7 |
+
STEPS, STATE_ORDER, OBJ_STATE_STEP_OVERRIDES,
|
| 8 |
+
CARRY_Z, PLACE_HEIGHT,
|
| 9 |
+
RETRACT_POS_X, RETRACT_POS_Y,
|
| 10 |
+
GRASP_Z_OFFSET, OBJ_GRASP_Z_OFFSETS, OBJ_CLOSE_Z_OFFSETS,
|
| 11 |
+
OBJ_GRASP_YAW_OFFSETS,
|
| 12 |
+
BASKET_CENTER_X, BASKET_CENTER_Y,
|
| 13 |
+
DEFAULT_PLACE_QUAT_W,
|
| 14 |
+
OBJ_GRASP_CENTER_OFFSETS,
|
| 15 |
+
OBJ_CARRY_Z, OBJ_PLACE_HEIGHTS, OBJ_PLACE_XY_OFFSETS,
|
| 16 |
+
OBJ_TRANSPORT_GRIPPER_CMDS, OBJ_KEEP_GRASP_QUAT_STATES,
|
| 17 |
+
OBJ_TRANSPORT_PUSH_BIASES,
|
| 18 |
+
OBJ_MANIPULATION_MODES, OBJ_PUSH_GRIPPER_CMDS,
|
| 19 |
+
OBJ_PUSH_APPROACH_CLEARANCE,
|
| 20 |
+
OBJ_PUSH_X_GAINS, OBJ_PUSH_MAX_X_CORRECTIONS,
|
| 21 |
+
OBJ_PUSH_Y_GAINS, OBJ_PUSH_MAX_Y_CORRECTIONS,
|
| 22 |
+
OBJ_PUSH_MIN_BEHIND,
|
| 23 |
+
OBJ_SERVO_TO_BASKET_STATES, OBJ_SERVO_XY_GAINS, OBJ_SERVO_MAX_XY,
|
| 24 |
+
OBJ_SERVO_HOLD_STATES, OBJ_SERVO_EXTRA_STEPS,
|
| 25 |
+
BASKET_IN_X, BASKET_IN_Y,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _build_grasp_matrix(long_axis: torch.Tensor, grip_z: torch.Tensor) -> torch.Tensor:
|
| 30 |
+
"""Build a right-handed gripper rotation matrix given the object's long axis.
|
| 31 |
+
|
| 32 |
+
The Piper gripper jaw opens along its LOCAL Y axis, so local Y must be
|
| 33 |
+
perpendicular to the object's long axis.
|
| 34 |
+
|
| 35 |
+
Frame layout (columns of R_grip):
|
| 36 |
+
col 0 (local X) = align_dir ∥ long_axis
|
| 37 |
+
col 1 (local Y) = jaw_dir ⊥ long_axis ← jaw opening direction
|
| 38 |
+
col 2 (local Z) = grip_z pointing down
|
| 39 |
+
|
| 40 |
+
Right-hand check: col0 × col1 = align_dir × jaw_dir = grip_z ✓
|
| 41 |
+
"""
|
| 42 |
+
jaw_dir = torch.linalg.cross(long_axis, grip_z) # ⊥ long_axis, in XY plane
|
| 43 |
+
jaw_dir = jaw_dir / jaw_dir.norm().clamp(min=1e-6)
|
| 44 |
+
align_dir = torch.linalg.cross(jaw_dir, grip_z) # ∥ long_axis
|
| 45 |
+
align_dir = align_dir / align_dir.norm().clamp(min=1e-6)
|
| 46 |
+
return torch.stack([align_dir, jaw_dir, grip_z], dim=1) # (3, 3)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def compute_grasp_quat(obj_quat_w: torch.Tensor, device: str) -> torch.Tensor:
|
| 50 |
+
"""Compute a top-down grasp quaternion for the object.
|
| 51 |
+
|
| 52 |
+
Finds the object axis most aligned with the world XY-plane (the long axis),
|
| 53 |
+
builds a gripper frame where the jaw (local Y) is perpendicular to that axis,
|
| 54 |
+
then picks the candidate orientation closest to the default top-down pose.
|
| 55 |
+
|
| 56 |
+
Parameters
|
| 57 |
+
----------
|
| 58 |
+
obj_quat_w : (4,) tensor, (w, x, y, z)
|
| 59 |
+
device : torch device string
|
| 60 |
+
|
| 61 |
+
Returns
|
| 62 |
+
-------
|
| 63 |
+
grasp_quat : (4,) tensor, (w, x, y, z)
|
| 64 |
+
"""
|
| 65 |
+
R_obj = matrix_from_quat(obj_quat_w.unsqueeze(0)).squeeze(0) # (3, 3)
|
| 66 |
+
grip_z = torch.tensor([0.0, 0.0, -1.0], device=device)
|
| 67 |
+
default_quat = torch.tensor(DEFAULT_PLACE_QUAT_W, dtype=torch.float32, device=device)
|
| 68 |
+
|
| 69 |
+
# Project each object column-axis onto XY plane; keep the most horizontal one(s)
|
| 70 |
+
norms, axes_xy = [], []
|
| 71 |
+
for col in range(3):
|
| 72 |
+
ax = torch.tensor([R_obj[0, col].item(), R_obj[1, col].item(), 0.0], device=device)
|
| 73 |
+
norms.append(ax.norm().item())
|
| 74 |
+
axes_xy.append(ax)
|
| 75 |
+
|
| 76 |
+
best_norm = max(norms)
|
| 77 |
+
candidates = [
|
| 78 |
+
axes_xy[c] / max(norms[c], 1e-6)
|
| 79 |
+
for c in range(3)
|
| 80 |
+
if norms[c] >= best_norm - 1e-3
|
| 81 |
+
]
|
| 82 |
+
|
| 83 |
+
# Among candidates, pick the one whose grasp frame is closest to the default orientation
|
| 84 |
+
best_cos = -2.0
|
| 85 |
+
long_axis = candidates[0]
|
| 86 |
+
for cand in candidates:
|
| 87 |
+
q_cand = quat_from_matrix(_build_grasp_matrix(cand, grip_z).unsqueeze(0)).squeeze(0)
|
| 88 |
+
cos_sim = torch.abs((q_cand * default_quat).sum()).item()
|
| 89 |
+
if cos_sim > best_cos:
|
| 90 |
+
best_cos = cos_sim
|
| 91 |
+
long_axis = cand
|
| 92 |
+
|
| 93 |
+
R_grip = _build_grasp_matrix(long_axis, grip_z) # (3, 3)
|
| 94 |
+
return quat_from_matrix(R_grip.unsqueeze(0)).squeeze(0) # (4,) w,x,y,z
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _quat_mul(q1: torch.Tensor, q2: torch.Tensor) -> torch.Tensor:
|
| 98 |
+
w1, x1, y1, z1 = q1.unbind()
|
| 99 |
+
w2, x2, y2, z2 = q2.unbind()
|
| 100 |
+
return torch.stack([
|
| 101 |
+
w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2,
|
| 102 |
+
w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
|
| 103 |
+
w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2,
|
| 104 |
+
w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2,
|
| 105 |
+
])
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
class PickPlaceStateMachine:
|
| 109 |
+
"""Finite state machine that sequences pick-and-place for multiple objects.
|
| 110 |
+
|
| 111 |
+
States (in order): INIT → PRE_GRASP → REACH → CLOSE → LIFT →
|
| 112 |
+
TRANSPORT → PLACE → OPEN → RETRACT → (next object or done)
|
| 113 |
+
"""
|
| 114 |
+
|
| 115 |
+
def __init__(self, object_indices: list[int], device: str):
|
| 116 |
+
self._obj_indices = object_indices
|
| 117 |
+
self._device = device
|
| 118 |
+
self._grasp_quat_cache: dict[int, torch.Tensor] = {}
|
| 119 |
+
self.reset()
|
| 120 |
+
|
| 121 |
+
def reset(self) -> None:
|
| 122 |
+
self._ptr = 0
|
| 123 |
+
self._state_idx = 0
|
| 124 |
+
self._count = 0
|
| 125 |
+
self.done = False
|
| 126 |
+
self._cached_obj_pos: torch.Tensor | None = None
|
| 127 |
+
self._servo_extra_counts: dict[tuple[int, str], int] = {}
|
| 128 |
+
self._grasp_quat_cache.clear()
|
| 129 |
+
|
| 130 |
+
def set_grasp_quat(self, obj_idx: int, obj_quat_w: torch.Tensor) -> None:
|
| 131 |
+
"""Pre-compute and cache the grasp quaternion for one object."""
|
| 132 |
+
grasp_quat = compute_grasp_quat(obj_quat_w, self._device)
|
| 133 |
+
yaw = OBJ_GRASP_YAW_OFFSETS.get(obj_idx, 0.0)
|
| 134 |
+
if abs(yaw) > 1e-6:
|
| 135 |
+
half = torch.tensor(0.5 * yaw, dtype=torch.float32, device=self._device)
|
| 136 |
+
yaw_quat = torch.stack([
|
| 137 |
+
torch.cos(half),
|
| 138 |
+
torch.tensor(0.0, dtype=torch.float32, device=self._device),
|
| 139 |
+
torch.tensor(0.0, dtype=torch.float32, device=self._device),
|
| 140 |
+
torch.sin(half),
|
| 141 |
+
])
|
| 142 |
+
grasp_quat = _quat_mul(yaw_quat, grasp_quat)
|
| 143 |
+
grasp_quat = grasp_quat / grasp_quat.norm().clamp(min=1e-6)
|
| 144 |
+
self._grasp_quat_cache[obj_idx] = grasp_quat
|
| 145 |
+
|
| 146 |
+
def tick(self, obj_pos: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, str]:
|
| 147 |
+
"""Advance the state machine by one step.
|
| 148 |
+
|
| 149 |
+
Parameters
|
| 150 |
+
----------
|
| 151 |
+
obj_pos : (3,) tensor — current object position in world frame
|
| 152 |
+
|
| 153 |
+
Returns
|
| 154 |
+
-------
|
| 155 |
+
ee_pos_des : (3,) target EE position
|
| 156 |
+
ee_quat_des : (4,) target EE orientation (w,x,y,z)
|
| 157 |
+
gripper_cmd : "open" | "close"
|
| 158 |
+
"""
|
| 159 |
+
s = self.state
|
| 160 |
+
d = self._device
|
| 161 |
+
|
| 162 |
+
# Freeze object position at start of PRE_GRASP to avoid drift during descent
|
| 163 |
+
if s == "PRE_GRASP" and self._count == 0:
|
| 164 |
+
self._cached_obj_pos = obj_pos.clone()
|
| 165 |
+
if s in ("REACH", "CLOSE", "LIFT") and self._cached_obj_pos is not None:
|
| 166 |
+
obj_pos = self._cached_obj_pos
|
| 167 |
+
|
| 168 |
+
ee_pos, gripper = self._get_target_pos_gripper(s, obj_pos, d)
|
| 169 |
+
ee_quat = self._get_target_quat(s, d)
|
| 170 |
+
|
| 171 |
+
self._count += 1
|
| 172 |
+
if self._count >= self._get_state_steps(s):
|
| 173 |
+
if self._should_hold_servo_state(s, obj_pos):
|
| 174 |
+
self._count = self._get_state_steps(s) - 1
|
| 175 |
+
return ee_pos, ee_quat, gripper
|
| 176 |
+
self._count = 0
|
| 177 |
+
if s == "RETRACT":
|
| 178 |
+
self._ptr += 1
|
| 179 |
+
self._cached_obj_pos = None
|
| 180 |
+
if self._ptr >= len(self._obj_indices):
|
| 181 |
+
self.done = True
|
| 182 |
+
return ee_pos, ee_quat, gripper
|
| 183 |
+
self._state_idx = STATE_ORDER.index("PRE_GRASP")
|
| 184 |
+
else:
|
| 185 |
+
self._state_idx += 1
|
| 186 |
+
|
| 187 |
+
return ee_pos, ee_quat, gripper
|
| 188 |
+
|
| 189 |
+
# ------------------------------------------------------------------ #
|
| 190 |
+
# Properties
|
| 191 |
+
# ------------------------------------------------------------------ #
|
| 192 |
+
|
| 193 |
+
@property
|
| 194 |
+
def state(self) -> str:
|
| 195 |
+
return STATE_ORDER[self._state_idx]
|
| 196 |
+
|
| 197 |
+
@property
|
| 198 |
+
def current_object_key(self) -> str:
|
| 199 |
+
return f"object_{self._obj_indices[self._ptr]}"
|
| 200 |
+
|
| 201 |
+
# ------------------------------------------------------------------ #
|
| 202 |
+
# Private helpers
|
| 203 |
+
# ------------------------------------------------------------------ #
|
| 204 |
+
|
| 205 |
+
def _get_target_pos_gripper(
|
| 206 |
+
self, s: str, obj_pos: torch.Tensor, d: str
|
| 207 |
+
) -> tuple[torch.Tensor, str]:
|
| 208 |
+
if self._is_push_mode():
|
| 209 |
+
return self._get_push_target_pos_gripper(s, obj_pos, d)
|
| 210 |
+
|
| 211 |
+
grasp_pos = self._get_grasp_pos(obj_pos, d)
|
| 212 |
+
if s == "INIT":
|
| 213 |
+
return torch.tensor([RETRACT_POS_X, RETRACT_POS_Y, CARRY_Z], device=d), "open"
|
| 214 |
+
elif s == "PRE_GRASP":
|
| 215 |
+
p = grasp_pos.clone(); p[2] = CARRY_Z
|
| 216 |
+
return p, "open"
|
| 217 |
+
elif s == "REACH":
|
| 218 |
+
p = grasp_pos.clone(); p[2] += self._get_grasp_z_offset()
|
| 219 |
+
return p, "open"
|
| 220 |
+
elif s == "CLOSE":
|
| 221 |
+
p = grasp_pos.clone(); p[2] += self._get_close_z_offset()
|
| 222 |
+
return p, "close"
|
| 223 |
+
elif s == "LIFT":
|
| 224 |
+
p = grasp_pos.clone(); p[2] = self._get_carry_z()
|
| 225 |
+
return p, self._get_transport_gripper_cmd()
|
| 226 |
+
elif s == "TRANSPORT":
|
| 227 |
+
servo = self._get_object_servo_target(s, obj_pos, grasp_pos, self._get_carry_z(), d)
|
| 228 |
+
if servo is not None:
|
| 229 |
+
return servo, self._get_transport_gripper_cmd()
|
| 230 |
+
x, y = self._get_place_xy()
|
| 231 |
+
return torch.tensor([x, y, self._get_carry_z()], device=d), self._get_transport_gripper_cmd()
|
| 232 |
+
elif s == "PLACE":
|
| 233 |
+
servo = self._get_object_servo_target(s, obj_pos, grasp_pos, self._get_place_height(), d)
|
| 234 |
+
if servo is not None:
|
| 235 |
+
return servo, self._get_transport_gripper_cmd()
|
| 236 |
+
x, y = self._get_place_xy()
|
| 237 |
+
return torch.tensor([x, y, self._get_place_height()], device=d), self._get_transport_gripper_cmd()
|
| 238 |
+
elif s == "OPEN":
|
| 239 |
+
servo = self._get_object_servo_target(s, obj_pos, grasp_pos, self._get_place_height(), d)
|
| 240 |
+
if servo is not None:
|
| 241 |
+
return servo, "open"
|
| 242 |
+
x, y = self._get_place_xy()
|
| 243 |
+
return torch.tensor([x, y, self._get_place_height()], device=d), "open"
|
| 244 |
+
elif s == "LIFT_RETRACT":
|
| 245 |
+
return torch.tensor([BASKET_CENTER_X, BASKET_CENTER_Y, CARRY_Z], device=d), "open"
|
| 246 |
+
elif s == "RETRACT":
|
| 247 |
+
return torch.tensor([RETRACT_POS_X, RETRACT_POS_Y, CARRY_Z], device=d), "open"
|
| 248 |
+
else:
|
| 249 |
+
raise ValueError(f"Unknown state: {s}")
|
| 250 |
+
|
| 251 |
+
def _get_grasp_pos(self, obj_pos: torch.Tensor, d: str) -> torch.Tensor:
|
| 252 |
+
cur_idx = self._obj_indices[min(self._ptr, len(self._obj_indices) - 1)]
|
| 253 |
+
offset = OBJ_GRASP_CENTER_OFFSETS.get(cur_idx, (0.0, 0.0, 0.0))
|
| 254 |
+
return obj_pos + torch.tensor(offset, dtype=torch.float32, device=d)
|
| 255 |
+
|
| 256 |
+
def _get_current_obj_idx(self) -> int:
|
| 257 |
+
return self._obj_indices[min(self._ptr, len(self._obj_indices) - 1)]
|
| 258 |
+
|
| 259 |
+
def _is_push_mode(self) -> bool:
|
| 260 |
+
return OBJ_MANIPULATION_MODES.get(self._get_current_obj_idx(), "pick") == "push"
|
| 261 |
+
|
| 262 |
+
def _get_push_gripper_cmd(self) -> str:
|
| 263 |
+
cur_idx = self._get_current_obj_idx()
|
| 264 |
+
return OBJ_PUSH_GRIPPER_CMDS.get(cur_idx, self._get_transport_gripper_cmd())
|
| 265 |
+
|
| 266 |
+
def _get_push_target_pos_gripper(
|
| 267 |
+
self, s: str, obj_pos: torch.Tensor, d: str
|
| 268 |
+
) -> tuple[torch.Tensor, str]:
|
| 269 |
+
"""Low table-contact pushing primitive for objects that do not pinch reliably."""
|
| 270 |
+
cur_idx = self._get_current_obj_idx()
|
| 271 |
+
contact_obj_pos = self._cached_obj_pos if self._cached_obj_pos is not None else obj_pos
|
| 272 |
+
start = self._get_grasp_pos(contact_obj_pos, d)
|
| 273 |
+
z_low = self._get_place_height()
|
| 274 |
+
|
| 275 |
+
if s == "INIT":
|
| 276 |
+
return torch.tensor([RETRACT_POS_X, RETRACT_POS_Y, CARRY_Z], device=d), "open"
|
| 277 |
+
if s == "PRE_GRASP":
|
| 278 |
+
p = start.clone()
|
| 279 |
+
p[2] = z_low + OBJ_PUSH_APPROACH_CLEARANCE.get(cur_idx, 0.14)
|
| 280 |
+
return p, "open"
|
| 281 |
+
if s in ("REACH", "CLOSE", "LIFT"):
|
| 282 |
+
p = start.clone()
|
| 283 |
+
p[2] = z_low
|
| 284 |
+
return p, self._get_push_gripper_cmd()
|
| 285 |
+
if s in ("TRANSPORT", "PLACE"):
|
| 286 |
+
place_x, place_y = self._get_place_xy()
|
| 287 |
+
target_xy = torch.tensor([place_x, place_y], dtype=torch.float32, device=d)
|
| 288 |
+
start_xy = contact_obj_pos[:2]
|
| 289 |
+
|
| 290 |
+
x_err = place_x - obj_pos[0]
|
| 291 |
+
x_gain = OBJ_PUSH_X_GAINS.get(cur_idx, 0.55)
|
| 292 |
+
x_max = OBJ_PUSH_MAX_X_CORRECTIONS.get(cur_idx, 0.08)
|
| 293 |
+
x_corr = torch.clamp(x_err * x_gain, min=-x_max, max=x_max)
|
| 294 |
+
|
| 295 |
+
progress = 1.0
|
| 296 |
+
if s == "TRANSPORT":
|
| 297 |
+
progress = min((self._count + 1) / max(self._get_state_steps(s), 1), 1.0)
|
| 298 |
+
progress = min(progress * 1.35, 1.0)
|
| 299 |
+
ref_xy = start_xy + (target_xy - start_xy) * progress
|
| 300 |
+
p_live = torch.cat([
|
| 301 |
+
ref_xy,
|
| 302 |
+
torch.tensor([z_low], dtype=torch.float32, device=d),
|
| 303 |
+
])
|
| 304 |
+
offset = torch.tensor(
|
| 305 |
+
OBJ_GRASP_CENTER_OFFSETS.get(cur_idx, (0.0, 0.0, 0.0)),
|
| 306 |
+
dtype=torch.float32,
|
| 307 |
+
device=d,
|
| 308 |
+
)
|
| 309 |
+
p_live = p_live + offset
|
| 310 |
+
p_live[0] = p_live[0] + x_corr
|
| 311 |
+
|
| 312 |
+
# Keep the pusher on the rear side of the object. If the reference
|
| 313 |
+
# sweep gets ahead of a lagging object, contact is lost or the object
|
| 314 |
+
# is knocked sideways instead of being driven into the basket.
|
| 315 |
+
min_behind = OBJ_PUSH_MIN_BEHIND.get(cur_idx, 0.03)
|
| 316 |
+
p_live[1] = torch.maximum(
|
| 317 |
+
p_live[1],
|
| 318 |
+
obj_pos[1] + torch.tensor(min_behind, dtype=torch.float32, device=d),
|
| 319 |
+
)
|
| 320 |
+
|
| 321 |
+
# During the hold phase, apply a bounded inward preload without
|
| 322 |
+
# allowing the pusher centre to cross in front of the object.
|
| 323 |
+
y_err = place_y - obj_pos[1]
|
| 324 |
+
y_gain = OBJ_PUSH_Y_GAINS.get(cur_idx, 0.85)
|
| 325 |
+
y_max = OBJ_PUSH_MAX_Y_CORRECTIONS.get(cur_idx, 0.22)
|
| 326 |
+
inward = torch.clamp(y_err * y_gain, min=-y_max, max=0.0)
|
| 327 |
+
p_live[1] = torch.maximum(p_live[1] + inward, obj_pos[1] + min_behind)
|
| 328 |
+
p_live[2] = z_low
|
| 329 |
+
|
| 330 |
+
if s == "TRANSPORT":
|
| 331 |
+
p = start + (p_live - start) * min(progress * 3.0, 1.0)
|
| 332 |
+
else:
|
| 333 |
+
p = p_live
|
| 334 |
+
return p, self._get_push_gripper_cmd()
|
| 335 |
+
if s == "OPEN":
|
| 336 |
+
p = self._get_grasp_pos(obj_pos, d)
|
| 337 |
+
p[2] = z_low
|
| 338 |
+
return p, "open"
|
| 339 |
+
if s == "LIFT_RETRACT":
|
| 340 |
+
x, y = self._get_place_xy()
|
| 341 |
+
return torch.tensor([x, y, CARRY_Z], device=d), "open"
|
| 342 |
+
if s == "RETRACT":
|
| 343 |
+
return torch.tensor([RETRACT_POS_X, RETRACT_POS_Y, CARRY_Z], device=d), "open"
|
| 344 |
+
raise ValueError(f"Unknown state: {s}")
|
| 345 |
+
|
| 346 |
+
def _get_grasp_z_offset(self) -> float:
|
| 347 |
+
cur_idx = self._get_current_obj_idx()
|
| 348 |
+
return OBJ_GRASP_Z_OFFSETS.get(cur_idx, GRASP_Z_OFFSET)
|
| 349 |
+
|
| 350 |
+
def _get_close_z_offset(self) -> float:
|
| 351 |
+
cur_idx = self._get_current_obj_idx()
|
| 352 |
+
return OBJ_CLOSE_Z_OFFSETS.get(cur_idx, self._get_grasp_z_offset())
|
| 353 |
+
|
| 354 |
+
def _get_carry_z(self) -> float:
|
| 355 |
+
cur_idx = self._get_current_obj_idx()
|
| 356 |
+
return OBJ_CARRY_Z.get(cur_idx, CARRY_Z)
|
| 357 |
+
|
| 358 |
+
def _get_place_height(self) -> float:
|
| 359 |
+
cur_idx = self._get_current_obj_idx()
|
| 360 |
+
return OBJ_PLACE_HEIGHTS.get(cur_idx, PLACE_HEIGHT)
|
| 361 |
+
|
| 362 |
+
def _get_place_xy(self) -> tuple[float, float]:
|
| 363 |
+
cur_idx = self._get_current_obj_idx()
|
| 364 |
+
dx, dy = OBJ_PLACE_XY_OFFSETS.get(cur_idx, (0.0, 0.0))
|
| 365 |
+
return BASKET_CENTER_X + dx, BASKET_CENTER_Y + dy
|
| 366 |
+
|
| 367 |
+
def _get_transport_gripper_cmd(self) -> str:
|
| 368 |
+
cur_idx = self._get_current_obj_idx()
|
| 369 |
+
return OBJ_TRANSPORT_GRIPPER_CMDS.get(cur_idx, "close")
|
| 370 |
+
|
| 371 |
+
def _get_state_steps(self, s: str) -> int:
|
| 372 |
+
cur_idx = self._get_current_obj_idx()
|
| 373 |
+
return OBJ_STATE_STEP_OVERRIDES.get(cur_idx, {}).get(s, STEPS[s])
|
| 374 |
+
|
| 375 |
+
def _get_transport_push_bias(self) -> tuple[float, float, float] | None:
|
| 376 |
+
cur_idx = self._get_current_obj_idx()
|
| 377 |
+
return OBJ_TRANSPORT_PUSH_BIASES.get(cur_idx)
|
| 378 |
+
|
| 379 |
+
def _get_object_servo_target(
|
| 380 |
+
self,
|
| 381 |
+
s: str,
|
| 382 |
+
obj_pos: torch.Tensor,
|
| 383 |
+
grasp_pos: torch.Tensor,
|
| 384 |
+
z: float,
|
| 385 |
+
d: str,
|
| 386 |
+
) -> torch.Tensor | None:
|
| 387 |
+
cur_idx = self._get_current_obj_idx()
|
| 388 |
+
if s not in OBJ_SERVO_TO_BASKET_STATES.get(cur_idx, ()):
|
| 389 |
+
push_bias = self._get_transport_push_bias()
|
| 390 |
+
if push_bias is None:
|
| 391 |
+
return None
|
| 392 |
+
p = grasp_pos + torch.tensor(push_bias, dtype=torch.float32, device=d)
|
| 393 |
+
p[2] = z
|
| 394 |
+
return p
|
| 395 |
+
|
| 396 |
+
x, y = self._get_place_xy()
|
| 397 |
+
target_xy = torch.tensor([x, y], dtype=torch.float32, device=d)
|
| 398 |
+
xy_error = target_xy - obj_pos[:2]
|
| 399 |
+
gain = OBJ_SERVO_XY_GAINS.get(cur_idx, 1.0)
|
| 400 |
+
max_xy = OBJ_SERVO_MAX_XY.get(cur_idx, 0.25)
|
| 401 |
+
correction = xy_error * gain
|
| 402 |
+
norm = torch.linalg.norm(correction).clamp(min=1e-6)
|
| 403 |
+
if norm.item() > max_xy:
|
| 404 |
+
correction = correction / norm * max_xy
|
| 405 |
+
if s == "TRANSPORT":
|
| 406 |
+
progress = min((self._count + 1) / max(self._get_state_steps(s), 1), 1.0)
|
| 407 |
+
correction = correction * max(0.15, progress)
|
| 408 |
+
|
| 409 |
+
p = grasp_pos.clone()
|
| 410 |
+
p[:2] = p[:2] + correction
|
| 411 |
+
push_bias = self._get_transport_push_bias()
|
| 412 |
+
if push_bias is not None:
|
| 413 |
+
p = p + torch.tensor(push_bias, dtype=torch.float32, device=d)
|
| 414 |
+
p[2] = z
|
| 415 |
+
return p
|
| 416 |
+
|
| 417 |
+
def _should_hold_servo_state(self, s: str, obj_pos: torch.Tensor) -> bool:
|
| 418 |
+
cur_idx = self._get_current_obj_idx()
|
| 419 |
+
if s not in OBJ_SERVO_HOLD_STATES.get(cur_idx, ()):
|
| 420 |
+
return False
|
| 421 |
+
dx = abs(float(obj_pos[0].item() - BASKET_CENTER_X))
|
| 422 |
+
dy = abs(float(obj_pos[1].item() - BASKET_CENTER_Y))
|
| 423 |
+
if dx <= BASKET_IN_X * 0.85 and dy <= BASKET_IN_Y * 0.85:
|
| 424 |
+
return False
|
| 425 |
+
key = (cur_idx, s)
|
| 426 |
+
count = self._servo_extra_counts.get(key, 0)
|
| 427 |
+
if count >= OBJ_SERVO_EXTRA_STEPS.get(cur_idx, 0):
|
| 428 |
+
return False
|
| 429 |
+
self._servo_extra_counts[key] = count + 1
|
| 430 |
+
return True
|
| 431 |
+
|
| 432 |
+
def _get_target_quat(self, s: str, d: str) -> torch.Tensor:
|
| 433 |
+
default_quat = torch.tensor(DEFAULT_PLACE_QUAT_W, dtype=torch.float32, device=d)
|
| 434 |
+
cur_idx = self._get_current_obj_idx()
|
| 435 |
+
if self._is_push_mode() and s in ("REACH", "CLOSE", "LIFT", "TRANSPORT", "PLACE", "OPEN"):
|
| 436 |
+
return self._grasp_quat_cache.get(cur_idx, default_quat)
|
| 437 |
+
if s in OBJ_KEEP_GRASP_QUAT_STATES.get(cur_idx, ("REACH", "CLOSE", "LIFT")):
|
| 438 |
+
return self._grasp_quat_cache.get(cur_idx, default_quat)
|
| 439 |
+
return default_quat
|
scripts/act/trace_task_e_policy.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Trace Task-E policy rollout with object positions at fixed intervals."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
|
| 7 |
+
from isaaclab.app import AppLauncher
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
parser = argparse.ArgumentParser()
|
| 11 |
+
parser.add_argument("--checkpoint", required=True)
|
| 12 |
+
parser.add_argument("--solution_module", default="solution_act")
|
| 13 |
+
parser.add_argument("--task", default="ATEC-TaskE-Piper")
|
| 14 |
+
parser.add_argument("--seed", type=int, default=11)
|
| 15 |
+
parser.add_argument("--max_steps", type=int, default=1800)
|
| 16 |
+
parser.add_argument("--interval", type=int, default=100)
|
| 17 |
+
AppLauncher.add_app_launcher_args(parser)
|
| 18 |
+
args_cli = parser.parse_args()
|
| 19 |
+
args_cli.enable_cameras = True
|
| 20 |
+
|
| 21 |
+
repo_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
|
| 22 |
+
demo_dir = os.path.join(repo_root, "demo")
|
| 23 |
+
if repo_root not in sys.path:
|
| 24 |
+
sys.path.insert(0, repo_root)
|
| 25 |
+
if demo_dir not in sys.path:
|
| 26 |
+
sys.path.insert(0, demo_dir)
|
| 27 |
+
os.environ["ATEC_ACT_POLICY_PATH"] = os.path.abspath(args_cli.checkpoint)
|
| 28 |
+
|
| 29 |
+
app_launcher = AppLauncher(args_cli)
|
| 30 |
+
simulation_app = app_launcher.app
|
| 31 |
+
|
| 32 |
+
import importlib # noqa: E402
|
| 33 |
+
|
| 34 |
+
import gymnasium as gym # noqa: E402
|
| 35 |
+
import torch # noqa: E402
|
| 36 |
+
from isaaclab.envs import DirectMARLEnv, multi_agent_to_single_agent # noqa: E402
|
| 37 |
+
from isaaclab_tasks.utils import parse_env_cfg # noqa: E402
|
| 38 |
+
|
| 39 |
+
import atec_rl_lab.tasks # noqa: F401,E402
|
| 40 |
+
from scripts.act.task_e.collector import basket_status_lines # noqa: E402
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _object_summary(env) -> str:
|
| 44 |
+
return " | ".join(basket_status_lines(env, [1, 2, 3]))
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def main() -> None:
|
| 48 |
+
env_cfg = parse_env_cfg(args_cli.task, device=args_cli.device, num_envs=1)
|
| 49 |
+
env_cfg.seed = args_cli.seed
|
| 50 |
+
env = gym.make(args_cli.task, cfg=env_cfg)
|
| 51 |
+
if isinstance(env.unwrapped, DirectMARLEnv):
|
| 52 |
+
env = multi_agent_to_single_agent(env)
|
| 53 |
+
|
| 54 |
+
policy = importlib.import_module(args_cli.solution_module).AlgSolution()
|
| 55 |
+
obs, _ = env.reset(seed=args_cli.seed)
|
| 56 |
+
policy.reset_episode()
|
| 57 |
+
total_reward = 0.0
|
| 58 |
+
|
| 59 |
+
try:
|
| 60 |
+
print(f"[TRACE_STEP] step=0 score=0.00 {_object_summary(env)}", flush=True)
|
| 61 |
+
for step in range(1, args_cli.max_steps + 1):
|
| 62 |
+
with torch.inference_mode():
|
| 63 |
+
resp = policy.predicts(obs, total_reward)
|
| 64 |
+
action = torch.as_tensor(resp["action"], dtype=torch.float32, device=args_cli.device).view(1, -1)
|
| 65 |
+
obs, reward, terminated, truncated, info = env.step(action)
|
| 66 |
+
sim_dt = info["Step_dt"]
|
| 67 |
+
total_reward += reward.mean().item() / sim_dt if isinstance(reward, torch.Tensor) else float(reward) / sim_dt
|
| 68 |
+
if step % args_cli.interval == 0 or bool(terminated.item() or truncated.item()):
|
| 69 |
+
print(
|
| 70 |
+
f"[TRACE_STEP] step={step} score={total_reward:.2f} {_object_summary(env)}",
|
| 71 |
+
flush=True,
|
| 72 |
+
)
|
| 73 |
+
if bool(terminated.item() or truncated.item()):
|
| 74 |
+
break
|
| 75 |
+
print(f"[RESULT] score={total_reward:.2f} steps={step}", flush=True)
|
| 76 |
+
finally:
|
| 77 |
+
env.close()
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
if __name__ == "__main__":
|
| 81 |
+
try:
|
| 82 |
+
main()
|
| 83 |
+
finally:
|
| 84 |
+
simulation_app.close()
|
scripts/act/train_task_e.py
ADDED
|
@@ -0,0 +1,442 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
ALGO_NAME = 'BC_ACT'
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import random
|
| 5 |
+
import time
|
| 6 |
+
from collections import defaultdict
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from typing import Optional
|
| 9 |
+
|
| 10 |
+
import h5py
|
| 11 |
+
import numpy as np
|
| 12 |
+
import torch
|
| 13 |
+
import torch.nn as nn
|
| 14 |
+
import torch.optim as optim
|
| 15 |
+
import torch.nn.functional as F
|
| 16 |
+
import torchvision.transforms as T
|
| 17 |
+
from torch.utils.data.dataset import Dataset
|
| 18 |
+
from torch.utils.data.sampler import RandomSampler, BatchSampler
|
| 19 |
+
from torch.utils.data.dataloader import DataLoader
|
| 20 |
+
from torch.utils.tensorboard import SummaryWriter
|
| 21 |
+
from diffusers.training_utils import EMAModel
|
| 22 |
+
|
| 23 |
+
from atec_rl_lab.train.act.act.detr.backbone import build_backbone
|
| 24 |
+
from atec_rl_lab.train.act.act.detr.transformer import build_transformer
|
| 25 |
+
from atec_rl_lab.train.act.act.detr.detr_vae import build_encoder, DETRVAE
|
| 26 |
+
from atec_rl_lab.train.act.act.utils import IterationBasedBatchSampler, worker_init_fn
|
| 27 |
+
import tyro
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@dataclass
|
| 31 |
+
class Args:
|
| 32 |
+
exp_name: Optional[str] = None
|
| 33 |
+
"""the name of this experiment"""
|
| 34 |
+
seed: int = 1
|
| 35 |
+
"""seed of the experiment"""
|
| 36 |
+
torch_deterministic: bool = True
|
| 37 |
+
"""if toggled, `torch.backends.cudnn.deterministic=False`"""
|
| 38 |
+
cuda: bool = True
|
| 39 |
+
"""if toggled, cuda will be enabled by default"""
|
| 40 |
+
track: bool = False
|
| 41 |
+
"""if toggled, this experiment will be tracked with Weights and Biases"""
|
| 42 |
+
wandb_project_name: str = "ATEC2026"
|
| 43 |
+
"""the wandb's project name"""
|
| 44 |
+
wandb_entity: Optional[str] = None
|
| 45 |
+
"""the entity (team) of wandb's project"""
|
| 46 |
+
|
| 47 |
+
demo_path: str = './datasets/atec_task_e/trajectory.hdf5'
|
| 48 |
+
"""path to the HDF5 demo dataset produced by collect_demos_task_e.py"""
|
| 49 |
+
num_demos: Optional[int] = None
|
| 50 |
+
"""number of trajectories to load (None = all)"""
|
| 51 |
+
total_iters: int = 1_000_000
|
| 52 |
+
"""total training iterations"""
|
| 53 |
+
batch_size: int = 256
|
| 54 |
+
"""batch size"""
|
| 55 |
+
|
| 56 |
+
# ACT specific
|
| 57 |
+
lr: float = 1e-4
|
| 58 |
+
"""learning rate"""
|
| 59 |
+
kl_weight: float = 10
|
| 60 |
+
"""weight for the KL loss term"""
|
| 61 |
+
temporal_agg: bool = True
|
| 62 |
+
"""if toggled, temporal ensembling will be performed at inference"""
|
| 63 |
+
|
| 64 |
+
# Backbone
|
| 65 |
+
position_embedding: str = 'sine'
|
| 66 |
+
backbone: str = 'resnet18'
|
| 67 |
+
lr_backbone: float = 1e-5
|
| 68 |
+
masks: bool = False
|
| 69 |
+
dilation: bool = False
|
| 70 |
+
include_depth: bool = False
|
| 71 |
+
"""always False — depth not collected; kept for backbone API compatibility"""
|
| 72 |
+
include_rgb: bool = True
|
| 73 |
+
"""use RGB images as input (requires --save_images during collection)"""
|
| 74 |
+
|
| 75 |
+
# Transformer
|
| 76 |
+
enc_layers: int = 2
|
| 77 |
+
dec_layers: int = 4
|
| 78 |
+
dim_feedforward: int = 512
|
| 79 |
+
hidden_dim: int = 256
|
| 80 |
+
dropout: float = 0.1
|
| 81 |
+
nheads: int = 8
|
| 82 |
+
num_queries: int = 30
|
| 83 |
+
pre_norm: bool = False
|
| 84 |
+
use_xsa: bool = False
|
| 85 |
+
"""replace transformer self-attention/FFN blocks with the local XSA variant"""
|
| 86 |
+
|
| 87 |
+
log_freq: int = 1000
|
| 88 |
+
"""frequency of logging training metrics"""
|
| 89 |
+
save_freq: int = 5000
|
| 90 |
+
"""frequency of saving model checkpoints"""
|
| 91 |
+
num_dataload_workers: int = 0
|
| 92 |
+
"""number of DataLoader worker processes"""
|
| 93 |
+
resume_checkpoint: Optional[str] = None
|
| 94 |
+
"""optional checkpoint to continue training from"""
|
| 95 |
+
resume_iter: Optional[int] = None
|
| 96 |
+
"""absolute iteration for a legacy checkpoint that does not store train_iter"""
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class DemoDataset_ACT(Dataset):
|
| 100 |
+
"""Load IsaacLab Task-E HDF5 demos into memory.
|
| 101 |
+
|
| 102 |
+
HDF5 structure (produced by collect_demos_task_e.py):
|
| 103 |
+
traj_N/obs (T, 8) joint positions (qpos)
|
| 104 |
+
traj_N/actions (T, 8) env actions
|
| 105 |
+
traj_N/images/rgb (T, H, W, 3) uint8 RGB — optional
|
| 106 |
+
"""
|
| 107 |
+
|
| 108 |
+
def __init__(self, data_path: str, num_queries: int,
|
| 109 |
+
num_traj: Optional[int] = None, include_rgb: bool = True):
|
| 110 |
+
self.num_queries = num_queries
|
| 111 |
+
self.include_rgb = include_rgb
|
| 112 |
+
self.transforms = T.Resize((224, 224), antialias=True)
|
| 113 |
+
|
| 114 |
+
# load raw data
|
| 115 |
+
states_list: list[torch.Tensor] = []
|
| 116 |
+
actions_list: list[torch.Tensor] = []
|
| 117 |
+
rgb_list: list[torch.Tensor] = [] # only when include_rgb is True
|
| 118 |
+
has_images = None
|
| 119 |
+
|
| 120 |
+
with h5py.File(data_path, 'r') as f:
|
| 121 |
+
traj_keys = sorted(f.keys(), key=lambda k: int(k.split('_')[1]))
|
| 122 |
+
if num_traj is not None:
|
| 123 |
+
traj_keys = traj_keys[:num_traj]
|
| 124 |
+
|
| 125 |
+
for key in traj_keys:
|
| 126 |
+
grp = f[key]
|
| 127 |
+
states_list.append(torch.from_numpy(grp['obs'][:].astype(np.float32)))
|
| 128 |
+
actions_list.append(torch.from_numpy(grp['actions'][:].astype(np.float32)))
|
| 129 |
+
|
| 130 |
+
if include_rgb:
|
| 131 |
+
if has_images is None:
|
| 132 |
+
has_images = 'images' in grp
|
| 133 |
+
if has_images and 'images' in grp:
|
| 134 |
+
rgb_arr = grp['images/rgb'][:] # (T, H, W, 3) uint8
|
| 135 |
+
rgb_t = torch.from_numpy(rgb_arr) # uint8
|
| 136 |
+
# (T, 3, H, W) → resize → (T, 3, 224, 224)
|
| 137 |
+
rgb_t = self.transforms(rgb_t.permute(0, 3, 1, 2))
|
| 138 |
+
# add camera dim → (T, 1, 3, 224, 224)
|
| 139 |
+
rgb_list.append(rgb_t.unsqueeze(1))
|
| 140 |
+
|
| 141 |
+
if has_images is None:
|
| 142 |
+
has_images = False
|
| 143 |
+
self.has_images = has_images and include_rgb and len(rgb_list) > 0
|
| 144 |
+
|
| 145 |
+
if include_rgb and not self.has_images:
|
| 146 |
+
print('[WARN] include_rgb=True but no images found in dataset. '
|
| 147 |
+
'Re-collect with --save_images, or set include_rgb=False.')
|
| 148 |
+
|
| 149 |
+
self.num_traj = len(states_list)
|
| 150 |
+
self.states = states_list # list of (T, 8)
|
| 151 |
+
self.actions = actions_list # list of (T, 8)
|
| 152 |
+
self.rgb = rgb_list # list of (T, 1, 3, 224, 224) or empty
|
| 153 |
+
|
| 154 |
+
# state/action dims
|
| 155 |
+
self.state_dim = self.states[0].shape[1]
|
| 156 |
+
self.act_dim = self.actions[0].shape[1]
|
| 157 |
+
|
| 158 |
+
# index slices: (traj_idx, timestep)
|
| 159 |
+
self.slices = [
|
| 160 |
+
(i, t)
|
| 161 |
+
for i, acts in enumerate(self.actions)
|
| 162 |
+
for t in range(acts.shape[0])
|
| 163 |
+
]
|
| 164 |
+
print(f'Loaded {self.num_traj} trajectories, {len(self.slices)} timesteps. '
|
| 165 |
+
f'state_dim={self.state_dim}, act_dim={self.act_dim}, '
|
| 166 |
+
f'has_images={self.has_images}')
|
| 167 |
+
|
| 168 |
+
# normalisation stats (pd_joint_pos = absolute actions → normalise)
|
| 169 |
+
self.norm_stats = self._compute_norm_stats()
|
| 170 |
+
|
| 171 |
+
# ------------------------------------------------------------------
|
| 172 |
+
|
| 173 |
+
def _pad_action(self, act_seq: torch.Tensor) -> torch.Tensor:
|
| 174 |
+
"""Pad a short action chunk by repeating the last action."""
|
| 175 |
+
shortage = self.num_queries - act_seq.shape[0]
|
| 176 |
+
if shortage > 0:
|
| 177 |
+
act_seq = torch.cat([act_seq, act_seq[-1:].repeat(shortage, 1)], dim=0)
|
| 178 |
+
return act_seq
|
| 179 |
+
|
| 180 |
+
def _compute_norm_stats(self) -> dict:
|
| 181 |
+
# Vectorised: stack each full trajectory then slice — avoids 110k tiny ops
|
| 182 |
+
all_states = torch.cat(self.states, dim=0) # (total_T, state_dim)
|
| 183 |
+
all_actions = torch.cat(self.actions, dim=0) # (total_T, act_dim)
|
| 184 |
+
|
| 185 |
+
state_mean = all_states.mean(0, keepdim=True)
|
| 186 |
+
state_std = all_states.std(0, keepdim=True).clamp(1e-2)
|
| 187 |
+
act_mean = all_actions.mean(0, keepdim=True)
|
| 188 |
+
act_std = all_actions.std(0, keepdim=True).clamp(1e-2)
|
| 189 |
+
|
| 190 |
+
return dict(state_mean=state_mean, state_std=state_std,
|
| 191 |
+
action_mean=act_mean, action_std=act_std)
|
| 192 |
+
|
| 193 |
+
def __len__(self):
|
| 194 |
+
return len(self.slices)
|
| 195 |
+
|
| 196 |
+
def __getitem__(self, index):
|
| 197 |
+
traj_idx, ts = self.slices[index]
|
| 198 |
+
|
| 199 |
+
state = self.states[traj_idx][ts]
|
| 200 |
+
act_seq = self._pad_action(self.actions[traj_idx][ts:ts + self.num_queries])
|
| 201 |
+
|
| 202 |
+
# normalise
|
| 203 |
+
state = (state - self.norm_stats['state_mean'][0]) / self.norm_stats['state_std'][0]
|
| 204 |
+
act_seq = (act_seq - self.norm_stats['action_mean']) / self.norm_stats['action_std']
|
| 205 |
+
|
| 206 |
+
obs = dict(state=state)
|
| 207 |
+
if self.has_images:
|
| 208 |
+
obs['rgb'] = self.rgb[traj_idx][ts] # (1, 3, 224, 224) uint8
|
| 209 |
+
|
| 210 |
+
return {'observations': obs, 'actions': act_seq}
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
class Agent(nn.Module):
|
| 215 |
+
def __init__(self, state_dim: int, act_dim: int, args: Args):
|
| 216 |
+
super().__init__()
|
| 217 |
+
self.state_dim = state_dim
|
| 218 |
+
self.act_dim = act_dim
|
| 219 |
+
self.kl_weight = args.kl_weight
|
| 220 |
+
self.normalize = T.Normalize(mean=[0.485, 0.456, 0.406],
|
| 221 |
+
std=[0.229, 0.224, 0.225])
|
| 222 |
+
self.include_rgb = args.include_rgb
|
| 223 |
+
|
| 224 |
+
# CNN backbone — None for state-only mode (DETRVAE handles both paths)
|
| 225 |
+
backbones = [build_backbone(args)] if args.include_rgb else None
|
| 226 |
+
|
| 227 |
+
# CVAE decoder
|
| 228 |
+
transformer = build_transformer(args)
|
| 229 |
+
|
| 230 |
+
# CVAE encoder
|
| 231 |
+
encoder = build_encoder(args)
|
| 232 |
+
|
| 233 |
+
# ACT ( CVAE encoder + (CNN backbones + CVAE decoder) )
|
| 234 |
+
self.model = DETRVAE(
|
| 235 |
+
backbones,
|
| 236 |
+
transformer,
|
| 237 |
+
encoder,
|
| 238 |
+
state_dim=state_dim,
|
| 239 |
+
action_dim=act_dim,
|
| 240 |
+
num_queries=args.num_queries,
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
def _preprocess_rgb(self, obs: dict) -> None:
|
| 244 |
+
if self.include_rgb and 'rgb' in obs:
|
| 245 |
+
obs['rgb'] = obs['rgb'].float() / 255.0
|
| 246 |
+
# obs['rgb']: (B, num_cams, 3, 224, 224)
|
| 247 |
+
B, N, C, H, W = obs['rgb'].shape
|
| 248 |
+
obs['rgb'] = self.normalize(obs['rgb'].view(B * N, C, H, W)).view(B, N, C, H, W)
|
| 249 |
+
|
| 250 |
+
def _model_input(self, obs: dict):
|
| 251 |
+
# DETRVAE state-only path expects the state tensor directly, not a dict
|
| 252 |
+
return obs if self.include_rgb else obs['state']
|
| 253 |
+
|
| 254 |
+
def compute_loss(self, obs: dict, action_seq: torch.Tensor) -> dict:
|
| 255 |
+
self._preprocess_rgb(obs)
|
| 256 |
+
a_hat, (mu, logvar) = self.model(self._model_input(obs), action_seq)
|
| 257 |
+
|
| 258 |
+
total_kld, _, _ = kl_divergence(mu, logvar)
|
| 259 |
+
l1 = F.l1_loss(action_seq, a_hat)
|
| 260 |
+
|
| 261 |
+
return dict(l1=l1, kl=total_kld[0],
|
| 262 |
+
loss=l1 + total_kld[0] * self.kl_weight)
|
| 263 |
+
|
| 264 |
+
def get_action(self, obs: dict) -> torch.Tensor:
|
| 265 |
+
self._preprocess_rgb(obs)
|
| 266 |
+
a_hat, _ = self.model(self._model_input(obs))
|
| 267 |
+
return a_hat
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def kl_divergence(mu, logvar):
|
| 271 |
+
if mu.data.ndimension() == 4:
|
| 272 |
+
mu = mu.view(mu.size(0), mu.size(1))
|
| 273 |
+
logvar = logvar.view(logvar.size(0), logvar.size(1))
|
| 274 |
+
klds = -0.5 * (1 + logvar - mu.pow(2) - logvar.exp())
|
| 275 |
+
total_kld = klds.sum(1).mean(0, True)
|
| 276 |
+
dim_kld = klds.mean(0)
|
| 277 |
+
mean_kld = klds.mean(1).mean(0, True)
|
| 278 |
+
return total_kld, dim_kld, mean_kld
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def save_ckpt(run_name: str, tag: str, train_iter: int) -> None:
|
| 282 |
+
os.makedirs(f'runs/{run_name}/checkpoints', exist_ok=True)
|
| 283 |
+
ema.copy_to(ema_agent.parameters())
|
| 284 |
+
ckpt = {
|
| 285 |
+
'norm_stats': dataset.norm_stats,
|
| 286 |
+
'model_args': vars(args),
|
| 287 |
+
'train_iter': train_iter,
|
| 288 |
+
'agent': agent.state_dict(),
|
| 289 |
+
'ema_agent': ema_agent.state_dict(),
|
| 290 |
+
'optimizer': optimizer.state_dict(),
|
| 291 |
+
'lr_scheduler': lr_scheduler.state_dict(),
|
| 292 |
+
}
|
| 293 |
+
if hasattr(ema, 'state_dict'):
|
| 294 |
+
ckpt['ema'] = ema.state_dict()
|
| 295 |
+
torch.save(ckpt, f'runs/{run_name}/checkpoints/{tag}.pt')
|
| 296 |
+
print(f'[INFO] Saved checkpoint: runs/{run_name}/checkpoints/{tag}.pt')
|
| 297 |
+
|
| 298 |
+
if __name__ == '__main__':
|
| 299 |
+
args = tyro.cli(Args)
|
| 300 |
+
|
| 301 |
+
if args.exp_name is None:
|
| 302 |
+
args.exp_name = os.path.basename(__file__)[:-len('.py')]
|
| 303 |
+
run_name = f"{args.exp_name}__{args.seed}__{int(time.time())}"
|
| 304 |
+
else:
|
| 305 |
+
run_name = args.exp_name
|
| 306 |
+
|
| 307 |
+
# seeding
|
| 308 |
+
random.seed(args.seed)
|
| 309 |
+
np.random.seed(args.seed)
|
| 310 |
+
torch.manual_seed(args.seed)
|
| 311 |
+
torch.backends.cudnn.deterministic = args.torch_deterministic
|
| 312 |
+
|
| 313 |
+
device = torch.device('cuda' if torch.cuda.is_available() and args.cuda else 'cpu')
|
| 314 |
+
|
| 315 |
+
# dataset & dataloader
|
| 316 |
+
dataset = DemoDataset_ACT(
|
| 317 |
+
args.demo_path,
|
| 318 |
+
num_queries=args.num_queries,
|
| 319 |
+
num_traj=args.num_demos,
|
| 320 |
+
include_rgb=args.include_rgb,
|
| 321 |
+
)
|
| 322 |
+
if args.num_demos is None:
|
| 323 |
+
args.num_demos = dataset.num_traj
|
| 324 |
+
|
| 325 |
+
sampler = RandomSampler(dataset, replacement=False)
|
| 326 |
+
batch_sampler = BatchSampler(sampler, batch_size=args.batch_size, drop_last=True)
|
| 327 |
+
start_iter = 0
|
| 328 |
+
batch_sampler = IterationBasedBatchSampler(batch_sampler, args.total_iters)
|
| 329 |
+
train_dataloader = DataLoader(
|
| 330 |
+
dataset,
|
| 331 |
+
batch_sampler=batch_sampler,
|
| 332 |
+
num_workers=args.num_dataload_workers,
|
| 333 |
+
worker_init_fn=lambda wid: worker_init_fn(wid, base_seed=args.seed),
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
# logging
|
| 337 |
+
if args.track:
|
| 338 |
+
import wandb
|
| 339 |
+
wandb.init(
|
| 340 |
+
project=args.wandb_project_name,
|
| 341 |
+
entity=args.wandb_entity,
|
| 342 |
+
sync_tensorboard=True,
|
| 343 |
+
config=vars(args),
|
| 344 |
+
name=run_name,
|
| 345 |
+
save_code=True,
|
| 346 |
+
group='ACT',
|
| 347 |
+
tags=['act'],
|
| 348 |
+
)
|
| 349 |
+
writer = SummaryWriter(f'runs/{run_name}')
|
| 350 |
+
writer.add_text(
|
| 351 |
+
'hyperparameters',
|
| 352 |
+
'|param|value|\n|-|-|\n' +
|
| 353 |
+
'\n'.join(f'|{k}|{v}|' for k, v in vars(args).items()),
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
# agent
|
| 357 |
+
agent = Agent(dataset.state_dim, dataset.act_dim, args).to(device)
|
| 358 |
+
ema_agent = Agent(dataset.state_dim, dataset.act_dim, args).to(device)
|
| 359 |
+
|
| 360 |
+
param_dicts = [
|
| 361 |
+
{'params': [p for n, p in agent.named_parameters()
|
| 362 |
+
if 'backbone' not in n and p.requires_grad]},
|
| 363 |
+
{'params': [p for n, p in agent.named_parameters()
|
| 364 |
+
if 'backbone' in n and p.requires_grad],
|
| 365 |
+
'lr': args.lr_backbone},
|
| 366 |
+
]
|
| 367 |
+
optimizer = optim.AdamW(param_dicts, lr=args.lr, weight_decay=1e-4)
|
| 368 |
+
lr_drop = max(int(2 / 3 * args.total_iters), 1)
|
| 369 |
+
lr_scheduler = optim.lr_scheduler.StepLR(optimizer, lr_drop)
|
| 370 |
+
ema = EMAModel(parameters=agent.parameters(), power=0.75)
|
| 371 |
+
|
| 372 |
+
if args.resume_checkpoint:
|
| 373 |
+
ckpt = torch.load(args.resume_checkpoint, map_location=device, weights_only=False)
|
| 374 |
+
weight_key = 'agent'
|
| 375 |
+
if weight_key not in ckpt:
|
| 376 |
+
raise KeyError(f"Checkpoint {args.resume_checkpoint} has no '{weight_key}' weights")
|
| 377 |
+
agent.load_state_dict(ckpt[weight_key])
|
| 378 |
+
if 'ema_agent' in ckpt:
|
| 379 |
+
ema_agent.load_state_dict(ckpt['ema_agent'])
|
| 380 |
+
if 'optimizer' in ckpt:
|
| 381 |
+
optimizer.load_state_dict(ckpt['optimizer'])
|
| 382 |
+
if 'lr_scheduler' in ckpt:
|
| 383 |
+
lr_scheduler.load_state_dict(ckpt['lr_scheduler'])
|
| 384 |
+
if 'ema' in ckpt and hasattr(ema, 'load_state_dict'):
|
| 385 |
+
ema.load_state_dict(ckpt['ema'])
|
| 386 |
+
start_iter = int(ckpt.get('train_iter') or args.resume_iter or 0)
|
| 387 |
+
if start_iter >= args.total_iters:
|
| 388 |
+
raise ValueError(
|
| 389 |
+
f"resume start_iter={start_iter} is >= total_iters={args.total_iters}; "
|
| 390 |
+
"increase --total_iters or choose an earlier checkpoint"
|
| 391 |
+
)
|
| 392 |
+
print(f'[INFO] Resumed checkpoint {args.resume_checkpoint} at iter {start_iter}')
|
| 393 |
+
|
| 394 |
+
# training loop
|
| 395 |
+
agent.train()
|
| 396 |
+
best_loss = float('inf')
|
| 397 |
+
timings = defaultdict(float)
|
| 398 |
+
|
| 399 |
+
for local_iter, data_batch in enumerate(train_dataloader):
|
| 400 |
+
cur_iter = start_iter + local_iter
|
| 401 |
+
if cur_iter >= args.total_iters:
|
| 402 |
+
break
|
| 403 |
+
last_tick = time.time()
|
| 404 |
+
|
| 405 |
+
obs_batch = {k: v.to(device, non_blocking=True)
|
| 406 |
+
for k, v in data_batch['observations'].items()}
|
| 407 |
+
act_batch = data_batch['actions'].to(device, non_blocking=True)
|
| 408 |
+
|
| 409 |
+
loss_dict = agent.compute_loss(obs=obs_batch, action_seq=act_batch)
|
| 410 |
+
total_loss = loss_dict['loss']
|
| 411 |
+
|
| 412 |
+
optimizer.zero_grad()
|
| 413 |
+
total_loss.backward()
|
| 414 |
+
optimizer.step()
|
| 415 |
+
lr_scheduler.step()
|
| 416 |
+
ema.step(agent.parameters())
|
| 417 |
+
|
| 418 |
+
timings['update'] += time.time() - last_tick
|
| 419 |
+
|
| 420 |
+
if cur_iter % args.log_freq == 0:
|
| 421 |
+
loss_val = total_loss.item()
|
| 422 |
+
print(f'Iter {cur_iter:7d} loss={loss_val:.4f} '
|
| 423 |
+
f'l1={loss_dict["l1"].item():.4f} '
|
| 424 |
+
f'kl={loss_dict["kl"].item():.4f}')
|
| 425 |
+
writer.add_scalar('charts/lr', optimizer.param_groups[0]['lr'], cur_iter)
|
| 426 |
+
writer.add_scalar('charts/lr_backbone', optimizer.param_groups[1]['lr'], cur_iter)
|
| 427 |
+
writer.add_scalar('losses/total', loss_val, cur_iter)
|
| 428 |
+
writer.add_scalar('losses/l1', loss_dict['l1'].item(), cur_iter)
|
| 429 |
+
writer.add_scalar('losses/kl', loss_dict['kl'].item(), cur_iter)
|
| 430 |
+
for k, v in timings.items():
|
| 431 |
+
writer.add_scalar(f'time/{k}', v, cur_iter)
|
| 432 |
+
|
| 433 |
+
if loss_val < best_loss:
|
| 434 |
+
best_loss = loss_val
|
| 435 |
+
save_ckpt(run_name, 'best_loss', cur_iter)
|
| 436 |
+
|
| 437 |
+
if args.save_freq > 0 and cur_iter % args.save_freq == 0 and cur_iter > 0:
|
| 438 |
+
save_ckpt(run_name, str(cur_iter), cur_iter)
|
| 439 |
+
|
| 440 |
+
save_ckpt(run_name, 'final', min(args.total_iters, cur_iter + 1))
|
| 441 |
+
writer.close()
|
| 442 |
+
print(f'[INFO] Training done. Run: runs/{run_name}')
|
scripts/graspnet_task_e/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""GraspNet adapters for ATEC Task E."""
|
| 2 |
+
|
scripts/graspnet_task_e/anygrasp_adapter.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""AnyGrasp SDK bridge for ATEC Task E.
|
| 2 |
+
|
| 3 |
+
AnyGrasp predicts grasp candidates from RGB-D point clouds in the camera frame.
|
| 4 |
+
For Task E we keep the same execution contract as the TunTun/GraspNet adapter:
|
| 5 |
+
use the model for contact centre, jaw yaw, score and width, then hand a
|
| 6 |
+
top-down-friendly world-frame ``TaskEGrasp`` to the existing Piper primitive.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
from functools import lru_cache
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
import ctypes
|
| 14 |
+
import os
|
| 15 |
+
import sys
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
from scipy.spatial.transform import Rotation
|
| 19 |
+
|
| 20 |
+
from scripts.graspnet_task_e.tuntun_adapter import TaskEGrasp, camera_arrays
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
REPO_ROOT = Path(__file__).resolve().parents[2]
|
| 24 |
+
ANYGRASP_ROOT = REPO_ROOT / "third_party" / "anygrasp_sdk"
|
| 25 |
+
DETECTION_ROOT = ANYGRASP_ROOT / "grasp_detection"
|
| 26 |
+
CHECKPOINT_PATH = DETECTION_ROOT / "log" / "checkpoint_detection.tar"
|
| 27 |
+
SSL11_DIR = Path(
|
| 28 |
+
"/home/ubuntu/projects/manipdojo2026/micromamba/envs/genmanip-sim/lib/python3.10/site-packages/"
|
| 29 |
+
"isaacsim/exts/omni.isaac.ros2_bridge/humble/lib"
|
| 30 |
+
)
|
| 31 |
+
TOOLS_DIR = REPO_ROOT / "tools" / "anygrasp"
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _ensure_anygrasp_paths() -> None:
|
| 35 |
+
det = str(DETECTION_ROOT)
|
| 36 |
+
if det not in sys.path:
|
| 37 |
+
sys.path.insert(0, det)
|
| 38 |
+
tools = str(TOOLS_DIR)
|
| 39 |
+
old_path = os.environ.get("PATH", "")
|
| 40 |
+
if TOOLS_DIR.exists() and tools not in old_path.split(":"):
|
| 41 |
+
os.environ["PATH"] = f"{tools}:{old_path}" if old_path else tools
|
| 42 |
+
ssl = str(SSL11_DIR)
|
| 43 |
+
old_ld = os.environ.get("LD_LIBRARY_PATH", "")
|
| 44 |
+
if SSL11_DIR.exists() and ssl not in old_ld.split(":"):
|
| 45 |
+
os.environ["LD_LIBRARY_PATH"] = f"{ssl}:{old_ld}" if old_ld else ssl
|
| 46 |
+
# lib_cxx.so is linked against OpenSSL 1.1. In long-running Isaac Python
|
| 47 |
+
# processes, changing LD_LIBRARY_PATH after startup is not enough, so load
|
| 48 |
+
# the exact libraries by absolute path before importing gsnet/lib_cxx.
|
| 49 |
+
for name in ("libcrypto.so.1.1", "libssl.so.1.1"):
|
| 50 |
+
path = SSL11_DIR / name
|
| 51 |
+
if path.exists():
|
| 52 |
+
ctypes.CDLL(str(path), mode=ctypes.RTLD_GLOBAL)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _check_anygrasp_files() -> None:
|
| 56 |
+
missing = []
|
| 57 |
+
for path in [
|
| 58 |
+
DETECTION_ROOT / "gsnet.so",
|
| 59 |
+
DETECTION_ROOT / "lib_cxx.so",
|
| 60 |
+
DETECTION_ROOT / "license" / "licenseCfg.json",
|
| 61 |
+
CHECKPOINT_PATH,
|
| 62 |
+
]:
|
| 63 |
+
if not path.exists():
|
| 64 |
+
missing.append(str(path))
|
| 65 |
+
if missing:
|
| 66 |
+
raise FileNotFoundError("AnyGrasp SDK is not fully installed:\n" + "\n".join(missing))
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@lru_cache(maxsize=1)
|
| 70 |
+
def _load_anygrasp_detector():
|
| 71 |
+
_ensure_anygrasp_paths()
|
| 72 |
+
_check_anygrasp_files()
|
| 73 |
+
from argparse import Namespace
|
| 74 |
+
from gsnet import AnyGrasp
|
| 75 |
+
|
| 76 |
+
cfg = Namespace(
|
| 77 |
+
checkpoint_path=str(CHECKPOINT_PATH),
|
| 78 |
+
max_gripper_width=0.085,
|
| 79 |
+
gripper_height=0.03,
|
| 80 |
+
top_down_grasp=True,
|
| 81 |
+
debug=False,
|
| 82 |
+
)
|
| 83 |
+
detector = AnyGrasp(cfg)
|
| 84 |
+
detector.load_net()
|
| 85 |
+
return detector
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _points_from_rgbd(
|
| 89 |
+
rgb: np.ndarray,
|
| 90 |
+
depth: np.ndarray,
|
| 91 |
+
mask: np.ndarray,
|
| 92 |
+
K: np.ndarray,
|
| 93 |
+
*,
|
| 94 |
+
expand_px: int = 0,
|
| 95 |
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
| 96 |
+
use_mask = mask > 0
|
| 97 |
+
if expand_px > 0 and np.any(use_mask):
|
| 98 |
+
ys0, xs0 = np.where(use_mask)
|
| 99 |
+
y1 = max(int(ys0.min()) - expand_px, 0)
|
| 100 |
+
y2 = min(int(ys0.max()) + expand_px + 1, mask.shape[0])
|
| 101 |
+
x1 = max(int(xs0.min()) - expand_px, 0)
|
| 102 |
+
x2 = min(int(xs0.max()) + expand_px + 1, mask.shape[1])
|
| 103 |
+
use_mask = np.zeros_like(use_mask, dtype=bool)
|
| 104 |
+
use_mask[y1:y2, x1:x2] = True
|
| 105 |
+
valid = use_mask & np.isfinite(depth) & (depth > 0.0) & (depth < 6.0)
|
| 106 |
+
ys, xs = np.where(valid)
|
| 107 |
+
if len(xs) == 0:
|
| 108 |
+
raise RuntimeError("No valid masked depth points for AnyGrasp.")
|
| 109 |
+
|
| 110 |
+
z = depth[ys, xs].astype(np.float32)
|
| 111 |
+
x = (xs.astype(np.float32) - float(K[0, 2])) / float(K[0, 0]) * z
|
| 112 |
+
y = (ys.astype(np.float32) - float(K[1, 2])) / float(K[1, 1]) * z
|
| 113 |
+
points = np.stack([x, y, z], axis=1).astype(np.float32)
|
| 114 |
+
colors = (rgb[ys, xs, :3].astype(np.float32) / 255.0).astype(np.float32)
|
| 115 |
+
return points, colors, np.stack([ys, xs], axis=1)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _lims_for_points(points: np.ndarray, pad: float = 0.04) -> list[float]:
|
| 119 |
+
lo = points.min(axis=0)
|
| 120 |
+
hi = points.max(axis=0)
|
| 121 |
+
return [
|
| 122 |
+
float(lo[0] - pad),
|
| 123 |
+
float(hi[0] + pad),
|
| 124 |
+
float(lo[1] - pad),
|
| 125 |
+
float(hi[1] + pad),
|
| 126 |
+
float(max(0.0, lo[2] - pad)),
|
| 127 |
+
float(hi[2] + pad),
|
| 128 |
+
]
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def _select_anygrasp_candidate(gg, points_cam: np.ndarray):
|
| 132 |
+
if gg is None or len(gg) == 0:
|
| 133 |
+
raise RuntimeError("AnyGrasp returned no grasps after filtering.")
|
| 134 |
+
gg = gg.nms().sort_by_score()
|
| 135 |
+
grasps = list(gg)
|
| 136 |
+
if not grasps:
|
| 137 |
+
raise RuntimeError("AnyGrasp returned no grasps after filtering.")
|
| 138 |
+
|
| 139 |
+
center = np.median(points_cam, axis=0)
|
| 140 |
+
spread = float(np.linalg.norm(np.percentile(points_cam, 90, axis=0) - np.percentile(points_cam, 10, axis=0)))
|
| 141 |
+
spread = max(spread, 1e-3)
|
| 142 |
+
|
| 143 |
+
def rank(g) -> float:
|
| 144 |
+
dist = float(np.linalg.norm(np.asarray(g.translation, dtype=np.float64) - center))
|
| 145 |
+
# Keep score dominant, but reject edge candidates that are far from the
|
| 146 |
+
# segmented object core. This mirrors the proven GraspNet selector.
|
| 147 |
+
return float(g.score) * 0.65 + max(0.0, 1.0 - dist / spread) * 0.35
|
| 148 |
+
|
| 149 |
+
return max(grasps[:128], key=rank)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def infer_anygrasp_from_camera(camera, mask: np.ndarray) -> TaskEGrasp:
|
| 153 |
+
"""Run AnyGrasp SDK and convert the selected grasp to Task-E world pose."""
|
| 154 |
+
rgb, depth, K, pos_w, quat_wxyz_ros = camera_arrays(camera)
|
| 155 |
+
detector = _load_anygrasp_detector()
|
| 156 |
+
attempts = [
|
| 157 |
+
(0, 0.04, True, False, True),
|
| 158 |
+
(0, 0.08, False, False, False),
|
| 159 |
+
(24, 0.08, False, False, False),
|
| 160 |
+
]
|
| 161 |
+
last_error: Exception | None = None
|
| 162 |
+
points_cam = colors = None
|
| 163 |
+
grasp = None
|
| 164 |
+
for expand_px, lim_pad, apply_object_mask, dense_grasp, collision_detection in attempts:
|
| 165 |
+
try:
|
| 166 |
+
points_cam, colors, _pixels = _points_from_rgbd(rgb, depth, mask, K, expand_px=expand_px)
|
| 167 |
+
if len(points_cam) < 64:
|
| 168 |
+
raise RuntimeError(f"Too few masked points for AnyGrasp: {len(points_cam)}")
|
| 169 |
+
lims = _lims_for_points(points_cam, pad=lim_pad)
|
| 170 |
+
print(
|
| 171 |
+
"[ANYGRASP] "
|
| 172 |
+
f"points={len(points_cam)} expand_px={expand_px} lim_pad={lim_pad:.3f} "
|
| 173 |
+
f"object_mask={apply_object_mask} dense={dense_grasp} collision={collision_detection}",
|
| 174 |
+
flush=True,
|
| 175 |
+
)
|
| 176 |
+
gg, _cloud = detector.get_grasp(
|
| 177 |
+
points_cam,
|
| 178 |
+
colors,
|
| 179 |
+
lims=lims,
|
| 180 |
+
apply_object_mask=apply_object_mask,
|
| 181 |
+
dense_grasp=dense_grasp,
|
| 182 |
+
collision_detection=collision_detection,
|
| 183 |
+
)
|
| 184 |
+
grasp = _select_anygrasp_candidate(gg, points_cam)
|
| 185 |
+
break
|
| 186 |
+
except Exception as exc:
|
| 187 |
+
last_error = exc
|
| 188 |
+
print(f"[ANYGRASP] attempt failed: {exc}", flush=True)
|
| 189 |
+
if grasp is None or points_cam is None:
|
| 190 |
+
raise RuntimeError(f"AnyGrasp failed for all attempts: {last_error}")
|
| 191 |
+
|
| 192 |
+
rot_w_cam = Rotation.from_quat(
|
| 193 |
+
[quat_wxyz_ros[1], quat_wxyz_ros[2], quat_wxyz_ros[3], quat_wxyz_ros[0]]
|
| 194 |
+
).as_matrix()
|
| 195 |
+
t_cam = np.asarray(grasp.translation, dtype=np.float64)
|
| 196 |
+
t_w = rot_w_cam @ t_cam + pos_w
|
| 197 |
+
|
| 198 |
+
pts_w = (rot_w_cam @ points_cam.astype(np.float64).T).T + pos_w
|
| 199 |
+
z_gate = float(np.percentile(pts_w[:, 2], 70))
|
| 200 |
+
upper = pts_w[pts_w[:, 2] >= z_gate]
|
| 201 |
+
if len(upper) > 16:
|
| 202 |
+
t_w[:2] = np.median(upper[:, :2], axis=0)
|
| 203 |
+
else:
|
| 204 |
+
t_w[:2] = np.median(pts_w[:, :2], axis=0)
|
| 205 |
+
t_w[2] = float(np.percentile(pts_w[:, 2], 85))
|
| 206 |
+
|
| 207 |
+
R_cam_grasp = np.asarray(grasp.rotation_matrix, dtype=np.float64)
|
| 208 |
+
jaw_hint_w = rot_w_cam @ R_cam_grasp[:, 1]
|
| 209 |
+
jaw_xy = np.array([jaw_hint_w[0], jaw_hint_w[1], 0.0], dtype=np.float64)
|
| 210 |
+
if np.linalg.norm(jaw_xy) < 1e-6:
|
| 211 |
+
jaw_xy = np.array([0.0, 1.0, 0.0], dtype=np.float64)
|
| 212 |
+
jaw_xy = jaw_xy / np.linalg.norm(jaw_xy)
|
| 213 |
+
grip_z = np.array([0.0, 0.0, -1.0], dtype=np.float64)
|
| 214 |
+
align_x = np.cross(jaw_xy, grip_z)
|
| 215 |
+
align_x = align_x / max(np.linalg.norm(align_x), 1e-6)
|
| 216 |
+
jaw_y = np.cross(grip_z, align_x)
|
| 217 |
+
jaw_y = jaw_y / max(np.linalg.norm(jaw_y), 1e-6)
|
| 218 |
+
R_w_tool = np.stack([align_x, jaw_y, grip_z], axis=1)
|
| 219 |
+
quat_xyzw = Rotation.from_matrix(R_w_tool).as_quat()
|
| 220 |
+
quat_wxyz = np.array([quat_xyzw[3], quat_xyzw[0], quat_xyzw[1], quat_xyzw[2]], dtype=np.float64)
|
| 221 |
+
|
| 222 |
+
return TaskEGrasp(
|
| 223 |
+
translation_w=t_w.astype(np.float64),
|
| 224 |
+
quat_wxyz_w=quat_wxyz,
|
| 225 |
+
score=float(grasp.score),
|
| 226 |
+
width=float(grasp.width),
|
| 227 |
+
raw_translation_cam=t_cam,
|
| 228 |
+
)
|
scripts/graspnet_task_e/debug_solution_pca_execution.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Measure execution error for demo.solution_pca in Task E.
|
| 2 |
+
|
| 3 |
+
Uses simulator internals only for debugging: object root, gripper_base, link7,
|
| 4 |
+
and link8 positions. The submission policy still only receives observations.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import argparse
|
| 10 |
+
import os
|
| 11 |
+
import sys
|
| 12 |
+
import time
|
| 13 |
+
|
| 14 |
+
from isaaclab.app import AppLauncher
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
parser = argparse.ArgumentParser()
|
| 18 |
+
parser.add_argument("--task", type=str, default="ATEC-TaskE-Piper")
|
| 19 |
+
parser.add_argument("--seed", type=int, default=12)
|
| 20 |
+
parser.add_argument("--object", type=int, default=3)
|
| 21 |
+
parser.add_argument("--max_steps", type=int, default=2500)
|
| 22 |
+
parser.add_argument("--solution_module", type=str, default="solution_pca")
|
| 23 |
+
AppLauncher.add_app_launcher_args(parser)
|
| 24 |
+
args_cli = parser.parse_args()
|
| 25 |
+
args_cli.enable_cameras = True
|
| 26 |
+
|
| 27 |
+
repo_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
|
| 28 |
+
demo_dir = os.path.join(repo_root, "demo")
|
| 29 |
+
if repo_root not in sys.path:
|
| 30 |
+
sys.path.insert(0, repo_root)
|
| 31 |
+
if demo_dir not in sys.path:
|
| 32 |
+
sys.path.insert(0, demo_dir)
|
| 33 |
+
|
| 34 |
+
app_launcher = AppLauncher(args_cli)
|
| 35 |
+
simulation_app = app_launcher.app
|
| 36 |
+
|
| 37 |
+
import gymnasium as gym # noqa: E402
|
| 38 |
+
import importlib # noqa: E402
|
| 39 |
+
import numpy as np # noqa: E402
|
| 40 |
+
import torch # noqa: E402
|
| 41 |
+
from isaaclab.envs import DirectMARLEnv, multi_agent_to_single_agent # noqa: E402
|
| 42 |
+
from isaaclab_tasks.utils import parse_env_cfg # noqa: E402
|
| 43 |
+
|
| 44 |
+
import atec_rl_lab.tasks # noqa: F401,E402
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def main() -> None:
|
| 48 |
+
env_cfg = parse_env_cfg(args_cli.task, device=args_cli.device, num_envs=1)
|
| 49 |
+
env_cfg.seed = args_cli.seed
|
| 50 |
+
env = gym.make(args_cli.task, cfg=env_cfg)
|
| 51 |
+
if isinstance(env.unwrapped, DirectMARLEnv):
|
| 52 |
+
env = multi_agent_to_single_agent(env)
|
| 53 |
+
|
| 54 |
+
module = importlib.import_module(args_cli.solution_module)
|
| 55 |
+
AlgSolution = module.AlgSolution
|
| 56 |
+
policy = AlgSolution()
|
| 57 |
+
try:
|
| 58 |
+
obs, _ = env.reset(seed=args_cli.seed)
|
| 59 |
+
policy.reset_episode()
|
| 60 |
+
robot = env.unwrapped.scene.articulations["robot"]
|
| 61 |
+
obj = env.unwrapped.scene.rigid_objects[f"object_{args_cli.object}"]
|
| 62 |
+
gb_id = int(robot.find_bodies("gripper_base")[0][0])
|
| 63 |
+
link7_id = int(robot.find_bodies("link7")[0][0])
|
| 64 |
+
link8_id = int(robot.find_bodies("link8")[0][0])
|
| 65 |
+
obj_initial = obj.data.root_pos_w[0].detach().cpu().numpy().astype(np.float64)
|
| 66 |
+
|
| 67 |
+
best = {
|
| 68 |
+
"finger_dist": (999.0, None, 0, None),
|
| 69 |
+
"gb_dist": (999.0, None, 0, None),
|
| 70 |
+
"max_z_gain": (-999.0, None, 0, None),
|
| 71 |
+
"pin_finger_err": (999.0, None, 0, None),
|
| 72 |
+
"pin_gb_err": (999.0, None, 0, None),
|
| 73 |
+
}
|
| 74 |
+
stage_best = {}
|
| 75 |
+
pin_err_sum = {"finger": 0.0, "gb": 0.0}
|
| 76 |
+
pin_err_n = 0
|
| 77 |
+
total_reward = 0.0
|
| 78 |
+
start = time.time()
|
| 79 |
+
for step in range(args_cli.max_steps):
|
| 80 |
+
with torch.inference_mode():
|
| 81 |
+
resp = policy.predicts(obs, total_reward)
|
| 82 |
+
action = torch.as_tensor(resp["action"], dtype=torch.float32, device=args_cli.device).view(1, -1)
|
| 83 |
+
obs, reward, terminated, truncated, info = env.step(action)
|
| 84 |
+
sim_dt = info["Step_dt"]
|
| 85 |
+
total_reward += reward.mean().item() / sim_dt if isinstance(reward, torch.Tensor) else float(reward) / sim_dt
|
| 86 |
+
|
| 87 |
+
obj_pos = obj.data.root_pos_w[0, :3].detach().cpu().numpy().astype(np.float64)
|
| 88 |
+
gb = robot.data.body_pos_w[0, gb_id, :3].detach().cpu().numpy().astype(np.float64)
|
| 89 |
+
f7 = robot.data.body_pos_w[0, link7_id, :3].detach().cpu().numpy().astype(np.float64)
|
| 90 |
+
f8 = robot.data.body_pos_w[0, link8_id, :3].detach().cpu().numpy().astype(np.float64)
|
| 91 |
+
finger = 0.5 * (f7 + f8)
|
| 92 |
+
qpos = policy._obs_qpos(obs)
|
| 93 |
+
pin_finger = policy.ik.finger_center_world(qpos)
|
| 94 |
+
pin_gb_b, _ = policy.ik.fk_base(qpos[:6])
|
| 95 |
+
pin_gb = module.BASE_POS_W + module.R_W_B @ pin_gb_b
|
| 96 |
+
gap = float(np.linalg.norm(f7 - f8))
|
| 97 |
+
fd = float(np.linalg.norm(finger - obj_pos))
|
| 98 |
+
gd = float(np.linalg.norm(gb - obj_pos))
|
| 99 |
+
pfe = float(np.linalg.norm(pin_finger - finger))
|
| 100 |
+
pge = float(np.linalg.norm(pin_gb - gb))
|
| 101 |
+
pin_err_sum["finger"] += pfe
|
| 102 |
+
pin_err_sum["gb"] += pge
|
| 103 |
+
pin_err_n += 1
|
| 104 |
+
zg = float(obj_pos[2] - obj_initial[2])
|
| 105 |
+
plan_idx = getattr(policy, "plan_idx", -1)
|
| 106 |
+
target_step = getattr(policy, "step_in_target", -1)
|
| 107 |
+
label = "none"
|
| 108 |
+
plan = getattr(policy, "plan", None)
|
| 109 |
+
if isinstance(plan, list) and 0 <= plan_idx < len(plan):
|
| 110 |
+
label = getattr(plan[plan_idx], "label", str(plan_idx))
|
| 111 |
+
stage = stage_best.setdefault(
|
| 112 |
+
label,
|
| 113 |
+
{
|
| 114 |
+
"min_finger": (999.0, None, 0, None),
|
| 115 |
+
"max_z_gain": (-999.0, None, 0, None),
|
| 116 |
+
"min_gap": (999.0, 0),
|
| 117 |
+
"last": None,
|
| 118 |
+
},
|
| 119 |
+
)
|
| 120 |
+
if fd < stage["min_finger"][0]:
|
| 121 |
+
stage["min_finger"] = (fd, finger - obj_pos, step, (plan_idx, target_step, gap, qpos[6], qpos[7]))
|
| 122 |
+
if zg > stage["max_z_gain"][0]:
|
| 123 |
+
stage["max_z_gain"] = (zg, obj_pos.copy(), step, (plan_idx, target_step, gap, qpos[6], qpos[7]))
|
| 124 |
+
if gap < stage["min_gap"][0]:
|
| 125 |
+
stage["min_gap"] = (gap, step)
|
| 126 |
+
stage["last"] = (finger - obj_pos, obj_pos.copy(), gap, qpos[6], qpos[7], step)
|
| 127 |
+
if fd < best["finger_dist"][0]:
|
| 128 |
+
best["finger_dist"] = (fd, finger - obj_pos, step, (plan_idx, target_step, gap))
|
| 129 |
+
if gd < best["gb_dist"][0]:
|
| 130 |
+
best["gb_dist"] = (gd, gb - obj_pos, step, (plan_idx, target_step, gap))
|
| 131 |
+
if zg > best["max_z_gain"][0]:
|
| 132 |
+
best["max_z_gain"] = (zg, obj_pos.copy(), step, (plan_idx, target_step, gap))
|
| 133 |
+
if pfe < best["pin_finger_err"][0]:
|
| 134 |
+
best["pin_finger_err"] = (pfe, pin_finger - finger, step, (plan_idx, target_step, gap))
|
| 135 |
+
if pge < best["pin_gb_err"][0]:
|
| 136 |
+
best["pin_gb_err"] = (pge, pin_gb - gb, step, (plan_idx, target_step, gap))
|
| 137 |
+
if bool(terminated.item() or truncated.item()):
|
| 138 |
+
break
|
| 139 |
+
|
| 140 |
+
final = obj.data.root_pos_w[0, :3].detach().cpu().numpy().astype(np.float64)
|
| 141 |
+
print(f"[EXEC_DEBUG] seed={args_cli.seed} obj={args_cli.object} score={total_reward:.2f} wall={time.time()-start:.1f}s")
|
| 142 |
+
print(f"[EXEC_DEBUG] initial=({obj_initial[0]:.4f},{obj_initial[1]:.4f},{obj_initial[2]:.4f}) final=({final[0]:.4f},{final[1]:.4f},{final[2]:.4f})")
|
| 143 |
+
if pin_err_n:
|
| 144 |
+
print(f"[EXEC_DEBUG] pin_mean_err finger={pin_err_sum['finger']/pin_err_n:.4f} gb={pin_err_sum['gb']/pin_err_n:.4f}")
|
| 145 |
+
for key, (value, vec, step, meta) in best.items():
|
| 146 |
+
if vec is None:
|
| 147 |
+
print(f"[EXEC_DEBUG] {key}=none")
|
| 148 |
+
elif key == "max_z_gain":
|
| 149 |
+
print(f"[EXEC_DEBUG] {key}={value:.4f} obj=({vec[0]:.4f},{vec[1]:.4f},{vec[2]:.4f}) step={step} meta={meta}")
|
| 150 |
+
else:
|
| 151 |
+
print(f"[EXEC_DEBUG] {key}={value:.4f} vec=({vec[0]:+.4f},{vec[1]:+.4f},{vec[2]:+.4f}) step={step} meta={meta}")
|
| 152 |
+
for label, stats in stage_best.items():
|
| 153 |
+
if not any(k in label for k in ("reach", "insert", "close", "lift", "mid", "release")):
|
| 154 |
+
continue
|
| 155 |
+
fd, fvec, fstep, fmeta = stats["min_finger"]
|
| 156 |
+
zg, zobj, zstep, zmeta = stats["max_z_gain"]
|
| 157 |
+
last = stats["last"]
|
| 158 |
+
if fvec is None or zobj is None or last is None:
|
| 159 |
+
continue
|
| 160 |
+
lvec, lobj, lgap, lq7, lq8, lstep = last
|
| 161 |
+
print(
|
| 162 |
+
f"[STAGE_DEBUG] label={label} min_fd={fd:.4f} "
|
| 163 |
+
f"min_vec=({fvec[0]:+.4f},{fvec[1]:+.4f},{fvec[2]:+.4f}) "
|
| 164 |
+
f"min_meta={fmeta} max_z_gain={zg:.4f} "
|
| 165 |
+
f"z_obj=({zobj[0]:.4f},{zobj[1]:.4f},{zobj[2]:.4f}) z_meta={zmeta} "
|
| 166 |
+
f"last_vec=({lvec[0]:+.4f},{lvec[1]:+.4f},{lvec[2]:+.4f}) "
|
| 167 |
+
f"last_obj=({lobj[0]:.4f},{lobj[1]:.4f},{lobj[2]:.4f}) "
|
| 168 |
+
f"last_gap={lgap:.4f} last_q=({lq7:.4f},{lq8:.4f}) last_step={lstep}"
|
| 169 |
+
)
|
| 170 |
+
finally:
|
| 171 |
+
env.close()
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
if __name__ == "__main__":
|
| 175 |
+
try:
|
| 176 |
+
main()
|
| 177 |
+
finally:
|
| 178 |
+
simulation_app.close()
|
scripts/graspnet_task_e/debug_solution_pca_perception.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Compare submit-style RGB-D PCA estimates against Task-E simulator truth.
|
| 2 |
+
|
| 3 |
+
This script uses simulator object roots only for debugging/calibration. It is
|
| 4 |
+
not part of the submission policy.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import argparse
|
| 10 |
+
import os
|
| 11 |
+
import sys
|
| 12 |
+
|
| 13 |
+
from isaaclab.app import AppLauncher
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
parser = argparse.ArgumentParser()
|
| 17 |
+
parser.add_argument("--task", type=str, default="ATEC-TaskE-Piper")
|
| 18 |
+
parser.add_argument("--seed", type=int, default=12)
|
| 19 |
+
parser.add_argument("--settle_steps", type=int, default=5)
|
| 20 |
+
AppLauncher.add_app_launcher_args(parser)
|
| 21 |
+
args_cli = parser.parse_args()
|
| 22 |
+
args_cli.enable_cameras = True
|
| 23 |
+
|
| 24 |
+
repo_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
|
| 25 |
+
demo_dir = os.path.join(repo_root, "demo")
|
| 26 |
+
if repo_root not in sys.path:
|
| 27 |
+
sys.path.insert(0, repo_root)
|
| 28 |
+
if demo_dir not in sys.path:
|
| 29 |
+
sys.path.insert(0, demo_dir)
|
| 30 |
+
|
| 31 |
+
app_launcher = AppLauncher(args_cli)
|
| 32 |
+
simulation_app = app_launcher.app
|
| 33 |
+
|
| 34 |
+
import gymnasium as gym # noqa: E402
|
| 35 |
+
import numpy as np # noqa: E402
|
| 36 |
+
import torch # noqa: E402
|
| 37 |
+
from isaaclab.envs import DirectMARLEnv, multi_agent_to_single_agent # noqa: E402
|
| 38 |
+
from isaaclab_tasks.utils import parse_env_cfg # noqa: E402
|
| 39 |
+
|
| 40 |
+
import atec_rl_lab.tasks # noqa: F401,E402
|
| 41 |
+
import solution_pca # noqa: E402
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def main() -> None:
|
| 45 |
+
env_cfg = parse_env_cfg(args_cli.task, device=args_cli.device, num_envs=1)
|
| 46 |
+
env_cfg.seed = args_cli.seed
|
| 47 |
+
env = gym.make(args_cli.task, cfg=env_cfg)
|
| 48 |
+
if isinstance(env.unwrapped, DirectMARLEnv):
|
| 49 |
+
env = multi_agent_to_single_agent(env)
|
| 50 |
+
|
| 51 |
+
policy = solution_pca.AlgSolution()
|
| 52 |
+
try:
|
| 53 |
+
obs, _ = env.reset(seed=args_cli.seed)
|
| 54 |
+
zero = torch.zeros((1, 8), dtype=torch.float32, device=args_cli.device)
|
| 55 |
+
for _ in range(max(0, args_cli.settle_steps)):
|
| 56 |
+
obs, *_ = env.step(zero)
|
| 57 |
+
|
| 58 |
+
rgb, depth = policy._video_rgb_depth(obs)
|
| 59 |
+
print(f"[PERCEPTION_DEBUG] seed={args_cli.seed} settle_steps={args_cli.settle_steps}")
|
| 60 |
+
for obj_idx in (1, 2, 3):
|
| 61 |
+
est, rot = policy._estimate_grasp(rgb, depth, obj_idx)
|
| 62 |
+
pick_xy = est[:2] + solution_pca.OBJ_GRASP_CENTER_OFFSETS[obj_idx]
|
| 63 |
+
obj = env.unwrapped.scene.rigid_objects[f"object_{obj_idx}"]
|
| 64 |
+
truth = obj.data.root_pos_w[0].detach().cpu().numpy().astype(np.float64)
|
| 65 |
+
delta = est - truth
|
| 66 |
+
pick_delta = np.r_[pick_xy - truth[:2], est[2] - truth[2]]
|
| 67 |
+
jaw_yaw = float(np.arctan2(rot[1, 1], rot[0, 1]))
|
| 68 |
+
print(
|
| 69 |
+
"[PERCEPTION_DEBUG] "
|
| 70 |
+
f"obj={obj_idx} truth=({truth[0]:.4f},{truth[1]:.4f},{truth[2]:.4f}) "
|
| 71 |
+
f"est=({est[0]:.4f},{est[1]:.4f},{est[2]:.4f}) "
|
| 72 |
+
f"delta=({delta[0]:+.4f},{delta[1]:+.4f},{delta[2]:+.4f}) "
|
| 73 |
+
f"pick_delta=({pick_delta[0]:+.4f},{pick_delta[1]:+.4f},{pick_delta[2]:+.4f}) "
|
| 74 |
+
f"jaw_yaw={jaw_yaw:+.3f}"
|
| 75 |
+
)
|
| 76 |
+
finally:
|
| 77 |
+
env.close()
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
if __name__ == "__main__":
|
| 81 |
+
try:
|
| 82 |
+
main()
|
| 83 |
+
finally:
|
| 84 |
+
simulation_app.close()
|
scripts/graspnet_task_e/pca_aabb_adapter.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""GraspGen-style PCA/AABB grasp prior for ATEC Task E.
|
| 2 |
+
|
| 3 |
+
This mirrors the core idea used by the PiPER GraspGen demo: reconstruct the
|
| 4 |
+
segmented RGB-D points, run PCA, build an oriented AABB, and use its center as a
|
| 5 |
+
geometric grasp prior. The Task-E runner may still override orientation with
|
| 6 |
+
the calibrated Piper quaternion.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
from scipy.spatial.transform import Rotation
|
| 13 |
+
|
| 14 |
+
from scripts.graspnet_task_e.tuntun_adapter import TaskEGrasp, camera_arrays
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _masked_world_points(camera, mask: np.ndarray) -> np.ndarray:
|
| 18 |
+
_rgb, depth, K, pos_w, quat_wxyz_ros = camera_arrays(camera)
|
| 19 |
+
valid = (mask > 0) & np.isfinite(depth) & (depth > 0.0) & (depth < 6.0)
|
| 20 |
+
if not np.any(valid):
|
| 21 |
+
raise RuntimeError("No valid masked depth points for PCA/AABB grasp.")
|
| 22 |
+
ys, xs = np.where(valid)
|
| 23 |
+
z = depth[ys, xs].astype(np.float64)
|
| 24 |
+
x = (xs.astype(np.float64) - float(K[0, 2])) / float(K[0, 0]) * z
|
| 25 |
+
y = (ys.astype(np.float64) - float(K[1, 2])) / float(K[1, 1]) * z
|
| 26 |
+
pts_cam = np.stack([x, y, z], axis=1)
|
| 27 |
+
rot_w_cam = Rotation.from_quat(
|
| 28 |
+
[quat_wxyz_ros[1], quat_wxyz_ros[2], quat_wxyz_ros[3], quat_wxyz_ros[0]]
|
| 29 |
+
).as_matrix()
|
| 30 |
+
return (rot_w_cam @ pts_cam.T).T + pos_w
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _pca_aabb(points_w: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray, int]:
|
| 34 |
+
pts = np.asarray(points_w, dtype=np.float64)
|
| 35 |
+
if pts.shape[0] < 4:
|
| 36 |
+
raise RuntimeError("Too few points for PCA/AABB grasp.")
|
| 37 |
+
|
| 38 |
+
centroid = np.mean(pts, axis=0)
|
| 39 |
+
centered = pts - centroid
|
| 40 |
+
covariance = (centered.T @ centered) / max(centered.shape[0] - 1, 1)
|
| 41 |
+
eigen_values, eigen_vectors = np.linalg.eigh(covariance)
|
| 42 |
+
|
| 43 |
+
ev = eigen_vectors.copy()
|
| 44 |
+
ev[:, 2] = np.cross(ev[:, 0], ev[:, 1])
|
| 45 |
+
ev[:, 1] = np.cross(ev[:, 2], ev[:, 0])
|
| 46 |
+
ev[:, 0] = np.cross(ev[:, 1], ev[:, 2])
|
| 47 |
+
for i in range(3):
|
| 48 |
+
norm = np.linalg.norm(ev[:, i])
|
| 49 |
+
if norm > 1e-10:
|
| 50 |
+
ev[:, i] /= norm
|
| 51 |
+
|
| 52 |
+
order = np.argsort(eigen_values)[::-1]
|
| 53 |
+
R = ev[:, order].copy()
|
| 54 |
+
if np.linalg.det(R) < 0:
|
| 55 |
+
R[:, 2] = -R[:, 2]
|
| 56 |
+
|
| 57 |
+
local = (R.T @ (pts - centroid).T).T
|
| 58 |
+
min_pt = np.min(local, axis=0)
|
| 59 |
+
max_pt = np.max(local, axis=0)
|
| 60 |
+
extents = max_pt - min_pt
|
| 61 |
+
center_local = (min_pt + max_pt) * 0.5
|
| 62 |
+
center_w = R @ center_local + centroid
|
| 63 |
+
grasp_axis = int(np.argmin(extents))
|
| 64 |
+
return center_w.astype(np.float64), R.astype(np.float64), extents.astype(np.float64), grasp_axis
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def infer_pca_aabb_from_camera(camera, mask: np.ndarray, object_index: int | None = None) -> TaskEGrasp:
|
| 68 |
+
"""Return a GraspGen-style geometric grasp prior from segmented RGB-D."""
|
| 69 |
+
pts_w = _masked_world_points(camera, mask)
|
| 70 |
+
|
| 71 |
+
# Use the visible object body. Box/bottle masks are most stable with the
|
| 72 |
+
# upper visible surface median, while the banana's curved mask is less
|
| 73 |
+
# stable there and works better from the oriented AABB center.
|
| 74 |
+
center_w, R_pca, extents, grasp_axis = _pca_aabb(pts_w)
|
| 75 |
+
z_gate = float(np.percentile(pts_w[:, 2], 70))
|
| 76 |
+
upper = pts_w[pts_w[:, 2] >= z_gate]
|
| 77 |
+
exec_center = center_w.copy()
|
| 78 |
+
if object_index != 3 and len(upper) > 16:
|
| 79 |
+
exec_center[:2] = np.median(upper[:, :2], axis=0)
|
| 80 |
+
exec_center[2] = float(np.percentile(pts_w[:, 2], 85))
|
| 81 |
+
|
| 82 |
+
if grasp_axis == 0:
|
| 83 |
+
jaw_hint_w = R_pca[:, 1]
|
| 84 |
+
elif grasp_axis == 1:
|
| 85 |
+
jaw_hint_w = R_pca[:, 0]
|
| 86 |
+
else:
|
| 87 |
+
jaw_hint_w = R_pca[:, 0]
|
| 88 |
+
|
| 89 |
+
jaw_xy = np.array([jaw_hint_w[0], jaw_hint_w[1], 0.0], dtype=np.float64)
|
| 90 |
+
if np.linalg.norm(jaw_xy) < 1e-6:
|
| 91 |
+
jaw_xy = np.array([0.0, 1.0, 0.0], dtype=np.float64)
|
| 92 |
+
jaw_xy /= np.linalg.norm(jaw_xy)
|
| 93 |
+
grip_z = np.array([0.0, 0.0, -1.0], dtype=np.float64)
|
| 94 |
+
align_x = np.cross(jaw_xy, grip_z)
|
| 95 |
+
align_x /= max(np.linalg.norm(align_x), 1e-6)
|
| 96 |
+
jaw_y = np.cross(grip_z, align_x)
|
| 97 |
+
jaw_y /= max(np.linalg.norm(jaw_y), 1e-6)
|
| 98 |
+
R_w_tool = np.stack([align_x, jaw_y, grip_z], axis=1)
|
| 99 |
+
quat_xyzw = Rotation.from_matrix(R_w_tool).as_quat()
|
| 100 |
+
quat_wxyz = np.array([quat_xyzw[3], quat_xyzw[0], quat_xyzw[1], quat_xyzw[2]], dtype=np.float64)
|
| 101 |
+
|
| 102 |
+
width = float(extents[grasp_axis])
|
| 103 |
+
score = 1.0 / (1.0 + float(np.linalg.norm(extents)))
|
| 104 |
+
print(
|
| 105 |
+
f"[PCA_AABB] points={len(pts_w)} extents=({extents[0]:.3f},{extents[1]:.3f},{extents[2]:.3f}) "
|
| 106 |
+
f"axis={grasp_axis} width={width:.3f}"
|
| 107 |
+
)
|
| 108 |
+
return TaskEGrasp(
|
| 109 |
+
translation_w=exec_center.astype(np.float64),
|
| 110 |
+
quat_wxyz_w=quat_wxyz,
|
| 111 |
+
score=score,
|
| 112 |
+
width=width,
|
| 113 |
+
raw_translation_cam=np.zeros(3, dtype=np.float64),
|
| 114 |
+
)
|
scripts/graspnet_task_e/run_anygrasp_pick.sh
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
| 5 |
+
PYTHON_BIN="${PYTHON_BIN:-/home/ubuntu/envs/genmanip-isaac5-py311/bin/python}"
|
| 6 |
+
|
| 7 |
+
OBJ="${1:-3}"
|
| 8 |
+
if (( $# > 0 )); then
|
| 9 |
+
shift
|
| 10 |
+
fi
|
| 11 |
+
SEED="${1:-11}"
|
| 12 |
+
if (( $# > 0 )); then
|
| 13 |
+
shift
|
| 14 |
+
fi
|
| 15 |
+
MASK_PROVIDER="${MASK_PROVIDER:-oracle}"
|
| 16 |
+
VIDEO_PATH="${VIDEO_PATH:-logs/videos/task_e_anygrasp/anygrasp_obj${OBJ}_seed${SEED}.mp4}"
|
| 17 |
+
DEBUG_NPZ="${DEBUG_NPZ:-logs/anygrasp_task_e/obj${OBJ}_seed${SEED}_debug.npz}"
|
| 18 |
+
|
| 19 |
+
cd "${REPO_ROOT}"
|
| 20 |
+
|
| 21 |
+
exec env OMNI_KIT_ACCEPT_EULA=YES PYTHONUNBUFFERED=1 "${PYTHON_BIN}" \
|
| 22 |
+
scripts/graspnet_task_e/run_graspnet_pick.py \
|
| 23 |
+
--grasp_provider anygrasp \
|
| 24 |
+
--object "${OBJ}" \
|
| 25 |
+
--seed "${SEED}" \
|
| 26 |
+
--mask_provider "${MASK_PROVIDER}" \
|
| 27 |
+
--use_task_quat \
|
| 28 |
+
--tcp_z_offset 0.040 \
|
| 29 |
+
--close_z_offset -0.020 \
|
| 30 |
+
--close_steps 160 \
|
| 31 |
+
--move_steps 200 \
|
| 32 |
+
--transport_steps 1400 \
|
| 33 |
+
--place_steps 260 \
|
| 34 |
+
--video_path "${VIDEO_PATH}" \
|
| 35 |
+
--save_debug_npz "${DEBUG_NPZ}" \
|
| 36 |
+
--headless \
|
| 37 |
+
"$@"
|
scripts/graspnet_task_e/run_graspnet_pick.py
ADDED
|
@@ -0,0 +1,844 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Smoke-test a GraspNet-guided Task-E pick-and-place primitive.
|
| 2 |
+
|
| 3 |
+
This is intentionally separate from ACT training. It tests whether TunTunClaw
|
| 4 |
+
GraspNet can produce a usable grasp centre/yaw from Task-E RGB-D observations.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import argparse
|
| 10 |
+
import os
|
| 11 |
+
import subprocess
|
| 12 |
+
import sys
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
import json
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
REPO_ROOT = Path(__file__).resolve().parents[2]
|
| 18 |
+
if str(REPO_ROOT) not in sys.path:
|
| 19 |
+
sys.path.insert(0, str(REPO_ROOT))
|
| 20 |
+
|
| 21 |
+
from isaaclab.app import AppLauncher
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
parser = argparse.ArgumentParser(description="Run one Task-E grasp-guided pick trial.")
|
| 25 |
+
parser.add_argument("--grasp_provider", choices=["graspnet", "anygrasp", "pca"], default="graspnet")
|
| 26 |
+
parser.add_argument("--object", type=int, default=1, choices=[1, 2, 3])
|
| 27 |
+
parser.add_argument("--seed", type=int, default=7)
|
| 28 |
+
parser.add_argument("--video_path", default="logs/videos/task_e_graspnet/graspnet_pick_obj1.mp4")
|
| 29 |
+
parser.add_argument("--tcp_z_offset", type=float, default=0.055)
|
| 30 |
+
parser.add_argument("--close_z_offset", type=float, default=None)
|
| 31 |
+
parser.add_argument("--pregrasp_z", type=float, default=0.30)
|
| 32 |
+
parser.add_argument("--lift_z", type=float, default=0.30)
|
| 33 |
+
parser.add_argument("--place_z", type=float, default=0.18)
|
| 34 |
+
parser.add_argument("--release_z", type=float, default=0.32)
|
| 35 |
+
parser.add_argument("--open_release_z", type=float, default=None)
|
| 36 |
+
parser.add_argument("--place_x_offset", type=float, default=0.0)
|
| 37 |
+
parser.add_argument("--place_y_offset", type=float, default=0.0)
|
| 38 |
+
parser.add_argument("--basket_center_release", action=argparse.BooleanOptionalAction, default=True)
|
| 39 |
+
parser.add_argument("--basket_servo_gain", type=float, default=1.0)
|
| 40 |
+
parser.add_argument("--basket_servo_max_xy", type=float, default=0.30)
|
| 41 |
+
parser.add_argument("--staged_transport", action=argparse.BooleanOptionalAction, default=True)
|
| 42 |
+
parser.add_argument("--transport_servo_fraction", type=float, default=0.25)
|
| 43 |
+
parser.add_argument("--basket_xy_tol", type=float, default=0.055)
|
| 44 |
+
parser.add_argument("--basket_hold_steps", type=int, default=900)
|
| 45 |
+
parser.add_argument("--basket_stable_steps", type=int, default=80)
|
| 46 |
+
parser.add_argument("--basket_recovery_steps", type=int, default=900)
|
| 47 |
+
parser.add_argument("--dynamic_finger_servo", action=argparse.BooleanOptionalAction, default=True)
|
| 48 |
+
parser.add_argument("--close_steps", type=int, default=70)
|
| 49 |
+
parser.add_argument("--preclose_insert_steps", type=int, default=0)
|
| 50 |
+
parser.add_argument("--preclose_insert_dx", type=float, default=0.0)
|
| 51 |
+
parser.add_argument("--preclose_insert_dy", type=float, default=0.0)
|
| 52 |
+
parser.add_argument("--move_steps", type=int, default=160)
|
| 53 |
+
parser.add_argument("--transport_steps", type=int, default=None)
|
| 54 |
+
parser.add_argument("--place_steps", type=int, default=None)
|
| 55 |
+
parser.add_argument("--settle_steps", type=int, default=120)
|
| 56 |
+
parser.add_argument("--force_default_quat", action="store_true")
|
| 57 |
+
parser.add_argument("--use_task_quat", action="store_true")
|
| 58 |
+
parser.add_argument("--no_finger_servo", action="store_true")
|
| 59 |
+
parser.add_argument("--no_object_offset", action="store_true")
|
| 60 |
+
parser.add_argument("--post_push", action="store_true")
|
| 61 |
+
parser.add_argument("--auto_table_push_on_slip", action=argparse.BooleanOptionalAction, default=True)
|
| 62 |
+
parser.add_argument("--post_push_steps", type=int, default=600)
|
| 63 |
+
parser.add_argument("--post_push_behind", type=float, default=0.075)
|
| 64 |
+
parser.add_argument("--post_push_z", type=float, default=0.055)
|
| 65 |
+
parser.add_argument("--drag_recovery_steps", type=int, default=1200)
|
| 66 |
+
parser.add_argument("--mask_provider", choices=["oracle", "band", "sam3"], default="oracle")
|
| 67 |
+
parser.add_argument(
|
| 68 |
+
"--sam3_python",
|
| 69 |
+
default="/home/ubuntu/Documents/01Proj/sam3d_gs/.venv/bin/python",
|
| 70 |
+
help="Python executable for the isolated SAM3 environment.",
|
| 71 |
+
)
|
| 72 |
+
parser.add_argument("--sam3_threshold", type=float, default=0.35)
|
| 73 |
+
parser.add_argument("--sam3_mask_threshold", type=float, default=0.5)
|
| 74 |
+
parser.add_argument(
|
| 75 |
+
"--sam3_prompt",
|
| 76 |
+
action="append",
|
| 77 |
+
default=None,
|
| 78 |
+
help="SAM3 text prompt. Can repeat. Defaults are selected from --object.",
|
| 79 |
+
)
|
| 80 |
+
parser.add_argument("--save_debug_npz", default="logs/graspnet_task_e/latest_debug.npz")
|
| 81 |
+
AppLauncher.add_app_launcher_args(parser)
|
| 82 |
+
args_cli = parser.parse_args()
|
| 83 |
+
args_cli.enable_cameras = True
|
| 84 |
+
|
| 85 |
+
app_launcher = AppLauncher(args_cli)
|
| 86 |
+
simulation_app = app_launcher.app
|
| 87 |
+
|
| 88 |
+
import imageio.v2 as imageio
|
| 89 |
+
import numpy as np
|
| 90 |
+
import torch
|
| 91 |
+
|
| 92 |
+
from isaaclab.actuators import ImplicitActuatorCfg
|
| 93 |
+
from isaaclab.envs import ManagerBasedRLEnv
|
| 94 |
+
|
| 95 |
+
from atec_rl_lab.tasks.task_e.env_cfg import (
|
| 96 |
+
BASKET_CENTER_X,
|
| 97 |
+
BASKET_CENTER_Y,
|
| 98 |
+
TABLE_TOP_Z,
|
| 99 |
+
TaskEEnvPiperCfg,
|
| 100 |
+
)
|
| 101 |
+
from atec_rl_lab.utils import CartesianController
|
| 102 |
+
|
| 103 |
+
from scripts.act.task_e.collector import basket_status_lines, check_objects_in_basket
|
| 104 |
+
from scripts.act.task_e.config import (
|
| 105 |
+
ACTION_SCALE,
|
| 106 |
+
ACT_DAMPING,
|
| 107 |
+
ACT_EFFORT_LIMIT,
|
| 108 |
+
ACT_STIFFNESS,
|
| 109 |
+
ACT_VEL_LIMIT,
|
| 110 |
+
ARM_JOINT_NAMES,
|
| 111 |
+
CARRY_Z,
|
| 112 |
+
DEFAULT_PLACE_QUAT_W,
|
| 113 |
+
EE_BODY_NAME,
|
| 114 |
+
GRIPPER_CLOSE_POS,
|
| 115 |
+
GRIPPER_JOINT_NAMES,
|
| 116 |
+
GRIPPER_OPEN_POS,
|
| 117 |
+
OBJ_GRASP_CENTER_OFFSETS,
|
| 118 |
+
OBJ_GRASP_Z_OFFSETS,
|
| 119 |
+
OBJ_CLOSE_Z_OFFSETS,
|
| 120 |
+
OBJ_FINGER_CENTER_SERVO_GAIN,
|
| 121 |
+
OBJ_FINGER_CENTER_SERVO_MAX_XY,
|
| 122 |
+
OBJ_FINGER_CENTER_SERVO_TARGET_Z,
|
| 123 |
+
OBJ_FINGER_CENTER_SERVO_MAX_Z,
|
| 124 |
+
RETRACT_POS_X,
|
| 125 |
+
RETRACT_POS_Y,
|
| 126 |
+
)
|
| 127 |
+
from scripts.act.task_e.state_machine import compute_grasp_quat
|
| 128 |
+
from scripts.graspnet_task_e.tuntun_adapter import (
|
| 129 |
+
camera_arrays,
|
| 130 |
+
infer_grasp_from_camera,
|
| 131 |
+
oracle_object_mask,
|
| 132 |
+
rgbd_band_object_mask,
|
| 133 |
+
pos_to_torch,
|
| 134 |
+
quat_wxyz_to_torch,
|
| 135 |
+
)
|
| 136 |
+
from scripts.graspnet_task_e.anygrasp_adapter import infer_anygrasp_from_camera
|
| 137 |
+
from scripts.graspnet_task_e.pca_aabb_adapter import infer_pca_aabb_from_camera
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
GRASPNET_CLOSE_Z_DEFAULTS = {
|
| 141 |
+
3: -0.005,
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
SAM_MASK_P85_Z_MAX = {
|
| 145 |
+
1: TABLE_TOP_Z + 0.13,
|
| 146 |
+
2: TABLE_TOP_Z + 0.19,
|
| 147 |
+
3: TABLE_TOP_Z + 0.085,
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def build_env() -> ManagerBasedRLEnv:
|
| 152 |
+
cfg = TaskEEnvPiperCfg()
|
| 153 |
+
cfg.seed = args_cli.seed
|
| 154 |
+
cfg.scene.num_envs = 1
|
| 155 |
+
cfg.episode_length_s = 90.0
|
| 156 |
+
cfg.scene.robot.actuators["default"] = ImplicitActuatorCfg(
|
| 157 |
+
joint_names_expr=[".*"],
|
| 158 |
+
effort_limit=ACT_EFFORT_LIMIT,
|
| 159 |
+
velocity_limit=ACT_VEL_LIMIT,
|
| 160 |
+
stiffness=ACT_STIFFNESS,
|
| 161 |
+
damping=ACT_DAMPING,
|
| 162 |
+
)
|
| 163 |
+
return ManagerBasedRLEnv(cfg)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def step_pose(
|
| 167 |
+
env,
|
| 168 |
+
robot,
|
| 169 |
+
ik_ctrl,
|
| 170 |
+
arm_ids,
|
| 171 |
+
gripper_ids,
|
| 172 |
+
default_jpos,
|
| 173 |
+
pos_w,
|
| 174 |
+
quat_w,
|
| 175 |
+
gripper,
|
| 176 |
+
frames,
|
| 177 |
+
camera,
|
| 178 |
+
n_steps,
|
| 179 |
+
*,
|
| 180 |
+
obj_idx: int | None = None,
|
| 181 |
+
obj=None,
|
| 182 |
+
finger_body_indices: tuple[int, int] | None = None,
|
| 183 |
+
servo_center_xy: np.ndarray | None = None,
|
| 184 |
+
servo_current_object_xy: bool = False,
|
| 185 |
+
finger_target_xy: np.ndarray | None = None,
|
| 186 |
+
finger_target_z: float | None = None,
|
| 187 |
+
finger_servo_gain: float = 1.0,
|
| 188 |
+
finger_servo_max_xy: float = 0.12,
|
| 189 |
+
finger_servo_max_z: float = 0.04,
|
| 190 |
+
object_target_xy: np.ndarray | None = None,
|
| 191 |
+
object_servo_gain: float = 1.0,
|
| 192 |
+
object_servo_max_xy: float = 0.30,
|
| 193 |
+
) -> dict[str, float | list[float] | None]:
|
| 194 |
+
dev = env.unwrapped.device
|
| 195 |
+
pos_np = np.asarray(pos_w, dtype=np.float64)
|
| 196 |
+
quat_t = quat_wxyz_to_torch(np.asarray(quat_w, dtype=np.float64), dev)
|
| 197 |
+
grip_t = torch.tensor([gripper], dtype=torch.float32, device=dev)
|
| 198 |
+
stats: dict[str, float | list[float] | None] = {
|
| 199 |
+
"min_finger_dist": None,
|
| 200 |
+
"min_finger_vec": None,
|
| 201 |
+
"min_finger_gap": None,
|
| 202 |
+
"min_finger_q": None,
|
| 203 |
+
"last_finger_q": None,
|
| 204 |
+
}
|
| 205 |
+
for _ in range(n_steps):
|
| 206 |
+
target_np = pos_np.copy()
|
| 207 |
+
if obj is not None and object_target_xy is not None:
|
| 208 |
+
obj_pos = obj.data.root_pos_w[0].detach()
|
| 209 |
+
target_xy = torch.tensor(object_target_xy, dtype=torch.float32, device=dev)
|
| 210 |
+
xy_error = target_xy - obj_pos[:2]
|
| 211 |
+
correction = xy_error * object_servo_gain
|
| 212 |
+
corr_norm = torch.linalg.norm(correction).clamp(min=1e-6)
|
| 213 |
+
if corr_norm.item() > object_servo_max_xy:
|
| 214 |
+
correction = correction / corr_norm * object_servo_max_xy
|
| 215 |
+
target_np[:2] = target_np[:2] + correction.detach().cpu().numpy()
|
| 216 |
+
if finger_body_indices is not None and not args_cli.no_finger_servo and (
|
| 217 |
+
finger_target_xy is not None or (obj_idx is not None and obj is not None and servo_center_xy is not None)
|
| 218 |
+
):
|
| 219 |
+
f0 = robot.data.body_pos_w[0, finger_body_indices[0], :3].detach()
|
| 220 |
+
f1 = robot.data.body_pos_w[0, finger_body_indices[1], :3].detach()
|
| 221 |
+
finger_center = 0.5 * (f0 + f1)
|
| 222 |
+
obj_pos = obj.data.root_pos_w[0].detach() if obj is not None else None
|
| 223 |
+
if finger_target_xy is not None:
|
| 224 |
+
target_xy = torch.tensor(finger_target_xy, dtype=torch.float32, device=dev)
|
| 225 |
+
elif servo_current_object_xy and obj_pos is not None:
|
| 226 |
+
target_xy = obj_pos[:2]
|
| 227 |
+
else:
|
| 228 |
+
target_xy = torch.tensor(servo_center_xy, dtype=torch.float32, device=dev)
|
| 229 |
+
grasp_center = torch.tensor(
|
| 230 |
+
[
|
| 231 |
+
float(target_xy[0].item()),
|
| 232 |
+
float(target_xy[1].item()),
|
| 233 |
+
float(obj_pos[2].item()) if obj_pos is not None else float(finger_center[2].item()),
|
| 234 |
+
],
|
| 235 |
+
dtype=torch.float32,
|
| 236 |
+
device=dev,
|
| 237 |
+
)
|
| 238 |
+
finger_vec = finger_center - grasp_center
|
| 239 |
+
finger_dist = float(torch.linalg.norm(finger_vec).item())
|
| 240 |
+
finger_gap = float(torch.linalg.norm(f0 - f1).item())
|
| 241 |
+
if stats["min_finger_dist"] is None or finger_dist < float(stats["min_finger_dist"]):
|
| 242 |
+
stats["min_finger_dist"] = finger_dist
|
| 243 |
+
stats["min_finger_vec"] = [float(v) for v in finger_vec.detach().cpu().tolist()]
|
| 244 |
+
if stats["min_finger_gap"] is None or finger_gap < float(stats["min_finger_gap"]):
|
| 245 |
+
stats["min_finger_gap"] = finger_gap
|
| 246 |
+
q = robot.data.joint_pos[0, gripper_ids].detach().cpu().numpy()
|
| 247 |
+
stats["min_finger_q"] = [float(q[0]), float(q[1])]
|
| 248 |
+
q = robot.data.joint_pos[0, gripper_ids].detach().cpu().numpy()
|
| 249 |
+
stats["last_finger_q"] = [float(q[0]), float(q[1])]
|
| 250 |
+
xy_error = finger_center[:2] - target_xy
|
| 251 |
+
if finger_target_xy is not None or servo_current_object_xy or torch.linalg.norm(xy_error).item() <= 0.18:
|
| 252 |
+
gain = finger_servo_gain if finger_target_xy is not None else OBJ_FINGER_CENTER_SERVO_GAIN.get(obj_idx, 0.85)
|
| 253 |
+
correction = -xy_error * gain
|
| 254 |
+
max_xy = finger_servo_max_xy if finger_target_xy is not None else OBJ_FINGER_CENTER_SERVO_MAX_XY.get(obj_idx, 0.08)
|
| 255 |
+
corr_norm = torch.linalg.norm(correction).clamp(min=1e-6)
|
| 256 |
+
if corr_norm.item() > max_xy:
|
| 257 |
+
correction = correction / corr_norm * max_xy
|
| 258 |
+
target_np[:2] = target_np[:2] + correction.detach().cpu().numpy()
|
| 259 |
+
if finger_target_z is not None:
|
| 260 |
+
z_error = finger_target_z - float(finger_center[2].item())
|
| 261 |
+
z_correction = max(-finger_servo_max_z, min(finger_servo_max_z, z_error * gain))
|
| 262 |
+
target_np[2] = target_np[2] + z_correction
|
| 263 |
+
elif obj_pos is not None and obj_idx in OBJ_FINGER_CENTER_SERVO_TARGET_Z:
|
| 264 |
+
target_rel_z = OBJ_FINGER_CENTER_SERVO_TARGET_Z[obj_idx]
|
| 265 |
+
z_error = target_rel_z - float((finger_center[2] - obj_pos[2]).item())
|
| 266 |
+
max_z = OBJ_FINGER_CENTER_SERVO_MAX_Z.get(obj_idx, 0.02)
|
| 267 |
+
z_correction = min(0.0, max(-max_z, z_error * gain))
|
| 268 |
+
target_np[2] = target_np[2] + z_correction
|
| 269 |
+
pos_t = pos_to_torch(target_np, dev)
|
| 270 |
+
arm_des = ik_ctrl.compute(pos_t, quat_t)
|
| 271 |
+
target = robot.data.joint_pos.clone()
|
| 272 |
+
target[:, arm_ids] = arm_des
|
| 273 |
+
target[:, gripper_ids] = grip_t
|
| 274 |
+
action = (target - default_jpos) / ACTION_SCALE
|
| 275 |
+
env.step(action)
|
| 276 |
+
robot.update(dt=env.unwrapped.physics_dt)
|
| 277 |
+
if frames is not None:
|
| 278 |
+
rgba = camera.data.output["rgb"][0].detach().cpu().numpy()
|
| 279 |
+
frames.append(rgba[..., :3])
|
| 280 |
+
return stats
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def step_until_object_center_stable(
|
| 284 |
+
env,
|
| 285 |
+
robot,
|
| 286 |
+
ik_ctrl,
|
| 287 |
+
arm_ids,
|
| 288 |
+
gripper_ids,
|
| 289 |
+
default_jpos,
|
| 290 |
+
pos_w,
|
| 291 |
+
quat_w,
|
| 292 |
+
gripper,
|
| 293 |
+
frames,
|
| 294 |
+
camera,
|
| 295 |
+
*,
|
| 296 |
+
obj,
|
| 297 |
+
target_xy: np.ndarray,
|
| 298 |
+
xy_tol: float,
|
| 299 |
+
stable_steps: int,
|
| 300 |
+
max_steps: int,
|
| 301 |
+
object_servo_gain: float,
|
| 302 |
+
object_servo_max_xy: float,
|
| 303 |
+
obj_idx: int | None = None,
|
| 304 |
+
finger_body_indices: tuple[int, int] | None = None,
|
| 305 |
+
servo_center_xy: np.ndarray | None = None,
|
| 306 |
+
servo_current_object_xy: bool = True,
|
| 307 |
+
) -> dict[str, float | int | list[float]]:
|
| 308 |
+
stable = 0
|
| 309 |
+
min_xy_err = 999.0
|
| 310 |
+
last_obj_pos = None
|
| 311 |
+
for step in range(max_steps):
|
| 312 |
+
step_pose(
|
| 313 |
+
env,
|
| 314 |
+
robot,
|
| 315 |
+
ik_ctrl,
|
| 316 |
+
arm_ids,
|
| 317 |
+
gripper_ids,
|
| 318 |
+
default_jpos,
|
| 319 |
+
pos_w,
|
| 320 |
+
quat_w,
|
| 321 |
+
gripper,
|
| 322 |
+
frames,
|
| 323 |
+
camera,
|
| 324 |
+
1,
|
| 325 |
+
obj_idx=obj_idx,
|
| 326 |
+
obj=obj,
|
| 327 |
+
finger_body_indices=finger_body_indices,
|
| 328 |
+
servo_center_xy=servo_center_xy,
|
| 329 |
+
servo_current_object_xy=servo_current_object_xy,
|
| 330 |
+
object_target_xy=target_xy,
|
| 331 |
+
object_servo_gain=object_servo_gain,
|
| 332 |
+
object_servo_max_xy=object_servo_max_xy,
|
| 333 |
+
)
|
| 334 |
+
obj_pos = obj.data.root_pos_w[0].detach().cpu().numpy().astype(np.float64)
|
| 335 |
+
last_obj_pos = obj_pos
|
| 336 |
+
xy_err = float(np.linalg.norm(obj_pos[:2] - target_xy))
|
| 337 |
+
min_xy_err = min(min_xy_err, xy_err)
|
| 338 |
+
if xy_err <= xy_tol:
|
| 339 |
+
stable += 1
|
| 340 |
+
if stable >= stable_steps:
|
| 341 |
+
break
|
| 342 |
+
else:
|
| 343 |
+
stable = 0
|
| 344 |
+
if last_obj_pos is None:
|
| 345 |
+
last_obj_pos = obj.data.root_pos_w[0].detach().cpu().numpy().astype(np.float64)
|
| 346 |
+
return {
|
| 347 |
+
"steps": step + 1 if max_steps > 0 else 0,
|
| 348 |
+
"stable": stable,
|
| 349 |
+
"min_xy_err": min_xy_err,
|
| 350 |
+
"final_xy_err": float(np.linalg.norm(last_obj_pos[:2] - target_xy)),
|
| 351 |
+
"final_obj_pos": [float(v) for v in last_obj_pos.tolist()],
|
| 352 |
+
}
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def sam3_prompts_for_object(obj_idx: int) -> list[str]:
|
| 356 |
+
defaults = {
|
| 357 |
+
1: ["sugar box", "box", "rectangular object"],
|
| 358 |
+
2: ["mustard bottle", "bottle", "yellow bottle"],
|
| 359 |
+
3: ["banana", "curved yellow object"],
|
| 360 |
+
}
|
| 361 |
+
return defaults.get(obj_idx, ["object"])
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def select_sam_candidate_by_world_band(candidates_path: Path, camera, obj_idx: int) -> np.ndarray | None:
|
| 365 |
+
from scipy.spatial.transform import Rotation
|
| 366 |
+
from scripts.act.task_e.config import OBJ_SPAWN_X_MIN, OBJ_SPAWN_X_MAX, OBJ_SPAWN_Y_BANDS
|
| 367 |
+
|
| 368 |
+
if not candidates_path.exists():
|
| 369 |
+
return None
|
| 370 |
+
data = np.load(candidates_path, allow_pickle=False)
|
| 371 |
+
masks = data["masks"].astype(bool)
|
| 372 |
+
metas = json.loads(str(data["metas"]))
|
| 373 |
+
_rgb, depth, K, pos_w, quat_wxyz_ros = camera_arrays(camera)
|
| 374 |
+
rot_w_cam = Rotation.from_quat(
|
| 375 |
+
[quat_wxyz_ros[1], quat_wxyz_ros[2], quat_wxyz_ros[3], quat_wxyz_ros[0]]
|
| 376 |
+
).as_matrix()
|
| 377 |
+
y0, y1 = OBJ_SPAWN_Y_BANDS[obj_idx]
|
| 378 |
+
scored = []
|
| 379 |
+
for idx, mask in enumerate(masks):
|
| 380 |
+
valid = mask & np.isfinite(depth) & (depth > 0.0) & (depth < 6.0)
|
| 381 |
+
ys, xs = np.where(valid)
|
| 382 |
+
if len(xs) < 64:
|
| 383 |
+
continue
|
| 384 |
+
z = depth[ys, xs].astype(np.float64)
|
| 385 |
+
x_cam = (xs.astype(np.float64) - float(K[0, 2])) / float(K[0, 0]) * z
|
| 386 |
+
y_cam = (ys.astype(np.float64) - float(K[1, 2])) / float(K[1, 1]) * z
|
| 387 |
+
pts_cam = np.stack([x_cam, y_cam, z], axis=1)
|
| 388 |
+
pts_w = (rot_w_cam @ pts_cam.T).T + pos_w
|
| 389 |
+
keep = (
|
| 390 |
+
(pts_w[:, 0] >= OBJ_SPAWN_X_MIN - 0.10)
|
| 391 |
+
& (pts_w[:, 0] <= OBJ_SPAWN_X_MAX + 0.10)
|
| 392 |
+
& (pts_w[:, 1] >= y0 - 0.08)
|
| 393 |
+
& (pts_w[:, 1] <= y1 + 0.08)
|
| 394 |
+
& (pts_w[:, 2] >= TABLE_TOP_Z + 0.005)
|
| 395 |
+
& (pts_w[:, 2] <= TABLE_TOP_Z + 0.26)
|
| 396 |
+
)
|
| 397 |
+
band_count = int(np.count_nonzero(keep))
|
| 398 |
+
band_ratio = band_count / max(len(xs), 1)
|
| 399 |
+
if band_count < 64:
|
| 400 |
+
continue
|
| 401 |
+
band_pts = pts_w[keep]
|
| 402 |
+
p85_z = float(np.percentile(band_pts[:, 2], 85))
|
| 403 |
+
if p85_z > SAM_MASK_P85_Z_MAX.get(obj_idx, TABLE_TOP_Z + 0.18):
|
| 404 |
+
continue
|
| 405 |
+
score = float(metas[idx].get("score", 0.0))
|
| 406 |
+
# Prefer masks that live in the object's legal spawn band. Score is
|
| 407 |
+
# secondary because open-vocabulary prompts can rate distractors high.
|
| 408 |
+
scored.append((band_ratio, band_count, score, -p85_z, idx, keep, ys, xs))
|
| 409 |
+
if not scored:
|
| 410 |
+
print("[SAM3] no candidate survived world-band filter; using best SAM3 mask")
|
| 411 |
+
return None
|
| 412 |
+
band_ratio, band_count, score, neg_p85_z, idx, keep, ys, xs = max(scored, key=lambda x: (x[1], x[0], x[2], x[3]))
|
| 413 |
+
refined = np.zeros_like(masks[idx], dtype=np.bool_)
|
| 414 |
+
refined[ys[keep], xs[keep]] = True
|
| 415 |
+
meta = metas[idx]
|
| 416 |
+
print(
|
| 417 |
+
f"[SAM3] selected_candidate={idx} prompt={meta.get('prompt')} score={score:.3f} "
|
| 418 |
+
f"band_ratio={band_ratio:.3f} band_pixels={band_count} p85_z={-neg_p85_z:.3f}"
|
| 419 |
+
)
|
| 420 |
+
return refined
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
def sam3_object_mask(camera, rgb: np.ndarray, obj_idx: int, debug_dir: Path) -> np.ndarray:
|
| 424 |
+
if not Path(args_cli.sam3_python).exists():
|
| 425 |
+
raise RuntimeError(f"SAM3 python not found: {args_cli.sam3_python}")
|
| 426 |
+
debug_dir.mkdir(parents=True, exist_ok=True)
|
| 427 |
+
image_path = debug_dir / f"sam3_obj{obj_idx}_rgb.png"
|
| 428 |
+
mask_path = debug_dir / f"sam3_obj{obj_idx}_mask.npy"
|
| 429 |
+
meta_path = debug_dir / f"sam3_obj{obj_idx}_meta.json"
|
| 430 |
+
candidates_path = debug_dir / f"sam3_obj{obj_idx}_candidates.npz"
|
| 431 |
+
imageio.imwrite(str(image_path), rgb.astype(np.uint8))
|
| 432 |
+
prompts = args_cli.sam3_prompt or sam3_prompts_for_object(obj_idx)
|
| 433 |
+
cmd = [
|
| 434 |
+
args_cli.sam3_python,
|
| 435 |
+
str(Path(__file__).with_name("sam3_segment_image.py")),
|
| 436 |
+
"--image",
|
| 437 |
+
str(image_path),
|
| 438 |
+
"--out_mask",
|
| 439 |
+
str(mask_path),
|
| 440 |
+
"--out_meta",
|
| 441 |
+
str(meta_path),
|
| 442 |
+
"--out_candidates",
|
| 443 |
+
str(candidates_path),
|
| 444 |
+
"--threshold",
|
| 445 |
+
str(args_cli.sam3_threshold),
|
| 446 |
+
"--mask_threshold",
|
| 447 |
+
str(args_cli.sam3_mask_threshold),
|
| 448 |
+
]
|
| 449 |
+
for prompt in prompts:
|
| 450 |
+
cmd.extend(["--prompt", prompt])
|
| 451 |
+
print(f"[SAM3] prompts={prompts} image={image_path}")
|
| 452 |
+
subprocess.run(cmd, check=True)
|
| 453 |
+
mask = np.load(mask_path).astype(bool)
|
| 454 |
+
if candidates_path.exists():
|
| 455 |
+
refined = select_sam_candidate_by_world_band(candidates_path, camera=camera, obj_idx=obj_idx)
|
| 456 |
+
if refined is not None:
|
| 457 |
+
mask = refined
|
| 458 |
+
np.save(mask_path, mask.astype(np.bool_))
|
| 459 |
+
print(f"[SAM3] mask_pixels={int(mask.sum())} meta={meta_path}")
|
| 460 |
+
return mask
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
def object_z_gain(env, obj_idx: int, z0: float) -> float:
|
| 464 |
+
pos = env.unwrapped.scene.rigid_objects[f"object_{obj_idx}"].data.root_pos_w[0]
|
| 465 |
+
return float(pos[2].item() - z0)
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
def run_table_push_recovery(
|
| 469 |
+
env,
|
| 470 |
+
robot,
|
| 471 |
+
ik_ctrl,
|
| 472 |
+
arm_ids,
|
| 473 |
+
gripper_ids,
|
| 474 |
+
default_jpos,
|
| 475 |
+
frames,
|
| 476 |
+
camera,
|
| 477 |
+
obj,
|
| 478 |
+
topdown_quat,
|
| 479 |
+
finger_body_indices: tuple[int, int] | None,
|
| 480 |
+
) -> None:
|
| 481 |
+
cur = obj.data.root_pos_w[0].detach().cpu().numpy().astype(np.float64)
|
| 482 |
+
push_z = TABLE_TOP_Z + args_cli.post_push_z
|
| 483 |
+
behind = args_cli.post_push_behind
|
| 484 |
+
# Approach from the positive-Y side and push toward the basket center. This
|
| 485 |
+
# is the deterministic fallback when the object has slipped back to the table.
|
| 486 |
+
push_start = np.array([cur[0], cur[1] + behind, push_z], dtype=np.float64)
|
| 487 |
+
push_mid = np.array([BASKET_CENTER_X, BASKET_CENTER_Y + behind, push_z], dtype=np.float64)
|
| 488 |
+
push_end = np.array([BASKET_CENTER_X, BASKET_CENTER_Y + behind * 0.20, push_z], dtype=np.float64)
|
| 489 |
+
print(
|
| 490 |
+
f"[TABLE_PUSH] cur=({cur[0]:.3f},{cur[1]:.3f},{cur[2]:.3f}) "
|
| 491 |
+
f"start=({push_start[0]:.3f},{push_start[1]:.3f},{push_start[2]:.3f}) "
|
| 492 |
+
f"mid=({push_mid[0]:.3f},{push_mid[1]:.3f},{push_mid[2]:.3f}) "
|
| 493 |
+
f"end=({push_end[0]:.3f},{push_end[1]:.3f},{push_end[2]:.3f})"
|
| 494 |
+
)
|
| 495 |
+
contact_z = TABLE_TOP_Z + max(args_cli.post_push_z, 0.025)
|
| 496 |
+
step_pose(env, robot, ik_ctrl, arm_ids, gripper_ids, default_jpos, push_start, topdown_quat, GRIPPER_OPEN_POS, frames, camera, 120, finger_body_indices=finger_body_indices, finger_target_xy=push_start[:2], finger_target_z=contact_z)
|
| 497 |
+
step_pose(env, robot, ik_ctrl, arm_ids, gripper_ids, default_jpos, push_start, topdown_quat, GRIPPER_CLOSE_POS, frames, camera, 80, finger_body_indices=finger_body_indices, finger_target_xy=push_start[:2], finger_target_z=contact_z)
|
| 498 |
+
step_pose(env, robot, ik_ctrl, arm_ids, gripper_ids, default_jpos, push_mid, topdown_quat, GRIPPER_CLOSE_POS, frames, camera, max(args_cli.post_push_steps // 2, 1), finger_body_indices=finger_body_indices, finger_target_xy=push_mid[:2], finger_target_z=contact_z)
|
| 499 |
+
step_pose(env, robot, ik_ctrl, arm_ids, gripper_ids, default_jpos, push_end, topdown_quat, GRIPPER_CLOSE_POS, frames, camera, max(args_cli.post_push_steps // 2, 1), finger_body_indices=finger_body_indices, finger_target_xy=push_end[:2], finger_target_z=contact_z)
|
| 500 |
+
step_pose(env, robot, ik_ctrl, arm_ids, gripper_ids, default_jpos, push_end, topdown_quat, GRIPPER_OPEN_POS, frames, camera, 80)
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
def run_closed_drag_recovery(
|
| 504 |
+
env,
|
| 505 |
+
robot,
|
| 506 |
+
ik_ctrl,
|
| 507 |
+
arm_ids,
|
| 508 |
+
gripper_ids,
|
| 509 |
+
default_jpos,
|
| 510 |
+
frames,
|
| 511 |
+
camera,
|
| 512 |
+
obj,
|
| 513 |
+
quat_w,
|
| 514 |
+
finger_body_indices: tuple[int, int] | None,
|
| 515 |
+
) -> None:
|
| 516 |
+
cur = obj.data.root_pos_w[0].detach().cpu().numpy().astype(np.float64)
|
| 517 |
+
drag_z = TABLE_TOP_Z + max(args_cli.post_push_z, 0.025)
|
| 518 |
+
# Keep the gripper closed and continue from the current contact region.
|
| 519 |
+
# The intermediate target stays slightly behind the basket center so the
|
| 520 |
+
# object is swept into the success box instead of being abandoned early.
|
| 521 |
+
drag_start = np.array([cur[0], cur[1], drag_z], dtype=np.float64)
|
| 522 |
+
drag_mid = np.array([BASKET_CENTER_X, (cur[1] + BASKET_CENTER_Y) * 0.5, drag_z], dtype=np.float64)
|
| 523 |
+
drag_end = np.array([BASKET_CENTER_X, BASKET_CENTER_Y, drag_z], dtype=np.float64)
|
| 524 |
+
print(
|
| 525 |
+
f"[CLOSED_DRAG] cur=({cur[0]:.3f},{cur[1]:.3f},{cur[2]:.3f}) "
|
| 526 |
+
f"start=({drag_start[0]:.3f},{drag_start[1]:.3f},{drag_start[2]:.3f}) "
|
| 527 |
+
f"mid=({drag_mid[0]:.3f},{drag_mid[1]:.3f},{drag_mid[2]:.3f}) "
|
| 528 |
+
f"end=({drag_end[0]:.3f},{drag_end[1]:.3f},{drag_end[2]:.3f})"
|
| 529 |
+
)
|
| 530 |
+
step_pose(env, robot, ik_ctrl, arm_ids, gripper_ids, default_jpos, drag_start, quat_w, GRIPPER_CLOSE_POS, frames, camera, 120, finger_body_indices=finger_body_indices, finger_target_xy=drag_start[:2], finger_target_z=drag_z)
|
| 531 |
+
step_pose(env, robot, ik_ctrl, arm_ids, gripper_ids, default_jpos, drag_mid, quat_w, GRIPPER_CLOSE_POS, frames, camera, max(args_cli.drag_recovery_steps // 2, 1), finger_body_indices=finger_body_indices, finger_target_xy=drag_mid[:2], finger_target_z=drag_z)
|
| 532 |
+
step_pose(env, robot, ik_ctrl, arm_ids, gripper_ids, default_jpos, drag_end, quat_w, GRIPPER_CLOSE_POS, frames, camera, max(args_cli.drag_recovery_steps // 2, 1), finger_body_indices=finger_body_indices, finger_target_xy=drag_end[:2], finger_target_z=drag_z)
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
def main() -> None:
|
| 536 |
+
env = build_env()
|
| 537 |
+
dev = env.unwrapped.device
|
| 538 |
+
env.reset()
|
| 539 |
+
|
| 540 |
+
robot = env.unwrapped.scene.articulations["robot"]
|
| 541 |
+
robot.write_joint_state_to_sim(robot.data.default_joint_pos, torch.zeros_like(robot.data.default_joint_vel))
|
| 542 |
+
default_jpos = robot.data.default_joint_pos.clone()
|
| 543 |
+
arm_ids, _ = robot.find_joints(ARM_JOINT_NAMES)
|
| 544 |
+
gripper_ids, _ = robot.find_joints(GRIPPER_JOINT_NAMES)
|
| 545 |
+
link7_ids, _ = robot.find_bodies("link7")
|
| 546 |
+
link8_ids, _ = robot.find_bodies("link8")
|
| 547 |
+
finger_body_indices = None
|
| 548 |
+
if len(link7_ids) > 0 and len(link8_ids) > 0:
|
| 549 |
+
finger_body_indices = (int(link7_ids[0]), int(link8_ids[0]))
|
| 550 |
+
camera = env.unwrapped.scene["video_cam"]
|
| 551 |
+
|
| 552 |
+
ik_ctrl = CartesianController(
|
| 553 |
+
robot=robot,
|
| 554 |
+
ee_body_name=EE_BODY_NAME,
|
| 555 |
+
arm_joint_names=ARM_JOINT_NAMES,
|
| 556 |
+
num_envs=1,
|
| 557 |
+
device=dev,
|
| 558 |
+
command_type="pose",
|
| 559 |
+
lambda_val=0.05,
|
| 560 |
+
max_joint_delta=0.18,
|
| 561 |
+
)
|
| 562 |
+
ik_ctrl.reset()
|
| 563 |
+
|
| 564 |
+
frames: list[np.ndarray] = []
|
| 565 |
+
home = np.array([RETRACT_POS_X, RETRACT_POS_Y, CARRY_Z], dtype=np.float64)
|
| 566 |
+
topdown_quat = np.asarray(DEFAULT_PLACE_QUAT_W, dtype=np.float64)
|
| 567 |
+
for _ in range(2):
|
| 568 |
+
step_pose(env, robot, ik_ctrl, arm_ids, gripper_ids, default_jpos, home, topdown_quat, GRIPPER_OPEN_POS, frames, camera, 80)
|
| 569 |
+
|
| 570 |
+
obj = env.unwrapped.scene.rigid_objects[f"object_{args_cli.object}"]
|
| 571 |
+
obj_initial = obj.data.root_pos_w[0].detach().cpu().numpy().astype(np.float64)
|
| 572 |
+
|
| 573 |
+
rgb, depth, K, pos_w, quat_wxyz_ros = camera_arrays(camera)
|
| 574 |
+
debug_dir = Path(args_cli.save_debug_npz).with_suffix("")
|
| 575 |
+
if args_cli.mask_provider == "band":
|
| 576 |
+
mask = rgbd_band_object_mask(camera, args_cli.object)
|
| 577 |
+
elif args_cli.mask_provider == "sam3":
|
| 578 |
+
mask = sam3_object_mask(camera, rgb, args_cli.object, debug_dir)
|
| 579 |
+
else:
|
| 580 |
+
mask = oracle_object_mask(env, camera, args_cli.object)
|
| 581 |
+
Path(args_cli.save_debug_npz).parent.mkdir(parents=True, exist_ok=True)
|
| 582 |
+
np.savez_compressed(
|
| 583 |
+
args_cli.save_debug_npz,
|
| 584 |
+
rgb=rgb,
|
| 585 |
+
depth=depth,
|
| 586 |
+
mask=mask,
|
| 587 |
+
K=K,
|
| 588 |
+
camera_pos_w=pos_w,
|
| 589 |
+
camera_quat_wxyz_ros=quat_wxyz_ros,
|
| 590 |
+
object_initial=obj_initial,
|
| 591 |
+
)
|
| 592 |
+
if args_cli.grasp_provider == "anygrasp":
|
| 593 |
+
grasp = infer_anygrasp_from_camera(camera, mask)
|
| 594 |
+
elif args_cli.grasp_provider == "pca":
|
| 595 |
+
grasp = infer_pca_aabb_from_camera(camera, mask, object_index=args_cli.object)
|
| 596 |
+
else:
|
| 597 |
+
grasp = infer_grasp_from_camera(camera, mask)
|
| 598 |
+
print(
|
| 599 |
+
f"[GRASP] provider={args_cli.grasp_provider} obj={args_cli.object} "
|
| 600 |
+
f"score={grasp.score:.4f} width={grasp.width:.4f} "
|
| 601 |
+
f"t_w=({grasp.translation_w[0]:.3f},{grasp.translation_w[1]:.3f},{grasp.translation_w[2]:.3f})"
|
| 602 |
+
)
|
| 603 |
+
|
| 604 |
+
pick_xy = grasp.translation_w[:2].copy()
|
| 605 |
+
if not args_cli.no_object_offset:
|
| 606 |
+
pick_xy += np.asarray(OBJ_GRASP_CENTER_OFFSETS.get(args_cli.object, (0.0, 0.0, 0.0))[:2], dtype=np.float64)
|
| 607 |
+
grasp_z = max(float(grasp.translation_w[2] + args_cli.tcp_z_offset), TABLE_TOP_Z + 0.055)
|
| 608 |
+
close_offset = (
|
| 609 |
+
GRASPNET_CLOSE_Z_DEFAULTS.get(
|
| 610 |
+
args_cli.object,
|
| 611 |
+
OBJ_CLOSE_Z_OFFSETS.get(args_cli.object, OBJ_GRASP_Z_OFFSETS.get(args_cli.object, args_cli.tcp_z_offset)),
|
| 612 |
+
)
|
| 613 |
+
if args_cli.close_z_offset is None
|
| 614 |
+
else args_cli.close_z_offset
|
| 615 |
+
)
|
| 616 |
+
close_z = max(float(obj_initial[2] + close_offset), TABLE_TOP_Z + 0.030)
|
| 617 |
+
if args_cli.force_default_quat:
|
| 618 |
+
grasp_quat = topdown_quat
|
| 619 |
+
elif args_cli.use_task_quat:
|
| 620 |
+
grasp_quat = compute_grasp_quat(obj.data.root_quat_w[0], dev).detach().cpu().numpy().astype(np.float64)
|
| 621 |
+
else:
|
| 622 |
+
grasp_quat = grasp.quat_wxyz_w
|
| 623 |
+
pre = np.array([pick_xy[0], pick_xy[1], TABLE_TOP_Z + args_cli.pregrasp_z], dtype=np.float64)
|
| 624 |
+
reach = np.array([pick_xy[0], pick_xy[1], grasp_z], dtype=np.float64)
|
| 625 |
+
close = np.array([pick_xy[0], pick_xy[1], close_z], dtype=np.float64)
|
| 626 |
+
lift = np.array([pick_xy[0], pick_xy[1], TABLE_TOP_Z + args_cli.lift_z], dtype=np.float64)
|
| 627 |
+
place = np.array(
|
| 628 |
+
[BASKET_CENTER_X + args_cli.place_x_offset, BASKET_CENTER_Y + args_cli.place_y_offset, TABLE_TOP_Z + args_cli.place_z],
|
| 629 |
+
dtype=np.float64,
|
| 630 |
+
)
|
| 631 |
+
release = np.array(
|
| 632 |
+
[BASKET_CENTER_X + args_cli.place_x_offset, BASKET_CENTER_Y + args_cli.place_y_offset, TABLE_TOP_Z + args_cli.release_z],
|
| 633 |
+
dtype=np.float64,
|
| 634 |
+
)
|
| 635 |
+
open_release = release.copy()
|
| 636 |
+
if args_cli.open_release_z is not None:
|
| 637 |
+
open_release[2] = TABLE_TOP_Z + float(args_cli.open_release_z)
|
| 638 |
+
basket_target_xy = np.array([BASKET_CENTER_X, BASKET_CENTER_Y], dtype=np.float64)
|
| 639 |
+
transport_steps = args_cli.transport_steps if args_cli.transport_steps is not None else args_cli.move_steps
|
| 640 |
+
place_steps = args_cli.place_steps if args_cli.place_steps is not None else args_cli.move_steps
|
| 641 |
+
print(
|
| 642 |
+
f"[PLAN] pick=({pick_xy[0]:.3f},{pick_xy[1]:.3f}) "
|
| 643 |
+
f"reach_z={reach[2]:.3f} close_z={close[2]:.3f} lift_z={lift[2]:.3f} "
|
| 644 |
+
f"place=({place[0]:.3f},{place[1]:.3f},{place[2]:.3f}) "
|
| 645 |
+
f"release=({release[0]:.3f},{release[1]:.3f},{release[2]:.3f}) "
|
| 646 |
+
f"open_release=({open_release[0]:.3f},{open_release[1]:.3f},{open_release[2]:.3f}) "
|
| 647 |
+
f"transport_steps={transport_steps} place_steps={place_steps} "
|
| 648 |
+
f"quat=({grasp_quat[0]:.3f},{grasp_quat[1]:.3f},{grasp_quat[2]:.3f},{grasp_quat[3]:.3f})"
|
| 649 |
+
)
|
| 650 |
+
|
| 651 |
+
servo_center_xy = pick_xy.astype(np.float64)
|
| 652 |
+
close_servo_xy = servo_center_xy.copy()
|
| 653 |
+
if args_cli.preclose_insert_steps > 0:
|
| 654 |
+
close_servo_xy = close_servo_xy + np.array(
|
| 655 |
+
[args_cli.preclose_insert_dx, args_cli.preclose_insert_dy],
|
| 656 |
+
dtype=np.float64,
|
| 657 |
+
)
|
| 658 |
+
print(
|
| 659 |
+
f"[PRECLOSE_INSERT] steps={args_cli.preclose_insert_steps} "
|
| 660 |
+
f"finger_target=({close_servo_xy[0]:.3f},{close_servo_xy[1]:.3f}) "
|
| 661 |
+
f"offset=({args_cli.preclose_insert_dx:+.3f},{args_cli.preclose_insert_dy:+.3f})"
|
| 662 |
+
)
|
| 663 |
+
step_pose(env, robot, ik_ctrl, arm_ids, gripper_ids, default_jpos, pre, grasp_quat, GRIPPER_OPEN_POS, frames, camera, args_cli.move_steps)
|
| 664 |
+
reach_stats = step_pose(
|
| 665 |
+
env, robot, ik_ctrl, arm_ids, gripper_ids, default_jpos, reach, grasp_quat, GRIPPER_OPEN_POS,
|
| 666 |
+
frames, camera, args_cli.move_steps, obj_idx=args_cli.object, obj=obj,
|
| 667 |
+
finger_body_indices=finger_body_indices, servo_center_xy=servo_center_xy,
|
| 668 |
+
)
|
| 669 |
+
insert_stats = None
|
| 670 |
+
if args_cli.preclose_insert_steps > 0:
|
| 671 |
+
insert_stats = step_pose(
|
| 672 |
+
env, robot, ik_ctrl, arm_ids, gripper_ids, default_jpos, close, grasp_quat, GRIPPER_OPEN_POS,
|
| 673 |
+
frames, camera, args_cli.preclose_insert_steps, obj_idx=args_cli.object, obj=obj,
|
| 674 |
+
finger_body_indices=finger_body_indices, finger_target_xy=close_servo_xy,
|
| 675 |
+
finger_target_z=close[2], finger_servo_gain=1.0,
|
| 676 |
+
finger_servo_max_xy=0.16, finger_servo_max_z=0.04,
|
| 677 |
+
)
|
| 678 |
+
close_stats = step_pose(
|
| 679 |
+
env, robot, ik_ctrl, arm_ids, gripper_ids, default_jpos, close, grasp_quat, GRIPPER_CLOSE_POS,
|
| 680 |
+
frames, camera, args_cli.close_steps, obj_idx=args_cli.object, obj=obj,
|
| 681 |
+
finger_body_indices=finger_body_indices, servo_center_xy=close_servo_xy,
|
| 682 |
+
)
|
| 683 |
+
z_gain_close = object_z_gain(env, args_cli.object, float(obj_initial[2]))
|
| 684 |
+
lift_stats = step_pose(
|
| 685 |
+
env, robot, ik_ctrl, arm_ids, gripper_ids, default_jpos, lift, grasp_quat, GRIPPER_CLOSE_POS,
|
| 686 |
+
frames, camera, args_cli.move_steps, obj_idx=args_cli.object, obj=obj,
|
| 687 |
+
finger_body_indices=finger_body_indices, servo_center_xy=close_servo_xy,
|
| 688 |
+
)
|
| 689 |
+
z_gain_lift = object_z_gain(env, args_cli.object, float(obj_initial[2]))
|
| 690 |
+
place_quat = grasp_quat if args_cli.object in (1, 2) else topdown_quat
|
| 691 |
+
place_servo_xy = basket_target_xy if args_cli.basket_center_release else None
|
| 692 |
+
release_stable = True
|
| 693 |
+
if args_cli.staged_transport and transport_steps >= 3:
|
| 694 |
+
servo_steps = int(round(transport_steps * max(0.0, min(1.0, args_cli.transport_servo_fraction))))
|
| 695 |
+
servo_steps = min(max(servo_steps, 1 if place_servo_xy is not None else 0), max(transport_steps - 2, 0))
|
| 696 |
+
carry_steps = max(transport_steps - servo_steps, 2)
|
| 697 |
+
first_steps = max(carry_steps // 2, 1)
|
| 698 |
+
second_steps = max(carry_steps - first_steps, 1)
|
| 699 |
+
mid = np.array(
|
| 700 |
+
[
|
| 701 |
+
(lift[0] + release[0]) * 0.5,
|
| 702 |
+
(lift[1] + release[1]) * 0.5,
|
| 703 |
+
max(lift[2], release[2]),
|
| 704 |
+
],
|
| 705 |
+
dtype=np.float64,
|
| 706 |
+
)
|
| 707 |
+
print(
|
| 708 |
+
f"[TRANSPORT] staged first={first_steps} second={second_steps} servo={servo_steps} "
|
| 709 |
+
f"mid=({mid[0]:.3f},{mid[1]:.3f},{mid[2]:.3f})"
|
| 710 |
+
)
|
| 711 |
+
step_pose(
|
| 712 |
+
env, robot, ik_ctrl, arm_ids, gripper_ids, default_jpos, mid, place_quat, GRIPPER_CLOSE_POS,
|
| 713 |
+
frames, camera, first_steps, obj_idx=args_cli.object, obj=obj,
|
| 714 |
+
finger_body_indices=finger_body_indices, servo_center_xy=servo_center_xy,
|
| 715 |
+
servo_current_object_xy=args_cli.dynamic_finger_servo,
|
| 716 |
+
)
|
| 717 |
+
step_pose(
|
| 718 |
+
env, robot, ik_ctrl, arm_ids, gripper_ids, default_jpos, release, place_quat, GRIPPER_CLOSE_POS,
|
| 719 |
+
frames, camera, second_steps, obj_idx=args_cli.object, obj=obj,
|
| 720 |
+
finger_body_indices=finger_body_indices, servo_center_xy=servo_center_xy,
|
| 721 |
+
servo_current_object_xy=args_cli.dynamic_finger_servo,
|
| 722 |
+
)
|
| 723 |
+
if servo_steps > 0:
|
| 724 |
+
step_pose(
|
| 725 |
+
env, robot, ik_ctrl, arm_ids, gripper_ids, default_jpos, release, place_quat, GRIPPER_CLOSE_POS,
|
| 726 |
+
frames, camera, servo_steps, obj_idx=args_cli.object, obj=obj,
|
| 727 |
+
finger_body_indices=finger_body_indices, servo_center_xy=servo_center_xy,
|
| 728 |
+
servo_current_object_xy=args_cli.dynamic_finger_servo,
|
| 729 |
+
object_target_xy=place_servo_xy,
|
| 730 |
+
object_servo_gain=args_cli.basket_servo_gain, object_servo_max_xy=args_cli.basket_servo_max_xy,
|
| 731 |
+
)
|
| 732 |
+
else:
|
| 733 |
+
step_pose(
|
| 734 |
+
env, robot, ik_ctrl, arm_ids, gripper_ids, default_jpos, release, place_quat, GRIPPER_CLOSE_POS,
|
| 735 |
+
frames, camera, transport_steps, obj_idx=args_cli.object, obj=obj,
|
| 736 |
+
finger_body_indices=finger_body_indices, servo_center_xy=servo_center_xy,
|
| 737 |
+
servo_current_object_xy=args_cli.dynamic_finger_servo,
|
| 738 |
+
object_target_xy=place_servo_xy,
|
| 739 |
+
object_servo_gain=args_cli.basket_servo_gain, object_servo_max_xy=args_cli.basket_servo_max_xy,
|
| 740 |
+
)
|
| 741 |
+
transport_pos = obj.data.root_pos_w[0].detach().cpu().numpy().astype(np.float64)
|
| 742 |
+
transport_xy_err = float(np.linalg.norm(transport_pos[:2] - basket_target_xy))
|
| 743 |
+
print(
|
| 744 |
+
f"[TRANSPORT_END] obj=({transport_pos[0]:.3f},{transport_pos[1]:.3f},{transport_pos[2]:.3f}) "
|
| 745 |
+
f"xy_err={transport_xy_err:.3f} lifted_z_gain={transport_pos[2] - obj_initial[2]:.3f}"
|
| 746 |
+
)
|
| 747 |
+
hold_stats = None
|
| 748 |
+
if place_servo_xy is not None:
|
| 749 |
+
hold_stats = step_until_object_center_stable(
|
| 750 |
+
env,
|
| 751 |
+
robot,
|
| 752 |
+
ik_ctrl,
|
| 753 |
+
arm_ids,
|
| 754 |
+
gripper_ids,
|
| 755 |
+
default_jpos,
|
| 756 |
+
release,
|
| 757 |
+
place_quat,
|
| 758 |
+
GRIPPER_CLOSE_POS,
|
| 759 |
+
frames,
|
| 760 |
+
camera,
|
| 761 |
+
obj=obj,
|
| 762 |
+
target_xy=place_servo_xy,
|
| 763 |
+
xy_tol=args_cli.basket_xy_tol,
|
| 764 |
+
stable_steps=args_cli.basket_stable_steps,
|
| 765 |
+
max_steps=args_cli.basket_hold_steps,
|
| 766 |
+
object_servo_gain=args_cli.basket_servo_gain,
|
| 767 |
+
object_servo_max_xy=args_cli.basket_servo_max_xy,
|
| 768 |
+
obj_idx=args_cli.object,
|
| 769 |
+
finger_body_indices=finger_body_indices,
|
| 770 |
+
servo_center_xy=servo_center_xy,
|
| 771 |
+
servo_current_object_xy=args_cli.dynamic_finger_servo,
|
| 772 |
+
)
|
| 773 |
+
print(f"[BASKET_HOLD] {hold_stats}")
|
| 774 |
+
if int(hold_stats["stable"]) < args_cli.basket_stable_steps:
|
| 775 |
+
print("[BASKET_HOLD] not stable; keeping gripper closed and running recovery servo before release")
|
| 776 |
+
hold_stats = step_until_object_center_stable(
|
| 777 |
+
env,
|
| 778 |
+
robot,
|
| 779 |
+
ik_ctrl,
|
| 780 |
+
arm_ids,
|
| 781 |
+
gripper_ids,
|
| 782 |
+
default_jpos,
|
| 783 |
+
place,
|
| 784 |
+
place_quat,
|
| 785 |
+
GRIPPER_CLOSE_POS,
|
| 786 |
+
frames,
|
| 787 |
+
camera,
|
| 788 |
+
obj=obj,
|
| 789 |
+
target_xy=place_servo_xy,
|
| 790 |
+
xy_tol=args_cli.basket_xy_tol,
|
| 791 |
+
stable_steps=args_cli.basket_stable_steps,
|
| 792 |
+
max_steps=args_cli.basket_recovery_steps,
|
| 793 |
+
object_servo_gain=args_cli.basket_servo_gain,
|
| 794 |
+
object_servo_max_xy=args_cli.basket_servo_max_xy,
|
| 795 |
+
obj_idx=args_cli.object,
|
| 796 |
+
finger_body_indices=finger_body_indices,
|
| 797 |
+
servo_center_xy=servo_center_xy,
|
| 798 |
+
servo_current_object_xy=args_cli.dynamic_finger_servo,
|
| 799 |
+
)
|
| 800 |
+
print(f"[BASKET_RECOVERY] {hold_stats}")
|
| 801 |
+
if int(hold_stats["stable"]) < args_cli.basket_stable_steps:
|
| 802 |
+
print("[BASKET_HOLD] still not stable; skipping open release to avoid early drop")
|
| 803 |
+
place_steps = 0
|
| 804 |
+
release_stable = False
|
| 805 |
+
open_target = open_release if args_cli.open_release_z is not None else release
|
| 806 |
+
if args_cli.open_release_z is not None:
|
| 807 |
+
step_pose(env, robot, ik_ctrl, arm_ids, gripper_ids, default_jpos, open_target, place_quat, GRIPPER_CLOSE_POS, frames, camera, 120)
|
| 808 |
+
step_pose(env, robot, ik_ctrl, arm_ids, gripper_ids, default_jpos, open_target, place_quat, GRIPPER_CLOSE_POS, frames, camera, 60)
|
| 809 |
+
if place_steps > 0:
|
| 810 |
+
step_pose(env, robot, ik_ctrl, arm_ids, gripper_ids, default_jpos, open_target, place_quat, GRIPPER_OPEN_POS, frames, camera, place_steps)
|
| 811 |
+
slipped_to_table = float(obj.data.root_pos_w[0, 2].item()) <= TABLE_TOP_Z + 0.08
|
| 812 |
+
need_push = not check_objects_in_basket(env, [args_cli.object]) and (
|
| 813 |
+
args_cli.post_push or (args_cli.auto_table_push_on_slip and (slipped_to_table or not release_stable))
|
| 814 |
+
)
|
| 815 |
+
if need_push:
|
| 816 |
+
run_closed_drag_recovery(env, robot, ik_ctrl, arm_ids, gripper_ids, default_jpos, frames, camera, obj, place_quat, finger_body_indices)
|
| 817 |
+
if not check_objects_in_basket(env, [args_cli.object]):
|
| 818 |
+
run_table_push_recovery(env, robot, ik_ctrl, arm_ids, gripper_ids, default_jpos, frames, camera, obj, topdown_quat, finger_body_indices)
|
| 819 |
+
step_pose(env, robot, ik_ctrl, arm_ids, gripper_ids, default_jpos, home, topdown_quat, GRIPPER_OPEN_POS, frames, camera, args_cli.settle_steps)
|
| 820 |
+
|
| 821 |
+
final_pos = obj.data.root_pos_w[0].detach().cpu().numpy().astype(np.float64)
|
| 822 |
+
inside = check_objects_in_basket(env, [args_cli.object])
|
| 823 |
+
print(
|
| 824 |
+
f"[RESULT] obj={args_cli.object} inside={inside} "
|
| 825 |
+
f"z_gain_close={z_gain_close:.3f} z_gain_lift={z_gain_lift:.3f} "
|
| 826 |
+
f"final=({final_pos[0]:.3f},{final_pos[1]:.3f},{final_pos[2]:.3f})"
|
| 827 |
+
)
|
| 828 |
+
print(f"[TRACE] reach={reach_stats} insert={insert_stats} close={close_stats} lift={lift_stats}")
|
| 829 |
+
for line in basket_status_lines(env, [args_cli.object]):
|
| 830 |
+
print(f"[BASKET] {line}")
|
| 831 |
+
|
| 832 |
+
video_path = Path(args_cli.video_path)
|
| 833 |
+
video_path.parent.mkdir(parents=True, exist_ok=True)
|
| 834 |
+
if frames:
|
| 835 |
+
imageio.mimwrite(str(video_path), frames, fps=50, quality=7)
|
| 836 |
+
print(f"[VIDEO] {video_path.resolve()}")
|
| 837 |
+
env.close()
|
| 838 |
+
|
| 839 |
+
|
| 840 |
+
if __name__ == "__main__":
|
| 841 |
+
try:
|
| 842 |
+
main()
|
| 843 |
+
finally:
|
| 844 |
+
simulation_app.close()
|
scripts/graspnet_task_e/sam3_segment_image.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run local SAM3 on a saved RGB image and write a binary mask.
|
| 2 |
+
|
| 3 |
+
This script is intentionally small and dependency-isolated: Task-E/Isaac can
|
| 4 |
+
call it from the SAM3 virtualenv without installing SAM3 into the Isaac env.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import argparse
|
| 10 |
+
import json
|
| 11 |
+
import sys
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
from PIL import Image
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
PROMPT_INPAINT = Path("/home/ubuntu/Documents/01Proj/sam3d_gs/submodule/Prompt-Inpaint")
|
| 19 |
+
if not PROMPT_INPAINT.exists():
|
| 20 |
+
raise SystemExit(f"Prompt-Inpaint not found: {PROMPT_INPAINT}")
|
| 21 |
+
sys.path.insert(0, str(PROMPT_INPAINT))
|
| 22 |
+
|
| 23 |
+
from src.sam3_predictor import SAM3Predictor # noqa: E402
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _bbox_area(mask: np.ndarray) -> int:
|
| 27 |
+
ys, xs = np.nonzero(mask)
|
| 28 |
+
if len(xs) == 0:
|
| 29 |
+
return 0
|
| 30 |
+
return int((xs.max() - xs.min() + 1) * (ys.max() - ys.min() + 1))
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def main() -> None:
|
| 34 |
+
parser = argparse.ArgumentParser(description="Segment one image with local SAM3.")
|
| 35 |
+
parser.add_argument("--image", required=True, help="Input RGB image path.")
|
| 36 |
+
parser.add_argument("--out_mask", required=True, help="Output .npy binary mask path.")
|
| 37 |
+
parser.add_argument("--out_meta", default=None, help="Optional JSON metadata output.")
|
| 38 |
+
parser.add_argument("--out_candidates", default=None, help="Optional .npz with all candidate masks.")
|
| 39 |
+
parser.add_argument("--prompt", action="append", required=True, help="Text prompt. Can repeat.")
|
| 40 |
+
parser.add_argument("--threshold", type=float, default=0.35)
|
| 41 |
+
parser.add_argument("--mask_threshold", type=float, default=0.5)
|
| 42 |
+
parser.add_argument(
|
| 43 |
+
"--model",
|
| 44 |
+
default="/home/ubuntu/Documents/01Proj/sam3d_gs/submodule/Prompt-Inpaint/checkpoints/sam3.pt",
|
| 45 |
+
)
|
| 46 |
+
args = parser.parse_args()
|
| 47 |
+
|
| 48 |
+
image = np.asarray(Image.open(args.image).convert("RGB"))
|
| 49 |
+
predictor = SAM3Predictor(
|
| 50 |
+
model_id=args.model,
|
| 51 |
+
device="cuda",
|
| 52 |
+
threshold=args.threshold,
|
| 53 |
+
mask_threshold=args.mask_threshold,
|
| 54 |
+
)
|
| 55 |
+
predictor.set_image(image)
|
| 56 |
+
|
| 57 |
+
detections = []
|
| 58 |
+
for prompt in args.prompt:
|
| 59 |
+
detections.extend(predictor.detect(prompt))
|
| 60 |
+
|
| 61 |
+
candidates = []
|
| 62 |
+
image_area = image.shape[0] * image.shape[1]
|
| 63 |
+
for det in detections:
|
| 64 |
+
if det.mask is None:
|
| 65 |
+
continue
|
| 66 |
+
mask = det.mask.astype(bool)
|
| 67 |
+
area = int(mask.sum())
|
| 68 |
+
if area < 40 or area > int(image_area * 0.35):
|
| 69 |
+
continue
|
| 70 |
+
candidates.append(
|
| 71 |
+
{
|
| 72 |
+
"prompt": det.label,
|
| 73 |
+
"score": float(det.score),
|
| 74 |
+
"bbox": [int(v) for v in det.bbox],
|
| 75 |
+
"area": area,
|
| 76 |
+
"bbox_area": _bbox_area(mask),
|
| 77 |
+
"mask": mask,
|
| 78 |
+
}
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
if not candidates:
|
| 82 |
+
raise SystemExit("SAM3 produced no usable mask")
|
| 83 |
+
|
| 84 |
+
# Prefer confident, compact object masks. This avoids selecting the table or
|
| 85 |
+
# a merged scene-sized region when prompts are broad.
|
| 86 |
+
best = max(candidates, key=lambda c: (c["score"], -c["bbox_area"]))
|
| 87 |
+
out_mask = Path(args.out_mask)
|
| 88 |
+
out_mask.parent.mkdir(parents=True, exist_ok=True)
|
| 89 |
+
np.save(out_mask, best["mask"].astype(np.bool_))
|
| 90 |
+
|
| 91 |
+
if args.out_meta:
|
| 92 |
+
meta = {k: v for k, v in best.items() if k != "mask"}
|
| 93 |
+
meta["num_candidates"] = len(candidates)
|
| 94 |
+
Path(args.out_meta).parent.mkdir(parents=True, exist_ok=True)
|
| 95 |
+
Path(args.out_meta).write_text(json.dumps(meta, indent=2), encoding="utf-8")
|
| 96 |
+
|
| 97 |
+
if args.out_candidates:
|
| 98 |
+
cand_path = Path(args.out_candidates)
|
| 99 |
+
cand_path.parent.mkdir(parents=True, exist_ok=True)
|
| 100 |
+
masks = np.stack([c["mask"].astype(np.bool_) for c in candidates], axis=0)
|
| 101 |
+
metas = [
|
| 102 |
+
{k: v for k, v in c.items() if k != "mask"}
|
| 103 |
+
for c in candidates
|
| 104 |
+
]
|
| 105 |
+
np.savez_compressed(cand_path, masks=masks, metas=json.dumps(metas))
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
if __name__ == "__main__":
|
| 109 |
+
main()
|
scripts/graspnet_task_e/tuntun_adapter.py
ADDED
|
@@ -0,0 +1,388 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small Task-E bridge around the TunTunClaw GraspNet API.
|
| 2 |
+
|
| 3 |
+
The GraspNet model predicts grasps in the camera/ROS frame. Task E executes a
|
| 4 |
+
top-down Piper grasp in world frame, so this adapter intentionally uses
|
| 5 |
+
GraspNet for the contact centre and jaw yaw, then forces a stable top-down
|
| 6 |
+
orientation for the Piper gripper.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
from dataclasses import dataclass
|
| 12 |
+
from functools import lru_cache
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
import os
|
| 15 |
+
import sys
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
import torch
|
| 19 |
+
from scipy.spatial.transform import Rotation
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
REPO_ROOT = Path(__file__).resolve().parents[2]
|
| 23 |
+
TUNTUN_ROOT = REPO_ROOT / "third_party" / "tuntunclaw"
|
| 24 |
+
GRASPNET_ROOT = TUNTUN_ROOT / "graspnet-baseline"
|
| 25 |
+
CHECKPOINT_PATH = TUNTUN_ROOT / "temp" / "logs" / "log_rs" / "checkpoint-rs.tar"
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _ensure_tuntun_paths() -> None:
|
| 29 |
+
paths = [
|
| 30 |
+
GRASPNET_ROOT / "models",
|
| 31 |
+
GRASPNET_ROOT / "dataset",
|
| 32 |
+
GRASPNET_ROOT / "utils",
|
| 33 |
+
GRASPNET_ROOT / "graspnetAPI",
|
| 34 |
+
TUNTUN_ROOT / "manipulator_grasp",
|
| 35 |
+
]
|
| 36 |
+
for path in paths:
|
| 37 |
+
p = str(path)
|
| 38 |
+
if p not in sys.path:
|
| 39 |
+
sys.path.insert(0, p)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@dataclass(frozen=True)
|
| 43 |
+
class TaskEGrasp:
|
| 44 |
+
translation_w: np.ndarray
|
| 45 |
+
quat_wxyz_w: np.ndarray
|
| 46 |
+
score: float
|
| 47 |
+
width: float
|
| 48 |
+
raw_translation_cam: np.ndarray
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def camera_arrays(camera) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
|
| 52 |
+
"""Return RGB, depth, K, camera position and ROS-frame quaternion."""
|
| 53 |
+
rgb = camera.data.output["rgb"][0].detach().cpu().numpy()[..., :3]
|
| 54 |
+
depth = camera.data.output["depth"][0].detach().cpu().numpy()
|
| 55 |
+
if depth.ndim == 3:
|
| 56 |
+
depth = depth[..., 0]
|
| 57 |
+
K = camera.data.intrinsic_matrices[0].detach().cpu().numpy()
|
| 58 |
+
pos_w = camera.data.pos_w[0].detach().cpu().numpy()
|
| 59 |
+
quat_wxyz_ros = camera.data.quat_w_ros[0].detach().cpu().numpy()
|
| 60 |
+
return rgb, depth.astype(np.float32), K.astype(np.float32), pos_w.astype(np.float64), quat_wxyz_ros.astype(np.float64)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def project_world_points_to_image(points_w: np.ndarray, K: np.ndarray, pos_w: np.ndarray, quat_wxyz_ros: np.ndarray) -> np.ndarray:
|
| 64 |
+
"""Project world points into a ROS camera image."""
|
| 65 |
+
rot_w_cam = Rotation.from_quat(
|
| 66 |
+
[quat_wxyz_ros[1], quat_wxyz_ros[2], quat_wxyz_ros[3], quat_wxyz_ros[0]]
|
| 67 |
+
).as_matrix()
|
| 68 |
+
pts_cam = (rot_w_cam.T @ (points_w - pos_w).T).T
|
| 69 |
+
z = np.clip(pts_cam[:, 2], 1e-6, None)
|
| 70 |
+
u = K[0, 0] * pts_cam[:, 0] / z + K[0, 2]
|
| 71 |
+
v = K[1, 1] * pts_cam[:, 1] / z + K[1, 2]
|
| 72 |
+
return np.stack([u, v, pts_cam[:, 2]], axis=1)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def oracle_object_mask(env, camera, obj_idx: int, pad_px: int = 24) -> np.ndarray:
|
| 76 |
+
"""Create a temporary ROI mask by projecting the known simulated object bbox.
|
| 77 |
+
|
| 78 |
+
This is for fast grasp primitive debugging. Once the primitive is stable,
|
| 79 |
+
replace this mask provider with RGB-D segmentation/VLM masks for submission.
|
| 80 |
+
"""
|
| 81 |
+
from atec_rl_lab.tasks.task_e.env_cfg import OBJ_HALF_EXTENTS, TABLE_TOP_Z
|
| 82 |
+
|
| 83 |
+
rgb, depth, K, pos_w, quat_wxyz_ros = camera_arrays(camera)
|
| 84 |
+
h, w = depth.shape[:2]
|
| 85 |
+
obj = env.unwrapped.scene.rigid_objects[f"object_{obj_idx}"]
|
| 86 |
+
center = obj.data.root_pos_w[0].detach().cpu().numpy().astype(np.float64)
|
| 87 |
+
hx, hy = OBJ_HALF_EXTENTS[f"object_{obj_idx}"]
|
| 88 |
+
z_lo = TABLE_TOP_Z + 0.005
|
| 89 |
+
z_hi = max(center[2] + 0.16, TABLE_TOP_Z + 0.08)
|
| 90 |
+
corners = np.array(
|
| 91 |
+
[
|
| 92 |
+
[center[0] + sx * hx, center[1] + sy * hy, z]
|
| 93 |
+
for sx in (-1.0, 1.0)
|
| 94 |
+
for sy in (-1.0, 1.0)
|
| 95 |
+
for z in (z_lo, z_hi)
|
| 96 |
+
],
|
| 97 |
+
dtype=np.float64,
|
| 98 |
+
)
|
| 99 |
+
uvz = project_world_points_to_image(corners, K, pos_w, quat_wxyz_ros)
|
| 100 |
+
valid = uvz[:, 2] > 0.02
|
| 101 |
+
mask = np.zeros((h, w), dtype=np.uint8)
|
| 102 |
+
if not np.any(valid):
|
| 103 |
+
return mask
|
| 104 |
+
u = uvz[valid, 0]
|
| 105 |
+
v = uvz[valid, 1]
|
| 106 |
+
x1 = int(np.clip(np.floor(u.min()) - pad_px, 0, w - 1))
|
| 107 |
+
y1 = int(np.clip(np.floor(v.min()) - pad_px, 0, h - 1))
|
| 108 |
+
x2 = int(np.clip(np.ceil(u.max()) + pad_px, 0, w - 1))
|
| 109 |
+
y2 = int(np.clip(np.ceil(v.max()) + pad_px, 0, h - 1))
|
| 110 |
+
if x2 > x1 and y2 > y1:
|
| 111 |
+
mask[y1 : y2 + 1, x1 : x2 + 1] = 255
|
| 112 |
+
# Remove obvious background/table pixels while keeping the object surface.
|
| 113 |
+
obj_depth = depth[mask > 0]
|
| 114 |
+
obj_depth = obj_depth[np.isfinite(obj_depth) & (obj_depth > 0.0)]
|
| 115 |
+
if obj_depth.size:
|
| 116 |
+
d_min = float(np.percentile(obj_depth, 3))
|
| 117 |
+
d_max = float(np.percentile(obj_depth, 70))
|
| 118 |
+
mask[(depth < d_min - 0.03) | (depth > d_max + 0.06)] = 0
|
| 119 |
+
# Debug oracle refinement: keep only RGB-D points whose reconstructed
|
| 120 |
+
# world coordinates lie inside the selected object's AABB. The first
|
| 121 |
+
# rectangular ROI can include neighboring objects for banana/long
|
| 122 |
+
# shapes, which shifts GraspNet's execution centre by tens of cm.
|
| 123 |
+
ys, xs = np.where((mask > 0) & np.isfinite(depth) & (depth > 0.0))
|
| 124 |
+
if len(xs) > 0:
|
| 125 |
+
z = depth[ys, xs].astype(np.float64)
|
| 126 |
+
x_cam = (xs.astype(np.float64) - float(K[0, 2])) / float(K[0, 0]) * z
|
| 127 |
+
y_cam = (ys.astype(np.float64) - float(K[1, 2])) / float(K[1, 1]) * z
|
| 128 |
+
pts_cam = np.stack([x_cam, y_cam, z], axis=1)
|
| 129 |
+
rot_w_cam = Rotation.from_quat(
|
| 130 |
+
[quat_wxyz_ros[1], quat_wxyz_ros[2], quat_wxyz_ros[3], quat_wxyz_ros[0]]
|
| 131 |
+
).as_matrix()
|
| 132 |
+
pts_w = (rot_w_cam @ pts_cam.T).T + pos_w
|
| 133 |
+
keep = (
|
| 134 |
+
(pts_w[:, 0] >= center[0] - hx - 0.025)
|
| 135 |
+
& (pts_w[:, 0] <= center[0] + hx + 0.025)
|
| 136 |
+
& (pts_w[:, 1] >= center[1] - hy - 0.025)
|
| 137 |
+
& (pts_w[:, 1] <= center[1] + hy + 0.025)
|
| 138 |
+
& (pts_w[:, 2] >= TABLE_TOP_Z - 0.010)
|
| 139 |
+
& (pts_w[:, 2] <= center[2] + 0.180)
|
| 140 |
+
)
|
| 141 |
+
refined = np.zeros_like(mask)
|
| 142 |
+
refined[ys[keep], xs[keep]] = 255
|
| 143 |
+
if np.count_nonzero(refined) > 128:
|
| 144 |
+
mask = refined
|
| 145 |
+
return mask
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
_BAND_Z_LIMITS = {
|
| 149 |
+
1: (0.035, 0.130), # sugar box: reject table pixels and high gripper links
|
| 150 |
+
2: (0.020, 0.190), # mustard bottle
|
| 151 |
+
3: (0.012, 0.095), # banana
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def rgbd_band_object_mask(camera, obj_idx: int, margin_y: float = 0.045) -> np.ndarray:
|
| 156 |
+
"""Segment a Task-E object from RGB-D using legal scene priors.
|
| 157 |
+
|
| 158 |
+
The official randomizer keeps each object type in a distinct world-Y band.
|
| 159 |
+
Reconstructing the video camera depth into world coordinates lets us isolate
|
| 160 |
+
the object without reading simulator object state. This is the intended
|
| 161 |
+
replacement for ``oracle_object_mask`` in submission-style tests.
|
| 162 |
+
"""
|
| 163 |
+
from scripts.act.task_e.config import OBJ_SPAWN_X_MIN, OBJ_SPAWN_X_MAX, OBJ_SPAWN_Y_BANDS
|
| 164 |
+
from atec_rl_lab.tasks.task_e.env_cfg import TABLE_TOP_Z
|
| 165 |
+
|
| 166 |
+
rgb, depth, K, pos_w, quat_wxyz_ros = camera_arrays(camera)
|
| 167 |
+
valid = np.isfinite(depth) & (depth > 0.0) & (depth < 6.0)
|
| 168 |
+
ys, xs = np.where(valid)
|
| 169 |
+
mask = np.zeros(depth.shape[:2], dtype=np.uint8)
|
| 170 |
+
if len(xs) == 0:
|
| 171 |
+
return mask
|
| 172 |
+
|
| 173 |
+
z = depth[ys, xs].astype(np.float64)
|
| 174 |
+
x_cam = (xs.astype(np.float64) - float(K[0, 2])) / float(K[0, 0]) * z
|
| 175 |
+
y_cam = (ys.astype(np.float64) - float(K[1, 2])) / float(K[1, 1]) * z
|
| 176 |
+
pts_cam = np.stack([x_cam, y_cam, z], axis=1)
|
| 177 |
+
rot_w_cam = Rotation.from_quat(
|
| 178 |
+
[quat_wxyz_ros[1], quat_wxyz_ros[2], quat_wxyz_ros[3], quat_wxyz_ros[0]]
|
| 179 |
+
).as_matrix()
|
| 180 |
+
pts_w = (rot_w_cam @ pts_cam.T).T + pos_w
|
| 181 |
+
|
| 182 |
+
y0, y1 = OBJ_SPAWN_Y_BANDS[obj_idx]
|
| 183 |
+
z_min_rel, z_max_rel = _BAND_Z_LIMITS.get(obj_idx, (0.006, 0.24))
|
| 184 |
+
rgb_pts = rgb[ys, xs].astype(np.float32)
|
| 185 |
+
maxc = rgb_pts.max(axis=1)
|
| 186 |
+
minc = rgb_pts.min(axis=1)
|
| 187 |
+
sat = maxc - minc
|
| 188 |
+
non_gray = (sat > 18.0) | (maxc > 170.0)
|
| 189 |
+
world_keep = (
|
| 190 |
+
(pts_w[:, 0] >= OBJ_SPAWN_X_MIN - 0.08)
|
| 191 |
+
& (pts_w[:, 0] <= OBJ_SPAWN_X_MAX + 0.08)
|
| 192 |
+
& (pts_w[:, 1] >= y0 - margin_y)
|
| 193 |
+
& (pts_w[:, 1] <= y1 + margin_y)
|
| 194 |
+
& (pts_w[:, 2] >= TABLE_TOP_Z + z_min_rel)
|
| 195 |
+
& (pts_w[:, 2] <= TABLE_TOP_Z + z_max_rel)
|
| 196 |
+
& non_gray
|
| 197 |
+
)
|
| 198 |
+
mask[ys[world_keep], xs[world_keep]] = 255
|
| 199 |
+
|
| 200 |
+
# Fill the component's rectangular holes lightly; GraspNet expects enough
|
| 201 |
+
# depth samples and the box has large white low-saturation areas.
|
| 202 |
+
if np.count_nonzero(mask) > 0:
|
| 203 |
+
yy, xx = np.where(mask > 0)
|
| 204 |
+
x1, x2 = int(xx.min()), int(xx.max())
|
| 205 |
+
y1p, y2p = int(yy.min()), int(yy.max())
|
| 206 |
+
roi = np.zeros_like(mask)
|
| 207 |
+
roi[y1p : y2p + 1, x1 : x2 + 1] = 255
|
| 208 |
+
fill_keep = roi[ys, xs] > 0
|
| 209 |
+
fill_keep &= (
|
| 210 |
+
(pts_w[:, 1] >= y0 - margin_y)
|
| 211 |
+
& (pts_w[:, 1] <= y1 + margin_y)
|
| 212 |
+
& (pts_w[:, 2] >= TABLE_TOP_Z + z_min_rel)
|
| 213 |
+
& (pts_w[:, 2] <= TABLE_TOP_Z + z_max_rel)
|
| 214 |
+
)
|
| 215 |
+
mask[ys[fill_keep], xs[fill_keep]] = 255
|
| 216 |
+
return mask
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
@lru_cache(maxsize=1)
|
| 220 |
+
def _load_graspnet_model():
|
| 221 |
+
_ensure_tuntun_paths()
|
| 222 |
+
if not CHECKPOINT_PATH.exists():
|
| 223 |
+
raise FileNotFoundError(
|
| 224 |
+
f"GraspNet checkpoint missing: {CHECKPOINT_PATH}. "
|
| 225 |
+
"Download official checkpoint-rs.tar there first."
|
| 226 |
+
)
|
| 227 |
+
from graspnet import GraspNet
|
| 228 |
+
|
| 229 |
+
net = GraspNet(
|
| 230 |
+
input_feature_dim=0,
|
| 231 |
+
num_view=300,
|
| 232 |
+
num_angle=12,
|
| 233 |
+
num_depth=4,
|
| 234 |
+
cylinder_radius=0.05,
|
| 235 |
+
hmin=-0.02,
|
| 236 |
+
hmax_list=[0.01, 0.02, 0.03, 0.04],
|
| 237 |
+
is_training=False,
|
| 238 |
+
)
|
| 239 |
+
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
| 240 |
+
net.to(device)
|
| 241 |
+
checkpoint = torch.load(CHECKPOINT_PATH, map_location=device)
|
| 242 |
+
net.load_state_dict(checkpoint["model_state_dict"])
|
| 243 |
+
net.eval()
|
| 244 |
+
return net
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def _run_graspnet(rgb: np.ndarray, depth: np.ndarray, mask: np.ndarray, K: np.ndarray):
|
| 248 |
+
_ensure_tuntun_paths()
|
| 249 |
+
import open3d as o3d
|
| 250 |
+
from collision_detector import ModelFreeCollisionDetector
|
| 251 |
+
from data_utils import CameraInfo, create_point_cloud_from_depth_image
|
| 252 |
+
from graspnet import pred_decode
|
| 253 |
+
from graspnetAPI import GraspGroup
|
| 254 |
+
|
| 255 |
+
color = rgb.astype(np.float32) / 255.0
|
| 256 |
+
height, width = depth.shape[:2]
|
| 257 |
+
camera_info = CameraInfo(width, height, float(K[0, 0]), float(K[1, 1]), float(K[0, 2]), float(K[1, 2]), 1.0)
|
| 258 |
+
cloud = create_point_cloud_from_depth_image(depth, camera_info, organized=True)
|
| 259 |
+
|
| 260 |
+
valid = (mask > 0) & np.isfinite(depth) & (depth > 0.0) & (depth < 6.0)
|
| 261 |
+
cloud_masked = cloud[valid]
|
| 262 |
+
color_masked = color[valid]
|
| 263 |
+
if len(cloud_masked) == 0:
|
| 264 |
+
raise RuntimeError("No valid masked depth points for GraspNet.")
|
| 265 |
+
|
| 266 |
+
num_point = 5000
|
| 267 |
+
if len(cloud_masked) >= num_point:
|
| 268 |
+
idxs = np.random.choice(len(cloud_masked), num_point, replace=False)
|
| 269 |
+
else:
|
| 270 |
+
idxs = np.concatenate(
|
| 271 |
+
[np.arange(len(cloud_masked)), np.random.choice(len(cloud_masked), num_point - len(cloud_masked), replace=True)]
|
| 272 |
+
)
|
| 273 |
+
cloud_sampled = torch.from_numpy(cloud_masked[idxs][None].astype(np.float32)).to(
|
| 274 |
+
torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
| 275 |
+
)
|
| 276 |
+
end_points = {"point_clouds": cloud_sampled, "cloud_colors": color_masked[idxs]}
|
| 277 |
+
|
| 278 |
+
net = _load_graspnet_model()
|
| 279 |
+
with torch.no_grad():
|
| 280 |
+
end_points = net(end_points)
|
| 281 |
+
grasp_preds = pred_decode(end_points)
|
| 282 |
+
|
| 283 |
+
gg = GraspGroup(grasp_preds[0].detach().cpu().numpy()).nms().sort_by_score()
|
| 284 |
+
if len(gg) > 128:
|
| 285 |
+
gg = gg[:128]
|
| 286 |
+
|
| 287 |
+
cloud_o3d = o3d.geometry.PointCloud()
|
| 288 |
+
cloud_o3d.points = o3d.utility.Vector3dVector(cloud_masked.astype(np.float32))
|
| 289 |
+
cloud_o3d.colors = o3d.utility.Vector3dVector(color_masked.astype(np.float32))
|
| 290 |
+
try:
|
| 291 |
+
detector = ModelFreeCollisionDetector(np.asarray(cloud_o3d.points, dtype=np.float32), voxel_size=0.01)
|
| 292 |
+
collision_mask = detector.detect(gg, approach_dist=0.05, collision_thresh=0.01)
|
| 293 |
+
gg = gg[~collision_mask]
|
| 294 |
+
except Exception as exc:
|
| 295 |
+
print(f"[graspnet] collision check skipped: {exc}")
|
| 296 |
+
|
| 297 |
+
gg = gg.sort_by_score()
|
| 298 |
+
grasps = list(gg)
|
| 299 |
+
if not grasps:
|
| 300 |
+
raise RuntimeError("No GraspNet candidates after filtering.")
|
| 301 |
+
center = np.mean(cloud_masked, axis=0)
|
| 302 |
+
# TunTunClaw's empirical selector: prefer grasps near the segmented object centre.
|
| 303 |
+
max_dist = max(np.linalg.norm(g.translation - center) for g in grasps) or 1.0
|
| 304 |
+
best = max(grasps, key=lambda g: float(g.score) * 0.1 + (1.0 - np.linalg.norm(g.translation - center) / max_dist) * 0.9)
|
| 305 |
+
out = GraspGroup()
|
| 306 |
+
out.add(best)
|
| 307 |
+
return out
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def _load_graspnet():
|
| 311 |
+
_ensure_tuntun_paths()
|
| 312 |
+
if not CHECKPOINT_PATH.exists():
|
| 313 |
+
raise FileNotFoundError(
|
| 314 |
+
f"GraspNet checkpoint missing: {CHECKPOINT_PATH}. "
|
| 315 |
+
"Download official checkpoint-rs.tar there first."
|
| 316 |
+
)
|
| 317 |
+
return _run_graspnet
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def infer_grasp_from_camera(camera, mask: np.ndarray) -> TaskEGrasp:
|
| 321 |
+
"""Run TunTunClaw GraspNet and convert the selected grasp to Task-E world pose."""
|
| 322 |
+
rgb, depth, _K, pos_w, quat_wxyz_ros = camera_arrays(camera)
|
| 323 |
+
run_grasp_inference = _load_graspnet()
|
| 324 |
+
gg = run_grasp_inference(rgb, depth, mask, _K)
|
| 325 |
+
if len(gg) == 0:
|
| 326 |
+
raise RuntimeError("GraspNet returned no grasps.")
|
| 327 |
+
grasp = list(gg)[0]
|
| 328 |
+
|
| 329 |
+
rot_w_cam = Rotation.from_quat(
|
| 330 |
+
[quat_wxyz_ros[1], quat_wxyz_ros[2], quat_wxyz_ros[3], quat_wxyz_ros[0]]
|
| 331 |
+
).as_matrix()
|
| 332 |
+
t_cam = np.asarray(grasp.translation, dtype=np.float64)
|
| 333 |
+
t_w = rot_w_cam @ t_cam + pos_w
|
| 334 |
+
valid = (mask > 0) & np.isfinite(depth) & (depth > 0.0) & (depth < 6.0)
|
| 335 |
+
if np.any(valid):
|
| 336 |
+
ys, xs = np.where(valid)
|
| 337 |
+
z = depth[ys, xs].astype(np.float64)
|
| 338 |
+
x = (xs.astype(np.float64) - float(_K[0, 2])) / float(_K[0, 0]) * z
|
| 339 |
+
y = (ys.astype(np.float64) - float(_K[1, 2])) / float(_K[1, 1]) * z
|
| 340 |
+
pts_cam = np.stack([x, y, z], axis=1)
|
| 341 |
+
pts_w = (rot_w_cam @ pts_cam.T).T + pos_w
|
| 342 |
+
# For top-down Piper execution, the upper object-surface cloud is more
|
| 343 |
+
# stable than a single GraspNet seed point on box/bottle edges. Keep
|
| 344 |
+
# GraspNet's yaw/width/score, recenter only the execution target.
|
| 345 |
+
z_gate = float(np.percentile(pts_w[:, 2], 70))
|
| 346 |
+
upper = pts_w[pts_w[:, 2] >= z_gate]
|
| 347 |
+
if len(upper) > 16:
|
| 348 |
+
# The highest-score GraspNet seed often sits on a visible edge for
|
| 349 |
+
# Task-E boxes/bottles. Piper's parallel jaw is more reliable when
|
| 350 |
+
# executed through the segmented object's robust surface centre.
|
| 351 |
+
t_w[:2] = np.median(upper[:, :2], axis=0)
|
| 352 |
+
else:
|
| 353 |
+
t_w[:2] = np.median(pts_w[:, :2], axis=0)
|
| 354 |
+
t_w[2] = float(np.percentile(pts_w[:, 2], 85))
|
| 355 |
+
|
| 356 |
+
# GraspNet's first column is the approach axis. We keep its jaw hint but
|
| 357 |
+
# force the Piper tool z-axis downward because the Task-E IK/top-down setup
|
| 358 |
+
# is much more stable than arbitrary 6-DoF wrist poses.
|
| 359 |
+
R_cam_grasp = np.asarray(grasp.rotation_matrix, dtype=np.float64)
|
| 360 |
+
jaw_hint_w = rot_w_cam @ R_cam_grasp[:, 1]
|
| 361 |
+
jaw_xy = np.array([jaw_hint_w[0], jaw_hint_w[1], 0.0], dtype=np.float64)
|
| 362 |
+
if np.linalg.norm(jaw_xy) < 1e-6:
|
| 363 |
+
jaw_xy = np.array([0.0, 1.0, 0.0], dtype=np.float64)
|
| 364 |
+
jaw_xy = jaw_xy / np.linalg.norm(jaw_xy)
|
| 365 |
+
grip_z = np.array([0.0, 0.0, -1.0], dtype=np.float64)
|
| 366 |
+
align_x = np.cross(jaw_xy, grip_z)
|
| 367 |
+
align_x = align_x / max(np.linalg.norm(align_x), 1e-6)
|
| 368 |
+
jaw_y = np.cross(grip_z, align_x)
|
| 369 |
+
jaw_y = jaw_y / max(np.linalg.norm(jaw_y), 1e-6)
|
| 370 |
+
R_w_tool = np.stack([align_x, jaw_y, grip_z], axis=1)
|
| 371 |
+
quat_xyzw = Rotation.from_matrix(R_w_tool).as_quat()
|
| 372 |
+
quat_wxyz = np.array([quat_xyzw[3], quat_xyzw[0], quat_xyzw[1], quat_xyzw[2]], dtype=np.float64)
|
| 373 |
+
|
| 374 |
+
return TaskEGrasp(
|
| 375 |
+
translation_w=t_w.astype(np.float64),
|
| 376 |
+
quat_wxyz_w=quat_wxyz,
|
| 377 |
+
score=float(grasp.score),
|
| 378 |
+
width=float(grasp.width),
|
| 379 |
+
raw_translation_cam=t_cam,
|
| 380 |
+
)
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def quat_wxyz_to_torch(quat_wxyz: np.ndarray, device: str) -> torch.Tensor:
|
| 384 |
+
return torch.tensor([quat_wxyz], dtype=torch.float32, device=device)
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
def pos_to_torch(pos: np.ndarray, device: str) -> torch.Tensor:
|
| 388 |
+
return torch.tensor([pos], dtype=torch.float32, device=device)
|
scripts/pi05/compare_pi05_vs_act_baseline.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Compare a pi0.5 Task-E eval directory against the current ACT/XSA evidence."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import re
|
| 9 |
+
import statistics
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
RESULT_RE = re.compile(r"\[RESULT\].*?score=([0-9.]+).*?steps=([0-9]+).*?done=(True|False)")
|
| 13 |
+
BASKET_RE = re.compile(r"\[BASKET\].*?(object_[123]): .*?inside=(True|False)")
|
| 14 |
+
|
| 15 |
+
DEFAULT_BASELINE_LOGS = [
|
| 16 |
+
Path("logs/eval_task_e_xsa_final_seed11_recheck.log"),
|
| 17 |
+
Path("logs/eval_task_e_xsa_final_seed12_recheck.log"),
|
| 18 |
+
Path("logs/eval_task_e_xsa_final_seed13_recheck.log"),
|
| 19 |
+
Path("logs/eval_task_e_deployed_xsa_final_seed11_verify.log"),
|
| 20 |
+
]
|
| 21 |
+
CURRENT_POLICY_SHA = "c3eacae3f1b0ec8ccde9fdc05d680fff119cc2ca70e1f79e4ddd5610c4bbfa93"
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def parse_log(path: Path) -> tuple[float | None, dict[str, bool]]:
|
| 25 |
+
if not path.exists():
|
| 26 |
+
return None, {}
|
| 27 |
+
text = path.read_text(errors="replace")
|
| 28 |
+
result = RESULT_RE.search(text)
|
| 29 |
+
baskets = {obj: inside == "True" for obj, inside in BASKET_RE.findall(text)}
|
| 30 |
+
return (float(result.group(1)) if result else None), baskets
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def collect_pi05(eval_dir: Path) -> list[tuple[Path, float, dict[str, bool]]]:
|
| 34 |
+
rows = []
|
| 35 |
+
for log in sorted(eval_dir.glob("seed*.log")):
|
| 36 |
+
score, baskets = parse_log(log)
|
| 37 |
+
if score is not None:
|
| 38 |
+
rows.append((log, score, baskets))
|
| 39 |
+
return rows
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def print_rows(title: str, rows: list[tuple[Path, float, dict[str, bool]]]) -> None:
|
| 43 |
+
print(f"[{title}]")
|
| 44 |
+
if not rows:
|
| 45 |
+
print(" no complete result logs")
|
| 46 |
+
return
|
| 47 |
+
for path, score, baskets in rows:
|
| 48 |
+
basket_text = ", ".join(f"{obj}={inside}" for obj, inside in sorted(baskets.items()))
|
| 49 |
+
print(f" {path}: score={score:.2f}; {basket_text or 'basket=unknown'}")
|
| 50 |
+
scores = [score for _, score, _ in rows]
|
| 51 |
+
print(
|
| 52 |
+
f" summary: n={len(scores)} mean={statistics.fmean(scores):.2f} "
|
| 53 |
+
f"min={min(scores):.2f} max={max(scores):.2f}"
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def main() -> int:
|
| 58 |
+
parser = argparse.ArgumentParser()
|
| 59 |
+
parser.add_argument("eval_dir", type=Path)
|
| 60 |
+
parser.add_argument("--repo", type=Path, default=Path.cwd())
|
| 61 |
+
args = parser.parse_args()
|
| 62 |
+
|
| 63 |
+
repo = args.repo.resolve()
|
| 64 |
+
eval_dir = args.eval_dir if args.eval_dir.is_absolute() else repo / args.eval_dir
|
| 65 |
+
baseline_rows = []
|
| 66 |
+
for log in DEFAULT_BASELINE_LOGS:
|
| 67 |
+
path = log if log.is_absolute() else repo / log
|
| 68 |
+
score, baskets = parse_log(path)
|
| 69 |
+
if score is not None:
|
| 70 |
+
baseline_rows.append((path, score, baskets))
|
| 71 |
+
|
| 72 |
+
pi05_rows = collect_pi05(eval_dir)
|
| 73 |
+
print(f"[CURRENT_DEPLOYED_POLICY_SHA] {CURRENT_POLICY_SHA}")
|
| 74 |
+
print_rows("ACT_XSA_BASELINE_EVIDENCE", baseline_rows)
|
| 75 |
+
print_rows("PI05_CANDIDATE_EVIDENCE", pi05_rows)
|
| 76 |
+
|
| 77 |
+
if len(pi05_rows) < 3:
|
| 78 |
+
print("[DECISION] HOLD: pi0.5 does not yet have all seed11/12/13 results.")
|
| 79 |
+
return 0
|
| 80 |
+
|
| 81 |
+
pi05_scores = [score for _, score, _ in pi05_rows]
|
| 82 |
+
baseline_independent = [score for path, score, _ in baseline_rows if "xsa_final_seed" in path.name]
|
| 83 |
+
baseline_mean = statistics.fmean(baseline_independent) if baseline_independent else 0.0
|
| 84 |
+
pi05_mean = statistics.fmean(pi05_scores)
|
| 85 |
+
|
| 86 |
+
if min(pi05_scores) >= baseline_mean and pi05_mean > baseline_mean:
|
| 87 |
+
print("[DECISION] REVIEW_FOR_DEPLOY: pi0.5 is clearly better on this evidence set.")
|
| 88 |
+
else:
|
| 89 |
+
print("[DECISION] HOLD_ACT_XSA: pi0.5 is not clearly better than the current ACT/XSA baseline.")
|
| 90 |
+
return 0
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
if __name__ == "__main__":
|
| 94 |
+
raise SystemExit(main())
|
scripts/pi05/convert_task_e_hdf5_to_lerobot.py
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Convert ATEC Task E ACT HDF5 demos to a LeRobot dataset for OpenPI/pi0.5.
|
| 3 |
+
|
| 4 |
+
The existing Task E demos store a single 8-DoF Piper arm action:
|
| 5 |
+
6 arm joints + 2 gripper joints. The local OpenPI EBench tabletop policy
|
| 6 |
+
expects a 16-D fixed-base action split as 12 arm joints + 4 gripper joints,
|
| 7 |
+
so this converter pads the unused second-arm slots with zeros.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import argparse
|
| 13 |
+
import os
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
import shutil
|
| 16 |
+
|
| 17 |
+
import h5py
|
| 18 |
+
import numpy as np
|
| 19 |
+
from lerobot.common.datasets.lerobot_dataset import LeRobotDataset
|
| 20 |
+
from tqdm import tqdm
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
DEFAULT_PROMPT = "identify all objects, pick them up, and place them into the target basket"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _sorted_traj_keys(h5_file: h5py.File) -> list[str]:
|
| 27 |
+
keys = [key for key in h5_file.keys() if key.startswith("traj_")]
|
| 28 |
+
return sorted(keys, key=lambda item: int(item.split("_", 1)[1]))
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _pad_state(qpos8: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
| 32 |
+
qpos8 = np.asarray(qpos8, dtype=np.float32)
|
| 33 |
+
joints = np.zeros(12, dtype=np.float32)
|
| 34 |
+
gripper = np.zeros(4, dtype=np.float32)
|
| 35 |
+
joints[:6] = qpos8[:6]
|
| 36 |
+
gripper[:2] = qpos8[6:8]
|
| 37 |
+
return joints, gripper
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _pad_action(action8: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
| 41 |
+
action8 = np.asarray(action8, dtype=np.float32)
|
| 42 |
+
joints = np.zeros(12, dtype=np.float32)
|
| 43 |
+
gripper = np.zeros(4, dtype=np.float32)
|
| 44 |
+
joints[:6] = action8[:6]
|
| 45 |
+
gripper[:2] = action8[6:8]
|
| 46 |
+
return joints, gripper
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def create_dataset(
|
| 50 |
+
*,
|
| 51 |
+
repo_id: str,
|
| 52 |
+
root: Path,
|
| 53 |
+
fps: int,
|
| 54 |
+
use_videos: bool,
|
| 55 |
+
overwrite: bool,
|
| 56 |
+
image_writer_processes: int,
|
| 57 |
+
image_writer_threads: int,
|
| 58 |
+
image_height: int,
|
| 59 |
+
image_width: int,
|
| 60 |
+
) -> LeRobotDataset:
|
| 61 |
+
dataset_dir = root / repo_id
|
| 62 |
+
if dataset_dir.exists():
|
| 63 |
+
if not overwrite:
|
| 64 |
+
raise FileExistsError(f"{dataset_dir} already exists; pass --overwrite to replace it")
|
| 65 |
+
shutil.rmtree(dataset_dir)
|
| 66 |
+
|
| 67 |
+
features = {
|
| 68 |
+
"video.overlook_camera_view": {
|
| 69 |
+
"dtype": "image",
|
| 70 |
+
"shape": (image_height, image_width, 3),
|
| 71 |
+
"names": ["height", "width", "channel"],
|
| 72 |
+
},
|
| 73 |
+
"video.left_camera_view": {
|
| 74 |
+
"dtype": "image",
|
| 75 |
+
"shape": (image_height, image_width, 3),
|
| 76 |
+
"names": ["height", "width", "channel"],
|
| 77 |
+
},
|
| 78 |
+
"video.right_camera_view": {
|
| 79 |
+
"dtype": "image",
|
| 80 |
+
"shape": (image_height, image_width, 3),
|
| 81 |
+
"names": ["height", "width", "channel"],
|
| 82 |
+
},
|
| 83 |
+
"state.joints": {
|
| 84 |
+
"dtype": "float32",
|
| 85 |
+
"shape": (12,),
|
| 86 |
+
"names": ["joint"],
|
| 87 |
+
},
|
| 88 |
+
"state.gripper": {
|
| 89 |
+
"dtype": "float32",
|
| 90 |
+
"shape": (4,),
|
| 91 |
+
"names": ["gripper"],
|
| 92 |
+
},
|
| 93 |
+
"action.joints": {
|
| 94 |
+
"dtype": "float32",
|
| 95 |
+
"shape": (12,),
|
| 96 |
+
"names": ["joint"],
|
| 97 |
+
},
|
| 98 |
+
"action.gripper": {
|
| 99 |
+
"dtype": "float32",
|
| 100 |
+
"shape": (4,),
|
| 101 |
+
"names": ["gripper"],
|
| 102 |
+
},
|
| 103 |
+
}
|
| 104 |
+
return LeRobotDataset.create(
|
| 105 |
+
repo_id=repo_id,
|
| 106 |
+
root=dataset_dir,
|
| 107 |
+
robot_type="atec_piper_task_e",
|
| 108 |
+
fps=fps,
|
| 109 |
+
features=features,
|
| 110 |
+
use_videos=use_videos,
|
| 111 |
+
image_writer_processes=image_writer_processes,
|
| 112 |
+
image_writer_threads=image_writer_threads,
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _resize_image(rgb: np.ndarray, height: int, width: int) -> np.ndarray:
|
| 117 |
+
if rgb.shape[0] == height and rgb.shape[1] == width:
|
| 118 |
+
return rgb
|
| 119 |
+
import cv2
|
| 120 |
+
|
| 121 |
+
return cv2.resize(rgb, (width, height), interpolation=cv2.INTER_AREA)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def convert(args: argparse.Namespace) -> None:
|
| 125 |
+
input_path = Path(args.input).expanduser().resolve()
|
| 126 |
+
root = Path(args.root).expanduser().resolve()
|
| 127 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 128 |
+
os.environ.setdefault("HF_LEROBOT_HOME", str(root))
|
| 129 |
+
|
| 130 |
+
dataset = create_dataset(
|
| 131 |
+
repo_id=args.repo_id,
|
| 132 |
+
root=root,
|
| 133 |
+
fps=args.fps,
|
| 134 |
+
use_videos=args.use_videos,
|
| 135 |
+
overwrite=args.overwrite,
|
| 136 |
+
image_writer_processes=args.image_writer_processes,
|
| 137 |
+
image_writer_threads=args.image_writer_threads,
|
| 138 |
+
image_height=args.image_height,
|
| 139 |
+
image_width=args.image_width,
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
with h5py.File(input_path, "r") as h5_file:
|
| 143 |
+
traj_keys = _sorted_traj_keys(h5_file)
|
| 144 |
+
if args.max_episodes is not None:
|
| 145 |
+
traj_keys = traj_keys[: args.max_episodes]
|
| 146 |
+
if not traj_keys:
|
| 147 |
+
raise ValueError(f"No traj_* groups found in {input_path}")
|
| 148 |
+
|
| 149 |
+
for traj_key in tqdm(traj_keys, desc="episodes"):
|
| 150 |
+
group = h5_file[traj_key]
|
| 151 |
+
qpos = group["obs"]
|
| 152 |
+
actions = group["actions"]
|
| 153 |
+
images = group["images/rgb"]
|
| 154 |
+
length = min(len(qpos), len(actions), len(images))
|
| 155 |
+
if length <= 0:
|
| 156 |
+
continue
|
| 157 |
+
|
| 158 |
+
for step in range(0, length, args.stride):
|
| 159 |
+
state_joints, state_gripper = _pad_state(qpos[step])
|
| 160 |
+
action_joints, action_gripper = _pad_action(actions[step])
|
| 161 |
+
rgb = _resize_image(images[step], args.image_height, args.image_width)
|
| 162 |
+
dataset.add_frame(
|
| 163 |
+
{
|
| 164 |
+
"video.overlook_camera_view": rgb,
|
| 165 |
+
"video.left_camera_view": rgb,
|
| 166 |
+
"video.right_camera_view": rgb,
|
| 167 |
+
"state.joints": state_joints,
|
| 168 |
+
"state.gripper": state_gripper,
|
| 169 |
+
"action.joints": action_joints,
|
| 170 |
+
"action.gripper": action_gripper,
|
| 171 |
+
"task": args.prompt,
|
| 172 |
+
}
|
| 173 |
+
)
|
| 174 |
+
dataset.save_episode()
|
| 175 |
+
|
| 176 |
+
print(f"[OK] Wrote LeRobot dataset repo_id={args.repo_id} root={root}")
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def parse_args() -> argparse.Namespace:
|
| 180 |
+
parser = argparse.ArgumentParser()
|
| 181 |
+
parser.add_argument(
|
| 182 |
+
"--input",
|
| 183 |
+
default="datasets/atec_task_e_obj321_servo_100demos/trajectory_filtered.hdf5",
|
| 184 |
+
help="Filtered ATEC Task E HDF5 file.",
|
| 185 |
+
)
|
| 186 |
+
parser.add_argument(
|
| 187 |
+
"--root",
|
| 188 |
+
default="/home/ubuntu/projects/robotics_shared/datasets/lerobot",
|
| 189 |
+
help="LeRobot dataset root. Also exported as HF_LEROBOT_HOME by this script.",
|
| 190 |
+
)
|
| 191 |
+
parser.add_argument("--repo_id", default="atec/task_e_obj321_servo_100demos")
|
| 192 |
+
parser.add_argument("--prompt", default=DEFAULT_PROMPT)
|
| 193 |
+
parser.add_argument("--fps", type=int, default=50)
|
| 194 |
+
parser.add_argument("--image_height", type=int, default=224)
|
| 195 |
+
parser.add_argument("--image_width", type=int, default=224)
|
| 196 |
+
parser.add_argument("--stride", type=int, default=1, help="Temporal subsampling stride.")
|
| 197 |
+
parser.add_argument("--max_episodes", type=int, default=None)
|
| 198 |
+
parser.add_argument("--use_videos", action=argparse.BooleanOptionalAction, default=False)
|
| 199 |
+
parser.add_argument("--overwrite", action="store_true")
|
| 200 |
+
parser.add_argument("--image_writer_processes", type=int, default=0)
|
| 201 |
+
parser.add_argument("--image_writer_threads", type=int, default=0)
|
| 202 |
+
return parser.parse_args()
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
if __name__ == "__main__":
|
| 206 |
+
convert(parse_args())
|
scripts/pi05/convert_task_e_hdf5_to_lerobot_native8.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Convert ATEC Task E HDF5 demos to a native 8D Piper LeRobot dataset.
|
| 3 |
+
|
| 4 |
+
This variant keeps the ATEC action/state representation intact:
|
| 5 |
+
6 arm joints + 2 gripper joints. The OpenPI transform pads the 8D vector to
|
| 6 |
+
the pi0.5 model dimension later, which avoids the old fixed-base 12+4 mapping.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import os
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
import shutil
|
| 15 |
+
|
| 16 |
+
import h5py
|
| 17 |
+
import numpy as np
|
| 18 |
+
from lerobot.common.datasets.lerobot_dataset import LeRobotDataset
|
| 19 |
+
from tqdm import tqdm
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
DEFAULT_PROMPT = "identify all objects, pick them up, and place them into the target basket"
|
| 23 |
+
DEFAULT_JOINT_POS = np.asarray([0.0, 1.2, -1.5, 0.0, 1.2, 0.0, 0.035, -0.035], dtype=np.float32)
|
| 24 |
+
ACTION_SCALE = np.float32(0.5)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _sorted_traj_keys(h5_file: h5py.File) -> list[str]:
|
| 28 |
+
keys = [key for key in h5_file.keys() if key.startswith("traj_")]
|
| 29 |
+
return sorted(keys, key=lambda item: int(item.split("_", 1)[1]))
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _resize_image(rgb: np.ndarray, height: int, width: int) -> np.ndarray:
|
| 33 |
+
if rgb.shape[0] == height and rgb.shape[1] == width:
|
| 34 |
+
return rgb
|
| 35 |
+
import cv2
|
| 36 |
+
|
| 37 |
+
return cv2.resize(rgb, (width, height), interpolation=cv2.INTER_AREA)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def create_dataset(
|
| 41 |
+
*,
|
| 42 |
+
repo_id: str,
|
| 43 |
+
root: Path,
|
| 44 |
+
fps: int,
|
| 45 |
+
use_videos: bool,
|
| 46 |
+
overwrite: bool,
|
| 47 |
+
image_writer_processes: int,
|
| 48 |
+
image_writer_threads: int,
|
| 49 |
+
image_height: int,
|
| 50 |
+
image_width: int,
|
| 51 |
+
) -> LeRobotDataset:
|
| 52 |
+
dataset_dir = root / repo_id
|
| 53 |
+
if dataset_dir.exists():
|
| 54 |
+
if not overwrite:
|
| 55 |
+
raise FileExistsError(f"{dataset_dir} already exists; pass --overwrite to replace it")
|
| 56 |
+
shutil.rmtree(dataset_dir)
|
| 57 |
+
|
| 58 |
+
features = {
|
| 59 |
+
"video.base_camera_view": {
|
| 60 |
+
"dtype": "image",
|
| 61 |
+
"shape": (image_height, image_width, 3),
|
| 62 |
+
"names": ["height", "width", "channel"],
|
| 63 |
+
},
|
| 64 |
+
"state": {
|
| 65 |
+
"dtype": "float32",
|
| 66 |
+
"shape": (8,),
|
| 67 |
+
"names": ["state"],
|
| 68 |
+
},
|
| 69 |
+
"action": {
|
| 70 |
+
"dtype": "float32",
|
| 71 |
+
"shape": (8,),
|
| 72 |
+
"names": ["action"],
|
| 73 |
+
},
|
| 74 |
+
}
|
| 75 |
+
return LeRobotDataset.create(
|
| 76 |
+
repo_id=repo_id,
|
| 77 |
+
root=dataset_dir,
|
| 78 |
+
robot_type="atec_piper_task_e_native8",
|
| 79 |
+
fps=fps,
|
| 80 |
+
features=features,
|
| 81 |
+
use_videos=use_videos,
|
| 82 |
+
image_writer_processes=image_writer_processes,
|
| 83 |
+
image_writer_threads=image_writer_threads,
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def convert(args: argparse.Namespace) -> None:
|
| 88 |
+
input_path = Path(args.input).expanduser().resolve()
|
| 89 |
+
root = Path(args.root).expanduser().resolve()
|
| 90 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 91 |
+
os.environ.setdefault("HF_LEROBOT_HOME", str(root))
|
| 92 |
+
|
| 93 |
+
dataset = create_dataset(
|
| 94 |
+
repo_id=args.repo_id,
|
| 95 |
+
root=root,
|
| 96 |
+
fps=args.fps,
|
| 97 |
+
use_videos=args.use_videos,
|
| 98 |
+
overwrite=args.overwrite,
|
| 99 |
+
image_writer_processes=args.image_writer_processes,
|
| 100 |
+
image_writer_threads=args.image_writer_threads,
|
| 101 |
+
image_height=args.image_height,
|
| 102 |
+
image_width=args.image_width,
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
frame_count = 0
|
| 106 |
+
with h5py.File(input_path, "r") as h5_file:
|
| 107 |
+
traj_keys = _sorted_traj_keys(h5_file)
|
| 108 |
+
if args.max_episodes is not None:
|
| 109 |
+
traj_keys = traj_keys[: args.max_episodes]
|
| 110 |
+
if not traj_keys:
|
| 111 |
+
raise ValueError(f"No traj_* groups found in {input_path}")
|
| 112 |
+
|
| 113 |
+
for traj_key in tqdm(traj_keys, desc="episodes"):
|
| 114 |
+
group = h5_file[traj_key]
|
| 115 |
+
qpos = group["obs"]
|
| 116 |
+
actions = group["actions"]
|
| 117 |
+
images = group["images/rgb"]
|
| 118 |
+
length = min(len(qpos), len(actions), len(images))
|
| 119 |
+
if length <= 0:
|
| 120 |
+
continue
|
| 121 |
+
|
| 122 |
+
written_this_episode = 0
|
| 123 |
+
for step in range(0, length, args.stride):
|
| 124 |
+
if args.max_frames_per_episode is not None and written_this_episode >= args.max_frames_per_episode:
|
| 125 |
+
break
|
| 126 |
+
rgb = _resize_image(images[step], args.image_height, args.image_width)
|
| 127 |
+
action = np.asarray(actions[step], dtype=np.float32)
|
| 128 |
+
if args.action_mode == "absolute_target":
|
| 129 |
+
action = DEFAULT_JOINT_POS + ACTION_SCALE * action
|
| 130 |
+
elif args.action_mode != "env_action":
|
| 131 |
+
raise ValueError(f"Unsupported --action_mode={args.action_mode!r}")
|
| 132 |
+
dataset.add_frame(
|
| 133 |
+
{
|
| 134 |
+
"video.base_camera_view": rgb,
|
| 135 |
+
"state": np.asarray(qpos[step], dtype=np.float32),
|
| 136 |
+
"action": action,
|
| 137 |
+
"task": args.prompt,
|
| 138 |
+
}
|
| 139 |
+
)
|
| 140 |
+
frame_count += 1
|
| 141 |
+
written_this_episode += 1
|
| 142 |
+
dataset.save_episode()
|
| 143 |
+
|
| 144 |
+
print(
|
| 145 |
+
f"[OK] Wrote native8 LeRobot dataset repo_id={args.repo_id} "
|
| 146 |
+
f"root={root} episodes={len(traj_keys)} frames={frame_count}"
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def parse_args() -> argparse.Namespace:
|
| 151 |
+
parser = argparse.ArgumentParser()
|
| 152 |
+
parser.add_argument("--input", default="datasets/atec_task_e_obj321_servo_100demos/trajectory_filtered.hdf5")
|
| 153 |
+
parser.add_argument("--root", default="/home/ubuntu/projects/robotics_shared/datasets/lerobot")
|
| 154 |
+
parser.add_argument("--repo_id", default="atec/task_e_obj321_servo_20demos_native8_s1_224")
|
| 155 |
+
parser.add_argument("--prompt", default=DEFAULT_PROMPT)
|
| 156 |
+
parser.add_argument("--fps", type=int, default=50)
|
| 157 |
+
parser.add_argument("--image_height", type=int, default=224)
|
| 158 |
+
parser.add_argument("--image_width", type=int, default=224)
|
| 159 |
+
parser.add_argument("--stride", type=int, default=1)
|
| 160 |
+
parser.add_argument("--max_episodes", type=int, default=20)
|
| 161 |
+
parser.add_argument(
|
| 162 |
+
"--max_frames_per_episode",
|
| 163 |
+
type=int,
|
| 164 |
+
default=None,
|
| 165 |
+
help="Optional cap after stride sampling; useful for fast bridge sanity checks on long raw demos.",
|
| 166 |
+
)
|
| 167 |
+
parser.add_argument(
|
| 168 |
+
"--action_mode",
|
| 169 |
+
choices=("env_action", "absolute_target"),
|
| 170 |
+
default="env_action",
|
| 171 |
+
help=(
|
| 172 |
+
"Store raw ATEC env actions, or convert them to absolute joint targets with "
|
| 173 |
+
"joint_target = default_joint_pos + 0.5 * env_action."
|
| 174 |
+
),
|
| 175 |
+
)
|
| 176 |
+
parser.add_argument("--use_videos", action=argparse.BooleanOptionalAction, default=False)
|
| 177 |
+
parser.add_argument("--overwrite", action="store_true")
|
| 178 |
+
parser.add_argument("--image_writer_processes", type=int, default=5)
|
| 179 |
+
parser.add_argument("--image_writer_threads", type=int, default=10)
|
| 180 |
+
return parser.parse_args()
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
if __name__ == "__main__":
|
| 184 |
+
convert(parse_args())
|
scripts/pi05/eval_task_e_pi05.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Rollout evaluation for a Task-E pi0.5 websocket policy."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import os
|
| 8 |
+
import sys
|
| 9 |
+
import time
|
| 10 |
+
from datetime import datetime
|
| 11 |
+
|
| 12 |
+
from isaaclab.app import AppLauncher
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
parser = argparse.ArgumentParser(description="Evaluate an OpenPI/pi0.5 server on ATEC Task E.")
|
| 16 |
+
parser.add_argument("--task", type=str, default="ATEC-TaskE-Piper")
|
| 17 |
+
parser.add_argument("--episodes", type=int, default=1)
|
| 18 |
+
parser.add_argument("--max_steps", type=int, default=1500)
|
| 19 |
+
parser.add_argument("--video_path", type=str, default=None, help="Optional MP4 output path for episode 1.")
|
| 20 |
+
parser.add_argument("--video_interval", type=int, default=2)
|
| 21 |
+
parser.add_argument("--video_fps", type=int, default=25)
|
| 22 |
+
parser.add_argument("--seed", type=int, default=None)
|
| 23 |
+
parser.add_argument("--host", type=str, default="127.0.0.1")
|
| 24 |
+
parser.add_argument("--port", type=int, default=8000)
|
| 25 |
+
parser.add_argument("--action_repeat", type=int, default=5)
|
| 26 |
+
parser.add_argument("--solution_module", type=str, default="solution_pi05")
|
| 27 |
+
parser.add_argument("--disable_fabric", action="store_true", default=False)
|
| 28 |
+
parser.add_argument("--debug", action="store_true", default=False)
|
| 29 |
+
AppLauncher.add_app_launcher_args(parser)
|
| 30 |
+
args_cli = parser.parse_args()
|
| 31 |
+
args_cli.enable_cameras = True
|
| 32 |
+
|
| 33 |
+
repo_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
|
| 34 |
+
os.environ["ATEC_PI05_HOST"] = args_cli.host
|
| 35 |
+
os.environ["ATEC_PI05_PORT"] = str(args_cli.port)
|
| 36 |
+
os.environ["ATEC_PI05_ACTION_REPEAT"] = str(args_cli.action_repeat)
|
| 37 |
+
|
| 38 |
+
app_launcher = AppLauncher(args_cli)
|
| 39 |
+
simulation_app = app_launcher.app
|
| 40 |
+
|
| 41 |
+
import gymnasium as gym # noqa: E402
|
| 42 |
+
import torch # noqa: E402
|
| 43 |
+
|
| 44 |
+
from isaaclab.envs import DirectMARLEnv, multi_agent_to_single_agent # noqa: E402
|
| 45 |
+
from isaaclab_tasks.utils import parse_env_cfg # noqa: E402
|
| 46 |
+
|
| 47 |
+
import atec_rl_lab.tasks # noqa: F401, E402
|
| 48 |
+
|
| 49 |
+
demo_dir = os.path.join(repo_root, "demo")
|
| 50 |
+
if repo_root not in sys.path:
|
| 51 |
+
sys.path.insert(0, repo_root)
|
| 52 |
+
if demo_dir not in sys.path:
|
| 53 |
+
sys.path.insert(0, demo_dir)
|
| 54 |
+
|
| 55 |
+
from scripts.act.task_e.collector import basket_status_lines # noqa: E402
|
| 56 |
+
import importlib # noqa: E402
|
| 57 |
+
|
| 58 |
+
AlgSolution = importlib.import_module(args_cli.solution_module).AlgSolution # noqa: E402
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _frame_from_obs(obs) -> object:
|
| 62 |
+
rgb = obs["image"]["video_rgb"]
|
| 63 |
+
if isinstance(rgb, torch.Tensor):
|
| 64 |
+
frame = rgb[0].detach().cpu()
|
| 65 |
+
if frame.ndim == 3 and frame.shape[0] in (3, 4):
|
| 66 |
+
frame = frame.permute(1, 2, 0)
|
| 67 |
+
if frame.shape[-1] == 4:
|
| 68 |
+
frame = frame[..., :3]
|
| 69 |
+
if frame.dtype != torch.uint8:
|
| 70 |
+
frame = (frame.float() * 255.0).clamp(0, 255).to(torch.uint8)
|
| 71 |
+
return frame.numpy()
|
| 72 |
+
return rgb[0]
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _resolve_video_path() -> str | None:
|
| 76 |
+
if args_cli.video_path is None:
|
| 77 |
+
return None
|
| 78 |
+
if args_cli.video_path:
|
| 79 |
+
return os.path.abspath(args_cli.video_path)
|
| 80 |
+
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 81 |
+
return os.path.join(repo_root, "logs", "videos", "task_e_pi05_eval", f"eval_{stamp}.mp4")
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def evaluate() -> list[dict[str, float]]:
|
| 85 |
+
env_cfg = parse_env_cfg(
|
| 86 |
+
args_cli.task,
|
| 87 |
+
device=args_cli.device,
|
| 88 |
+
num_envs=1,
|
| 89 |
+
use_fabric=not args_cli.disable_fabric,
|
| 90 |
+
)
|
| 91 |
+
if args_cli.seed is not None:
|
| 92 |
+
env_cfg.seed = args_cli.seed
|
| 93 |
+
env = gym.make(args_cli.task, cfg=env_cfg)
|
| 94 |
+
if isinstance(env.unwrapped, DirectMARLEnv):
|
| 95 |
+
env = multi_agent_to_single_agent(env)
|
| 96 |
+
|
| 97 |
+
policy = AlgSolution()
|
| 98 |
+
video_path = _resolve_video_path()
|
| 99 |
+
writer = None
|
| 100 |
+
if video_path is not None:
|
| 101 |
+
import imageio.v2 as imageio
|
| 102 |
+
|
| 103 |
+
os.makedirs(os.path.dirname(video_path), exist_ok=True)
|
| 104 |
+
writer = imageio.get_writer(video_path, fps=args_cli.video_fps, quality=7)
|
| 105 |
+
print(f"[INFO] Recording episode 1 video to: {video_path}")
|
| 106 |
+
|
| 107 |
+
results = []
|
| 108 |
+
try:
|
| 109 |
+
for episode in range(args_cli.episodes):
|
| 110 |
+
reset_kwargs = {"seed": args_cli.seed + episode} if args_cli.seed is not None else {}
|
| 111 |
+
obs, _ = env.reset(**reset_kwargs)
|
| 112 |
+
policy.reset_episode()
|
| 113 |
+
total_reward = 0.0
|
| 114 |
+
elapsed_time = 0.0
|
| 115 |
+
steps = 0
|
| 116 |
+
done = False
|
| 117 |
+
start_wall = time.time()
|
| 118 |
+
if writer is not None and episode == 0:
|
| 119 |
+
writer.append_data(_frame_from_obs(obs))
|
| 120 |
+
|
| 121 |
+
while simulation_app.is_running() and steps < args_cli.max_steps:
|
| 122 |
+
resp = policy.predicts(obs, total_reward)
|
| 123 |
+
if resp["giveup"]:
|
| 124 |
+
break
|
| 125 |
+
action = torch.as_tensor(resp["action"], dtype=torch.float32, device=args_cli.device).view(1, -1)
|
| 126 |
+
obs, reward, terminated, truncated, info = env.step(action)
|
| 127 |
+
|
| 128 |
+
sim_dt = info["Step_dt"]
|
| 129 |
+
total_reward += reward.mean().item() / sim_dt if isinstance(reward, torch.Tensor) else float(reward) / sim_dt
|
| 130 |
+
if isinstance(info, dict) and "Elapsed_Time" in info:
|
| 131 |
+
elapsed = info["Elapsed_Time"]
|
| 132 |
+
elapsed_time = elapsed.item() if hasattr(elapsed, "item") else float(elapsed)
|
| 133 |
+
else:
|
| 134 |
+
elapsed_time += env.unwrapped.step_dt
|
| 135 |
+
done = bool(terminated.item() or truncated.item())
|
| 136 |
+
steps += 1
|
| 137 |
+
if writer is not None and episode == 0 and steps % max(1, args_cli.video_interval) == 0:
|
| 138 |
+
writer.append_data(_frame_from_obs(obs))
|
| 139 |
+
if args_cli.debug and steps % 100 == 0:
|
| 140 |
+
print(f"[DEBUG] episode={episode + 1} step={steps} score={total_reward:.2f}")
|
| 141 |
+
if done:
|
| 142 |
+
break
|
| 143 |
+
|
| 144 |
+
result = {
|
| 145 |
+
"episode": episode + 1,
|
| 146 |
+
"score": float(total_reward),
|
| 147 |
+
"elapsed_time": float(elapsed_time),
|
| 148 |
+
"steps": float(steps),
|
| 149 |
+
"done": float(done),
|
| 150 |
+
"wall_time": time.time() - start_wall,
|
| 151 |
+
}
|
| 152 |
+
results.append(result)
|
| 153 |
+
try:
|
| 154 |
+
for line in basket_status_lines(env, [1, 2, 3]):
|
| 155 |
+
print(f"[BASKET] episode={episode + 1} {line}")
|
| 156 |
+
except Exception as exc:
|
| 157 |
+
if args_cli.debug:
|
| 158 |
+
print(f"[DEBUG] basket status unavailable: {exc}")
|
| 159 |
+
print(
|
| 160 |
+
"[RESULT] "
|
| 161 |
+
f"episode={result['episode']:.0f} "
|
| 162 |
+
f"score={result['score']:.2f} "
|
| 163 |
+
f"elapsed_time={result['elapsed_time']:.2f} "
|
| 164 |
+
f"steps={result['steps']:.0f} "
|
| 165 |
+
f"done={bool(result['done'])} "
|
| 166 |
+
f"wall_time={result['wall_time']:.1f}s"
|
| 167 |
+
)
|
| 168 |
+
finally:
|
| 169 |
+
if writer is not None:
|
| 170 |
+
writer.close()
|
| 171 |
+
env.close()
|
| 172 |
+
|
| 173 |
+
return results
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
if __name__ == "__main__":
|
| 177 |
+
try:
|
| 178 |
+
results = evaluate()
|
| 179 |
+
if results:
|
| 180 |
+
scores = torch.tensor([r["score"] for r in results], dtype=torch.float32)
|
| 181 |
+
print(f"[SUMMARY] episodes={len(results)} mean_score={scores.mean().item():.2f} best_score={scores.max().item():.2f}")
|
| 182 |
+
finally:
|
| 183 |
+
simulation_app.close()
|
scripts/pi05/run_pi05_20demos_after_convert.sh
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
REPO=/home/ubuntu/Documents/01Proj/13atec/ATEC2026_Simulation_Challenge
|
| 5 |
+
OPENPI=/home/ubuntu/src/openpi-ebench-clean
|
| 6 |
+
PY=/home/ubuntu/envs/openpi-pi05/bin/python
|
| 7 |
+
CONFIG=pi05_atec_task_e_20demos_s5_224
|
| 8 |
+
CONVERT_UNIT_FILE="$REPO/logs/pi05_convert_task_e_s5_224_20demos.latest_unit"
|
| 9 |
+
STAMP="$(date +%Y%m%d%H%M%S)"
|
| 10 |
+
NORM_LOG="$REPO/logs/pi05_norm_task_e_20demos_s5_224_${STAMP}.log"
|
| 11 |
+
TRAIN_LOG="$REPO/logs/pi05_train_task_e_20demos_s5_224_${STAMP}.log"
|
| 12 |
+
|
| 13 |
+
export HF_LEROBOT_HOME=/home/ubuntu/projects/robotics_shared/datasets/lerobot
|
| 14 |
+
export HF_HOME=/home/ubuntu/projects/robotics_shared/hf_cache
|
| 15 |
+
export PYTHONPATH="$OPENPI/src:$OPENPI/packages/openpi-client/src"
|
| 16 |
+
export XLA_PYTHON_CLIENT_MEM_FRACTION="${XLA_PYTHON_CLIENT_MEM_FRACTION:-0.80}"
|
| 17 |
+
|
| 18 |
+
cd "$OPENPI"
|
| 19 |
+
|
| 20 |
+
if [[ -f "$CONVERT_UNIT_FILE" ]]; then
|
| 21 |
+
convert_unit="$(cat "$CONVERT_UNIT_FILE").service"
|
| 22 |
+
echo "[INFO] Waiting for $convert_unit"
|
| 23 |
+
while systemctl --user is-active --quiet "$convert_unit"; do
|
| 24 |
+
sleep 60
|
| 25 |
+
done
|
| 26 |
+
systemctl --user is-failed --quiet "$convert_unit" && {
|
| 27 |
+
echo "[ERROR] Conversion unit failed: $convert_unit"
|
| 28 |
+
systemctl --user status "$convert_unit" --no-pager --lines=80 || true
|
| 29 |
+
exit 1
|
| 30 |
+
}
|
| 31 |
+
fi
|
| 32 |
+
|
| 33 |
+
echo "[INFO] Computing norm stats for $CONFIG" | tee "$NORM_LOG"
|
| 34 |
+
"$PY" scripts/compute_norm_stats.py \
|
| 35 |
+
--config-name "$CONFIG" \
|
| 36 |
+
--max-frames 7000 2>&1 | tee -a "$NORM_LOG"
|
| 37 |
+
|
| 38 |
+
echo "[INFO] Training $CONFIG" | tee "$TRAIN_LOG"
|
| 39 |
+
"$PY" scripts/train.py \
|
| 40 |
+
"$CONFIG" \
|
| 41 |
+
--exp-name atec_task_e_pi05_20demos_s5_224_2k_${STAMP} \
|
| 42 |
+
--overwrite 2>&1 | tee -a "$TRAIN_LOG"
|
scripts/pi05/run_pi05_eval_checkpoint.sh
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
REPO=/home/ubuntu/Documents/01Proj/13atec/ATEC2026_Simulation_Challenge
|
| 5 |
+
OPENPI=/home/ubuntu/src/openpi-ebench-clean
|
| 6 |
+
OPENPI_PY=/home/ubuntu/envs/openpi-pi05/bin/python
|
| 7 |
+
ISAAC_PY=/home/ubuntu/envs/genmanip-isaac5-py311/bin/python
|
| 8 |
+
|
| 9 |
+
CONFIG="${CONFIG:-pi05_atec_task_e_s5_224}"
|
| 10 |
+
CHECKPOINT_DIR="${1:-${CHECKPOINT_DIR:-}}"
|
| 11 |
+
PORT="${PORT:-8015}"
|
| 12 |
+
ACTION_REPEAT="${ACTION_REPEAT:-5}"
|
| 13 |
+
STAMP="$(date +%Y%m%d%H%M%S)"
|
| 14 |
+
SERVER_LOG="$REPO/logs/pi05_policy_server_${STAMP}.log"
|
| 15 |
+
EVAL_DIR="$REPO/logs/pi05_eval_${STAMP}"
|
| 16 |
+
|
| 17 |
+
if [[ -z "$CHECKPOINT_DIR" ]]; then
|
| 18 |
+
CHECKPOINT_DIR="$(find /home/ubuntu/projects/robotics_shared/checkpoints/openpi/atec_runs/checkpoints/"$CONFIG" -mindepth 2 -maxdepth 2 -type d -regex '.*/[0-9]+' 2>/dev/null | sort -V | tail -1 || true)"
|
| 19 |
+
fi
|
| 20 |
+
if [[ -z "$CHECKPOINT_DIR" || ! -d "$CHECKPOINT_DIR" ]]; then
|
| 21 |
+
echo "[ERROR] Checkpoint dir not found. Pass it as argv[1] or set CHECKPOINT_DIR." >&2
|
| 22 |
+
exit 1
|
| 23 |
+
fi
|
| 24 |
+
|
| 25 |
+
mkdir -p "$EVAL_DIR" "$REPO/logs/videos/task_e_pi05_eval"
|
| 26 |
+
|
| 27 |
+
export HF_LEROBOT_HOME=/home/ubuntu/projects/robotics_shared/datasets/lerobot
|
| 28 |
+
export HF_HOME=/home/ubuntu/projects/robotics_shared/hf_cache
|
| 29 |
+
export PYTHONPATH="$OPENPI/src:$OPENPI/packages/openpi-client/src"
|
| 30 |
+
|
| 31 |
+
cd "$OPENPI"
|
| 32 |
+
"$OPENPI_PY" scripts/serve_policy.py \
|
| 33 |
+
--port "$PORT" \
|
| 34 |
+
policy:checkpoint \
|
| 35 |
+
--policy.config "$CONFIG" \
|
| 36 |
+
--policy.dir "$CHECKPOINT_DIR" \
|
| 37 |
+
> "$SERVER_LOG" 2>&1 &
|
| 38 |
+
server_pid=$!
|
| 39 |
+
|
| 40 |
+
cleanup() {
|
| 41 |
+
kill "$server_pid" 2>/dev/null || true
|
| 42 |
+
}
|
| 43 |
+
trap cleanup EXIT
|
| 44 |
+
|
| 45 |
+
echo "[INFO] Started OpenPI server pid=$server_pid port=$PORT checkpoint=$CHECKPOINT_DIR"
|
| 46 |
+
for _ in $(seq 1 120); do
|
| 47 |
+
if grep -q "Creating server" "$SERVER_LOG" 2>/dev/null; then
|
| 48 |
+
break
|
| 49 |
+
fi
|
| 50 |
+
if ! kill -0 "$server_pid" 2>/dev/null; then
|
| 51 |
+
echo "[ERROR] OpenPI server exited early. Tail:" >&2
|
| 52 |
+
tail -80 "$SERVER_LOG" >&2 || true
|
| 53 |
+
exit 1
|
| 54 |
+
fi
|
| 55 |
+
sleep 5
|
| 56 |
+
done
|
| 57 |
+
|
| 58 |
+
export OMNI_KIT_ACCEPT_EULA=YES
|
| 59 |
+
export PYTHONUNBUFFERED=1
|
| 60 |
+
export PYTHONPATH="/home/ubuntu/envs/genmanip-isaac5-py311/lib/python3.11/site-packages/isaaclab/source/isaaclab:/home/ubuntu/envs/genmanip-isaac5-py311/lib/python3.11/site-packages/isaaclab/source/isaaclab_assets:/home/ubuntu/envs/genmanip-isaac5-py311/lib/python3.11/site-packages/isaaclab/source/isaaclab_tasks:$REPO/source/atec_rl_lab:$REPO/scripts/act"
|
| 61 |
+
|
| 62 |
+
cd "$REPO"
|
| 63 |
+
for seed in 11 12 13; do
|
| 64 |
+
video_arg=()
|
| 65 |
+
if [[ "$seed" == "11" ]]; then
|
| 66 |
+
video_arg=(--video_path "$REPO/logs/videos/task_e_pi05_eval/pi05_${CONFIG}_seed11_${STAMP}.mp4")
|
| 67 |
+
fi
|
| 68 |
+
"$ISAAC_PY" scripts/pi05/eval_task_e_pi05.py \
|
| 69 |
+
--episodes 1 \
|
| 70 |
+
--seed "$seed" \
|
| 71 |
+
--host 127.0.0.1 \
|
| 72 |
+
--port "$PORT" \
|
| 73 |
+
--action_repeat "$ACTION_REPEAT" \
|
| 74 |
+
--headless \
|
| 75 |
+
--disable_fabric \
|
| 76 |
+
"${video_arg[@]}" \
|
| 77 |
+
> "$EVAL_DIR/seed${seed}.log" 2>&1
|
| 78 |
+
tail -12 "$EVAL_DIR/seed${seed}.log"
|
| 79 |
+
done
|
| 80 |
+
|
| 81 |
+
"$ISAAC_PY" scripts/pi05/summarize_pi05_eval.py "$EVAL_DIR" || true
|
| 82 |
+
"$ISAAC_PY" scripts/pi05/compare_pi05_vs_act_baseline.py "$EVAL_DIR" --repo "$REPO" || true
|
| 83 |
+
echo "[INFO] Eval logs: $EVAL_DIR"
|
| 84 |
+
echo "[INFO] Server log: $SERVER_LOG"
|
scripts/pi05/run_pi05_native8_100demos_prepare.sh
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
REPO=/home/ubuntu/Documents/01Proj/13atec/ATEC2026_Simulation_Challenge
|
| 5 |
+
OPENPI=/home/ubuntu/src/openpi-ebench-clean
|
| 6 |
+
PY=/home/ubuntu/envs/openpi-pi05/bin/python
|
| 7 |
+
CONFIG=pi05_atec_task_e_native8_100demos_s1_224
|
| 8 |
+
REPO_ID=atec/task_e_obj321_servo_100demos_native8_s1_224
|
| 9 |
+
STAMP="$(date +%Y%m%d%H%M%S)"
|
| 10 |
+
|
| 11 |
+
export HF_LEROBOT_HOME=/data/Data4TB/01Proj/13atec/robotics_shared/datasets/lerobot
|
| 12 |
+
export HF_HOME=/data/Data4TB/01Proj/13atec/robotics_shared/hf_cache
|
| 13 |
+
export PYTHONPATH="$OPENPI/src:$OPENPI/packages/openpi-client/src"
|
| 14 |
+
|
| 15 |
+
cd "$REPO"
|
| 16 |
+
"$PY" scripts/pi05/convert_task_e_hdf5_to_lerobot_native8.py \
|
| 17 |
+
--root "$HF_LEROBOT_HOME" \
|
| 18 |
+
--repo_id "$REPO_ID" \
|
| 19 |
+
--max_episodes 100 \
|
| 20 |
+
--stride 1 \
|
| 21 |
+
--fps 50 \
|
| 22 |
+
--overwrite \
|
| 23 |
+
2>&1 | tee "logs/pi05_native8_convert_100demos_s1_224_${STAMP}.log"
|
| 24 |
+
|
| 25 |
+
cd "$OPENPI"
|
| 26 |
+
"$PY" scripts/compute_norm_stats.py \
|
| 27 |
+
--config-name "$CONFIG" \
|
| 28 |
+
2>&1 | tee "$REPO/logs/pi05_native8_norm_100demos_s1_224_${STAMP}.log"
|
| 29 |
+
|
| 30 |
+
echo "[INFO] Prepared native8 100-demo dataset/norm stats for $CONFIG"
|
scripts/pi05/run_pi05_native8_100demos_s2_gate.sh
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
REPO=/home/ubuntu/Documents/01Proj/13atec/ATEC2026_Simulation_Challenge
|
| 5 |
+
OPENPI=/home/ubuntu/src/openpi-ebench-clean
|
| 6 |
+
PY=/home/ubuntu/envs/openpi-pi05/bin/python
|
| 7 |
+
CONFIG=pi05_atec_task_e_native8_100demos_s2_224
|
| 8 |
+
REPO_ID=atec/task_e_obj321_servo_100demos_native8_s2_224
|
| 9 |
+
STAMP="${ATEC_PI05_STAMP:-$(date +%Y%m%d%H%M%S)}"
|
| 10 |
+
|
| 11 |
+
export HF_LEROBOT_HOME=/data/Data4TB/01Proj/13atec/robotics_shared/datasets/lerobot
|
| 12 |
+
export HF_HOME=/data/Data4TB/01Proj/13atec/robotics_shared/hf_cache
|
| 13 |
+
export PYTHONPATH="$OPENPI/src:$OPENPI/packages/openpi-client/src"
|
| 14 |
+
|
| 15 |
+
mkdir -p "$REPO/logs"
|
| 16 |
+
|
| 17 |
+
cd "$REPO"
|
| 18 |
+
"$PY" scripts/pi05/convert_task_e_hdf5_to_lerobot_native8.py \
|
| 19 |
+
--root "$HF_LEROBOT_HOME" \
|
| 20 |
+
--repo_id "$REPO_ID" \
|
| 21 |
+
--max_episodes 100 \
|
| 22 |
+
--stride 2 \
|
| 23 |
+
--fps 25 \
|
| 24 |
+
--overwrite \
|
| 25 |
+
2>&1 | tee "logs/pi05_native8_convert_100demos_s2_224_${STAMP}.log"
|
| 26 |
+
|
| 27 |
+
cd "$OPENPI"
|
| 28 |
+
"$PY" scripts/compute_norm_stats.py \
|
| 29 |
+
--config-name "$CONFIG" \
|
| 30 |
+
2>&1 | tee "$REPO/logs/pi05_native8_norm_100demos_s2_224_${STAMP}.log"
|
| 31 |
+
|
| 32 |
+
"$PY" scripts/train.py \
|
| 33 |
+
"$CONFIG" \
|
| 34 |
+
--exp-name "atec_task_e_pi05_native8_100demos_s2_224_10k_${STAMP}" \
|
| 35 |
+
--overwrite \
|
| 36 |
+
2>&1 | tee "$REPO/logs/pi05_native8_train_100demos_s2_224_${STAMP}.log"
|
| 37 |
+
|
| 38 |
+
CKPT_DIR="$(find /data/Data4TB/01Proj/13atec/openpi_atec_runs/checkpoints/"$CONFIG" -mindepth 2 -maxdepth 2 -type d -regex '.*/[0-9]+' 2>/dev/null | sort -V | tail -1 || true)"
|
| 39 |
+
if [[ -z "$CKPT_DIR" ]]; then
|
| 40 |
+
echo "[ERROR] No checkpoint found after training for $CONFIG" >&2
|
| 41 |
+
exit 1
|
| 42 |
+
fi
|
| 43 |
+
|
| 44 |
+
cd "$REPO"
|
| 45 |
+
CONFIG="$CONFIG" ACTION_REPEAT=2 PORT=8023 \
|
| 46 |
+
scripts/pi05/run_pi05_native8_eval_checkpoint.sh "$CKPT_DIR" \
|
| 47 |
+
2>&1 | tee "logs/pi05_native8_eval_100demos_s2_224_${STAMP}.log"
|
scripts/pi05/run_pi05_native8_100demos_s2_lora_gate.sh
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
REPO=/home/ubuntu/Documents/01Proj/13atec/ATEC2026_Simulation_Challenge
|
| 5 |
+
OPENPI=/home/ubuntu/src/openpi-ebench-clean
|
| 6 |
+
PY=/home/ubuntu/envs/openpi-pi05/bin/python
|
| 7 |
+
CONFIG=pi05_atec_task_e_native8_100demos_s2_224_lora
|
| 8 |
+
BASE_CONFIG=pi05_atec_task_e_native8_100demos_s2_224
|
| 9 |
+
REPO_ID=atec/task_e_obj321_servo_100demos_native8_s2_224
|
| 10 |
+
STAMP="${ATEC_PI05_STAMP:-$(date +%Y%m%d%H%M%S)}"
|
| 11 |
+
|
| 12 |
+
export HF_LEROBOT_HOME=/data/Data4TB/01Proj/13atec/robotics_shared/datasets/lerobot
|
| 13 |
+
export HF_HOME=/data/Data4TB/01Proj/13atec/robotics_shared/hf_cache
|
| 14 |
+
export PYTHONPATH="$OPENPI/src:$OPENPI/packages/openpi-client/src"
|
| 15 |
+
|
| 16 |
+
DATA_DIR="$HF_LEROBOT_HOME/$REPO_ID"
|
| 17 |
+
BASE_ASSET_DIR="/data/Data4TB/01Proj/13atec/openpi_atec_runs/assets/$BASE_CONFIG/$REPO_ID"
|
| 18 |
+
LORA_ASSET_DIR="/data/Data4TB/01Proj/13atec/openpi_atec_runs/assets/$CONFIG/$REPO_ID"
|
| 19 |
+
|
| 20 |
+
mkdir -p "$REPO/logs"
|
| 21 |
+
|
| 22 |
+
if [[ ! -d "$DATA_DIR" ]]; then
|
| 23 |
+
echo "[ERROR] Missing native8 100-demo dataset: $DATA_DIR" >&2
|
| 24 |
+
echo "[ERROR] Run scripts/pi05/run_pi05_native8_100demos_s2_gate.sh once before LoRA." >&2
|
| 25 |
+
exit 1
|
| 26 |
+
fi
|
| 27 |
+
|
| 28 |
+
if [[ -f "$BASE_ASSET_DIR/norm_stats.json" ]]; then
|
| 29 |
+
mkdir -p "$LORA_ASSET_DIR"
|
| 30 |
+
cp "$BASE_ASSET_DIR/norm_stats.json" "$LORA_ASSET_DIR/norm_stats.json"
|
| 31 |
+
echo "[INFO] Reused norm stats from $BASE_ASSET_DIR"
|
| 32 |
+
else
|
| 33 |
+
cd "$OPENPI"
|
| 34 |
+
"$PY" scripts/compute_norm_stats.py \
|
| 35 |
+
--config-name "$CONFIG" \
|
| 36 |
+
2>&1 | tee "$REPO/logs/pi05_native8_lora_norm_100demos_s2_224_${STAMP}.log"
|
| 37 |
+
fi
|
| 38 |
+
|
| 39 |
+
cd "$OPENPI"
|
| 40 |
+
"$PY" scripts/train.py \
|
| 41 |
+
"$CONFIG" \
|
| 42 |
+
--exp-name "atec_task_e_pi05_native8_100demos_s2_224_lora_7500_${STAMP}" \
|
| 43 |
+
--overwrite \
|
| 44 |
+
2>&1 | tee "$REPO/logs/pi05_native8_lora_train_100demos_s2_224_${STAMP}.log"
|
| 45 |
+
|
| 46 |
+
CKPT_DIR="$(find /data/Data4TB/01Proj/13atec/openpi_atec_runs/checkpoints/"$CONFIG" -mindepth 2 -maxdepth 2 -type d -regex '.*/[0-9]+' 2>/dev/null | sort -V | tail -1 || true)"
|
| 47 |
+
if [[ -z "$CKPT_DIR" ]]; then
|
| 48 |
+
echo "[ERROR] No checkpoint found after training for $CONFIG" >&2
|
| 49 |
+
exit 1
|
| 50 |
+
fi
|
| 51 |
+
|
| 52 |
+
cd "$REPO"
|
| 53 |
+
CONFIG="$CONFIG" ACTION_REPEAT=2 PORT=8024 \
|
| 54 |
+
scripts/pi05/run_pi05_native8_eval_checkpoint.sh "$CKPT_DIR" \
|
| 55 |
+
2>&1 | tee "logs/pi05_native8_lora_eval_100demos_s2_224_${STAMP}.log"
|
scripts/pi05/run_pi05_native8_20demos_s2_smoke.sh
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
REPO=/home/ubuntu/Documents/01Proj/13atec/ATEC2026_Simulation_Challenge
|
| 5 |
+
OPENPI=/home/ubuntu/src/openpi-ebench-clean
|
| 6 |
+
PY=/home/ubuntu/envs/openpi-pi05/bin/python
|
| 7 |
+
CONFIG=pi05_atec_task_e_native8_20demos_s2_224
|
| 8 |
+
REPO_ID=atec/task_e_obj321_servo_20demos_native8_s2_224
|
| 9 |
+
STAMP="$(date +%Y%m%d%H%M%S)"
|
| 10 |
+
|
| 11 |
+
export HF_LEROBOT_HOME=/data/Data4TB/01Proj/13atec/robotics_shared/datasets/lerobot
|
| 12 |
+
export HF_HOME=/data/Data4TB/01Proj/13atec/robotics_shared/hf_cache
|
| 13 |
+
export PYTHONPATH="$OPENPI/src:$OPENPI/packages/openpi-client/src"
|
| 14 |
+
|
| 15 |
+
cd "$REPO"
|
| 16 |
+
"$PY" scripts/pi05/convert_task_e_hdf5_to_lerobot_native8.py \
|
| 17 |
+
--root "$HF_LEROBOT_HOME" \
|
| 18 |
+
--repo_id "$REPO_ID" \
|
| 19 |
+
--max_episodes 20 \
|
| 20 |
+
--stride 2 \
|
| 21 |
+
--fps 25 \
|
| 22 |
+
--overwrite \
|
| 23 |
+
2>&1 | tee "logs/pi05_native8_convert_20demos_s2_224_${STAMP}.log"
|
| 24 |
+
|
| 25 |
+
cd "$OPENPI"
|
| 26 |
+
"$PY" scripts/compute_norm_stats.py \
|
| 27 |
+
--config-name "$CONFIG" \
|
| 28 |
+
2>&1 | tee "$REPO/logs/pi05_native8_norm_20demos_s2_224_${STAMP}.log"
|
| 29 |
+
|
| 30 |
+
"$PY" scripts/train.py \
|
| 31 |
+
"$CONFIG" \
|
| 32 |
+
--exp-name "atec_task_e_pi05_native8_20demos_s2_224_3k_${STAMP}" \
|
| 33 |
+
--overwrite \
|
| 34 |
+
2>&1 | tee "$REPO/logs/pi05_native8_train_20demos_s2_224_${STAMP}.log"
|
| 35 |
+
|
| 36 |
+
CKPT_DIR="$(find /data/Data4TB/01Proj/13atec/openpi_atec_runs/checkpoints/"$CONFIG" -mindepth 2 -maxdepth 2 -type d -regex '.*/[0-9]+' 2>/dev/null | sort -V | tail -1 || true)"
|
| 37 |
+
if [[ -z "$CKPT_DIR" ]]; then
|
| 38 |
+
echo "[ERROR] No checkpoint found after training for $CONFIG" >&2
|
| 39 |
+
exit 1
|
| 40 |
+
fi
|
| 41 |
+
|
| 42 |
+
cd "$REPO"
|
| 43 |
+
CONFIG="$CONFIG" ACTION_REPEAT=2 PORT=8022 \
|
| 44 |
+
scripts/pi05/run_pi05_native8_eval_checkpoint.sh "$CKPT_DIR" \
|
| 45 |
+
2>&1 | tee "logs/pi05_native8_eval_20demos_s2_224_${STAMP}.log"
|
scripts/pi05/run_pi05_native8_20demos_smoke.sh
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
REPO=/home/ubuntu/Documents/01Proj/13atec/ATEC2026_Simulation_Challenge
|
| 5 |
+
OPENPI=/home/ubuntu/src/openpi-ebench-clean
|
| 6 |
+
PY=/home/ubuntu/envs/openpi-pi05/bin/python
|
| 7 |
+
CONFIG=pi05_atec_task_e_native8_20demos_s1_224
|
| 8 |
+
REPO_ID=atec/task_e_obj321_servo_20demos_native8_s1_224
|
| 9 |
+
STAMP="$(date +%Y%m%d%H%M%S)"
|
| 10 |
+
|
| 11 |
+
export HF_LEROBOT_HOME=/data/Data4TB/01Proj/13atec/robotics_shared/datasets/lerobot
|
| 12 |
+
export HF_HOME=/data/Data4TB/01Proj/13atec/robotics_shared/hf_cache
|
| 13 |
+
export PYTHONPATH="$OPENPI/src:$OPENPI/packages/openpi-client/src"
|
| 14 |
+
|
| 15 |
+
cd "$REPO"
|
| 16 |
+
"$PY" scripts/pi05/convert_task_e_hdf5_to_lerobot_native8.py \
|
| 17 |
+
--root "$HF_LEROBOT_HOME" \
|
| 18 |
+
--repo_id "$REPO_ID" \
|
| 19 |
+
--max_episodes 20 \
|
| 20 |
+
--stride 1 \
|
| 21 |
+
--fps 50 \
|
| 22 |
+
--overwrite \
|
| 23 |
+
2>&1 | tee "logs/pi05_native8_convert_20demos_s1_224_${STAMP}.log"
|
| 24 |
+
|
| 25 |
+
cd "$OPENPI"
|
| 26 |
+
"$PY" scripts/compute_norm_stats.py \
|
| 27 |
+
--config-name "$CONFIG" \
|
| 28 |
+
2>&1 | tee "$REPO/logs/pi05_native8_norm_20demos_s1_224_${STAMP}.log"
|
| 29 |
+
|
| 30 |
+
"$PY" scripts/train.py \
|
| 31 |
+
"$CONFIG" \
|
| 32 |
+
--exp-name "atec_task_e_pi05_native8_20demos_s1_224_5k_${STAMP}" \
|
| 33 |
+
--overwrite \
|
| 34 |
+
2>&1 | tee "$REPO/logs/pi05_native8_train_20demos_s1_224_${STAMP}.log"
|
scripts/pi05/run_pi05_native8_4demos_s2_sanity.sh
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
REPO=/home/ubuntu/Documents/01Proj/13atec/ATEC2026_Simulation_Challenge
|
| 5 |
+
OPENPI=/home/ubuntu/src/openpi-ebench-clean
|
| 6 |
+
PY=/home/ubuntu/envs/openpi-pi05/bin/python
|
| 7 |
+
CONFIG=pi05_atec_task_e_native8_4demos_s2_224
|
| 8 |
+
REPO_ID=atec/task_e_obj321_servo_4demos_native8_s2_224
|
| 9 |
+
STAMP="$(date +%Y%m%d%H%M%S)"
|
| 10 |
+
|
| 11 |
+
export HF_LEROBOT_HOME=/data/Data4TB/01Proj/13atec/robotics_shared/datasets/lerobot
|
| 12 |
+
export HF_HOME=/data/Data4TB/01Proj/13atec/robotics_shared/hf_cache
|
| 13 |
+
export PYTHONPATH="$OPENPI/src:$OPENPI/packages/openpi-client/src"
|
| 14 |
+
|
| 15 |
+
cd "$REPO"
|
| 16 |
+
"$PY" scripts/pi05/convert_task_e_hdf5_to_lerobot_native8.py \
|
| 17 |
+
--root "$HF_LEROBOT_HOME" \
|
| 18 |
+
--repo_id "$REPO_ID" \
|
| 19 |
+
--max_episodes 4 \
|
| 20 |
+
--stride 2 \
|
| 21 |
+
--fps 25 \
|
| 22 |
+
--overwrite \
|
| 23 |
+
2>&1 | tee "logs/pi05_native8_convert_4demos_s2_224_${STAMP}.log"
|
| 24 |
+
|
| 25 |
+
cd "$OPENPI"
|
| 26 |
+
"$PY" scripts/compute_norm_stats.py \
|
| 27 |
+
--config-name "$CONFIG" \
|
| 28 |
+
2>&1 | tee "$REPO/logs/pi05_native8_norm_4demos_s2_224_${STAMP}.log"
|
| 29 |
+
|
| 30 |
+
"$PY" scripts/train.py \
|
| 31 |
+
"$CONFIG" \
|
| 32 |
+
--exp-name "atec_task_e_pi05_native8_4demos_s2_224_1k_${STAMP}" \
|
| 33 |
+
--overwrite \
|
| 34 |
+
2>&1 | tee "$REPO/logs/pi05_native8_train_4demos_s2_224_${STAMP}.log"
|
| 35 |
+
|
| 36 |
+
CKPT_DIR="$(find /data/Data4TB/01Proj/13atec/openpi_atec_runs/checkpoints/"$CONFIG" -mindepth 2 -maxdepth 2 -type d -regex '.*/[0-9]+' 2>/dev/null | sort -V | tail -1 || true)"
|
| 37 |
+
if [[ -z "$CKPT_DIR" ]]; then
|
| 38 |
+
echo "[ERROR] No checkpoint found after training for $CONFIG" >&2
|
| 39 |
+
exit 1
|
| 40 |
+
fi
|
| 41 |
+
|
| 42 |
+
cd "$REPO"
|
| 43 |
+
CONFIG="$CONFIG" ACTION_REPEAT=2 PORT=8023 MAX_STEPS=2200 \
|
| 44 |
+
scripts/pi05/run_pi05_native8_eval_checkpoint.sh "$CKPT_DIR" \
|
| 45 |
+
2>&1 | tee "logs/pi05_native8_eval_4demos_s2_224_${STAMP}.log"
|
scripts/pi05/run_pi05_native8_eval_checkpoint.sh
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
REPO=/home/ubuntu/Documents/01Proj/13atec/ATEC2026_Simulation_Challenge
|
| 5 |
+
OPENPI=/home/ubuntu/src/openpi-ebench-clean
|
| 6 |
+
OPENPI_PY=/home/ubuntu/envs/openpi-pi05/bin/python
|
| 7 |
+
ISAAC_PY=/home/ubuntu/envs/genmanip-isaac5-py311/bin/python
|
| 8 |
+
|
| 9 |
+
CONFIG="${CONFIG:-pi05_atec_task_e_native8_20demos_s1_224}"
|
| 10 |
+
CHECKPOINT_DIR="${1:-${CHECKPOINT_DIR:-}}"
|
| 11 |
+
PORT="${PORT:-8021}"
|
| 12 |
+
ACTION_REPEAT="${ACTION_REPEAT:-1}"
|
| 13 |
+
MAX_STEPS="${MAX_STEPS:-2200}"
|
| 14 |
+
SEEDS="${SEEDS:-11 12 13}"
|
| 15 |
+
STAMP="$(date +%Y%m%d%H%M%S)"
|
| 16 |
+
SERVER_LOG="$REPO/logs/pi05_native8_policy_server_${STAMP}.log"
|
| 17 |
+
EVAL_DIR="$REPO/logs/pi05_native8_eval_${STAMP}"
|
| 18 |
+
|
| 19 |
+
if [[ -z "$CHECKPOINT_DIR" ]]; then
|
| 20 |
+
CHECKPOINT_DIR="$(find /data/Data4TB/01Proj/13atec/openpi_atec_runs/checkpoints/"$CONFIG" -mindepth 2 -maxdepth 2 -type d -regex '.*/[0-9]+' 2>/dev/null | sort -V | tail -1 || true)"
|
| 21 |
+
fi
|
| 22 |
+
if [[ -z "$CHECKPOINT_DIR" || ! -d "$CHECKPOINT_DIR" ]]; then
|
| 23 |
+
echo "[ERROR] Checkpoint dir not found. Pass it as argv[1] or set CHECKPOINT_DIR." >&2
|
| 24 |
+
exit 1
|
| 25 |
+
fi
|
| 26 |
+
|
| 27 |
+
mkdir -p "$EVAL_DIR" "$REPO/logs/videos/task_e_pi05_native8_eval"
|
| 28 |
+
|
| 29 |
+
export HF_LEROBOT_HOME=/data/Data4TB/01Proj/13atec/robotics_shared/datasets/lerobot
|
| 30 |
+
export HF_HOME=/data/Data4TB/01Proj/13atec/robotics_shared/hf_cache
|
| 31 |
+
export PYTHONPATH="$OPENPI/src:$OPENPI/packages/openpi-client/src"
|
| 32 |
+
|
| 33 |
+
cd "$OPENPI"
|
| 34 |
+
"$OPENPI_PY" scripts/serve_policy.py \
|
| 35 |
+
--port "$PORT" \
|
| 36 |
+
policy:checkpoint \
|
| 37 |
+
--policy.config "$CONFIG" \
|
| 38 |
+
--policy.dir "$CHECKPOINT_DIR" \
|
| 39 |
+
> "$SERVER_LOG" 2>&1 &
|
| 40 |
+
server_pid=$!
|
| 41 |
+
|
| 42 |
+
cleanup() {
|
| 43 |
+
kill "$server_pid" 2>/dev/null || true
|
| 44 |
+
}
|
| 45 |
+
trap cleanup EXIT
|
| 46 |
+
|
| 47 |
+
echo "[INFO] Started OpenPI native8 server pid=$server_pid port=$PORT checkpoint=$CHECKPOINT_DIR"
|
| 48 |
+
for _ in $(seq 1 120); do
|
| 49 |
+
if grep -q "Creating server" "$SERVER_LOG" 2>/dev/null; then
|
| 50 |
+
break
|
| 51 |
+
fi
|
| 52 |
+
if ! kill -0 "$server_pid" 2>/dev/null; then
|
| 53 |
+
echo "[ERROR] OpenPI server exited early. Tail:" >&2
|
| 54 |
+
tail -80 "$SERVER_LOG" >&2 || true
|
| 55 |
+
exit 1
|
| 56 |
+
fi
|
| 57 |
+
sleep 5
|
| 58 |
+
done
|
| 59 |
+
|
| 60 |
+
export OMNI_KIT_ACCEPT_EULA=YES
|
| 61 |
+
export PYTHONUNBUFFERED=1
|
| 62 |
+
export PYTHONPATH="/home/ubuntu/envs/genmanip-isaac5-py311/lib/python3.11/site-packages/isaaclab/source/isaaclab:/home/ubuntu/envs/genmanip-isaac5-py311/lib/python3.11/site-packages/isaaclab/source/isaaclab_assets:/home/ubuntu/envs/genmanip-isaac5-py311/lib/python3.11/site-packages/isaaclab/source/isaaclab_tasks:$REPO/source/atec_rl_lab:$REPO/scripts/act"
|
| 63 |
+
|
| 64 |
+
cd "$REPO"
|
| 65 |
+
for seed in $SEEDS; do
|
| 66 |
+
video_arg=()
|
| 67 |
+
if [[ "$seed" == "11" ]]; then
|
| 68 |
+
video_arg=(--video_path "$REPO/logs/videos/task_e_pi05_native8_eval/pi05_native8_${CONFIG}_seed11_${STAMP}.mp4")
|
| 69 |
+
fi
|
| 70 |
+
"$ISAAC_PY" scripts/pi05/eval_task_e_pi05.py \
|
| 71 |
+
--episodes 1 \
|
| 72 |
+
--seed "$seed" \
|
| 73 |
+
--host 127.0.0.1 \
|
| 74 |
+
--port "$PORT" \
|
| 75 |
+
--action_repeat "$ACTION_REPEAT" \
|
| 76 |
+
--max_steps "$MAX_STEPS" \
|
| 77 |
+
--solution_module solution_pi05_native8 \
|
| 78 |
+
--headless \
|
| 79 |
+
--disable_fabric \
|
| 80 |
+
"${video_arg[@]}" \
|
| 81 |
+
> "$EVAL_DIR/seed${seed}.log" 2>&1
|
| 82 |
+
tail -12 "$EVAL_DIR/seed${seed}.log"
|
| 83 |
+
done
|
| 84 |
+
|
| 85 |
+
"$ISAAC_PY" scripts/pi05/summarize_pi05_eval.py "$EVAL_DIR" || true
|
| 86 |
+
echo "[INFO] Eval logs: $EVAL_DIR"
|
| 87 |
+
echo "[INFO] Server log: $SERVER_LOG"
|
scripts/pi05/run_pi05_native8_rawabs_1demo_s10_aefull_h10_10k_lr5.sh
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
REPO=/home/ubuntu/Documents/01Proj/13atec/ATEC2026_Simulation_Challenge
|
| 5 |
+
OPENPI=/home/ubuntu/src/openpi-ebench-clean
|
| 6 |
+
PY=/home/ubuntu/envs/openpi-pi05/bin/python
|
| 7 |
+
CONFIG=pi05_atec_task_e_native8_rawabs_1demo_s10_224_aefull_h10_10k_lr5
|
| 8 |
+
DATASET_DIR=/data/Data4TB/01Proj/13atec/robotics_shared/datasets/lerobot/atec/task_e_obj321_servo_rawabs_1demo_native8_s10_224
|
| 9 |
+
STAMP="${ATEC_PI05_STAMP:-$(date +%Y%m%d%H%M%S)}"
|
| 10 |
+
|
| 11 |
+
export HF_LEROBOT_HOME=/data/Data4TB/01Proj/13atec/robotics_shared/datasets/lerobot
|
| 12 |
+
export HF_HOME=/data/Data4TB/01Proj/13atec/robotics_shared/hf_cache
|
| 13 |
+
export PYTHONPATH="$OPENPI/src:$OPENPI/packages/openpi-client/src"
|
| 14 |
+
|
| 15 |
+
mkdir -p "$REPO/logs"
|
| 16 |
+
|
| 17 |
+
if [[ ! -d "$DATASET_DIR" ]]; then
|
| 18 |
+
echo "[ERROR] Missing dataset: $DATASET_DIR" >&2
|
| 19 |
+
exit 1
|
| 20 |
+
fi
|
| 21 |
+
|
| 22 |
+
cd "$OPENPI"
|
| 23 |
+
"$PY" scripts/compute_norm_stats.py \
|
| 24 |
+
--config-name "$CONFIG" \
|
| 25 |
+
2>&1 | tee "$REPO/logs/pi05_native8_rawabs_norm_1demo_s10_224_aefull_h10_10k_lr5_${STAMP}.log"
|
| 26 |
+
|
| 27 |
+
"$PY" scripts/train.py \
|
| 28 |
+
"$CONFIG" \
|
| 29 |
+
--exp-name "atec_task_e_pi05_native8_rawabs_1demo_s10_224_aefull_h10_10k_lr5_${STAMP}" \
|
| 30 |
+
--overwrite \
|
| 31 |
+
2>&1 | tee "$REPO/logs/pi05_native8_rawabs_train_1demo_s10_224_aefull_h10_10k_lr5_${STAMP}.log"
|
scripts/pi05/run_pi05_native8_rawabs_1demo_s10_aefull_h10_2k.sh
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
REPO=/home/ubuntu/Documents/01Proj/13atec/ATEC2026_Simulation_Challenge
|
| 5 |
+
OPENPI=/home/ubuntu/src/openpi-ebench-clean
|
| 6 |
+
PY=/home/ubuntu/envs/openpi-pi05/bin/python
|
| 7 |
+
CONFIG=pi05_atec_task_e_native8_rawabs_1demo_s10_224_aefull_h10_2k
|
| 8 |
+
DATASET_DIR=/data/Data4TB/01Proj/13atec/robotics_shared/datasets/lerobot/atec/task_e_obj321_servo_rawabs_1demo_native8_s10_224
|
| 9 |
+
STAMP="${ATEC_PI05_STAMP:-$(date +%Y%m%d%H%M%S)}"
|
| 10 |
+
|
| 11 |
+
export HF_LEROBOT_HOME=/data/Data4TB/01Proj/13atec/robotics_shared/datasets/lerobot
|
| 12 |
+
export HF_HOME=/data/Data4TB/01Proj/13atec/robotics_shared/hf_cache
|
| 13 |
+
export PYTHONPATH="$OPENPI/src:$OPENPI/packages/openpi-client/src"
|
| 14 |
+
|
| 15 |
+
mkdir -p "$REPO/logs"
|
| 16 |
+
|
| 17 |
+
if [[ ! -d "$DATASET_DIR" ]]; then
|
| 18 |
+
echo "[ERROR] Missing dataset: $DATASET_DIR" >&2
|
| 19 |
+
exit 1
|
| 20 |
+
fi
|
| 21 |
+
|
| 22 |
+
cd "$OPENPI"
|
| 23 |
+
"$PY" scripts/compute_norm_stats.py \
|
| 24 |
+
--config-name "$CONFIG" \
|
| 25 |
+
2>&1 | tee "$REPO/logs/pi05_native8_rawabs_norm_1demo_s10_224_aefull_h10_2k_${STAMP}.log"
|
| 26 |
+
|
| 27 |
+
"$PY" scripts/train.py \
|
| 28 |
+
"$CONFIG" \
|
| 29 |
+
--exp-name "atec_task_e_pi05_native8_rawabs_1demo_s10_224_aefull_h10_2k_${STAMP}" \
|
| 30 |
+
--overwrite \
|
| 31 |
+
2>&1 | tee "$REPO/logs/pi05_native8_rawabs_train_1demo_s10_224_aefull_h10_2k_${STAMP}.log"
|