Upload 264 files
#1
by WuJ1ng13 - opened
This view is limited to 50 files because it contains too many changes. See the raw diff here.
- .gitattributes +1 -0
- VLA-Adapter-UAV/eval_logs/Inference--CALVIN_Pro--4.50.log +3 -0
- VLA-Adapter-UAV/eval_logs/Inference--Long_Pro--96.4.log +0 -0
- VLA-Adapter-UAV/eval_logs/Inference--Object_Pro--99.6.log +0 -0
- VLA-Adapter-UAV/eval_logs/Inference--Spatial_Pro--99.6.log +0 -0
- VLA-Adapter-UAV/eval_logs/Inference-Goal--97.2.log +0 -0
- VLA-Adapter-UAV/eval_logs/Inference-Goal_Pro--98.2.log +0 -0
- VLA-Adapter-UAV/eval_logs/Inference-Long--95.0.log +0 -0
- VLA-Adapter-UAV/eval_logs/Inference-Object--99.2.log +0 -0
- VLA-Adapter-UAV/eval_logs/Inference-Spatial--97.8.log +0 -0
- VLA-Adapter-UAV/experiments/robot/__pycache__/openvla_utils.cpython-310.pyc +0 -0
- VLA-Adapter-UAV/experiments/robot/aloha/README.md +251 -0
- VLA-Adapter-UAV/experiments/robot/aloha/demo/sandwich_assembly_bimanual_demo.mp4 +3 -0
- VLA-Adapter-UAV/experiments/robot/aloha/eval_files/deploy_server.sh +14 -0
- VLA-Adapter-UAV/experiments/robot/aloha/eval_files/run_eval_client.sh +15 -0
- VLA-Adapter-UAV/experiments/robot/aloha/eval_files/run_eval_client_fake.sh +15 -0
- VLA-Adapter-UAV/experiments/robot/aloha/requirements_aloha.txt +29 -0
- VLA-Adapter-UAV/experiments/robot/aloha/run_cobot_client.py +681 -0
- VLA-Adapter-UAV/experiments/robot/aloha/run_fake_cobot_client.py +310 -0
- VLA-Adapter-UAV/experiments/robot/aloha/train_files/dinosiglip_vit_local_vision.py +215 -0
- VLA-Adapter-UAV/experiments/robot/aloha/train_files/download_models.sh +53 -0
- VLA-Adapter-UAV/experiments/robot/aloha/train_files/materialize_local_vision.py +183 -0
- VLA-Adapter-UAV/experiments/robot/aloha/train_files/qwen25.py +86 -0
- VLA-Adapter-UAV/experiments/robot/aloha/train_files/setup_training.sh +159 -0
- VLA-Adapter-UAV/experiments/robot/aloha/train_files/train_aloha.sh +91 -0
- VLA-Adapter-UAV/experiments/robot/libero/libero_requirements.txt +6 -0
- VLA-Adapter-UAV/experiments/robot/libero/libero_utils.py +87 -0
- VLA-Adapter-UAV/experiments/robot/libero/regenerate_libero_dataset.py +249 -0
- VLA-Adapter-UAV/experiments/robot/libero/run_libero_eval.py +555 -0
- VLA-Adapter-UAV/experiments/robot/libero/sample_libero_spatial_observation.pkl +3 -0
- VLA-Adapter-UAV/experiments/robot/openvla_utils.py +850 -0
- VLA-Adapter-UAV/experiments/robot/robot_utils.py +279 -0
- VLA-Adapter-UAV/experiments/robot/server_deploy/deploy.py +226 -0
- VLA-Adapter-UAV/prismatic/__init__.py +1 -0
- VLA-Adapter-UAV/prismatic/__pycache__/__init__.cpython-310.pyc +0 -0
- VLA-Adapter-UAV/prismatic/__pycache__/__init__.cpython-312.pyc +0 -0
- VLA-Adapter-UAV/prismatic/conf/__init__.py +3 -0
- VLA-Adapter-UAV/prismatic/conf/__pycache__/__init__.cpython-310.pyc +0 -0
- VLA-Adapter-UAV/prismatic/conf/__pycache__/__init__.cpython-312.pyc +0 -0
- VLA-Adapter-UAV/prismatic/conf/__pycache__/datasets.cpython-310.pyc +0 -0
- VLA-Adapter-UAV/prismatic/conf/__pycache__/datasets.cpython-312.pyc +0 -0
- VLA-Adapter-UAV/prismatic/conf/__pycache__/models.cpython-310.pyc +0 -0
- VLA-Adapter-UAV/prismatic/conf/__pycache__/vla.cpython-310.pyc +0 -0
- VLA-Adapter-UAV/prismatic/conf/datasets.py +133 -0
- VLA-Adapter-UAV/prismatic/conf/models.py +614 -0
- VLA-Adapter-UAV/prismatic/conf/vla.py +319 -0
- VLA-Adapter-UAV/prismatic/extern/__init__.py +0 -0
- VLA-Adapter-UAV/prismatic/extern/__pycache__/__init__.cpython-310.pyc +0 -0
- VLA-Adapter-UAV/prismatic/extern/hf/__init__.py +0 -0
- VLA-Adapter-UAV/prismatic/extern/hf/__pycache__/__init__.cpython-310.pyc +0 -0
.gitattributes
CHANGED
|
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 61 |
+
VLA-Adapter-UAV/eval_logs/Inference--CALVIN_Pro--4.50.log filter=lfs diff=lfs merge=lfs -text
|
VLA-Adapter-UAV/eval_logs/Inference--CALVIN_Pro--4.50.log
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:34b6827c00a51d32673100c0259341ba2e8e94d91e70daa054c2fd8025063ebe
|
| 3 |
+
size 14522527
|
VLA-Adapter-UAV/eval_logs/Inference--Long_Pro--96.4.log
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
VLA-Adapter-UAV/eval_logs/Inference--Object_Pro--99.6.log
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
VLA-Adapter-UAV/eval_logs/Inference--Spatial_Pro--99.6.log
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
VLA-Adapter-UAV/eval_logs/Inference-Goal--97.2.log
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
VLA-Adapter-UAV/eval_logs/Inference-Goal_Pro--98.2.log
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
VLA-Adapter-UAV/eval_logs/Inference-Long--95.0.log
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
VLA-Adapter-UAV/eval_logs/Inference-Object--99.2.log
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
VLA-Adapter-UAV/eval_logs/Inference-Spatial--97.8.log
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
VLA-Adapter-UAV/experiments/robot/__pycache__/openvla_utils.cpython-310.pyc
ADDED
|
Binary file (22 kB). View file
|
|
|
VLA-Adapter-UAV/experiments/robot/aloha/README.md
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<div align="center">
|
| 2 |
+
|
| 3 |
+
## Demo
|
| 4 |
+
|
| 5 |
+
<video src="https://github.com/user-attachments/assets/63538db5-c776-40d9-8909-802e4c599eef" controls width="80%"></video>
|
| 6 |
+
|
| 7 |
+
<br>
|
| 8 |
+
|
| 9 |
+
**Sandwich Assembly** — Pick bread from rack → place on tray → add lettuce → add ham → cover with bread
|
| 10 |
+
|
| 11 |
+
<sub>Cobot Magic | Bimanual 14-DOF | 3-Camera | 2× Speed</sub>
|
| 12 |
+
|
| 13 |
+
</div>
|
| 14 |
+
|
| 15 |
+
---
|
| 16 |
+
|
| 17 |
+
# ALOHA Real-World
|
| 18 |
+
|
| 19 |
+
Training, deployment, and evaluation pipeline for the ALOHA bimanual robot. For base installation, see the project root [`README.md`](../../../README.md). Successfully verified on [Cobot Magic](https://global.agilex.ai/products/cobot-magic).
|
| 20 |
+
|
| 21 |
+
## Directory Structure
|
| 22 |
+
|
| 23 |
+
```
|
| 24 |
+
experiments/robot/aloha/
|
| 25 |
+
├── train_files/
|
| 26 |
+
│ ├── train_aloha.sh # Training launcher (4-GPU torchrun)
|
| 27 |
+
│ ├── setup_training.sh # Dataset registration + optional local model loading
|
| 28 |
+
│ ├── download_models.sh # Download pretrained models (Qwen, DINOv2, SigLIP, Prismatic VLM)
|
| 29 |
+
│ ├── qwen25.py # Drop-in replacement for local Qwen loading
|
| 30 |
+
│ ├── materialize_local_vision.py # Drop-in replacement for local vision model loading
|
| 31 |
+
│ └── dinosiglip_vit_local_vision.py # Drop-in replacement for local DINOv2+SigLIP loading
|
| 32 |
+
├── eval_files/
|
| 33 |
+
│ ├── deploy_server.sh # Launch inference server (MsgPack HTTP)
|
| 34 |
+
│ ├── run_eval_client.sh # Real robot client (requires ROS)
|
| 35 |
+
│ └── run_eval_client_fake.sh # Fake-data client (no ROS needed, for sanity-checking the pipeline)
|
| 36 |
+
├── run_cobot_client.py # Real ROS inference loop (3 cameras + bimanual 14-DOF)
|
| 37 |
+
├── run_fake_cobot_client.py # Fake-data inference loop (generates synthetic observations)
|
| 38 |
+
├── requirements_aloha.txt # ALOHA-specific dependencies
|
| 39 |
+
└── README.md
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
## Prerequisites
|
| 43 |
+
|
| 44 |
+
After completing the base installation from the root directory, install the ALOHA-specific dependencies:
|
| 45 |
+
|
| 46 |
+
```bash
|
| 47 |
+
pip install -r experiments/robot/aloha/requirements_aloha.txt
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
> **Real-robot deployment only**: `run_cobot_client.py` depends on ROS (`rospy`, `cv_bridge`, `sensor_msgs`, etc.) and must be run inside a ROS environment on the robot machine. The fake client `run_fake_cobot_client.py` does not require ROS.
|
| 51 |
+
|
| 52 |
+
## Sanity Check: Verify the Inference Pipeline
|
| 53 |
+
|
| 54 |
+
To confirm the inference pipeline works end-to-end without training, download an example checkpoint and run the server + fake client.
|
| 55 |
+
|
| 56 |
+
```bash
|
| 57 |
+
# 1. Download the example checkpoint
|
| 58 |
+
huggingface-cli download --resume-download SII-CDZ/test_aloha_adapter \
|
| 59 |
+
--local-dir /path/to/SII-CDZ/test_aloha_adapter
|
| 60 |
+
|
| 61 |
+
# 2. Start the inference server (set PRETRAINED_CHECKPOINT in deploy_server.sh to the path above)
|
| 62 |
+
bash experiments/robot/aloha/eval_files/deploy_server.sh
|
| 63 |
+
|
| 64 |
+
# 3. In another terminal, run the fake-data client (no ROS / real robot required)
|
| 65 |
+
bash experiments/robot/aloha/eval_files/run_eval_client_fake.sh
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
The fake client sends synthetic 480x640x3 images and 14-DOF joint states to the server and checks whether action sequences are returned correctly. See [Deployment](#deployment) for detailed configuration.
|
| 69 |
+
|
| 70 |
+
## Pipeline
|
| 71 |
+
|
| 72 |
+
```bash
|
| 73 |
+
# 0. (Optional) Download pretrained models locally
|
| 74 |
+
bash experiments/robot/aloha/train_files/download_models.sh
|
| 75 |
+
|
| 76 |
+
# 1. Convert hdf5 real-robot data to TFDS format
|
| 77 |
+
# See: https://github.com/cheng-haha/rlds_sim/tree/main/aloha_realworld
|
| 78 |
+
|
| 79 |
+
# 2. Register the dataset
|
| 80 |
+
bash experiments/robot/aloha/train_files/setup_training.sh <dataset_name>
|
| 81 |
+
|
| 82 |
+
# 3. Train
|
| 83 |
+
bash experiments/robot/aloha/train_files/train_aloha.sh
|
| 84 |
+
|
| 85 |
+
# 4. Launch the inference server
|
| 86 |
+
bash experiments/robot/aloha/eval_files/deploy_server.sh
|
| 87 |
+
|
| 88 |
+
# 5. Run client-side evaluation
|
| 89 |
+
bash experiments/robot/aloha/eval_files/run_eval_client_fake.sh # fake-data sanity check
|
| 90 |
+
bash experiments/robot/aloha/eval_files/run_eval_client.sh # real-robot evaluation
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
## Training
|
| 94 |
+
|
| 95 |
+
<details>
|
| 96 |
+
<summary><b>Local Model Download (Optional)</b></summary>
|
| 97 |
+
|
| 98 |
+
If you cannot access the HF Hub or prefer fully offline training, download all pretrained models in advance:
|
| 99 |
+
|
| 100 |
+
```bash
|
| 101 |
+
bash experiments/robot/aloha/train_files/download_models.sh
|
| 102 |
+
# Or specify an HF token for private repos
|
| 103 |
+
HF_TOKEN=hf_xxx bash experiments/robot/aloha/train_files/download_models.sh
|
| 104 |
+
```
|
| 105 |
+
|
| 106 |
+
Models downloaded:
|
| 107 |
+
|
| 108 |
+
| Model | Local Path |
|
| 109 |
+
|-------|------------|
|
| 110 |
+
| `timm/vit_large_patch14_reg4_dinov2.lvd142m` | `${ROOT_DIR}/ai_models/timm/...` |
|
| 111 |
+
| `timm/ViT-SO400M-14-SigLIP` | `${ROOT_DIR}/ai_models/timm/...` |
|
| 112 |
+
| `Qwen/Qwen2.5-0.5B` | `${ROOT_DIR}/ai_models/Qwen/Qwen2.5-0.5B` |
|
| 113 |
+
| `Stanford-ILIAD/prism-qwen25-extra-dinosiglip-224px-0_5b` | `${ROOT_DIR}/ai_models/Stanford-ILIAD/...` |
|
| 114 |
+
|
| 115 |
+
After using the `--local-models` flag, `setup_training.sh` patches the project source files (`qwen25.py`, `materialize.py`, `dinosiglip_vit.py`) with local paths. To revert to online loading:
|
| 116 |
+
|
| 117 |
+
```bash
|
| 118 |
+
cd <project_root>
|
| 119 |
+
git restore prismatic/models/backbones/llm/qwen25.py
|
| 120 |
+
git restore prismatic/models/materialize.py
|
| 121 |
+
git restore prismatic/models/backbones/vision/dinosiglip_vit.py
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
</details>
|
| 125 |
+
|
| 126 |
+
### Data Preparation
|
| 127 |
+
|
| 128 |
+
ALOHA data must be converted to TFDS format. See [rlds_sim/aloha_realworld](https://github.com/cheng-haha/rlds_sim/tree/main/aloha_realworld) for the conversion tool.
|
| 129 |
+
|
| 130 |
+
### Configuration
|
| 131 |
+
|
| 132 |
+
Before training, update the default path variables in the following scripts.
|
| 133 |
+
|
| 134 |
+
**Key variables in `train_aloha.sh`:**
|
| 135 |
+
|
| 136 |
+
| Variable | Default | Description |
|
| 137 |
+
|----------|---------|-------------|
|
| 138 |
+
| `ROOT_DIR` | `/path/to/root` | Storage root directory |
|
| 139 |
+
| `DATA_ROOT_DIR` | `${ROOT_DIR}/datasets/cobot_aloha/tfds` | TFDS data directory |
|
| 140 |
+
| `VLM_PATH` | `${ROOT_DIR}/ai_models/Stanford-ILIAD/prism-qwen25-extra-dinosiglip-224px-0_5b` | VLM weights path |
|
| 141 |
+
| `DATASET_NAME` | `bowl_stack_and_shelf_aloha_realworld_50` | Dataset name |
|
| 142 |
+
| `WANDB_ENTITY` | `your-wandb-entity` | W&B user / team |
|
| 143 |
+
| `WANDB_PROJECT` | `vla_adapter` | W&B project name |
|
| 144 |
+
|
| 145 |
+
**Key variables in `setup_training.sh`:**
|
| 146 |
+
|
| 147 |
+
| Variable | Default | Description |
|
| 148 |
+
|----------|---------|-------------|
|
| 149 |
+
| `ROOT_DIR` | `/path/to/root` | Storage root directory |
|
| 150 |
+
| `LOCAL_QWEN_PATH` | `${ROOT_DIR}/ai_models/Qwen/Qwen2.5-0.5B` | Local Qwen model path |
|
| 151 |
+
| `LOCAL_TIMM_PATH` | `${ROOT_DIR}/ai_models/timm` | Local timm vision model path |
|
| 152 |
+
|
| 153 |
+
**Default training hyperparameters (built into `train_aloha.sh`):**
|
| 154 |
+
|
| 155 |
+
| Parameter | Value | Description |
|
| 156 |
+
|-----------|-------|-------------|
|
| 157 |
+
| `batch_size` | 12 | Per-GPU batch size |
|
| 158 |
+
| `nproc-per-node` | 4 | Number of GPUs |
|
| 159 |
+
| `learning_rate` | 2e-4 | Learning rate |
|
| 160 |
+
| `max_steps` | 10005 | Maximum training steps |
|
| 161 |
+
| `lora_rank` | 64 | LoRA rank |
|
| 162 |
+
| `num_images_in_input` | 3 | Number of input images (front + left wrist + right wrist) |
|
| 163 |
+
| `use_pro_version` | True | Use the Pro version (recommended) |
|
| 164 |
+
| `use_minivlm` | True | Use MiniVLM |
|
| 165 |
+
| `image_aug` | True | Image augmentation |
|
| 166 |
+
|
| 167 |
+
> To adjust hyperparameters (e.g., fewer GPUs or a different batch size), edit the corresponding variables directly in `train_aloha.sh`.
|
| 168 |
+
|
| 169 |
+
### Dataset Registration
|
| 170 |
+
|
| 171 |
+
`setup_training.sh` automatically registers a new dataset entry in `configs.py`, `mixtures.py`, and `transforms.py` (ALOHA bimanual config: 3 image observation keys + bimanual joint encoding).
|
| 172 |
+
|
| 173 |
+
```bash
|
| 174 |
+
# Register dataset only (models loaded from HF Hub)
|
| 175 |
+
bash experiments/robot/aloha/train_files/setup_training.sh bowl_stack_and_shelf_aloha_realworld_50
|
| 176 |
+
|
| 177 |
+
# Register dataset + enable local model loading (offline environment)
|
| 178 |
+
bash experiments/robot/aloha/train_files/setup_training.sh bowl_stack_and_shelf_aloha_realworld_50 --local-models
|
| 179 |
+
```
|
| 180 |
+
|
| 181 |
+
### Launch Training
|
| 182 |
+
|
| 183 |
+
```bash
|
| 184 |
+
bash experiments/robot/aloha/train_files/train_aloha.sh
|
| 185 |
+
```
|
| 186 |
+
|
| 187 |
+
Training outputs are saved to `outputs/<dataset_name>/<MODE>-<timestamp>/`; logs go to the `logs/` directory. W&B runs in offline mode by default.
|
| 188 |
+
|
| 189 |
+
## Deployment
|
| 190 |
+
|
| 191 |
+
Deployment follows a **server–client** architecture: the server loads a checkpoint and exposes an inference API over MsgPack HTTP; the client collects observations and sends requests to obtain action sequences.
|
| 192 |
+
|
| 193 |
+
### Server
|
| 194 |
+
|
| 195 |
+
Update the following variables in `deploy_server.sh`:
|
| 196 |
+
|
| 197 |
+
| Variable | Default | Description |
|
| 198 |
+
|----------|---------|-------------|
|
| 199 |
+
| `PRETRAINED_CHECKPOINT` | `/path/to/checkpoint_dir` | Trained checkpoint directory |
|
| 200 |
+
| `PORT` | `8888` | Server port |
|
| 201 |
+
| `DEVICE` | `0` | GPU device ID |
|
| 202 |
+
| `MODEL_FAMILY` | `openvla` | Model family |
|
| 203 |
+
|
| 204 |
+
```bash
|
| 205 |
+
bash experiments/robot/aloha/eval_files/deploy_server.sh
|
| 206 |
+
```
|
| 207 |
+
|
| 208 |
+
### Fake-Data Client (No ROS Required)
|
| 209 |
+
|
| 210 |
+
Verifies the inference pipeline using synthetic observations — no real robot or ROS environment needed. Generates 480x640x3 fake images and 14-DOF fake joint states.
|
| 211 |
+
|
| 212 |
+
Update the following variables in `run_eval_client_fake.sh`:
|
| 213 |
+
|
| 214 |
+
| Variable | Default | Description |
|
| 215 |
+
|----------|---------|-------------|
|
| 216 |
+
| `VLA_SERVER_URL` | `http://127.0.0.1:8888` | Server address |
|
| 217 |
+
| `TASK_LABEL` | `Use the right arm to stack...` | Task instruction |
|
| 218 |
+
| `UNNORM_KEY` | `bowl_stack_and_shelf_aloha_realworld_50` | Action un-normalization key (must match the training dataset) |
|
| 219 |
+
|
| 220 |
+
```bash
|
| 221 |
+
bash experiments/robot/aloha/eval_files/run_eval_client_fake.sh
|
| 222 |
+
```
|
| 223 |
+
|
| 224 |
+
### Real-Robot Client (Requires ROS)
|
| 225 |
+
|
| 226 |
+
Subscribes to 3 camera topics and bimanual joint states via ROS, queries the server for a new action sequence every `num_open_loop_steps` (default 25) steps, and supports multi-trial evaluation with automatic success-rate tracking.
|
| 227 |
+
|
| 228 |
+
**Default ROS topics:**
|
| 229 |
+
|
| 230 |
+
| Topic | Type | Description |
|
| 231 |
+
|-------|------|-------------|
|
| 232 |
+
| `/camera_f/color/image_raw` | Image | Front camera |
|
| 233 |
+
| `/camera_l/color/image_raw` | Image | Left wrist camera |
|
| 234 |
+
| `/camera_r/color/image_raw` | Image | Right wrist camera |
|
| 235 |
+
| `/puppet/joint_left` | JointState | Left arm joint state |
|
| 236 |
+
| `/puppet/joint_right` | JointState | Right arm joint state |
|
| 237 |
+
| `/master/joint_left` | JointState | Left arm joint command (published) |
|
| 238 |
+
| `/master/joint_right` | JointState | Right arm joint command (published) |
|
| 239 |
+
|
| 240 |
+
```bash
|
| 241 |
+
bash experiments/robot/aloha/eval_files/run_eval_client.sh
|
| 242 |
+
```
|
| 243 |
+
|
| 244 |
+
> To adapt to different robot hardware, modify the `OpenVLAConfig` dataclass in [`run_cobot_client.py`](./run_cobot_client.py) to adjust topic names, control frequency, open-loop steps, and other parameters.
|
| 245 |
+
|
| 246 |
+
## Notes
|
| 247 |
+
|
| 248 |
+
- Training defaults to 4 GPUs (`nproc-per-node 4`). For single-GPU training, update that value in `train_aloha.sh` and adjust `batch_size` accordingly.
|
| 249 |
+
- During real-robot evaluation, the operator is prompted to press Enter to start each trial; pressing Space + Enter stops the current trial early.
|
| 250 |
+
- Trial results (JSON) are saved under `experiments/logs/<unnorm_key>/`.
|
| 251 |
+
- For more ALOHA evaluation references, see [openvla-oft/experiments/robot/aloha](https://github.com/moojink/openvla-oft/tree/main/experiments/robot/aloha).
|
VLA-Adapter-UAV/experiments/robot/aloha/demo/sandwich_assembly_bimanual_demo.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:267930f056ca823f6d09ab7a1cc1f1676d4b663bcc202f7a4c8dc8ca8cc005d2
|
| 3 |
+
size 20089886
|
VLA-Adapter-UAV/experiments/robot/aloha/eval_files/deploy_server.sh
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
PROJECT_PATH=realworld_vla_adapter
|
| 2 |
+
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
| 3 |
+
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/../../../.." && pwd)"
|
| 4 |
+
export PYTHONPATH="${PROJECT_ROOT}"
|
| 5 |
+
pretrained_checkpoint="${PRETRAINED_CHECKPOINT:-/path/to/checkpoint_dir}"
|
| 6 |
+
port="${PORT:-8888}"
|
| 7 |
+
model_family="${MODEL_FAMILY:-openvla}"
|
| 8 |
+
device="${DEVICE:-0}"
|
| 9 |
+
|
| 10 |
+
python experiments/robot/server_deploy/deploy.py \
|
| 11 |
+
--pretrained_checkpoint $pretrained_checkpoint \
|
| 12 |
+
--model_family $model_family \
|
| 13 |
+
--port $port \
|
| 14 |
+
--device $device
|
VLA-Adapter-UAV/experiments/robot/aloha/eval_files/run_eval_client.sh
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
PROJECT_PATH=realworld_vla_adapter
|
| 2 |
+
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
| 3 |
+
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/../../../.." && pwd)"
|
| 4 |
+
export PYTHONPATH="${PROJECT_ROOT}"
|
| 5 |
+
|
| 6 |
+
# Allow passing the server URL as an argument or via VLA_SERVER_URL env variable.
|
| 7 |
+
VLA_SERVER_URL="${VLA_SERVER_URL:-http://127.0.0.1:8888}"
|
| 8 |
+
TASK_LABEL="${TASK_LABEL:-Use the right arm to stack the red bowl on the blue one, then use the left arm to place the stack on the shelf.}"
|
| 9 |
+
UNNORM_KEY="${UNNORM_KEY:-bowl_stack_and_shelf_aloha_realworld_50}"
|
| 10 |
+
|
| 11 |
+
python experiments/robot/aloha/run_cobot_client.py \
|
| 12 |
+
--use_vla_server \
|
| 13 |
+
--vla_server_url "${VLA_SERVER_URL}" \
|
| 14 |
+
--unnorm_key "${UNNORM_KEY}" \
|
| 15 |
+
--task_label "${TASK_LABEL}"
|
VLA-Adapter-UAV/experiments/robot/aloha/eval_files/run_eval_client_fake.sh
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
PROJECT_PATH=realworld_vla_adapter
|
| 2 |
+
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
| 3 |
+
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/../../../.." && pwd)"
|
| 4 |
+
export PYTHONPATH="${PROJECT_ROOT}"
|
| 5 |
+
|
| 6 |
+
# Allow passing the server URL as an argument or via VLA_SERVER_URL env variable.
|
| 7 |
+
VLA_SERVER_URL="${VLA_SERVER_URL:-http://127.0.0.1:8888}"
|
| 8 |
+
TASK_LABEL="${TASK_LABEL:-Use the right arm to stack the red bowl on the blue one, then use the left arm to place the stack on the shelf.}"
|
| 9 |
+
UNNORM_KEY="${UNNORM_KEY:-bowl_stack_and_shelf_aloha_realworld_50}"
|
| 10 |
+
|
| 11 |
+
python experiments/robot/aloha/run_fake_cobot_client.py \
|
| 12 |
+
--use_vla_server \
|
| 13 |
+
--vla_server_url "${VLA_SERVER_URL}" \
|
| 14 |
+
--unnorm_key "${UNNORM_KEY}" \
|
| 15 |
+
--task_label "${TASK_LABEL}"
|
VLA-Adapter-UAV/experiments/robot/aloha/requirements_aloha.txt
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Extra Python packages for `experiments/robot/aloha` after the base install in README:
|
| 2 |
+
# pip install torch==2.2.0 torchvision==0.17.0 torchaudio==2.2.0
|
| 3 |
+
# pip install -e .
|
| 4 |
+
# pip install packaging ninja
|
| 5 |
+
# pip install "flash-attn==2.5.5" --no-build-isolation
|
| 6 |
+
#
|
| 7 |
+
# Most training dependencies are already covered by the commands above.
|
| 8 |
+
# This file only keeps the ALOHA-specific extras that are still needed.
|
| 9 |
+
|
| 10 |
+
# Required by the msgpack HTTP client used in fake/real eval clients.
|
| 11 |
+
msgpack
|
| 12 |
+
msgpack-numpy
|
| 13 |
+
|
| 14 |
+
# Required by real-world ALOHA eval modules importing `real_env.py`.
|
| 15 |
+
dm-env
|
| 16 |
+
ipython
|
| 17 |
+
|
| 18 |
+
# Optional but recommended if you want rollout videos from `save_rollout_video()`.
|
| 19 |
+
imageio[ffmpeg]
|
| 20 |
+
|
| 21 |
+
# Not installable from pip here; these must come from your ROS / robot environment:
|
| 22 |
+
# rospy
|
| 23 |
+
# cv_bridge
|
| 24 |
+
# std_msgs
|
| 25 |
+
# sensor_msgs
|
| 26 |
+
# nav_msgs
|
| 27 |
+
# geometry_msgs
|
| 28 |
+
# interbotix_xs_modules
|
| 29 |
+
# interbotix_xs_msgs
|
VLA-Adapter-UAV/experiments/robot/aloha/run_cobot_client.py
ADDED
|
@@ -0,0 +1,681 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/python3
|
| 2 |
+
"""
|
| 3 |
+
inference_openvla_oft.py
|
| 4 |
+
|
| 5 |
+
A hybrid inference system that combines local ROS data collection with remote OpenVLA server inference.
|
| 6 |
+
This allows local robot control while leveraging cloud-based OpenVLA models.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import numpy as np
|
| 11 |
+
import os
|
| 12 |
+
import pickle
|
| 13 |
+
import argparse
|
| 14 |
+
import json
|
| 15 |
+
import select
|
| 16 |
+
from einops import rearrange
|
| 17 |
+
import socket
|
| 18 |
+
import sys
|
| 19 |
+
import time
|
| 20 |
+
import threading
|
| 21 |
+
import math
|
| 22 |
+
import logging
|
| 23 |
+
from collections import deque
|
| 24 |
+
from dataclasses import dataclass
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
from typing import Optional, Union
|
| 27 |
+
|
| 28 |
+
import rospy
|
| 29 |
+
from std_msgs.msg import Header
|
| 30 |
+
from geometry_msgs.msg import Twist
|
| 31 |
+
from sensor_msgs.msg import JointState, Image
|
| 32 |
+
from nav_msgs.msg import Odometry
|
| 33 |
+
from cv_bridge import CvBridge
|
| 34 |
+
|
| 35 |
+
# Append current directory so that interpreter can find experiments.robot
|
| 36 |
+
# sys.path.append("/home/agilex/openvla-oft")
|
| 37 |
+
sys.path.append(".")
|
| 38 |
+
|
| 39 |
+
from experiments.robot.aloha.aloha_utils import (
|
| 40 |
+
# get_aloha_env,
|
| 41 |
+
get_aloha_image,
|
| 42 |
+
get_aloha_wrist_images,
|
| 43 |
+
get_next_task_label,
|
| 44 |
+
# save_rollout_video,
|
| 45 |
+
)
|
| 46 |
+
from experiments.robot.openvla_utils import resize_image_for_policy
|
| 47 |
+
from experiments.robot.robot_utils import (
|
| 48 |
+
DATE_TIME,
|
| 49 |
+
MsgPackHttpClientPolicy,
|
| 50 |
+
get_image_resize_size,
|
| 51 |
+
set_seed_everywhere,
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
# Set up logging
|
| 55 |
+
logging.basicConfig(
|
| 56 |
+
level=logging.INFO,
|
| 57 |
+
format="%(asctime)s [%(levelname)s] %(message)s",
|
| 58 |
+
handlers=[logging.StreamHandler()],
|
| 59 |
+
)
|
| 60 |
+
logger = logging.getLogger(__name__)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@dataclass
|
| 64 |
+
class OpenVLAConfig:
|
| 65 |
+
# fmt: off
|
| 66 |
+
|
| 67 |
+
#################################################################################################################
|
| 68 |
+
# Model-specific parameters
|
| 69 |
+
#################################################################################################################
|
| 70 |
+
model_family: str = "openvla" # Model family
|
| 71 |
+
center_crop: bool = True # Center crop? (if trained w/ random crop image aug)
|
| 72 |
+
num_open_loop_steps: int = 25 # Number of actions to execute open-loop before requerying policy
|
| 73 |
+
unnorm_key: str = "" # Dataset key for action un-normalization
|
| 74 |
+
|
| 75 |
+
use_vla_server: bool = True # Whether to query remote VLA server for actions
|
| 76 |
+
vla_server_url: Union[str, Path] = "0.0.0.0" # Remote VLA server URL
|
| 77 |
+
|
| 78 |
+
#################################################################################################################
|
| 79 |
+
# Robot control parameters
|
| 80 |
+
#################################################################################################################
|
| 81 |
+
max_publish_step: int = 500 # Max number of steps per episode
|
| 82 |
+
publish_rate: int = 40 # Control frequency (Hz)
|
| 83 |
+
num_trials: int = 10 # Number of inference trials to record
|
| 84 |
+
use_relative_actions: bool = False # Whether to use relative actions (delta joint angles)
|
| 85 |
+
pos_lookahead_step: int = 25 # Number of steps to look ahead
|
| 86 |
+
|
| 87 |
+
#################################################################################################################
|
| 88 |
+
# ROS topic parameters
|
| 89 |
+
#################################################################################################################
|
| 90 |
+
img_front_topic: str = '/camera_f/color/image_raw'
|
| 91 |
+
img_left_topic: str = '/camera_l/color/image_raw'
|
| 92 |
+
img_right_topic: str = '/camera_r/color/image_raw'
|
| 93 |
+
puppet_arm_left_topic: str = '/puppet/joint_left'
|
| 94 |
+
puppet_arm_right_topic: str = '/puppet/joint_right'
|
| 95 |
+
puppet_arm_left_cmd_topic: str = '/master/joint_left'
|
| 96 |
+
puppet_arm_right_cmd_topic: str = '/master/joint_right'
|
| 97 |
+
robot_base_topic: str = '/odom_raw'
|
| 98 |
+
robot_base_cmd_topic: str = '/cmd_vel'
|
| 99 |
+
|
| 100 |
+
#################################################################################################################
|
| 101 |
+
# Robot base and movement parameters
|
| 102 |
+
#################################################################################################################
|
| 103 |
+
use_robot_base: bool = False # Whether to use robot base movement
|
| 104 |
+
arm_steps_length: list = None # Step sizes for each joint
|
| 105 |
+
use_actions_interpolation: bool = False # Whether to use action interpolation
|
| 106 |
+
|
| 107 |
+
#################################################################################################################
|
| 108 |
+
# Utils
|
| 109 |
+
#################################################################################################################
|
| 110 |
+
run_id_note: Optional[str] = None # Extra note to add to end of run ID for logging
|
| 111 |
+
local_log_dir: str = "./experiments/logs" # Local directory for eval logs
|
| 112 |
+
seed: int = 42 # Random Seed
|
| 113 |
+
task_label: str = "" # Default task label used when prompting operator
|
| 114 |
+
|
| 115 |
+
# fmt: on
|
| 116 |
+
|
| 117 |
+
def __post_init__(self):
|
| 118 |
+
if self.arm_steps_length is None:
|
| 119 |
+
self.arm_steps_length = [0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.2]
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class RosOperator:
|
| 123 |
+
"""ROS interface for robot control and data collection."""
|
| 124 |
+
|
| 125 |
+
def __init__(self, cfg: OpenVLAConfig):
|
| 126 |
+
self.cfg = cfg
|
| 127 |
+
self.robot_base_deque = None
|
| 128 |
+
self.puppet_arm_right_deque = None
|
| 129 |
+
self.puppet_arm_left_deque = None
|
| 130 |
+
self.img_front_deque = None
|
| 131 |
+
self.img_right_deque = None
|
| 132 |
+
self.img_left_deque = None
|
| 133 |
+
self.bridge = None
|
| 134 |
+
self.puppet_arm_left_publisher = None
|
| 135 |
+
self.puppet_arm_right_publisher = None
|
| 136 |
+
self.robot_base_publisher = None
|
| 137 |
+
self.puppet_arm_publish_thread = None
|
| 138 |
+
self.puppet_arm_publish_lock = None
|
| 139 |
+
self.ctrl_state = False
|
| 140 |
+
self.ctrl_state_lock = threading.Lock()
|
| 141 |
+
self.init()
|
| 142 |
+
self.init_ros()
|
| 143 |
+
|
| 144 |
+
def init(self):
|
| 145 |
+
"""Initialize data structures."""
|
| 146 |
+
self.bridge = CvBridge()
|
| 147 |
+
self.img_left_deque = deque()
|
| 148 |
+
self.img_right_deque = deque()
|
| 149 |
+
self.img_front_deque = deque()
|
| 150 |
+
self.puppet_arm_left_deque = deque()
|
| 151 |
+
self.puppet_arm_right_deque = deque()
|
| 152 |
+
self.robot_base_deque = deque()
|
| 153 |
+
self.puppet_arm_publish_lock = threading.Lock()
|
| 154 |
+
self.puppet_arm_publish_lock.acquire()
|
| 155 |
+
|
| 156 |
+
def puppet_arm_publish(self, left, right):
|
| 157 |
+
"""Publish joint commands to both arms."""
|
| 158 |
+
joint_state_msg = JointState()
|
| 159 |
+
joint_state_msg.header = Header()
|
| 160 |
+
joint_state_msg.header.stamp = rospy.Time.now()
|
| 161 |
+
joint_state_msg.name = ['joint0', 'joint1', 'joint2', 'joint3', 'joint4', 'joint5', 'joint6']
|
| 162 |
+
joint_state_msg.position = left
|
| 163 |
+
self.puppet_arm_left_publisher.publish(joint_state_msg)
|
| 164 |
+
joint_state_msg.position = right
|
| 165 |
+
self.puppet_arm_right_publisher.publish(joint_state_msg)
|
| 166 |
+
|
| 167 |
+
def robot_base_publish(self, vel):
|
| 168 |
+
"""Publish base velocity commands."""
|
| 169 |
+
vel_msg = Twist()
|
| 170 |
+
vel_msg.linear.x = vel[0]
|
| 171 |
+
vel_msg.linear.y = 0
|
| 172 |
+
vel_msg.linear.z = 0
|
| 173 |
+
vel_msg.angular.x = 0
|
| 174 |
+
vel_msg.angular.y = 0
|
| 175 |
+
vel_msg.angular.z = vel[1]
|
| 176 |
+
self.robot_base_publisher.publish(vel_msg)
|
| 177 |
+
|
| 178 |
+
def get_observation(self):
|
| 179 |
+
"""Get synchronized observation from all sensors."""
|
| 180 |
+
if (len(self.img_left_deque) == 0 or len(self.img_right_deque) == 0 or
|
| 181 |
+
len(self.img_front_deque) == 0 or len(self.puppet_arm_left_deque) == 0 or
|
| 182 |
+
len(self.puppet_arm_right_deque) == 0):
|
| 183 |
+
return None
|
| 184 |
+
|
| 185 |
+
if self.cfg.use_robot_base and len(self.robot_base_deque) == 0:
|
| 186 |
+
return None
|
| 187 |
+
|
| 188 |
+
# Get the latest timestamp from all sensors
|
| 189 |
+
frame_time = min([
|
| 190 |
+
self.img_left_deque[-1].header.stamp.to_sec(),
|
| 191 |
+
self.img_right_deque[-1].header.stamp.to_sec(),
|
| 192 |
+
self.img_front_deque[-1].header.stamp.to_sec()
|
| 193 |
+
])
|
| 194 |
+
|
| 195 |
+
# Check if all data is synchronized
|
| 196 |
+
if (self.img_left_deque[-1].header.stamp.to_sec() < frame_time or
|
| 197 |
+
self.img_right_deque[-1].header.stamp.to_sec() < frame_time or
|
| 198 |
+
self.img_front_deque[-1].header.stamp.to_sec() < frame_time or
|
| 199 |
+
self.puppet_arm_left_deque[-1].header.stamp.to_sec() < frame_time or
|
| 200 |
+
self.puppet_arm_right_deque[-1].header.stamp.to_sec() < frame_time):
|
| 201 |
+
return None
|
| 202 |
+
|
| 203 |
+
if (self.cfg.use_robot_base and
|
| 204 |
+
self.robot_base_deque[-1].header.stamp.to_sec() < frame_time):
|
| 205 |
+
return None
|
| 206 |
+
|
| 207 |
+
# Pop old data and get synchronized frames
|
| 208 |
+
while self.img_left_deque[0].header.stamp.to_sec() < frame_time:
|
| 209 |
+
self.img_left_deque.popleft()
|
| 210 |
+
img_left = self.bridge.imgmsg_to_cv2(self.img_left_deque.popleft(), 'passthrough')
|
| 211 |
+
|
| 212 |
+
while self.img_right_deque[0].header.stamp.to_sec() < frame_time:
|
| 213 |
+
self.img_right_deque.popleft()
|
| 214 |
+
img_right = self.bridge.imgmsg_to_cv2(self.img_right_deque.popleft(), 'passthrough')
|
| 215 |
+
|
| 216 |
+
while self.img_front_deque[0].header.stamp.to_sec() < frame_time:
|
| 217 |
+
self.img_front_deque.popleft()
|
| 218 |
+
img_front = self.bridge.imgmsg_to_cv2(self.img_front_deque.popleft(), 'passthrough')
|
| 219 |
+
|
| 220 |
+
while self.puppet_arm_left_deque[0].header.stamp.to_sec() < frame_time:
|
| 221 |
+
self.puppet_arm_left_deque.popleft()
|
| 222 |
+
puppet_arm_left = self.puppet_arm_left_deque.popleft()
|
| 223 |
+
|
| 224 |
+
while self.puppet_arm_right_deque[0].header.stamp.to_sec() < frame_time:
|
| 225 |
+
self.puppet_arm_right_deque.popleft()
|
| 226 |
+
puppet_arm_right = self.puppet_arm_right_deque.popleft()
|
| 227 |
+
|
| 228 |
+
robot_base = None
|
| 229 |
+
if self.cfg.use_robot_base:
|
| 230 |
+
while self.robot_base_deque[0].header.stamp.to_sec() < frame_time:
|
| 231 |
+
self.robot_base_deque.popleft()
|
| 232 |
+
robot_base = self.robot_base_deque.popleft()
|
| 233 |
+
|
| 234 |
+
# Construct observation dict
|
| 235 |
+
observation = {
|
| 236 |
+
'images': {
|
| 237 |
+
'cam_high': img_front,
|
| 238 |
+
'cam_left_wrist': img_left,
|
| 239 |
+
'cam_right_wrist': img_right
|
| 240 |
+
},
|
| 241 |
+
'qpos': np.concatenate((
|
| 242 |
+
np.array(puppet_arm_left.position),
|
| 243 |
+
np.array(puppet_arm_right.position)
|
| 244 |
+
), axis=0),
|
| 245 |
+
'qvel': np.concatenate((
|
| 246 |
+
np.array(puppet_arm_left.velocity),
|
| 247 |
+
np.array(puppet_arm_right.velocity)
|
| 248 |
+
), axis=0),
|
| 249 |
+
'effort': np.concatenate((
|
| 250 |
+
np.array(puppet_arm_left.effort),
|
| 251 |
+
np.array(puppet_arm_right.effort)
|
| 252 |
+
), axis=0)
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
if self.cfg.use_robot_base and robot_base is not None:
|
| 256 |
+
base_vel = [robot_base.twist.twist.linear.x, robot_base.twist.twist.angular.z]
|
| 257 |
+
observation['qpos'] = np.concatenate((observation['qpos'], base_vel), axis=0)
|
| 258 |
+
|
| 259 |
+
return observation
|
| 260 |
+
|
| 261 |
+
# ROS callback functions
|
| 262 |
+
def img_left_callback(self, msg):
|
| 263 |
+
if len(self.img_left_deque) >= 2000:
|
| 264 |
+
self.img_left_deque.popleft()
|
| 265 |
+
self.img_left_deque.append(msg)
|
| 266 |
+
|
| 267 |
+
def img_right_callback(self, msg):
|
| 268 |
+
if len(self.img_right_deque) >= 2000:
|
| 269 |
+
self.img_right_deque.popleft()
|
| 270 |
+
self.img_right_deque.append(msg)
|
| 271 |
+
|
| 272 |
+
def img_front_callback(self, msg):
|
| 273 |
+
if len(self.img_front_deque) >= 2000:
|
| 274 |
+
self.img_front_deque.popleft()
|
| 275 |
+
self.img_front_deque.append(msg)
|
| 276 |
+
|
| 277 |
+
def puppet_arm_left_callback(self, msg):
|
| 278 |
+
if len(self.puppet_arm_left_deque) >= 2000:
|
| 279 |
+
self.puppet_arm_left_deque.popleft()
|
| 280 |
+
self.puppet_arm_left_deque.append(msg)
|
| 281 |
+
|
| 282 |
+
def puppet_arm_right_callback(self, msg):
|
| 283 |
+
if len(self.puppet_arm_right_deque) >= 2000:
|
| 284 |
+
self.puppet_arm_right_deque.popleft()
|
| 285 |
+
self.puppet_arm_right_deque.append(msg)
|
| 286 |
+
|
| 287 |
+
def robot_base_callback(self, msg):
|
| 288 |
+
if len(self.robot_base_deque) >= 2000:
|
| 289 |
+
self.robot_base_deque.popleft()
|
| 290 |
+
self.robot_base_deque.append(msg)
|
| 291 |
+
|
| 292 |
+
def init_ros(self):
|
| 293 |
+
"""Initialize ROS node and subscribers/publishers."""
|
| 294 |
+
rospy.init_node('openvla_inference', anonymous=True)
|
| 295 |
+
|
| 296 |
+
# Subscribers
|
| 297 |
+
rospy.Subscriber(self.cfg.img_left_topic, Image, self.img_left_callback,
|
| 298 |
+
queue_size=1000, tcp_nodelay=True)
|
| 299 |
+
rospy.Subscriber(self.cfg.img_right_topic, Image, self.img_right_callback,
|
| 300 |
+
queue_size=1000, tcp_nodelay=True)
|
| 301 |
+
rospy.Subscriber(self.cfg.img_front_topic, Image, self.img_front_callback,
|
| 302 |
+
queue_size=1000, tcp_nodelay=True)
|
| 303 |
+
rospy.Subscriber(self.cfg.puppet_arm_left_topic, JointState, self.puppet_arm_left_callback,
|
| 304 |
+
queue_size=1000, tcp_nodelay=True)
|
| 305 |
+
rospy.Subscriber(self.cfg.puppet_arm_right_topic, JointState, self.puppet_arm_right_callback,
|
| 306 |
+
queue_size=1000, tcp_nodelay=True)
|
| 307 |
+
|
| 308 |
+
if self.cfg.use_robot_base:
|
| 309 |
+
rospy.Subscriber(self.cfg.robot_base_topic, Odometry, self.robot_base_callback,
|
| 310 |
+
queue_size=1000, tcp_nodelay=True)
|
| 311 |
+
|
| 312 |
+
# Publishers
|
| 313 |
+
self.puppet_arm_left_publisher = rospy.Publisher(self.cfg.puppet_arm_left_cmd_topic,
|
| 314 |
+
JointState, queue_size=10)
|
| 315 |
+
self.puppet_arm_right_publisher = rospy.Publisher(self.cfg.puppet_arm_right_cmd_topic,
|
| 316 |
+
JointState, queue_size=10)
|
| 317 |
+
if self.cfg.use_robot_base:
|
| 318 |
+
self.robot_base_publisher = rospy.Publisher(self.cfg.robot_base_cmd_topic,
|
| 319 |
+
Twist, queue_size=10)
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def validate_config(cfg: OpenVLAConfig) -> None:
|
| 323 |
+
"""Validate configuration parameters."""
|
| 324 |
+
assert cfg.use_vla_server, (
|
| 325 |
+
"Must use VLA server for remote inference! Please set --use_vla_server=True"
|
| 326 |
+
)
|
| 327 |
+
assert cfg.vla_server_url, "A valid --vla_server_url must be provided for MsgPack remote inference."
|
| 328 |
+
assert cfg.unnorm_key, "A valid --unnorm_key matching the deployed policy's dataset stats is required."
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def setup_logging(cfg: OpenVLAConfig):
|
| 332 |
+
"""Set up logging to file."""
|
| 333 |
+
# Create run ID
|
| 334 |
+
run_id = f"OPENVLA-INFERENCE-{cfg.model_family}-{DATE_TIME}"
|
| 335 |
+
if cfg.run_id_note is not None:
|
| 336 |
+
run_id += f"--{cfg.run_id_note}"
|
| 337 |
+
|
| 338 |
+
# Set up local logging
|
| 339 |
+
os.makedirs(cfg.local_log_dir, exist_ok=True)
|
| 340 |
+
local_log_filepath = os.path.join(cfg.local_log_dir, run_id + ".txt")
|
| 341 |
+
log_file = open(local_log_filepath, "w")
|
| 342 |
+
logger.info(f"Logging to local log file: {local_log_filepath}")
|
| 343 |
+
|
| 344 |
+
return log_file, local_log_filepath, run_id
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def log_message(message: str, log_file=None):
|
| 348 |
+
"""Log a message to console and optionally to a log file."""
|
| 349 |
+
print(message)
|
| 350 |
+
logger.info(message)
|
| 351 |
+
if log_file:
|
| 352 |
+
log_file.write(message + "\n")
|
| 353 |
+
log_file.flush()
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
def get_server_endpoint(cfg: OpenVLAConfig):
|
| 357 |
+
"""Get the server endpoint for remote inference."""
|
| 358 |
+
server_url = str(cfg.vla_server_url).strip()
|
| 359 |
+
if server_url.startswith("http"):
|
| 360 |
+
return server_url.rstrip("/")
|
| 361 |
+
|
| 362 |
+
# Support host[:port] inputs without protocol
|
| 363 |
+
host_and_path = server_url.split("/", 1)[0]
|
| 364 |
+
if ":" in host_and_path:
|
| 365 |
+
host, port = host_and_path.split(":", 1)
|
| 366 |
+
else:
|
| 367 |
+
host, port = host_and_path, "8777"
|
| 368 |
+
|
| 369 |
+
ip_address = socket.gethostbyname(host)
|
| 370 |
+
protocol = "https" if any(keyword in host for keyword in ("nat-notebook", "ngrok")) else "http"
|
| 371 |
+
return f"{protocol}://{ip_address}:{port}"
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def prepare_observation_for_server(obs_data, task_description, resize_size):
|
| 375 |
+
"""Prepare observation for OpenVLA server input."""
|
| 376 |
+
# Support both dict observations (real ROS bridge) and dm_env.TimeStep (ALOHA sim)
|
| 377 |
+
if isinstance(obs_data, dict) and "images" in obs_data:
|
| 378 |
+
img = obs_data["images"]["cam_high"]
|
| 379 |
+
left_wrist_img = obs_data["images"]["cam_left_wrist"]
|
| 380 |
+
right_wrist_img = obs_data["images"]["cam_right_wrist"]
|
| 381 |
+
else:
|
| 382 |
+
img = get_aloha_image(obs_data) # Main camera image
|
| 383 |
+
left_wrist_img, right_wrist_img = get_aloha_wrist_images(obs_data)
|
| 384 |
+
|
| 385 |
+
# Resize images to size expected by model
|
| 386 |
+
img_resized = resize_image_for_policy(img, resize_size)
|
| 387 |
+
left_wrist_img_resized = resize_image_for_policy(left_wrist_img, resize_size)
|
| 388 |
+
right_wrist_img_resized = resize_image_for_policy(right_wrist_img, resize_size)
|
| 389 |
+
|
| 390 |
+
# Prepare observations dict for server
|
| 391 |
+
observation = {
|
| 392 |
+
"full_image": img_resized,
|
| 393 |
+
"left_wrist_image": left_wrist_img_resized,
|
| 394 |
+
"right_wrist_image": right_wrist_img_resized,
|
| 395 |
+
"state": obs_data['qpos'],
|
| 396 |
+
"instruction": task_description,
|
| 397 |
+
}
|
| 398 |
+
|
| 399 |
+
return observation, img_resized, left_wrist_img_resized, right_wrist_img_resized
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
def manual_stop_requested() -> bool:
|
| 403 |
+
"""Check whether the operator requested to stop the current trial via stdin."""
|
| 404 |
+
if not sys.stdin.isatty():
|
| 405 |
+
return False
|
| 406 |
+
|
| 407 |
+
try:
|
| 408 |
+
ready, _, _ = select.select([sys.stdin], [], [], 0)
|
| 409 |
+
except (ValueError, OSError):
|
| 410 |
+
return False
|
| 411 |
+
|
| 412 |
+
if ready:
|
| 413 |
+
raw_input = sys.stdin.readline()
|
| 414 |
+
if raw_input == "":
|
| 415 |
+
return False
|
| 416 |
+
user_signal = raw_input.rstrip("\r\n")
|
| 417 |
+
if user_signal == " " or user_signal.lower() in {"space", "stop", "s"}:
|
| 418 |
+
return True
|
| 419 |
+
|
| 420 |
+
return False
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
def run_inference_loop(cfg: OpenVLAConfig, ros_operator: RosOperator, log_file=None, run_id: Optional[str] = None):
|
| 424 |
+
"""Main inference loop supporting multiple trials."""
|
| 425 |
+
resize_size = get_image_resize_size(cfg)
|
| 426 |
+
server_endpoint = get_server_endpoint(cfg)
|
| 427 |
+
client = MsgPackHttpClientPolicy(host=server_endpoint)
|
| 428 |
+
log_message(f"Connecting to OpenVLA server at: {client.infer_url}", log_file)
|
| 429 |
+
|
| 430 |
+
previous_task_description = cfg.task_label
|
| 431 |
+
STEP_DURATION_IN_SEC = 1.0 / cfg.publish_rate
|
| 432 |
+
rate = rospy.Rate(cfg.publish_rate)
|
| 433 |
+
|
| 434 |
+
# Nominal joint targets used to settle the robot before each attempt
|
| 435 |
+
left0 = [-0.00133514404296875, 0.00209808349609375, 0.01583099365234375,
|
| 436 |
+
-0.032616615295410156, -0.00286102294921875, 0.00095367431640625, 3.557830810546875]
|
| 437 |
+
right0 = [-0.00133514404296875, 0.00438690185546875, 0.034523963928222656,
|
| 438 |
+
-0.053597450256347656, -0.00476837158203125, -0.00209808349609375, 3.557830810546875]
|
| 439 |
+
|
| 440 |
+
trial_results = []
|
| 441 |
+
total_successes = 0
|
| 442 |
+
|
| 443 |
+
for trial_idx in range(cfg.num_trials):
|
| 444 |
+
log_message(f"\n========== Trial {trial_idx + 1}/{cfg.num_trials} ==========", log_file)
|
| 445 |
+
task_description = get_next_task_label(previous_task_description)
|
| 446 |
+
previous_task_description = task_description
|
| 447 |
+
log_message(f"Task: {task_description}", log_file)
|
| 448 |
+
log_message("Tip: press <Space> then Enter at any time to stop this trial early.", log_file)
|
| 449 |
+
|
| 450 |
+
action_queue = deque(maxlen=cfg.num_open_loop_steps)
|
| 451 |
+
t = 0
|
| 452 |
+
curr_state = None
|
| 453 |
+
|
| 454 |
+
ros_operator.puppet_arm_publish(left0, right0)
|
| 455 |
+
time.sleep(3)
|
| 456 |
+
log_message("Prepare the scene, and then press Enter to begin...", log_file)
|
| 457 |
+
input()
|
| 458 |
+
|
| 459 |
+
episode_start_time = time.time()
|
| 460 |
+
total_model_query_time = 0.0
|
| 461 |
+
|
| 462 |
+
try:
|
| 463 |
+
while t < cfg.max_publish_step and not rospy.is_shutdown():
|
| 464 |
+
if manual_stop_requested():
|
| 465 |
+
log_message("Manual stop requested; ending trial early.", log_file)
|
| 466 |
+
break
|
| 467 |
+
step_start_time = time.time()
|
| 468 |
+
|
| 469 |
+
obs_data = ros_operator.get_observation()
|
| 470 |
+
if obs_data is None:
|
| 471 |
+
log_message("Waiting for synchronized sensor data...", log_file)
|
| 472 |
+
rate.sleep()
|
| 473 |
+
continue
|
| 474 |
+
|
| 475 |
+
if len(action_queue) == 0:
|
| 476 |
+
log_message("Requerying OpenVLA server...", log_file)
|
| 477 |
+
observation, _, _, _ = prepare_observation_for_server(obs_data, task_description, resize_size)
|
| 478 |
+
observation["unnorm_key"] = cfg.unnorm_key
|
| 479 |
+
|
| 480 |
+
model_query_start_time = time.time()
|
| 481 |
+
try:
|
| 482 |
+
response = client.infer(observation)
|
| 483 |
+
actions = np.array(response["actions"])
|
| 484 |
+
actions = actions[: cfg.num_open_loop_steps]
|
| 485 |
+
total_model_query_time += time.time() - model_query_start_time
|
| 486 |
+
action_queue.extend(actions)
|
| 487 |
+
log_message(f"Received {len(actions)} actions from server", log_file)
|
| 488 |
+
except Exception as e:
|
| 489 |
+
log_message(f"Error querying server: {e}", log_file)
|
| 490 |
+
rate.sleep()
|
| 491 |
+
continue
|
| 492 |
+
|
| 493 |
+
action = action_queue.popleft()
|
| 494 |
+
log_message("-----------------------------------------------------", log_file)
|
| 495 |
+
log_message(f"t: {t}", log_file)
|
| 496 |
+
log_message(f"action: {action}", log_file)
|
| 497 |
+
|
| 498 |
+
if cfg.use_relative_actions:
|
| 499 |
+
if curr_state is None:
|
| 500 |
+
curr_state = obs_data['qpos']
|
| 501 |
+
rel_action = action
|
| 502 |
+
target_state = curr_state + rel_action
|
| 503 |
+
left_action = target_state[:7]
|
| 504 |
+
right_action = target_state[7:14]
|
| 505 |
+
curr_state = target_state
|
| 506 |
+
else:
|
| 507 |
+
left_action = action[:7]
|
| 508 |
+
right_action = action[7:14]
|
| 509 |
+
|
| 510 |
+
ros_operator.puppet_arm_publish(left_action, right_action)
|
| 511 |
+
|
| 512 |
+
if cfg.use_robot_base and len(action) > 14:
|
| 513 |
+
vel_action = action[14:16]
|
| 514 |
+
ros_operator.robot_base_publish(vel_action)
|
| 515 |
+
|
| 516 |
+
t += 1
|
| 517 |
+
|
| 518 |
+
step_elapsed_time = time.time() - step_start_time
|
| 519 |
+
if step_elapsed_time < STEP_DURATION_IN_SEC:
|
| 520 |
+
time.sleep(STEP_DURATION_IN_SEC - step_elapsed_time)
|
| 521 |
+
|
| 522 |
+
except (KeyboardInterrupt, Exception) as e:
|
| 523 |
+
if isinstance(e, KeyboardInterrupt):
|
| 524 |
+
log_message("\nCaught KeyboardInterrupt: Terminating episode early.", log_file)
|
| 525 |
+
else:
|
| 526 |
+
log_message(f"\nCaught exception: {e}", log_file)
|
| 527 |
+
|
| 528 |
+
episode_end_time = time.time()
|
| 529 |
+
num_queries = max(1, t // cfg.num_open_loop_steps)
|
| 530 |
+
avg_inference_time = total_model_query_time / num_queries
|
| 531 |
+
|
| 532 |
+
user_input = input("Success? Enter 'y' or 'n': ")
|
| 533 |
+
success = user_input.strip().lower() == "y"
|
| 534 |
+
if success:
|
| 535 |
+
total_successes += 1
|
| 536 |
+
|
| 537 |
+
current_trial_count = len(trial_results) + 1
|
| 538 |
+
success_rate = total_successes / current_trial_count
|
| 539 |
+
trial_stats = {
|
| 540 |
+
"trial_index": trial_idx + 1,
|
| 541 |
+
"task_description": task_description,
|
| 542 |
+
"success": success,
|
| 543 |
+
"total_steps": t,
|
| 544 |
+
"model_query_time": total_model_query_time,
|
| 545 |
+
"episode_duration": episode_end_time - episode_start_time,
|
| 546 |
+
"avg_inference_time": avg_inference_time,
|
| 547 |
+
"cumulative_success_rate": success_rate,
|
| 548 |
+
}
|
| 549 |
+
trial_results.append(trial_stats)
|
| 550 |
+
|
| 551 |
+
log_message("\nTrial summary:", log_file)
|
| 552 |
+
log_message(f"Total steps: {t}", log_file)
|
| 553 |
+
log_message(f"Total model query time: {total_model_query_time:.2f} sec", log_file)
|
| 554 |
+
log_message(f"Episode duration: {trial_stats['episode_duration']:.2f} sec", log_file)
|
| 555 |
+
log_message(f"Average inference time: {avg_inference_time:.3f} sec", log_file)
|
| 556 |
+
log_message(f"Success: {success}", log_file)
|
| 557 |
+
log_message(
|
| 558 |
+
f"Current success rate: {total_successes}/{len(trial_results)} ({success_rate * 100:.1f}%)",
|
| 559 |
+
log_file,
|
| 560 |
+
)
|
| 561 |
+
|
| 562 |
+
if rospy.is_shutdown():
|
| 563 |
+
break
|
| 564 |
+
|
| 565 |
+
if trial_results:
|
| 566 |
+
final_success_rate = total_successes / len(trial_results)
|
| 567 |
+
log_message("\nFinal multi-trial summary:", log_file)
|
| 568 |
+
log_message(f"Total trials run: {len(trial_results)}", log_file)
|
| 569 |
+
log_message(f"Total successes: {total_successes}", log_file)
|
| 570 |
+
log_message(f"Overall success rate: {final_success_rate * 100:.1f}%", log_file)
|
| 571 |
+
|
| 572 |
+
results_filename = f"{run_id or f'cobot_{DATE_TIME}'}_results.json"
|
| 573 |
+
results_subdir = os.path.join(cfg.local_log_dir, cfg.unnorm_key or "default")
|
| 574 |
+
os.makedirs(results_subdir, exist_ok=True)
|
| 575 |
+
results_path = os.path.join(results_subdir, results_filename)
|
| 576 |
+
with open(results_path, "w") as f:
|
| 577 |
+
json.dump(trial_results, f, indent=2)
|
| 578 |
+
log_message(f"Saved trial results to {results_path}", log_file)
|
| 579 |
+
|
| 580 |
+
return trial_results
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
def main():
|
| 584 |
+
"""Main function."""
|
| 585 |
+
parser = argparse.ArgumentParser(description="OpenVLA remote inference with local ROS control")
|
| 586 |
+
|
| 587 |
+
# Model parameters
|
| 588 |
+
parser.add_argument('--model_family', type=str, default='openvla', help='Model family')
|
| 589 |
+
parser.add_argument('--center_crop', action='store_true', help='Center crop images')
|
| 590 |
+
parser.add_argument('--num_open_loop_steps', type=int, default=25, help='Open loop steps')
|
| 591 |
+
|
| 592 |
+
# Server parameters
|
| 593 |
+
parser.add_argument('--use_vla_server', action='store_true', default=True, help='Use VLA server')
|
| 594 |
+
parser.add_argument('--vla_server_url', type=str, default='0.0.0.0', help='VLA server URL')
|
| 595 |
+
parser.add_argument('--unnorm_key', type=str, default='', help='Dataset key for action un-normalization')
|
| 596 |
+
|
| 597 |
+
# Robot control parameters
|
| 598 |
+
parser.add_argument('--max_publish_step', type=int, default=10000, help='Max steps per episode')
|
| 599 |
+
parser.add_argument('--publish_rate', type=int, default=40, help='Control frequency Hz')
|
| 600 |
+
parser.add_argument('--num_trials', type=int, default=10, help='Number of inference trials to record')
|
| 601 |
+
parser.add_argument('--use_relative_actions', action='store_true', help='Use relative actions')
|
| 602 |
+
parser.add_argument('--pos_lookahead_step', type=int, default=25, help='Lookahead steps')
|
| 603 |
+
|
| 604 |
+
# ROS topics
|
| 605 |
+
parser.add_argument('--img_front_topic', type=str, default='/camera_f/color/image_raw')
|
| 606 |
+
parser.add_argument('--img_left_topic', type=str, default='/camera_l/color/image_raw')
|
| 607 |
+
parser.add_argument('--img_right_topic', type=str, default='/camera_r/color/image_raw')
|
| 608 |
+
parser.add_argument('--puppet_arm_left_topic', type=str, default='/puppet/joint_left')
|
| 609 |
+
parser.add_argument('--puppet_arm_right_topic', type=str, default='/puppet/joint_right')
|
| 610 |
+
parser.add_argument('--puppet_arm_left_cmd_topic', type=str, default='/master/joint_left')
|
| 611 |
+
parser.add_argument('--puppet_arm_right_cmd_topic', type=str, default='/master/joint_right')
|
| 612 |
+
parser.add_argument('--robot_base_topic', type=str, default='/odom_raw')
|
| 613 |
+
parser.add_argument('--robot_base_cmd_topic', type=str, default='/cmd_vel')
|
| 614 |
+
|
| 615 |
+
# Robot base
|
| 616 |
+
parser.add_argument('--use_robot_base', action='store_true', help='Use robot base')
|
| 617 |
+
parser.add_argument('--use_actions_interpolation', action='store_true', help='Use action interpolation')
|
| 618 |
+
|
| 619 |
+
# Utils
|
| 620 |
+
parser.add_argument('--run_id_note', type=str, help='Run ID note')
|
| 621 |
+
parser.add_argument('--local_log_dir', type=str, default='./experiments/logs', help='Log directory')
|
| 622 |
+
parser.add_argument('--seed', type=int, default=7, help='Random seed')
|
| 623 |
+
parser.add_argument('--task_label', type=str, default='', help='Default task label for get_next_task_label')
|
| 624 |
+
|
| 625 |
+
args = parser.parse_args()
|
| 626 |
+
|
| 627 |
+
# Create config from args
|
| 628 |
+
cfg = OpenVLAConfig(
|
| 629 |
+
model_family=args.model_family,
|
| 630 |
+
center_crop=args.center_crop,
|
| 631 |
+
num_open_loop_steps=args.num_open_loop_steps,
|
| 632 |
+
use_vla_server=args.use_vla_server,
|
| 633 |
+
vla_server_url=args.vla_server_url,
|
| 634 |
+
unnorm_key=args.unnorm_key,
|
| 635 |
+
max_publish_step=args.max_publish_step,
|
| 636 |
+
publish_rate=args.publish_rate,
|
| 637 |
+
num_trials=args.num_trials,
|
| 638 |
+
use_relative_actions=args.use_relative_actions,
|
| 639 |
+
pos_lookahead_step=args.pos_lookahead_step,
|
| 640 |
+
img_front_topic=args.img_front_topic,
|
| 641 |
+
img_left_topic=args.img_left_topic,
|
| 642 |
+
img_right_topic=args.img_right_topic,
|
| 643 |
+
puppet_arm_left_topic=args.puppet_arm_left_topic,
|
| 644 |
+
puppet_arm_right_topic=args.puppet_arm_right_topic,
|
| 645 |
+
puppet_arm_left_cmd_topic=args.puppet_arm_left_cmd_topic,
|
| 646 |
+
puppet_arm_right_cmd_topic=args.puppet_arm_right_cmd_topic,
|
| 647 |
+
robot_base_topic=args.robot_base_topic,
|
| 648 |
+
robot_base_cmd_topic=args.robot_base_cmd_topic,
|
| 649 |
+
use_robot_base=args.use_robot_base,
|
| 650 |
+
use_actions_interpolation=args.use_actions_interpolation,
|
| 651 |
+
run_id_note=args.run_id_note,
|
| 652 |
+
local_log_dir=args.local_log_dir,
|
| 653 |
+
seed=args.seed,
|
| 654 |
+
task_label=args.task_label,
|
| 655 |
+
)
|
| 656 |
+
|
| 657 |
+
# Validate config
|
| 658 |
+
validate_config(cfg)
|
| 659 |
+
|
| 660 |
+
# Set random seed
|
| 661 |
+
set_seed_everywhere(cfg.seed)
|
| 662 |
+
|
| 663 |
+
# Setup logging
|
| 664 |
+
log_file, local_log_filepath, run_id = setup_logging(cfg)
|
| 665 |
+
|
| 666 |
+
# Initialize ROS operator
|
| 667 |
+
ros_operator = RosOperator(cfg)
|
| 668 |
+
|
| 669 |
+
log_message("OpenVLA remote inference initialized", log_file)
|
| 670 |
+
log_message(f"Config: {cfg}", log_file)
|
| 671 |
+
|
| 672 |
+
try:
|
| 673 |
+
# Run inference loop
|
| 674 |
+
run_inference_loop(cfg, ros_operator, log_file, run_id=run_id)
|
| 675 |
+
finally:
|
| 676 |
+
if log_file:
|
| 677 |
+
log_file.close()
|
| 678 |
+
|
| 679 |
+
|
| 680 |
+
if __name__ == "__main__":
|
| 681 |
+
main()
|
VLA-Adapter-UAV/experiments/robot/aloha/run_fake_cobot_client.py
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/python3
|
| 2 |
+
"""
|
| 3 |
+
run_fake_cobot_client.py
|
| 4 |
+
|
| 5 |
+
Lightweight client that mimics the cobot inference loop without requiring ROS.
|
| 6 |
+
It fabricates proprioception and image observations with the same shapes as the
|
| 7 |
+
real robot logs (e.g., qpos (14,), camera frames 480x640x3) and streams them to
|
| 8 |
+
the remote OpenVLA server over MsgPack HTTP.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import logging
|
| 13 |
+
import os
|
| 14 |
+
import socket
|
| 15 |
+
import sys
|
| 16 |
+
import time
|
| 17 |
+
from collections import deque
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from typing import Optional, Union
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
np.set_printoptions(precision=8, suppress=True)
|
| 24 |
+
|
| 25 |
+
from experiments.robot.openvla_utils import resize_image_for_policy
|
| 26 |
+
from experiments.robot.robot_utils import (
|
| 27 |
+
DATE_TIME,
|
| 28 |
+
MsgPackHttpClientPolicy,
|
| 29 |
+
get_image_resize_size,
|
| 30 |
+
set_seed_everywhere,
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
# Append current directory so that interpreter can find experiments.robot
|
| 34 |
+
sys.path.append(".")
|
| 35 |
+
|
| 36 |
+
# Set up logging
|
| 37 |
+
logging.basicConfig(
|
| 38 |
+
level=logging.INFO,
|
| 39 |
+
format="%(asctime)s [%(levelname)s] %(message)s",
|
| 40 |
+
handlers=[logging.StreamHandler()],
|
| 41 |
+
)
|
| 42 |
+
logger = logging.getLogger(__name__)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@dataclass
|
| 46 |
+
class FakeOpenVLAConfig:
|
| 47 |
+
# fmt: off
|
| 48 |
+
#################################################################################################################
|
| 49 |
+
# Server parameters
|
| 50 |
+
#################################################################################################################
|
| 51 |
+
use_vla_server: bool = True # Whether to query remote VLA server for actions
|
| 52 |
+
vla_server_url: Union[str, Path] = "0.0.0.0" # Remote VLA server URL
|
| 53 |
+
unnorm_key: str = "" # Dataset key for action un-normalization
|
| 54 |
+
|
| 55 |
+
#################################################################################################################
|
| 56 |
+
# Model parameters
|
| 57 |
+
#################################################################################################################
|
| 58 |
+
model_family: str = "openvla"
|
| 59 |
+
center_crop: bool = True
|
| 60 |
+
num_open_loop_steps: int = 25
|
| 61 |
+
|
| 62 |
+
#################################################################################################################
|
| 63 |
+
# Fake stream parameters
|
| 64 |
+
#################################################################################################################
|
| 65 |
+
sequence_length: int = 260 # Matches collected episode length
|
| 66 |
+
num_joints: int = 14 # qpos dimensionality per frame
|
| 67 |
+
image_height: int = 480
|
| 68 |
+
image_width: int = 640
|
| 69 |
+
max_publish_step: int = 1000 # Safety upper bound for loop
|
| 70 |
+
|
| 71 |
+
#################################################################################################################
|
| 72 |
+
# Utils
|
| 73 |
+
#################################################################################################################
|
| 74 |
+
run_id_note: Optional[str] = None
|
| 75 |
+
local_log_dir: str = "./experiments/logs"
|
| 76 |
+
seed: int = 7
|
| 77 |
+
task_label: str = "open the box"
|
| 78 |
+
# fmt: on
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class FakeRobotStream:
|
| 82 |
+
"""Generates deterministic fake proprio and image observations."""
|
| 83 |
+
|
| 84 |
+
def __init__(self, cfg: FakeOpenVLAConfig):
|
| 85 |
+
self.cfg = cfg
|
| 86 |
+
self.rng = np.random.default_rng(cfg.seed)
|
| 87 |
+
self.step = 0
|
| 88 |
+
|
| 89 |
+
def reset(self):
|
| 90 |
+
self.step = 0
|
| 91 |
+
|
| 92 |
+
def get_observation(self):
|
| 93 |
+
"""
|
| 94 |
+
Returns a dictionary shaped like the real ROS observation:
|
| 95 |
+
- images: cam_high, cam_left_wrist, cam_right_wrist in 480x640x3 uint8
|
| 96 |
+
- qpos: 14D vector (matches dataset episode shape (260, 14))
|
| 97 |
+
"""
|
| 98 |
+
if self.step >= self.cfg.sequence_length:
|
| 99 |
+
return None
|
| 100 |
+
|
| 101 |
+
t = self.step
|
| 102 |
+
base_angles = np.linspace(-np.pi, np.pi, self.cfg.num_joints)
|
| 103 |
+
qpos = np.sin(base_angles + 0.05 * t).astype(np.float32)
|
| 104 |
+
qpos += 0.01 * self.rng.standard_normal(self.cfg.num_joints).astype(np.float32)
|
| 105 |
+
|
| 106 |
+
observation = {
|
| 107 |
+
"images": {
|
| 108 |
+
"cam_high": self._generate_image(t, 0.0),
|
| 109 |
+
"cam_left_wrist": self._generate_image(t, 0.25),
|
| 110 |
+
"cam_right_wrist": self._generate_image(t, 0.5),
|
| 111 |
+
},
|
| 112 |
+
"qpos": qpos,
|
| 113 |
+
}
|
| 114 |
+
self.step += 1
|
| 115 |
+
return observation
|
| 116 |
+
|
| 117 |
+
def _generate_image(self, step: int, phase: float) -> np.ndarray:
|
| 118 |
+
"""Create a simple gradient pattern with slight temporal variation."""
|
| 119 |
+
height, width = self.cfg.image_height, self.cfg.image_width
|
| 120 |
+
x = np.linspace(0, 1, width, dtype=np.float32)
|
| 121 |
+
y = np.linspace(0, 1, height, dtype=np.float32)[:, None]
|
| 122 |
+
base = (x + y + 0.02 * step + phase) % 1.0
|
| 123 |
+
img = np.stack(
|
| 124 |
+
[
|
| 125 |
+
base,
|
| 126 |
+
np.roll(base, 1, axis=1),
|
| 127 |
+
np.roll(base, 2, axis=1),
|
| 128 |
+
],
|
| 129 |
+
axis=-1,
|
| 130 |
+
)
|
| 131 |
+
noise = self.rng.uniform(-0.02, 0.02, size=img.shape)
|
| 132 |
+
img = np.clip(img + noise, 0.0, 1.0)
|
| 133 |
+
return (img * 255).astype(np.uint8)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def setup_logging(cfg: FakeOpenVLAConfig):
|
| 137 |
+
"""Set up logging to file."""
|
| 138 |
+
run_id = f"OPENVLA-FAKE-INFERENCE-{cfg.model_family}-{DATE_TIME}"
|
| 139 |
+
if cfg.run_id_note is not None:
|
| 140 |
+
run_id += f"--{cfg.run_id_note}"
|
| 141 |
+
|
| 142 |
+
os.makedirs(cfg.local_log_dir, exist_ok=True)
|
| 143 |
+
local_log_filepath = os.path.join(cfg.local_log_dir, run_id + ".txt")
|
| 144 |
+
log_file = open(local_log_filepath, "w")
|
| 145 |
+
logger.info(f"Logging to local log file: {local_log_filepath}")
|
| 146 |
+
return log_file, local_log_filepath, run_id
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def log_message(message: str, log_file=None):
|
| 150 |
+
"""Log a message to console and optionally to a log file."""
|
| 151 |
+
print(message)
|
| 152 |
+
logger.info(message)
|
| 153 |
+
if log_file:
|
| 154 |
+
log_file.write(message + "\n")
|
| 155 |
+
log_file.flush()
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def validate_config(cfg: FakeOpenVLAConfig):
|
| 159 |
+
assert cfg.use_vla_server, "Fake client still requires --use_vla_server for remote inference."
|
| 160 |
+
assert cfg.vla_server_url, "A valid --vla_server_url must be provided."
|
| 161 |
+
assert cfg.unnorm_key, "A valid --unnorm_key matching the remote policy is required."
|
| 162 |
+
assert cfg.sequence_length > 0, "--sequence_length must be positive."
|
| 163 |
+
assert cfg.num_joints > 0, "--num_joints must be positive."
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def get_server_endpoint(cfg: FakeOpenVLAConfig):
|
| 167 |
+
"""Normalize different URL formats into a base URL for MsgPack client."""
|
| 168 |
+
server_url = str(cfg.vla_server_url).strip()
|
| 169 |
+
if server_url.startswith("http"):
|
| 170 |
+
return server_url.rstrip("/")
|
| 171 |
+
|
| 172 |
+
host_and_path = server_url.split("/", 1)[0]
|
| 173 |
+
if ":" in host_and_path:
|
| 174 |
+
host, port = host_and_path.split(":", 1)
|
| 175 |
+
else:
|
| 176 |
+
host, port = host_and_path, "8777"
|
| 177 |
+
|
| 178 |
+
ip_address = socket.gethostbyname(host)
|
| 179 |
+
protocol = "https" if any(keyword in host for keyword in ("nat-notebook", "ngrok")) else "http"
|
| 180 |
+
return f"{protocol}://{ip_address}:{port}"
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def prepare_observation_for_server(obs_data, task_description, resize_size, unnorm_key):
|
| 184 |
+
"""Format fake observation into the payload required by the server."""
|
| 185 |
+
img_front = resize_image_for_policy(obs_data["images"]["cam_high"], resize_size)
|
| 186 |
+
left_wrist = resize_image_for_policy(obs_data["images"]["cam_left_wrist"], resize_size)
|
| 187 |
+
right_wrist = resize_image_for_policy(obs_data["images"]["cam_right_wrist"], resize_size)
|
| 188 |
+
|
| 189 |
+
observation = {
|
| 190 |
+
"full_image": img_front,
|
| 191 |
+
"left_wrist_image": left_wrist,
|
| 192 |
+
"right_wrist_image": right_wrist,
|
| 193 |
+
"state": obs_data["qpos"],
|
| 194 |
+
"instruction": task_description,
|
| 195 |
+
"unnorm_key": unnorm_key,
|
| 196 |
+
}
|
| 197 |
+
return observation
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def run_inference_loop(cfg: FakeOpenVLAConfig, log_file=None):
|
| 201 |
+
"""Main fake inference loop."""
|
| 202 |
+
resize_size = get_image_resize_size(cfg)
|
| 203 |
+
server_endpoint = get_server_endpoint(cfg)
|
| 204 |
+
client = MsgPackHttpClientPolicy(host=server_endpoint)
|
| 205 |
+
log_message(f"Connecting to OpenVLA server at: {client.infer_url}", log_file)
|
| 206 |
+
log_message(f"Task: {cfg.task_label}", log_file)
|
| 207 |
+
|
| 208 |
+
stream = FakeRobotStream(cfg)
|
| 209 |
+
action_queue = deque(maxlen=cfg.num_open_loop_steps)
|
| 210 |
+
|
| 211 |
+
total_model_query_time = 0.0
|
| 212 |
+
t = 0
|
| 213 |
+
|
| 214 |
+
try:
|
| 215 |
+
while t < min(cfg.max_publish_step, cfg.sequence_length):
|
| 216 |
+
obs_data = stream.get_observation()
|
| 217 |
+
if obs_data is None:
|
| 218 |
+
log_message("Fake stream exhausted. Stopping episode.", log_file)
|
| 219 |
+
break
|
| 220 |
+
|
| 221 |
+
if len(action_queue) == 0:
|
| 222 |
+
observation = prepare_observation_for_server(
|
| 223 |
+
obs_data,
|
| 224 |
+
cfg.task_label,
|
| 225 |
+
resize_size,
|
| 226 |
+
cfg.unnorm_key,
|
| 227 |
+
)
|
| 228 |
+
log_message("Requerying OpenVLA server...", log_file)
|
| 229 |
+
model_query_start_time = time.time()
|
| 230 |
+
try:
|
| 231 |
+
response = client.infer(observation)
|
| 232 |
+
except Exception as exc:
|
| 233 |
+
log_message(f"Error querying server: {exc}", log_file)
|
| 234 |
+
break
|
| 235 |
+
actions = np.array(response["actions"])
|
| 236 |
+
actions = actions[: cfg.num_open_loop_steps]
|
| 237 |
+
total_model_query_time += time.time() - model_query_start_time
|
| 238 |
+
action_queue.extend(actions)
|
| 239 |
+
log_message(f"Received {len(actions)} actions from server", log_file)
|
| 240 |
+
|
| 241 |
+
action = action_queue.popleft()
|
| 242 |
+
log_message(f"Step {t}: action={action}", log_file)
|
| 243 |
+
t += 1
|
| 244 |
+
|
| 245 |
+
log_message("\nEpisode completed:", log_file)
|
| 246 |
+
log_message(f"Total steps: {t}", log_file)
|
| 247 |
+
log_message(f"Total model query time: {total_model_query_time:.2f} sec", log_file)
|
| 248 |
+
except KeyboardInterrupt:
|
| 249 |
+
log_message("\nCaught KeyboardInterrupt: Terminating episode early.", log_file)
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def main():
|
| 253 |
+
parser = argparse.ArgumentParser(description="Fake OpenVLA remote inference client (no ROS).")
|
| 254 |
+
|
| 255 |
+
# Server parameters
|
| 256 |
+
parser.add_argument("--use_vla_server", action="store_true", default=True, help="Use VLA server")
|
| 257 |
+
parser.add_argument("--vla_server_url", type=str, default="0.0.0.0", help="VLA server URL")
|
| 258 |
+
parser.add_argument("--unnorm_key", type=str, default="", help="Dataset key for action un-normalization")
|
| 259 |
+
|
| 260 |
+
# Model parameters
|
| 261 |
+
parser.add_argument("--model_family", type=str, default="openvla", help="Model family")
|
| 262 |
+
parser.add_argument("--center_crop", action="store_true", help="Center crop images")
|
| 263 |
+
parser.add_argument("--num_open_loop_steps", type=int, default=25, help="Open loop steps")
|
| 264 |
+
|
| 265 |
+
# Fake stream parameters
|
| 266 |
+
parser.add_argument("--sequence_length", type=int, default=260, help="Length of fake episode")
|
| 267 |
+
parser.add_argument("--num_joints", type=int, default=14, help="Dimensionality of qpos vector")
|
| 268 |
+
parser.add_argument("--image_height", type=int, default=480, help="Source image height")
|
| 269 |
+
parser.add_argument("--image_width", type=int, default=640, help="Source image width")
|
| 270 |
+
parser.add_argument("--max_publish_step", type=int, default=1000, help="Maximum steps to execute")
|
| 271 |
+
|
| 272 |
+
# Utils
|
| 273 |
+
parser.add_argument("--run_id_note", type=str, help="Run ID note")
|
| 274 |
+
parser.add_argument("--local_log_dir", type=str, default="./experiments/logs", help="Log directory")
|
| 275 |
+
parser.add_argument("--seed", type=int, default=7, help="Random seed")
|
| 276 |
+
parser.add_argument("--task_label", type=str, default="open the box", help="Task description")
|
| 277 |
+
|
| 278 |
+
args = parser.parse_args()
|
| 279 |
+
|
| 280 |
+
cfg = FakeOpenVLAConfig(
|
| 281 |
+
use_vla_server=args.use_vla_server,
|
| 282 |
+
vla_server_url=args.vla_server_url,
|
| 283 |
+
unnorm_key=args.unnorm_key,
|
| 284 |
+
model_family=args.model_family,
|
| 285 |
+
center_crop=args.center_crop,
|
| 286 |
+
num_open_loop_steps=args.num_open_loop_steps,
|
| 287 |
+
sequence_length=args.sequence_length,
|
| 288 |
+
num_joints=args.num_joints,
|
| 289 |
+
image_height=args.image_height,
|
| 290 |
+
image_width=args.image_width,
|
| 291 |
+
max_publish_step=args.max_publish_step,
|
| 292 |
+
run_id_note=args.run_id_note,
|
| 293 |
+
local_log_dir=args.local_log_dir,
|
| 294 |
+
seed=args.seed,
|
| 295 |
+
task_label=args.task_label,
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
validate_config(cfg)
|
| 299 |
+
set_seed_everywhere(cfg.seed)
|
| 300 |
+
|
| 301 |
+
log_file, _, _ = setup_logging(cfg)
|
| 302 |
+
try:
|
| 303 |
+
run_inference_loop(cfg, log_file)
|
| 304 |
+
finally:
|
| 305 |
+
if log_file:
|
| 306 |
+
log_file.close()
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
if __name__ == "__main__":
|
| 310 |
+
main()
|
VLA-Adapter-UAV/experiments/robot/aloha/train_files/dinosiglip_vit_local_vision.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
dinosiglip_vit.py
|
| 3 |
+
|
| 4 |
+
Vision backbone that returns concatenated features from both DINOv2 and SigLIP.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from functools import partial
|
| 9 |
+
from typing import Callable, Dict, Tuple
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
import timm
|
| 13 |
+
import torch
|
| 14 |
+
from PIL import Image
|
| 15 |
+
from timm.models.vision_transformer import Block, VisionTransformer
|
| 16 |
+
from torch.distributed.fsdp.wrap import _module_wrap_policy, _or_policy, transformer_auto_wrap_policy
|
| 17 |
+
from torchvision.transforms import Compose, Resize
|
| 18 |
+
|
| 19 |
+
from prismatic.models.backbones.vision.base_vision import (
|
| 20 |
+
ImageTransform,
|
| 21 |
+
LetterboxPad,
|
| 22 |
+
VisionBackbone,
|
| 23 |
+
compute_sequence_patches,
|
| 24 |
+
unpack_tuple,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
# Registry =>> Supported DinoSigLIP Pairs (as TIMM identifiers)
|
| 28 |
+
DINOSigLIP_VISION_BACKBONES = {
|
| 29 |
+
"dinosiglip-vit-so-224px": {
|
| 30 |
+
"dino": "vit_large_patch14_reg4_dinov2.lvd142m",
|
| 31 |
+
"siglip": "vit_so400m_patch14_siglip_224",
|
| 32 |
+
},
|
| 33 |
+
"dinosiglip-vit-so-384px": {
|
| 34 |
+
"dino": "vit_large_patch14_reg4_dinov2.lvd142m",
|
| 35 |
+
"siglip": "vit_so400m_patch14_siglip_384",
|
| 36 |
+
},
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@dataclass
|
| 41 |
+
class DinoSigLIPImageTransform:
|
| 42 |
+
dino_image_transform: ImageTransform
|
| 43 |
+
siglip_image_transform: ImageTransform
|
| 44 |
+
is_prismatic: bool = True
|
| 45 |
+
|
| 46 |
+
def __call__(self, img: Image, **kwargs: str) -> Dict[str, torch.Tensor]:
|
| 47 |
+
return {"dino": self.dino_image_transform(img, **kwargs), "siglip": self.siglip_image_transform(img, **kwargs)}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def find_hf_checkpoint(model_dir: Path) -> Path:
|
| 51 |
+
"""Find the model checkpoint file within a Hugging Face Hub cache directory."""
|
| 52 |
+
for pattern in ["*.bin"]:
|
| 53 |
+
if files := list(model_dir.glob(pattern)):
|
| 54 |
+
return files[0]
|
| 55 |
+
|
| 56 |
+
raise FileNotFoundError(f"No model checkpoint file found in {model_dir} or its snapshots.")
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class DinoSigLIPViTBackbone(VisionBackbone):
|
| 60 |
+
def __init__(
|
| 61 |
+
self,
|
| 62 |
+
vision_backbone_id: str,
|
| 63 |
+
image_resize_strategy: str,
|
| 64 |
+
default_image_size: int = 224,
|
| 65 |
+
image_sequence_len: int = 1,
|
| 66 |
+
vision_models_path: str = None,
|
| 67 |
+
) -> None:
|
| 68 |
+
super().__init__(
|
| 69 |
+
vision_backbone_id,
|
| 70 |
+
image_resize_strategy,
|
| 71 |
+
default_image_size=default_image_size,
|
| 72 |
+
image_sequence_len=image_sequence_len,
|
| 73 |
+
)
|
| 74 |
+
dino_model_name = DINOSigLIP_VISION_BACKBONES[vision_backbone_id]["dino"]
|
| 75 |
+
siglip_model_name = DINOSigLIP_VISION_BACKBONES[vision_backbone_id]["siglip"]
|
| 76 |
+
|
| 77 |
+
# Create model keyword arguments
|
| 78 |
+
dino_kwargs = {"pretrained": False, "num_classes": 0, "img_size": self.default_image_size}
|
| 79 |
+
siglip_kwargs = {"pretrained": False, "num_classes": 0, "img_size": self.default_image_size}
|
| 80 |
+
|
| 81 |
+
# If a local path is provided, update kwargs to load from local checkpoints.
|
| 82 |
+
if vision_models_path:
|
| 83 |
+
if siglip_model_name == 'vit_so400m_patch14_siglip_224':
|
| 84 |
+
siglip_model_local_path = 'ViT-SO400M-14-SigLIP'
|
| 85 |
+
else:
|
| 86 |
+
siglip_model_local_path = siglip_model_name
|
| 87 |
+
|
| 88 |
+
dino_dir = Path(vision_models_path) / f"{dino_model_name}"
|
| 89 |
+
siglip_dir = Path(vision_models_path) / f"{siglip_model_local_path}"
|
| 90 |
+
|
| 91 |
+
dino_checkpoint = find_hf_checkpoint(dino_dir)
|
| 92 |
+
siglip_checkpoint = find_hf_checkpoint(siglip_dir)
|
| 93 |
+
|
| 94 |
+
dino_kwargs["checkpoint_path"] = str(dino_checkpoint)
|
| 95 |
+
siglip_kwargs["checkpoint_path"] = str(siglip_checkpoint)
|
| 96 |
+
|
| 97 |
+
# Initialize both Featurizers (ViTs) by downloading from HF / TIMM Hub or loading from local path
|
| 98 |
+
self.dino_featurizer: VisionTransformer = timm.create_model(dino_model_name, **dino_kwargs)
|
| 99 |
+
self.dino_featurizer.eval()
|
| 100 |
+
|
| 101 |
+
self.siglip_featurizer: VisionTransformer = timm.create_model(siglip_model_name, **siglip_kwargs)
|
| 102 |
+
self.siglip_featurizer.eval()
|
| 103 |
+
|
| 104 |
+
# Monkey-Patch the `forward()` function of the featurizers to ensure FSDP-compatibility
|
| 105 |
+
# => Note: By default set `get_intermediate_layers` to return the *SECOND-TO-LAST* layer patches!
|
| 106 |
+
# => TODO (siddk) Remove after resolution of https://github.com/pytorch/pytorch/issues/109385
|
| 107 |
+
self.dino_featurizer.forward = unpack_tuple(
|
| 108 |
+
partial(self.dino_featurizer.get_intermediate_layers, n={len(self.dino_featurizer.blocks) - 2})
|
| 109 |
+
)
|
| 110 |
+
self.siglip_featurizer.forward = unpack_tuple(
|
| 111 |
+
partial(self.siglip_featurizer.get_intermediate_layers, n={len(self.siglip_featurizer.blocks) - 2})
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
# Get Configs for _both_ Featurizers =>> Note :: Override default image size for larger resolution models
|
| 115 |
+
self.dino_data_cfg = timm.data.resolve_model_data_config(self.dino_featurizer)
|
| 116 |
+
self.dino_data_cfg["input_size"] = (3, self.default_image_size, self.default_image_size)
|
| 117 |
+
|
| 118 |
+
self.siglip_data_cfg = timm.data.resolve_model_data_config(self.siglip_featurizer)
|
| 119 |
+
self.siglip_data_cfg["input_size"] = (3, self.default_image_size, self.default_image_size)
|
| 120 |
+
|
| 121 |
+
# Initialize *both* Transforms
|
| 122 |
+
default_dino_transform = timm.data.create_transform(**self.dino_data_cfg, is_training=False)
|
| 123 |
+
default_siglip_transform = timm.data.create_transform(**self.siglip_data_cfg, is_training=False)
|
| 124 |
+
|
| 125 |
+
# Fix =>> SigLIP default transform resizes to *larger* than `self.default_image_size` (crops image)!!
|
| 126 |
+
assert isinstance(default_siglip_transform, Compose), "Unexpected `default_image_transform`!"
|
| 127 |
+
assert isinstance(default_siglip_transform.transforms[0], Resize)
|
| 128 |
+
default_siglip_transform = Compose(
|
| 129 |
+
[
|
| 130 |
+
Resize(self.default_image_size, interpolation=default_siglip_transform.transforms[0].interpolation),
|
| 131 |
+
*default_siglip_transform.transforms[1:],
|
| 132 |
+
]
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
if self.image_resize_strategy == "resize-naive":
|
| 136 |
+
assert isinstance(default_dino_transform, Compose), "Unexpected `default_dino_image_transform`!"
|
| 137 |
+
assert isinstance(default_siglip_transform, Compose), "Unexpected `default_siglip_image_transform`!"
|
| 138 |
+
assert isinstance(default_dino_transform.transforms[0], Resize)
|
| 139 |
+
assert isinstance(default_siglip_transform.transforms[0], Resize)
|
| 140 |
+
|
| 141 |
+
target_size = (self.default_image_size, self.default_image_size)
|
| 142 |
+
dino_transform = Compose(
|
| 143 |
+
[
|
| 144 |
+
Resize(target_size, interpolation=default_dino_transform.transforms[0].interpolation),
|
| 145 |
+
*default_dino_transform.transforms[1:],
|
| 146 |
+
]
|
| 147 |
+
)
|
| 148 |
+
siglip_transform = Compose(
|
| 149 |
+
[
|
| 150 |
+
Resize(target_size, interpolation=default_siglip_transform.transforms[0].interpolation),
|
| 151 |
+
*default_siglip_transform.transforms[1:],
|
| 152 |
+
]
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
self.image_transform = DinoSigLIPImageTransform(dino_transform, siglip_transform)
|
| 156 |
+
|
| 157 |
+
elif self.image_resize_strategy == "resize-crop":
|
| 158 |
+
self.image_transform = DinoSigLIPImageTransform(default_dino_transform, default_siglip_transform)
|
| 159 |
+
|
| 160 |
+
elif self.image_resize_strategy == "letterbox":
|
| 161 |
+
assert isinstance(default_dino_transform, Compose), "Unexpected `default_dino_transform`!"
|
| 162 |
+
assert isinstance(default_siglip_transform, Compose), "Unexpected `default_siglip_transform`!"
|
| 163 |
+
assert (
|
| 164 |
+
"mean" in self.dino_data_cfg and "mean" in self.siglip_data_cfg
|
| 165 |
+
), "DinoSigLIP `data_cfg` missing `mean`!"
|
| 166 |
+
|
| 167 |
+
# Compute Padding Fill Value(s) (rescaled normalization mean if applicable)
|
| 168 |
+
dino_fill = tuple([int(x * 255) for x in self.dino_data_cfg["mean"]])
|
| 169 |
+
siglip_fill = tuple([int(x * 255) for x in self.siglip_data_cfg["mean"]])
|
| 170 |
+
|
| 171 |
+
# Build New Transform
|
| 172 |
+
self.image_transform = DinoSigLIPImageTransform(
|
| 173 |
+
Compose([LetterboxPad(dino_fill), *default_dino_transform.transforms]),
|
| 174 |
+
Compose([LetterboxPad(siglip_fill), *default_siglip_transform.transforms]),
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
else:
|
| 178 |
+
raise ValueError(f"Image Resize Strategy `{self.image_resize_strategy}` is not supported!")
|
| 179 |
+
|
| 180 |
+
def get_fsdp_wrapping_policy(self) -> Callable:
|
| 181 |
+
"""Return a simple FSDP policy that wraps each ViT block and then both of the _entire_ featurizers."""
|
| 182 |
+
vit_wrap_policy = partial(_module_wrap_policy, module_classes={VisionTransformer})
|
| 183 |
+
transformer_block_policy = partial(transformer_auto_wrap_policy, transformer_layer_cls={Block})
|
| 184 |
+
return partial(_or_policy, policies=[vit_wrap_policy, transformer_block_policy])
|
| 185 |
+
|
| 186 |
+
def forward(self, pixel_values: Dict[str, torch.Tensor]) -> torch.Tensor:
|
| 187 |
+
"""Runs the transformed image/pixel tensors through each vision backbone, returning concatenated patches."""
|
| 188 |
+
if self.image_sequence_len == 1:
|
| 189 |
+
dino_patches = self.dino_featurizer(pixel_values["dino"])
|
| 190 |
+
siglip_patches = self.siglip_featurizer(pixel_values["siglip"])
|
| 191 |
+
else:
|
| 192 |
+
featurizers = {
|
| 193 |
+
"dino": self.dino_featurizer,
|
| 194 |
+
"siglip": self.siglip_featurizer,
|
| 195 |
+
}
|
| 196 |
+
patches = compute_sequence_patches(pixel_values, featurizers, self.image_sequence_len)
|
| 197 |
+
dino_patches, siglip_patches = patches["dino"], patches["siglip"]
|
| 198 |
+
return torch.cat([dino_patches, siglip_patches], dim=2)
|
| 199 |
+
|
| 200 |
+
@property
|
| 201 |
+
def default_image_resolution(self) -> Tuple[int, int, int]:
|
| 202 |
+
return self.dino_data_cfg["input_size"]
|
| 203 |
+
|
| 204 |
+
@property
|
| 205 |
+
def embed_dim(self) -> int:
|
| 206 |
+
return self.dino_featurizer.embed_dim + self.siglip_featurizer.embed_dim
|
| 207 |
+
|
| 208 |
+
@property
|
| 209 |
+
def num_patches(self) -> int:
|
| 210 |
+
assert self.dino_featurizer.patch_embed.num_patches == self.siglip_featurizer.patch_embed.num_patches
|
| 211 |
+
return self.dino_featurizer.patch_embed.num_patches * self.image_sequence_len
|
| 212 |
+
|
| 213 |
+
@property
|
| 214 |
+
def half_precision_dtype(self) -> torch.dtype:
|
| 215 |
+
return torch.bfloat16
|
VLA-Adapter-UAV/experiments/robot/aloha/train_files/download_models.sh
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
#========== Download pretrained models from HuggingFace ==========#
|
| 3 |
+
#
|
| 4 |
+
# Usage:
|
| 5 |
+
# bash download_models.sh
|
| 6 |
+
# HF_TOKEN=your_huggingface_token bash download_models.sh
|
| 7 |
+
#
|
| 8 |
+
# HF_TOKEN is optional for public repos. If provided, it will be used.
|
| 9 |
+
# ROOT_DIR can be edited below or overridden via environment variable.
|
| 10 |
+
# Skips download if model directory already exists and is non-empty.
|
| 11 |
+
#
|
| 12 |
+
|
| 13 |
+
# User-configurable default root path.
|
| 14 |
+
DEFAULT_ROOT_DIR="/path/to/root"
|
| 15 |
+
ROOT_DIR="${ROOT_DIR:-${DEFAULT_ROOT_DIR}}"
|
| 16 |
+
MODEL_DIR="${ROOT_DIR}/ai_models"
|
| 17 |
+
HF_TOKEN="${HF_TOKEN:-}"
|
| 18 |
+
|
| 19 |
+
download_model() {
|
| 20 |
+
local repo="$1"
|
| 21 |
+
local local_dir="$2"
|
| 22 |
+
|
| 23 |
+
if [ -d "${local_dir}" ] && [ "$(ls -A "${local_dir}" 2>/dev/null)" ]; then
|
| 24 |
+
echo "[SKIP] ${repo} already exists at ${local_dir}"
|
| 25 |
+
return
|
| 26 |
+
fi
|
| 27 |
+
|
| 28 |
+
echo "[DOWNLOAD] ${repo} -> ${local_dir}"
|
| 29 |
+
if [ -n "${HF_TOKEN}" ]; then
|
| 30 |
+
huggingface-cli download --resume-download \
|
| 31 |
+
"${repo}" \
|
| 32 |
+
--local-dir "${local_dir}" \
|
| 33 |
+
--token "${HF_TOKEN}"
|
| 34 |
+
else
|
| 35 |
+
huggingface-cli download --resume-download \
|
| 36 |
+
"${repo}" \
|
| 37 |
+
--local-dir "${local_dir}"
|
| 38 |
+
fi
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
download_model "timm/vit_large_patch14_reg4_dinov2.lvd142m" \
|
| 42 |
+
"${MODEL_DIR}/timm/vit_large_patch14_reg4_dinov2.lvd142m"
|
| 43 |
+
|
| 44 |
+
download_model "timm/ViT-SO400M-14-SigLIP" \
|
| 45 |
+
"${MODEL_DIR}/timm/ViT-SO400M-14-SigLIP"
|
| 46 |
+
|
| 47 |
+
download_model "Qwen/Qwen2.5-0.5B" \
|
| 48 |
+
"${MODEL_DIR}/Qwen/Qwen2.5-0.5B"
|
| 49 |
+
|
| 50 |
+
download_model "St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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
materialize.py
|
| 3 |
+
|
| 4 |
+
Factory class for initializing Vision Backbones, LLM Backbones, and VLMs from a set registry; provides and exports
|
| 5 |
+
individual functions for clear control flow.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from typing import Optional, Tuple
|
| 9 |
+
|
| 10 |
+
from transformers import PreTrainedTokenizerBase
|
| 11 |
+
|
| 12 |
+
from prismatic.models.backbones.llm import LLaMa2LLMBackbone, LLMBackbone, MistralLLMBackbone, PhiLLMBackbone
|
| 13 |
+
from prismatic.models.backbones.llm.qwen25 import Qwen25LLMBackbone
|
| 14 |
+
from prismatic.models.backbones.vision import (
|
| 15 |
+
CLIPViTBackbone,
|
| 16 |
+
DinoCLIPViTBackbone,
|
| 17 |
+
DinoSigLIPViTBackbone,
|
| 18 |
+
DinoV2ViTBackbone,
|
| 19 |
+
ImageTransform,
|
| 20 |
+
IN1KViTBackbone,
|
| 21 |
+
SigLIPViTBackbone,
|
| 22 |
+
VisionBackbone,
|
| 23 |
+
)
|
| 24 |
+
from prismatic.models.vlms import PrismaticVLM
|
| 25 |
+
|
| 26 |
+
# === Registries =>> Maps ID --> {cls(), kwargs} :: Different Registries for Vision Backbones, LLM Backbones, VLMs ===
|
| 27 |
+
# fmt: off
|
| 28 |
+
|
| 29 |
+
# === Vision Backbone Registry ===
|
| 30 |
+
VISION_BACKBONES = {
|
| 31 |
+
# === 224px Backbones ===
|
| 32 |
+
"clip-vit-l": {"cls": CLIPViTBackbone, "kwargs": {"default_image_size": 224}},
|
| 33 |
+
"siglip-vit-so400m": {"cls": SigLIPViTBackbone, "kwargs": {"default_image_size": 224}},
|
| 34 |
+
"dinov2-vit-l": {"cls": DinoV2ViTBackbone, "kwargs": {"default_image_size": 224}},
|
| 35 |
+
"in1k-vit-l": {"cls": IN1KViTBackbone, "kwargs": {"default_image_size": 224}},
|
| 36 |
+
"dinosiglip-vit-so-224px": {"cls": DinoSigLIPViTBackbone, "kwargs": {"default_image_size": 224, "vision_models_path": "__LOCAL_TIMM_PATH__"}},
|
| 37 |
+
|
| 38 |
+
# === Assorted CLIP Backbones ===
|
| 39 |
+
"clip-vit-b": {"cls": CLIPViTBackbone, "kwargs": {"default_image_size": 224}},
|
| 40 |
+
"clip-vit-l-336px": {"cls": CLIPViTBackbone, "kwargs": {"default_image_size": 336}},
|
| 41 |
+
|
| 42 |
+
# === Assorted SigLIP Backbones ===
|
| 43 |
+
"siglip-vit-b16-224px": {"cls": SigLIPViTBackbone, "kwargs": {"default_image_size": 224}},
|
| 44 |
+
"siglip-vit-b16-256px": {"cls": SigLIPViTBackbone, "kwargs": {"default_image_size": 256}},
|
| 45 |
+
"siglip-vit-b16-384px": {"cls": SigLIPViTBackbone, "kwargs": {"default_image_size": 384}},
|
| 46 |
+
"siglip-vit-so400m-384px": {"cls": SigLIPViTBackbone, "kwargs": {"default_image_size": 384}},
|
| 47 |
+
|
| 48 |
+
# === Fused Backbones ===
|
| 49 |
+
"dinoclip-vit-l-336px": {"cls": DinoCLIPViTBackbone, "kwargs": {"default_image_size": 336}},
|
| 50 |
+
"dinosiglip-vit-so-384px": {"cls": DinoSigLIPViTBackbone, "kwargs": {"default_image_size": 384}},
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
# === Language Model Registry ===
|
| 55 |
+
LLM_BACKBONES = {
|
| 56 |
+
# === LLaMa-2 Pure (Non-Chat) Backbones ===
|
| 57 |
+
"llama2-7b-pure": {"cls": LLaMa2LLMBackbone, "kwargs": {}},
|
| 58 |
+
"llama2-13b-pure": {"cls": LLaMa2LLMBackbone, "kwargs": {}},
|
| 59 |
+
|
| 60 |
+
# === LLaMa-2 Chat Backbones ===
|
| 61 |
+
"llama2-7b-chat": {"cls": LLaMa2LLMBackbone, "kwargs": {}},
|
| 62 |
+
"llama2-13b-chat": {"cls": LLaMa2LLMBackbone, "kwargs": {}},
|
| 63 |
+
|
| 64 |
+
# === Vicuna-v1.5 Backbones ===
|
| 65 |
+
"vicuna-v15-7b": {"cls": LLaMa2LLMBackbone, "kwargs": {}},
|
| 66 |
+
"vicuna-v15-13b": {"cls": LLaMa2LLMBackbone, "kwargs": {}},
|
| 67 |
+
|
| 68 |
+
# === Mistral v0.1 Backbones ===
|
| 69 |
+
"mistral-v0.1-7b-pure": {"cls": MistralLLMBackbone, "kwargs": {}},
|
| 70 |
+
"mistral-v0.1-7b-instruct": {"cls": MistralLLMBackbone, "kwargs": {}},
|
| 71 |
+
|
| 72 |
+
# === Phi-2 Backbone ===
|
| 73 |
+
"phi-2-3b": {"cls": PhiLLMBackbone, "kwargs": {}},
|
| 74 |
+
|
| 75 |
+
# === Qwen2.5 Backbone ===
|
| 76 |
+
"qwen25-0_5b-pure": {"cls": Qwen25LLMBackbone, "kwargs": {}},
|
| 77 |
+
"qwen25-0_5b-extra": {"cls": Qwen25LLMBackbone, "kwargs": {"num_extra_tokens": 256}},
|
| 78 |
+
"qwen25-1_5b-pure": {"cls": Qwen25LLMBackbone, "kwargs": {}},
|
| 79 |
+
"qwen25-3b-pure": {"cls": Qwen25LLMBackbone, "kwargs": {}},
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
# fmt: on
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def get_vision_backbone_and_transform(
|
| 86 |
+
vision_backbone_id: str,
|
| 87 |
+
image_resize_strategy: str,
|
| 88 |
+
image_sequence_len: int,
|
| 89 |
+
) -> Tuple[VisionBackbone, ImageTransform]:
|
| 90 |
+
"""Instantiate a Vision Backbone, returning both the nn.Module wrapper class and default Image Transform."""
|
| 91 |
+
if vision_backbone_id in VISION_BACKBONES:
|
| 92 |
+
vision_cfg = VISION_BACKBONES[vision_backbone_id]
|
| 93 |
+
vision_backbone: VisionBackbone = vision_cfg["cls"](
|
| 94 |
+
vision_backbone_id, image_resize_strategy, image_sequence_len=image_sequence_len, **vision_cfg["kwargs"]
|
| 95 |
+
)
|
| 96 |
+
image_transform = vision_backbone.get_image_transform()
|
| 97 |
+
return vision_backbone, image_transform
|
| 98 |
+
|
| 99 |
+
else:
|
| 100 |
+
raise ValueError(f"Vision Backbone `{vision_backbone_id}` is not supported!")
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
# def _is_network_or_dns_error(e: Exception) -> bool:
|
| 104 |
+
# s = str(e)
|
| 105 |
+
# return (
|
| 106 |
+
# "Name or service not known" in s or
|
| 107 |
+
# "Failed to resolve" in s or
|
| 108 |
+
# "HTTPSConnectionPool" in s or
|
| 109 |
+
# isinstance(e, socket.gaierror)
|
| 110 |
+
# )
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# from typing import Tuple, Optional, Any, Dict
|
| 114 |
+
# def get_vision_backbone_and_transform(
|
| 115 |
+
# vision_backbone_id: str,
|
| 116 |
+
# image_resize_strategy: str,
|
| 117 |
+
# image_sequence_len: int,
|
| 118 |
+
# *,
|
| 119 |
+
# checkpoint_path: Optional[str] = None,
|
| 120 |
+
# pretrained: Optional[bool] = None,
|
| 121 |
+
# **extra_kwargs: Any,
|
| 122 |
+
# ) -> Tuple[VisionBackbone, ImageTransform]:
|
| 123 |
+
# """Instantiate a Vision Backbone, returning both the nn.Module wrapper class and default Image Transform."""
|
| 124 |
+
# if vision_backbone_id not in VISION_BACKBONES:
|
| 125 |
+
# raise ValueError(f"Vision Backbone `{vision_backbone_id}` is not supported!")
|
| 126 |
+
|
| 127 |
+
# vision_cfg = VISION_BACKBONES[vision_backbone_id]
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
# merged_kwargs: Dict[str, Any] = dict(vision_cfg["kwargs"])
|
| 131 |
+
# if pretrained is not None:
|
| 132 |
+
# merged_kwargs["pretrained"] = pretrained
|
| 133 |
+
# if checkpoint_path is not None:
|
| 134 |
+
# merged_kwargs["checkpoint_path"] = checkpoint_path
|
| 135 |
+
# merged_kwargs.update(extra_kwargs)
|
| 136 |
+
|
| 137 |
+
# vision_backbone: VisionBackbone = vision_cfg["cls"](
|
| 138 |
+
# vision_backbone_id,
|
| 139 |
+
# image_resize_strategy,
|
| 140 |
+
# image_sequence_len=image_sequence_len,
|
| 141 |
+
# **merged_kwargs,
|
| 142 |
+
# )
|
| 143 |
+
# image_transform = vision_backbone.get_image_transform()
|
| 144 |
+
# return vision_backbone, image_transform
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def get_llm_backbone_and_tokenizer(
|
| 148 |
+
llm_backbone_id: str,
|
| 149 |
+
llm_max_length: int = 2048,
|
| 150 |
+
hf_token: Optional[str] = None,
|
| 151 |
+
inference_mode: bool = False,
|
| 152 |
+
) -> Tuple[LLMBackbone, PreTrainedTokenizerBase]:
|
| 153 |
+
if llm_backbone_id in LLM_BACKBONES:
|
| 154 |
+
llm_cfg = LLM_BACKBONES[llm_backbone_id]
|
| 155 |
+
llm_backbone: LLMBackbone = llm_cfg["cls"](
|
| 156 |
+
llm_backbone_id,
|
| 157 |
+
llm_max_length=llm_max_length,
|
| 158 |
+
hf_token=hf_token,
|
| 159 |
+
inference_mode=inference_mode,
|
| 160 |
+
**llm_cfg["kwargs"],
|
| 161 |
+
)
|
| 162 |
+
tokenizer = llm_backbone.get_tokenizer()
|
| 163 |
+
return llm_backbone, tokenizer
|
| 164 |
+
|
| 165 |
+
else:
|
| 166 |
+
raise ValueError(f"LLM Backbone `{llm_backbone_id}` is not supported!")
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def get_vlm(
|
| 170 |
+
model_id: str,
|
| 171 |
+
arch_specifier: str,
|
| 172 |
+
vision_backbone: VisionBackbone,
|
| 173 |
+
llm_backbone: LLMBackbone,
|
| 174 |
+
enable_mixed_precision_training: bool = True,
|
| 175 |
+
) -> PrismaticVLM:
|
| 176 |
+
"""Lightweight wrapper around initializing a VLM, mostly for future-proofing (if one wants to add a new VLM)."""
|
| 177 |
+
return PrismaticVLM(
|
| 178 |
+
model_id,
|
| 179 |
+
vision_backbone,
|
| 180 |
+
llm_backbone,
|
| 181 |
+
enable_mixed_precision_training=enable_mixed_precision_training,
|
| 182 |
+
arch_specifier=arch_specifier,
|
| 183 |
+
)
|
VLA-Adapter-UAV/experiments/robot/aloha/train_files/qwen25.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
qwen2_5.py
|
| 3 |
+
|
| 4 |
+
Class definition for all LLMs derived from QwenForCausalLM.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from typing import Optional, Sequence, Type
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
from transformers import AutoModelForCausalLM
|
| 11 |
+
from transformers.models.qwen2.modeling_qwen2 import Qwen2DecoderLayer
|
| 12 |
+
|
| 13 |
+
from prismatic.models.backbones.llm.base_llm import HFCausalLLMBackbone
|
| 14 |
+
from prismatic.models.backbones.llm.prompting.base_prompter import PromptBuilder
|
| 15 |
+
from prismatic.models.backbones.llm.prompting.qwen_prompter import QwenPromptBuilder
|
| 16 |
+
|
| 17 |
+
# Registry =>> Support Qwen-2.5 Models (from HF Transformers)
|
| 18 |
+
# fmt: off
|
| 19 |
+
QWEN25_MODELS = {
|
| 20 |
+
# === Pure Qwen2.5 (non-instruct/chat-tuned) Models ===
|
| 21 |
+
"qwen25-0_5b-extra": {
|
| 22 |
+
"llm_family": "qwen2.5", "llm_cls": AutoModelForCausalLM, "hf_hub_path": "__LOCAL_QWEN_PATH__"
|
| 23 |
+
},
|
| 24 |
+
"qwen25-0_5b-pure": {
|
| 25 |
+
"llm_family": "qwen2.5", "llm_cls": AutoModelForCausalLM, "hf_hub_path": "Qwen/Qwen2.5-0.5B"
|
| 26 |
+
},
|
| 27 |
+
"qwen25-1_5b-pure": {
|
| 28 |
+
"llm_family": "qwen2.5", "llm_cls": AutoModelForCausalLM, "hf_hub_path": "Qwen/Qwen2.5-1.5B"
|
| 29 |
+
},
|
| 30 |
+
"qwen25-3b-pure": {
|
| 31 |
+
"llm_family": "qwen2.5", "llm_cls": AutoModelForCausalLM, "hf_hub_path": "Qwen/Qwen2.5-3B"
|
| 32 |
+
},
|
| 33 |
+
"qwen25-7b-pure": {
|
| 34 |
+
"llm_family": "qwen2.5", "llm_cls": AutoModelForCausalLM, "hf_hub_path": "Qwen/Qwen2.5-7B"
|
| 35 |
+
},
|
| 36 |
+
|
| 37 |
+
}
|
| 38 |
+
# fmt: on
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class Qwen25LLMBackbone(HFCausalLLMBackbone):
|
| 42 |
+
def __init__(
|
| 43 |
+
self,
|
| 44 |
+
llm_backbone_id: str,
|
| 45 |
+
llm_max_length: int = 2048,
|
| 46 |
+
hf_token: Optional[str] = None,
|
| 47 |
+
inference_mode: bool = False,
|
| 48 |
+
use_flash_attention_2: bool = True,
|
| 49 |
+
num_extra_tokens: int = 0,
|
| 50 |
+
) -> None:
|
| 51 |
+
super().__init__(
|
| 52 |
+
llm_backbone_id,
|
| 53 |
+
llm_max_length=llm_max_length,
|
| 54 |
+
hf_token=hf_token,
|
| 55 |
+
inference_mode=inference_mode,
|
| 56 |
+
use_flash_attention_2=use_flash_attention_2,
|
| 57 |
+
**QWEN25_MODELS[llm_backbone_id],
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
# add some more special tokens
|
| 61 |
+
if num_extra_tokens > 0:
|
| 62 |
+
added = self.tokenizer.add_tokens([f"<|extra_{i}|>" for i in range(num_extra_tokens)])
|
| 63 |
+
assert added == num_extra_tokens, f"Added {added} of {num_extra_tokens} extra tokens to tokenizer!"
|
| 64 |
+
print(f"Added {num_extra_tokens} extra tokens.")
|
| 65 |
+
|
| 66 |
+
# there is already a special token for Qwen
|
| 67 |
+
# self.tokenizer.add_special_tokens({"pad_token": "<PAD>"})
|
| 68 |
+
self.llm.config.pad_token_id = self.tokenizer.pad_token_id
|
| 69 |
+
self.llm.resize_token_embeddings(len(self.tokenizer), pad_to_multiple_of=64)
|
| 70 |
+
|
| 71 |
+
@property
|
| 72 |
+
def prompt_builder_fn(self) -> Type[PromptBuilder]:
|
| 73 |
+
return QwenPromptBuilder
|
| 74 |
+
|
| 75 |
+
@property
|
| 76 |
+
def transformer_layer_cls(self) -> Type[torch.nn.Module]:
|
| 77 |
+
return Qwen2DecoderLayer
|
| 78 |
+
|
| 79 |
+
@property
|
| 80 |
+
def half_precision_dtype(self) -> torch.dtype:
|
| 81 |
+
return torch.bfloat16
|
| 82 |
+
|
| 83 |
+
@property
|
| 84 |
+
def last_layer_finetune_modules(self) -> Sequence[torch.nn.Module]:
|
| 85 |
+
# TODO not sure that this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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
#========== One-click training setup: register dataset + local Qwen + optional local model loading ==========#
|
| 3 |
+
#
|
| 4 |
+
# Usage:
|
| 5 |
+
# bash setup_training.sh <dataset_name> [--local-models]
|
| 6 |
+
#
|
| 7 |
+
# Examples:
|
| 8 |
+
# # Register dataset only (vision models loaded from HF Hub)
|
| 9 |
+
# bash setup_training.sh bowl_stack_and_shelf_aloha_realworld_50
|
| 10 |
+
#
|
| 11 |
+
# # Register dataset + enable local model loading (no internet needed)
|
| 12 |
+
# bash setup_training.sh bowl_stack_and_shelf_aloha_realworld_50 --local-models
|
| 13 |
+
#
|
| 14 |
+
# What it does:
|
| 15 |
+
# 1. Adds the dataset entry to configs.py, mixtures.py, transforms.py
|
| 16 |
+
# 2. (--local-models) Replaces qwen25.py so qwen25-0_5b-extra loads from the local disk path
|
| 17 |
+
# 3. (--local-models) Replaces materialize.py and dinosiglip_vit.py with
|
| 18 |
+
# local-loading versions that read vision weights from disk instead of HF Hub
|
| 19 |
+
#
|
| 20 |
+
# How to restore overwritten files with git:
|
| 21 |
+
# cd <project_root>
|
| 22 |
+
# git restore prismatic/models/backbones/llm/qwen25.py
|
| 23 |
+
# git restore prismatic/models/materialize.py
|
| 24 |
+
# git restore prismatic/models/backbones/vision/dinosiglip_vit.py
|
| 25 |
+
#
|
| 26 |
+
# How to re-enable network download instead of local files:
|
| 27 |
+
# 1. Restore qwen25.py to re-enable HF loading for Qwen:
|
| 28 |
+
# git restore prismatic/models/backbones/llm/qwen25.py
|
| 29 |
+
# 2. If you previously used --local-models, also restore the two vision files:
|
| 30 |
+
# git restore prismatic/models/materialize.py
|
| 31 |
+
# git restore prismatic/models/backbones/vision/dinosiglip_vit.py
|
| 32 |
+
#
|
| 33 |
+
# Local path settings:
|
| 34 |
+
# Edit ROOT_DIR / LOCAL_QWEN_PATH / LOCAL_TIMM_PATH below before running this script.
|
| 35 |
+
# These values will be written into the overwritten training files.
|
| 36 |
+
#
|
| 37 |
+
|
| 38 |
+
set -euo pipefail
|
| 39 |
+
|
| 40 |
+
# User-configurable local model paths.
|
| 41 |
+
ROOT_DIR="${ROOT_DIR:-/path/to/root}"
|
| 42 |
+
LOCAL_QWEN_PATH="${LOCAL_QWEN_PATH:-${ROOT_DIR}/ai_models/Qwen/Qwen2.5-0.5B}"
|
| 43 |
+
LOCAL_TIMM_PATH="${LOCAL_TIMM_PATH:-${ROOT_DIR}/ai_models/timm}"
|
| 44 |
+
|
| 45 |
+
DATASET_NAME="${1:?Usage: bash setup_training.sh <dataset_name> [--local-models]}"
|
| 46 |
+
LOCAL_MODELS_FLAG="${2:-}"
|
| 47 |
+
|
| 48 |
+
# Auto-detect project root (script is at experiments/robot/aloha/train_files/)
|
| 49 |
+
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
| 50 |
+
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/../../../.." && pwd)"
|
| 51 |
+
|
| 52 |
+
CONFIGS="${PROJECT_ROOT}/prismatic/vla/datasets/rlds/oxe/configs.py"
|
| 53 |
+
MIXTURES="${PROJECT_ROOT}/prismatic/vla/datasets/rlds/oxe/mixtures.py"
|
| 54 |
+
TRANSFORMS="${PROJECT_ROOT}/prismatic/vla/datasets/rlds/oxe/transforms.py"
|
| 55 |
+
|
| 56 |
+
########################################
|
| 57 |
+
# Step 1: Register dataset
|
| 58 |
+
########################################
|
| 59 |
+
|
| 60 |
+
check_exists() {
|
| 61 |
+
if grep -q "\"${DATASET_NAME}\"" "$1" 2>/dev/null; then
|
| 62 |
+
echo "[SKIP] ${DATASET_NAME} already exists in $(basename $1)"
|
| 63 |
+
return 0
|
| 64 |
+
fi
|
| 65 |
+
return 1
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
render_template() {
|
| 69 |
+
local src="$1"
|
| 70 |
+
local dst="$2"
|
| 71 |
+
local qwen_escaped="${LOCAL_QWEN_PATH//&/\\&}"
|
| 72 |
+
local timm_escaped="${LOCAL_TIMM_PATH//&/\\&}"
|
| 73 |
+
|
| 74 |
+
sed \
|
| 75 |
+
-e "s|__LOCAL_QWEN_PATH__|${qwen_escaped}|g" \
|
| 76 |
+
-e "s|__LOCAL_TIMM_PATH__|${timm_escaped}|g" \
|
| 77 |
+
"${src}" > "${dst}"
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
# Add to configs.py
|
| 81 |
+
if ! check_exists "${CONFIGS}"; then
|
| 82 |
+
sed -i '/^}$/i\
|
| 83 |
+
"'"${DATASET_NAME}"'": {\
|
| 84 |
+
"image_obs_keys": {"primary": "image", "secondary": None, "left_wrist": "left_wrist_image", "right_wrist": "right_wrist_image"},\
|
| 85 |
+
"depth_obs_keys": {"primary": None, "secondary": None, "wrist": None},\
|
| 86 |
+
"state_obs_keys": ["state"],\
|
| 87 |
+
"state_encoding": StateEncoding.JOINT_BIMANUAL,\
|
| 88 |
+
"action_encoding": ActionEncoding.JOINT_POS_BIMANUAL,\
|
| 89 |
+
},' "${CONFIGS}"
|
| 90 |
+
echo "[ADDED] ${DATASET_NAME} to configs.py"
|
| 91 |
+
fi
|
| 92 |
+
|
| 93 |
+
# Add to mixtures.py
|
| 94 |
+
if ! check_exists "${MIXTURES}"; then
|
| 95 |
+
sed -i '/^# fmt: on$/i\
|
| 96 |
+
"'"${DATASET_NAME}"'": [\
|
| 97 |
+
("'"${DATASET_NAME}"'", 1.0),\
|
| 98 |
+
],' "${MIXTURES}"
|
| 99 |
+
echo "[ADDED] ${DATASET_NAME} to mixtures.py"
|
| 100 |
+
fi
|
| 101 |
+
|
| 102 |
+
# Add to transforms.py
|
| 103 |
+
if ! check_exists "${TRANSFORMS}"; then
|
| 104 |
+
sed -i '/^}$/i\
|
| 105 |
+
"'"${DATASET_NAME}"'": aloha_dataset_transform,' "${TRANSFORMS}"
|
| 106 |
+
echo "[ADDED] ${DATASET_NAME} to transforms.py"
|
| 107 |
+
fi
|
| 108 |
+
|
| 109 |
+
echo "[OK] Dataset '${DATASET_NAME}' registered."
|
| 110 |
+
|
| 111 |
+
########################################
|
| 112 |
+
# Step 2: Enable local model loading
|
| 113 |
+
########################################
|
| 114 |
+
|
| 115 |
+
if [ "${LOCAL_MODELS_FLAG}" = "--local-models" ] || [ "${LOCAL_MODELS_FLAG}" = "--local-vision" ]; then
|
| 116 |
+
QWEN25_SRC="${SCRIPT_DIR}/qwen25.py"
|
| 117 |
+
QWEN25_DST="${PROJECT_ROOT}/prismatic/models/backbones/llm/qwen25.py"
|
| 118 |
+
MATERIALIZE_SRC="${SCRIPT_DIR}/materialize_local_vision.py"
|
| 119 |
+
DINOSIGLIP_SRC="${SCRIPT_DIR}/dinosiglip_vit_local_vision.py"
|
| 120 |
+
MATERIALIZE_DST="${PROJECT_ROOT}/prismatic/models/materialize.py"
|
| 121 |
+
DINOSIGLIP_DST="${PROJECT_ROOT}/prismatic/models/backbones/vision/dinosiglip_vit.py"
|
| 122 |
+
|
| 123 |
+
if [ ! -f "${QWEN25_SRC}" ] || [ ! -f "${MATERIALIZE_SRC}" ] || [ ! -f "${DINOSIGLIP_SRC}" ]; then
|
| 124 |
+
echo "[ERROR] Local model files not found in ${SCRIPT_DIR}"
|
| 125 |
+
exit 1
|
| 126 |
+
fi
|
| 127 |
+
|
| 128 |
+
if [[ "${ROOT_DIR}" == "/path/to/root" ]] || [[ "${LOCAL_QWEN_PATH}" == /path/to/root/* ]] || [[ "${LOCAL_TIMM_PATH}" == /path/to/root/* ]]; then
|
| 129 |
+
echo "[ERROR] Please set ROOT_DIR, or set LOCAL_QWEN_PATH and LOCAL_TIMM_PATH explicitly before using --local-models."
|
| 130 |
+
exit 1
|
| 131 |
+
fi
|
| 132 |
+
|
| 133 |
+
render_template "${QWEN25_SRC}" "${QWEN25_DST}"
|
| 134 |
+
render_template "${MATERIALIZE_SRC}" "${MATERIALIZE_DST}"
|
| 135 |
+
cp "${DINOSIGLIP_SRC}" "${DINOSIGLIP_DST}"
|
| 136 |
+
echo "[OK] Local model loading enabled (materialize.py + dinosiglip_vit.py replaced)."
|
| 137 |
+
echo " Qwen will be loaded from local disk: ${LOCAL_QWEN_PATH}"
|
| 138 |
+
echo " Vision models will be loaded from local disk: ${LOCAL_TIMM_PATH}"
|
| 139 |
+
else
|
| 140 |
+
echo "[INFO] HF / default model loading remains enabled."
|
| 141 |
+
echo " Use --local-models if you want local Qwen + local vision loading."
|
| 142 |
+
fi
|
| 143 |
+
|
| 144 |
+
echo
|
| 145 |
+
echo "Configured local paths:"
|
| 146 |
+
echo " LOCAL_QWEN_PATH=${LOCAL_QWEN_PATH}"
|
| 147 |
+
echo " LOCAL_TIMM_PATH=${LOCAL_TIMM_PATH}"
|
| 148 |
+
echo
|
| 149 |
+
echo "Restore commands:"
|
| 150 |
+
echo " cd ${PROJECT_ROOT}"
|
| 151 |
+
echo " git restore prismatic/models/backbones/llm/qwen25.py"
|
| 152 |
+
echo " git restore prismatic/models/materialize.py"
|
| 153 |
+
echo " git restore prismatic/models/backbones/vision/dinosiglip_vit.py"
|
| 154 |
+
echo
|
| 155 |
+
echo "To re-enable network download:"
|
| 156 |
+
echo " - Restore qwen25.py to use HF for Qwen."
|
| 157 |
+
echo " - If you used --local-models, also restore materialize.py and dinosiglip_vit.py."
|
| 158 |
+
|
| 159 |
+
echo "Done."
|
VLA-Adapter-UAV/experiments/robot/aloha/train_files/train_aloha.sh
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
###
|
| 3 |
+
# @Description: raw finetuning script for bottle_cleanup task
|
| 4 |
+
# @FilePath: /github_projects/Inspire-cli/.claude/mnt/shared/vla_projects/realworld_vla_adapter/experiments/robot/aloha/train_files/train_aloha.sh
|
| 5 |
+
###
|
| 6 |
+
|
| 7 |
+
#========== Basic Settings ==========#
|
| 8 |
+
PROJECT_PATH=realworld_vla_adapter
|
| 9 |
+
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
| 10 |
+
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/../../../.." && pwd)"
|
| 11 |
+
ROOT_DIR="${ROOT_DIR:-/path/to/root}"
|
| 12 |
+
export WANDB_CONSOLE=off
|
| 13 |
+
export WANDB_MODE=offline
|
| 14 |
+
export PYTHONPATH="${PROJECT_ROOT}"
|
| 15 |
+
#========== Training Configuration ==========#
|
| 16 |
+
# Dataset and paths
|
| 17 |
+
data_name="${DATASET_NAME:-bowl_stack_and_shelf_aloha_realworld_50}"
|
| 18 |
+
data_root_dir="${DATA_ROOT_DIR:-${ROOT_DIR}/datasets/cobot_aloha/tfds}"
|
| 19 |
+
vlm_path="${VLM_PATH:-${ROOT_DIR}/ai_models/Stanford-ILIAD/prism-qwen25-extra-dinosiglip-224px-0_5b}"
|
| 20 |
+
config_file_path="${CONFIG_FILE_PATH:-pretrained_models/configs}"
|
| 21 |
+
|
| 22 |
+
# Training parameters
|
| 23 |
+
batch_size=12
|
| 24 |
+
grad_accumulation_steps=1
|
| 25 |
+
learning_rate=2e-4
|
| 26 |
+
max_steps=10005
|
| 27 |
+
num_steps_before_decay=5000
|
| 28 |
+
save_freq=2000
|
| 29 |
+
lr_warmup_steps=0
|
| 30 |
+
|
| 31 |
+
# Model configuration
|
| 32 |
+
num_images_in_input=3
|
| 33 |
+
lora_rank=64
|
| 34 |
+
use_film=False
|
| 35 |
+
use_proprio=True
|
| 36 |
+
use_lora=True
|
| 37 |
+
use_fz=False
|
| 38 |
+
use_minivlm=True
|
| 39 |
+
image_aug=True
|
| 40 |
+
save_latest_checkpoint_only=False
|
| 41 |
+
merge_lora_during_training=True
|
| 42 |
+
use_pro_version=True
|
| 43 |
+
# Wandb settings
|
| 44 |
+
wandb_entity="${WANDB_ENTITY:-your-wandb-entity}"
|
| 45 |
+
wandb_project="${WANDB_PROJECT:-vla_adapter}"
|
| 46 |
+
|
| 47 |
+
# Generate timestamp and run ID
|
| 48 |
+
current_time=$(date +"%Y%m%d_%H%M%S")
|
| 49 |
+
run_id_note="raw"
|
| 50 |
+
|
| 51 |
+
# Build MODE string with important configuration variables (excluding those already in run_id)
|
| 52 |
+
MODE="${run_id_note}_img${num_images_in_input}_mini${use_minivlm}_prop${use_proprio}_pro${use_pro_version}_film${use_film}"
|
| 53 |
+
|
| 54 |
+
# Build run_root_dir using MODE
|
| 55 |
+
run_root_dir="outputs/${data_name}/${MODE}-$current_time"
|
| 56 |
+
|
| 57 |
+
mkdir -p logs
|
| 58 |
+
|
| 59 |
+
#========== Training Execution ==========#
|
| 60 |
+
torchrun --standalone --nnodes 1 --nproc-per-node 4 vla-scripts/finetune.py \
|
| 61 |
+
--vlm_path $vlm_path \
|
| 62 |
+
--config_file_path $config_file_path \
|
| 63 |
+
--data_root_dir $data_root_dir \
|
| 64 |
+
--dataset_name $data_name \
|
| 65 |
+
--run_root_dir $run_root_dir \
|
| 66 |
+
--use_film $use_film \
|
| 67 |
+
--num_images_in_input $num_images_in_input \
|
| 68 |
+
--use_proprio $use_proprio \
|
| 69 |
+
--use_lora $use_lora \
|
| 70 |
+
--use_fz $use_fz \
|
| 71 |
+
--use_minivlm $use_minivlm \
|
| 72 |
+
--image_aug $image_aug \
|
| 73 |
+
--num_steps_before_decay $num_steps_before_decay \
|
| 74 |
+
--max_steps $max_steps \
|
| 75 |
+
--save_freq $save_freq \
|
| 76 |
+
--save_latest_checkpoint_only $save_latest_checkpoint_only \
|
| 77 |
+
--merge_lora_during_training $merge_lora_during_training \
|
| 78 |
+
--batch_size $batch_size \
|
| 79 |
+
--grad_accumulation_steps $grad_accumulation_steps \
|
| 80 |
+
--learning_rate $learning_rate \
|
| 81 |
+
--lora_rank $lora_rank \
|
| 82 |
+
--use_pro_version $use_pro_version \
|
| 83 |
+
--wandb_entity "$wandb_entity" \
|
| 84 |
+
--wandb_project "$wandb_project" \
|
| 85 |
+
--run_id_note $run_id_note \
|
| 86 |
+
--lr_warmup_steps $lr_warmup_steps
|
| 87 |
+
|
| 88 |
+
echo "Training started with run ID: $run_id_note"
|
| 89 |
+
echo "Output directory: $run_root_dir"
|
| 90 |
+
echo "Log file: logs/$run_id_note.log"
|
| 91 |
+
echo "Process ID: $!"
|
VLA-Adapter-UAV/experiments/robot/libero/libero_requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
imageio[ffmpeg]
|
| 2 |
+
robosuite==1.4.1
|
| 3 |
+
bddl
|
| 4 |
+
easydict
|
| 5 |
+
cloudpickle
|
| 6 |
+
gym
|
VLA-Adapter-UAV/experiments/robot/libero/libero_utils.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Utils for evaluating policies in LIBERO simulation environments."""
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
import imageio
|
| 7 |
+
import numpy as np
|
| 8 |
+
import tensorflow as tf
|
| 9 |
+
from libero.libero import get_libero_path
|
| 10 |
+
from libero.libero.envs import OffScreenRenderEnv
|
| 11 |
+
|
| 12 |
+
from experiments.robot.robot_utils import (
|
| 13 |
+
DATE,
|
| 14 |
+
DATE_TIME,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def get_libero_env(task, model_family, resolution=256):
|
| 19 |
+
"""Initializes and returns the LIBERO environment, along with the task description."""
|
| 20 |
+
task_description = task.language
|
| 21 |
+
task_bddl_file = os.path.join(get_libero_path("bddl_files"), task.problem_folder, task.bddl_file)
|
| 22 |
+
env_args = {"bddl_file_name": task_bddl_file, "camera_heights": resolution, "camera_widths": resolution}
|
| 23 |
+
env = OffScreenRenderEnv(**env_args)
|
| 24 |
+
env.seed(0) # IMPORTANT: seed seems to affect object positions even when using fixed initial state
|
| 25 |
+
return env, task_description
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def get_libero_dummy_action(model_family: str):
|
| 29 |
+
"""Get dummy/no-op action, used to roll out the simulation while the robot does nothing."""
|
| 30 |
+
return [0, 0, 0, 0, 0, 0, -1]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def get_libero_image(obs):
|
| 34 |
+
"""Extracts third-person image from observations and preprocesses it."""
|
| 35 |
+
img = obs["agentview_image"]
|
| 36 |
+
img = img[::-1, ::-1] # IMPORTANT: rotate 180 degrees to match train preprocessing
|
| 37 |
+
return img
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def get_libero_wrist_image(obs):
|
| 41 |
+
"""Extracts wrist camera image from observations and preprocesses it."""
|
| 42 |
+
img = obs["robot0_eye_in_hand_image"]
|
| 43 |
+
img = img[::-1, ::-1] # IMPORTANT: rotate 180 degrees to match train preprocessing
|
| 44 |
+
return img
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def save_rollout_video(rollout_images, idx, success, task_description, log_file=None, save_version=None):
|
| 48 |
+
"""Saves an MP4 replay of an episode."""
|
| 49 |
+
rollout_dir = f"./rollouts/{save_version}/{DATE}"
|
| 50 |
+
os.makedirs(rollout_dir, exist_ok=True)
|
| 51 |
+
processed_task_description = task_description.lower().replace(" ", "_").replace("\n", "_").replace(".", "_")[:50]
|
| 52 |
+
mp4_path = f"{rollout_dir}/{DATE_TIME}--episode={idx}--success={success}--task={processed_task_description}.mp4"
|
| 53 |
+
video_writer = imageio.get_writer(mp4_path, fps=30)
|
| 54 |
+
for img in rollout_images:
|
| 55 |
+
video_writer.append_data(img)
|
| 56 |
+
video_writer.close()
|
| 57 |
+
print(f"Saved rollout MP4 at path {mp4_path}")
|
| 58 |
+
if log_file is not None:
|
| 59 |
+
log_file.write(f"Saved rollout MP4 at path {mp4_path}\n")
|
| 60 |
+
return mp4_path
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def quat2axisangle(quat):
|
| 64 |
+
"""
|
| 65 |
+
Copied from robosuite: https://github.com/ARISE-Initiative/robosuite/blob/eafb81f54ffc104f905ee48a16bb15f059176ad3/robosuite/utils/transform_utils.py#L490C1-L512C55
|
| 66 |
+
|
| 67 |
+
Converts quaternion to axis-angle format.
|
| 68 |
+
Returns a unit vector direction scaled by its angle in radians.
|
| 69 |
+
|
| 70 |
+
Args:
|
| 71 |
+
quat (np.array): (x,y,z,w) vec4 float angles
|
| 72 |
+
|
| 73 |
+
Returns:
|
| 74 |
+
np.array: (ax,ay,az) axis-angle exponential coordinates
|
| 75 |
+
"""
|
| 76 |
+
# clip quaternion
|
| 77 |
+
if quat[3] > 1.0:
|
| 78 |
+
quat[3] = 1.0
|
| 79 |
+
elif quat[3] < -1.0:
|
| 80 |
+
quat[3] = -1.0
|
| 81 |
+
|
| 82 |
+
den = np.sqrt(1.0 - quat[3] * quat[3])
|
| 83 |
+
if math.isclose(den, 0.0):
|
| 84 |
+
# This is (close to) a zero degree rotation, immediately return
|
| 85 |
+
return np.zeros(3)
|
| 86 |
+
|
| 87 |
+
return (quat[:3] * 2.0 * math.acos(quat[3])) / den
|
VLA-Adapter-UAV/experiments/robot/libero/regenerate_libero_dataset.py
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Regenerates a LIBERO dataset (HDF5 files) by replaying demonstrations in the environments.
|
| 3 |
+
|
| 4 |
+
Notes:
|
| 5 |
+
- We save image observations at 256x256px resolution (instead of 128x128).
|
| 6 |
+
- We filter out transitions with "no-op" (zero) actions that do not change the robot's state.
|
| 7 |
+
- We filter out unsuccessful demonstrations.
|
| 8 |
+
- In the LIBERO HDF5 data -> RLDS data conversion (not shown here), we rotate the images by
|
| 9 |
+
180 degrees because we observe that the environments return images that are upside down
|
| 10 |
+
on our platform.
|
| 11 |
+
|
| 12 |
+
Usage:
|
| 13 |
+
python experiments/robot/libero/regenerate_libero_dataset.py \
|
| 14 |
+
--libero_task_suite [ libero_spatial | libero_object | libero_goal | libero_10 ] \
|
| 15 |
+
--libero_raw_data_dir <PATH TO RAW HDF5 DATASET DIR> \
|
| 16 |
+
--libero_target_dir <PATH TO TARGET DIR>
|
| 17 |
+
|
| 18 |
+
Example (LIBERO-Spatial):
|
| 19 |
+
python experiments/robot/libero/regenerate_libero_dataset.py \
|
| 20 |
+
--libero_task_suite libero_spatial \
|
| 21 |
+
--libero_raw_data_dir ./LIBERO/libero/datasets/libero_spatial \
|
| 22 |
+
--libero_target_dir ./LIBERO/libero/datasets/libero_spatial_no_noops
|
| 23 |
+
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
import argparse
|
| 27 |
+
import json
|
| 28 |
+
import os
|
| 29 |
+
import time
|
| 30 |
+
|
| 31 |
+
import h5py
|
| 32 |
+
import numpy as np
|
| 33 |
+
import robosuite.utils.transform_utils as T
|
| 34 |
+
import tqdm
|
| 35 |
+
from libero.libero import benchmark
|
| 36 |
+
|
| 37 |
+
from experiments.robot.libero.libero_utils import (
|
| 38 |
+
get_libero_dummy_action,
|
| 39 |
+
get_libero_env,
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
IMAGE_RESOLUTION = 256
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def is_noop(action, prev_action=None, threshold=1e-4):
|
| 47 |
+
"""
|
| 48 |
+
Returns whether an action is a no-op action.
|
| 49 |
+
|
| 50 |
+
A no-op action satisfies two criteria:
|
| 51 |
+
(1) All action dimensions, except for the last one (gripper action), are near zero.
|
| 52 |
+
(2) The gripper action is equal to the previous timestep's gripper action.
|
| 53 |
+
|
| 54 |
+
Explanation of (2):
|
| 55 |
+
Naively filtering out actions with just criterion (1) is not good because you will
|
| 56 |
+
remove actions where the robot is staying still but opening/closing its gripper.
|
| 57 |
+
So you also need to consider the current state (by checking the previous timestep's
|
| 58 |
+
gripper action as a proxy) to determine whether the action really is a no-op.
|
| 59 |
+
"""
|
| 60 |
+
# Special case: Previous action is None if this is the first action in the episode
|
| 61 |
+
# Then we only care about criterion (1)
|
| 62 |
+
if prev_action is None:
|
| 63 |
+
return np.linalg.norm(action[:-1]) < threshold
|
| 64 |
+
|
| 65 |
+
# Normal case: Check both criteria (1) and (2)
|
| 66 |
+
gripper_action = action[-1]
|
| 67 |
+
prev_gripper_action = prev_action[-1]
|
| 68 |
+
return np.linalg.norm(action[:-1]) < threshold and gripper_action == prev_gripper_action
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def main(args):
|
| 72 |
+
print(f"Regenerating {args.libero_task_suite} dataset!")
|
| 73 |
+
|
| 74 |
+
# Create target directory
|
| 75 |
+
if os.path.isdir(args.libero_target_dir):
|
| 76 |
+
user_input = input(f"Target directory already exists at path: {args.libero_target_dir}\nEnter 'y' to overwrite the directory, or anything else to exit: ")
|
| 77 |
+
if user_input != 'y':
|
| 78 |
+
exit()
|
| 79 |
+
os.makedirs(args.libero_target_dir, exist_ok=True)
|
| 80 |
+
|
| 81 |
+
# Prepare JSON file to record success/false and initial states per episode
|
| 82 |
+
metainfo_json_dict = {}
|
| 83 |
+
metainfo_json_out_path = f"./experiments/robot/libero/{args.libero_task_suite}_metainfo.json"
|
| 84 |
+
with open(metainfo_json_out_path, "w") as f:
|
| 85 |
+
# Just test that we can write to this file (we overwrite it later)
|
| 86 |
+
json.dump(metainfo_json_dict, f)
|
| 87 |
+
|
| 88 |
+
# Get task suite
|
| 89 |
+
benchmark_dict = benchmark.get_benchmark_dict()
|
| 90 |
+
task_suite = benchmark_dict[args.libero_task_suite]()
|
| 91 |
+
num_tasks_in_suite = task_suite.n_tasks
|
| 92 |
+
|
| 93 |
+
# Setup
|
| 94 |
+
num_replays = 0
|
| 95 |
+
num_success = 0
|
| 96 |
+
num_noops = 0
|
| 97 |
+
|
| 98 |
+
for task_id in tqdm.tqdm(range(num_tasks_in_suite)):
|
| 99 |
+
# Get task in suite
|
| 100 |
+
task = task_suite.get_task(task_id)
|
| 101 |
+
env, task_description = get_libero_env(task, "llava", resolution=IMAGE_RESOLUTION)
|
| 102 |
+
|
| 103 |
+
# Get dataset for task
|
| 104 |
+
orig_data_path = os.path.join(args.libero_raw_data_dir, f"{task.name}_demo.hdf5")
|
| 105 |
+
assert os.path.exists(orig_data_path), f"Cannot find raw data file {orig_data_path}."
|
| 106 |
+
orig_data_file = h5py.File(orig_data_path, "r")
|
| 107 |
+
orig_data = orig_data_file["data"]
|
| 108 |
+
|
| 109 |
+
# Create new HDF5 file for regenerated demos
|
| 110 |
+
new_data_path = os.path.join(args.libero_target_dir, f"{task.name}_demo.hdf5")
|
| 111 |
+
new_data_file = h5py.File(new_data_path, "w")
|
| 112 |
+
grp = new_data_file.create_group("data")
|
| 113 |
+
|
| 114 |
+
for i in range(len(orig_data.keys())):
|
| 115 |
+
# Get demo data
|
| 116 |
+
demo_data = orig_data[f"demo_{i}"]
|
| 117 |
+
orig_actions = demo_data["actions"][()]
|
| 118 |
+
orig_states = demo_data["states"][()]
|
| 119 |
+
|
| 120 |
+
# Reset environment, set initial state, and wait a few steps for environment to settle
|
| 121 |
+
env.reset()
|
| 122 |
+
env.set_init_state(orig_states[0])
|
| 123 |
+
for _ in range(10):
|
| 124 |
+
obs, reward, done, info = env.step(get_libero_dummy_action("llava"))
|
| 125 |
+
|
| 126 |
+
# Set up new data lists
|
| 127 |
+
states = []
|
| 128 |
+
actions = []
|
| 129 |
+
ee_states = []
|
| 130 |
+
gripper_states = []
|
| 131 |
+
joint_states = []
|
| 132 |
+
robot_states = []
|
| 133 |
+
agentview_images = []
|
| 134 |
+
eye_in_hand_images = []
|
| 135 |
+
|
| 136 |
+
# Replay original demo actions in environment and record observations
|
| 137 |
+
for _, action in enumerate(orig_actions):
|
| 138 |
+
# Skip transitions with no-op actions
|
| 139 |
+
prev_action = actions[-1] if len(actions) > 0 else None
|
| 140 |
+
if is_noop(action, prev_action):
|
| 141 |
+
print(f"\tSkipping no-op action: {action}")
|
| 142 |
+
num_noops += 1
|
| 143 |
+
continue
|
| 144 |
+
|
| 145 |
+
if states == []:
|
| 146 |
+
# In the first timestep, since we're using the original initial state to initialize the environment,
|
| 147 |
+
# copy the initial state (first state in episode) over from the original HDF5 to the new one
|
| 148 |
+
states.append(orig_states[0])
|
| 149 |
+
robot_states.append(demo_data["robot_states"][0])
|
| 150 |
+
else:
|
| 151 |
+
# For all other timesteps, get state from environment and record it
|
| 152 |
+
states.append(env.sim.get_state().flatten())
|
| 153 |
+
robot_states.append(
|
| 154 |
+
np.concatenate([obs["robot0_gripper_qpos"], obs["robot0_eef_pos"], obs["robot0_eef_quat"]])
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
# Record original action (from demo)
|
| 158 |
+
actions.append(action)
|
| 159 |
+
|
| 160 |
+
# Record data returned by environment
|
| 161 |
+
if "robot0_gripper_qpos" in obs:
|
| 162 |
+
gripper_states.append(obs["robot0_gripper_qpos"])
|
| 163 |
+
joint_states.append(obs["robot0_joint_pos"])
|
| 164 |
+
ee_states.append(
|
| 165 |
+
np.hstack(
|
| 166 |
+
(
|
| 167 |
+
obs["robot0_eef_pos"],
|
| 168 |
+
T.quat2axisangle(obs["robot0_eef_quat"]),
|
| 169 |
+
)
|
| 170 |
+
)
|
| 171 |
+
)
|
| 172 |
+
agentview_images.append(obs["agentview_image"])
|
| 173 |
+
eye_in_hand_images.append(obs["robot0_eye_in_hand_image"])
|
| 174 |
+
|
| 175 |
+
# Execute demo action in environment
|
| 176 |
+
obs, reward, done, info = env.step(action.tolist())
|
| 177 |
+
|
| 178 |
+
# At end of episode, save replayed trajectories to new HDF5 files (only keep successes)
|
| 179 |
+
if done:
|
| 180 |
+
dones = np.zeros(len(actions)).astype(np.uint8)
|
| 181 |
+
dones[-1] = 1
|
| 182 |
+
rewards = np.zeros(len(actions)).astype(np.uint8)
|
| 183 |
+
rewards[-1] = 1
|
| 184 |
+
assert len(actions) == len(agentview_images)
|
| 185 |
+
|
| 186 |
+
ep_data_grp = grp.create_group(f"demo_{i}")
|
| 187 |
+
obs_grp = ep_data_grp.create_group("obs")
|
| 188 |
+
obs_grp.create_dataset("gripper_states", data=np.stack(gripper_states, axis=0))
|
| 189 |
+
obs_grp.create_dataset("joint_states", data=np.stack(joint_states, axis=0))
|
| 190 |
+
obs_grp.create_dataset("ee_states", data=np.stack(ee_states, axis=0))
|
| 191 |
+
obs_grp.create_dataset("ee_pos", data=np.stack(ee_states, axis=0)[:, :3])
|
| 192 |
+
obs_grp.create_dataset("ee_ori", data=np.stack(ee_states, axis=0)[:, 3:])
|
| 193 |
+
obs_grp.create_dataset("agentview_rgb", data=np.stack(agentview_images, axis=0))
|
| 194 |
+
obs_grp.create_dataset("eye_in_hand_rgb", data=np.stack(eye_in_hand_images, axis=0))
|
| 195 |
+
ep_data_grp.create_dataset("actions", data=actions)
|
| 196 |
+
ep_data_grp.create_dataset("states", data=np.stack(states))
|
| 197 |
+
ep_data_grp.create_dataset("robot_states", data=np.stack(robot_states, axis=0))
|
| 198 |
+
ep_data_grp.create_dataset("rewards", data=rewards)
|
| 199 |
+
ep_data_grp.create_dataset("dones", data=dones)
|
| 200 |
+
|
| 201 |
+
num_success += 1
|
| 202 |
+
|
| 203 |
+
num_replays += 1
|
| 204 |
+
|
| 205 |
+
# Record success/false and initial environment state in metainfo dict
|
| 206 |
+
task_key = task_description.replace(" ", "_")
|
| 207 |
+
episode_key = f"demo_{i}"
|
| 208 |
+
if task_key not in metainfo_json_dict:
|
| 209 |
+
metainfo_json_dict[task_key] = {}
|
| 210 |
+
if episode_key not in metainfo_json_dict[task_key]:
|
| 211 |
+
metainfo_json_dict[task_key][episode_key] = {}
|
| 212 |
+
metainfo_json_dict[task_key][episode_key]["success"] = bool(done)
|
| 213 |
+
metainfo_json_dict[task_key][episode_key]["initial_state"] = orig_states[0].tolist()
|
| 214 |
+
|
| 215 |
+
# Write metainfo dict to JSON file
|
| 216 |
+
# (We repeatedly overwrite, rather than doing this once at the end, just in case the script crashes midway)
|
| 217 |
+
with open(metainfo_json_out_path, "w") as f:
|
| 218 |
+
json.dump(metainfo_json_dict, f, indent=2)
|
| 219 |
+
|
| 220 |
+
# Count total number of successful replays so far
|
| 221 |
+
print(
|
| 222 |
+
f"Total # episodes replayed: {num_replays}, Total # successes: {num_success} ({num_success / num_replays * 100:.1f} %)"
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
# Report total number of no-op actions filtered out so far
|
| 226 |
+
print(f" Total # no-op actions filtered out: {num_noops}")
|
| 227 |
+
|
| 228 |
+
# Close HDF5 files
|
| 229 |
+
orig_data_file.close()
|
| 230 |
+
new_data_file.close()
|
| 231 |
+
print(f"Saved regenerated demos for task '{task_description}' at: {new_data_path}")
|
| 232 |
+
|
| 233 |
+
print(f"Dataset regeneration complete! Saved new dataset at: {args.libero_target_dir}")
|
| 234 |
+
print(f"Saved metainfo JSON at: {metainfo_json_out_path}")
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
if __name__ == "__main__":
|
| 238 |
+
# Parse command-line arguments
|
| 239 |
+
parser = argparse.ArgumentParser()
|
| 240 |
+
parser.add_argument("--libero_task_suite", type=str, choices=["libero_spatial", "libero_object", "libero_goal", "libero_10", "libero_90"],
|
| 241 |
+
help="LIBERO task suite. Example: libero_spatial", required=True)
|
| 242 |
+
parser.add_argument("--libero_raw_data_dir", type=str,
|
| 243 |
+
help="Path to directory containing raw HDF5 dataset. Example: ./LIBERO/libero/datasets/libero_spatial", required=True)
|
| 244 |
+
parser.add_argument("--libero_target_dir", type=str,
|
| 245 |
+
help="Path to regenerated dataset directory. Example: ./LIBERO/libero/datasets/libero_spatial_no_noops", required=True)
|
| 246 |
+
args = parser.parse_args()
|
| 247 |
+
|
| 248 |
+
# Start data regeneration
|
| 249 |
+
main(args)
|
VLA-Adapter-UAV/experiments/robot/libero/run_libero_eval.py
ADDED
|
@@ -0,0 +1,555 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
run_libero_eval.py
|
| 3 |
+
|
| 4 |
+
Evaluates a trained policy in a LIBERO simulation benchmark task suite.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import json
|
| 8 |
+
import logging
|
| 9 |
+
import os
|
| 10 |
+
import sys
|
| 11 |
+
from collections import deque
|
| 12 |
+
from dataclasses import dataclass
|
| 13 |
+
from enum import Enum
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from typing import Optional, Union
|
| 16 |
+
|
| 17 |
+
import draccus
|
| 18 |
+
import numpy as np
|
| 19 |
+
import tqdm
|
| 20 |
+
from libero.libero import benchmark
|
| 21 |
+
|
| 22 |
+
import wandb
|
| 23 |
+
|
| 24 |
+
# Append current directory so that interpreter can find experiments.robot
|
| 25 |
+
sys.path.append("../..")
|
| 26 |
+
from experiments.robot.libero.libero_utils import (
|
| 27 |
+
get_libero_dummy_action,
|
| 28 |
+
get_libero_env,
|
| 29 |
+
get_libero_image,
|
| 30 |
+
get_libero_wrist_image,
|
| 31 |
+
quat2axisangle,
|
| 32 |
+
save_rollout_video,
|
| 33 |
+
)
|
| 34 |
+
from experiments.robot.openvla_utils import (
|
| 35 |
+
get_action_head,
|
| 36 |
+
get_noisy_action_projector,
|
| 37 |
+
get_processor,
|
| 38 |
+
get_proprio_projector,
|
| 39 |
+
resize_image_for_policy,
|
| 40 |
+
)
|
| 41 |
+
from experiments.robot.robot_utils import (
|
| 42 |
+
DATE_TIME,
|
| 43 |
+
get_action,
|
| 44 |
+
get_image_resize_size,
|
| 45 |
+
get_model,
|
| 46 |
+
invert_gripper_action,
|
| 47 |
+
normalize_gripper_action,
|
| 48 |
+
set_seed_everywhere,
|
| 49 |
+
)
|
| 50 |
+
from prismatic.vla.constants import NUM_ACTIONS_CHUNK
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
# Define task suite constants
|
| 54 |
+
class TaskSuite(str, Enum):
|
| 55 |
+
LIBERO_SPATIAL = "libero_spatial"
|
| 56 |
+
LIBERO_OBJECT = "libero_object"
|
| 57 |
+
LIBERO_GOAL = "libero_goal"
|
| 58 |
+
LIBERO_10 = "libero_10"
|
| 59 |
+
LIBERO_90 = "libero_90"
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# Define max steps for each task suite
|
| 63 |
+
TASK_MAX_STEPS = {
|
| 64 |
+
TaskSuite.LIBERO_SPATIAL: 220, # longest training demo has 193 steps
|
| 65 |
+
TaskSuite.LIBERO_OBJECT: 280, # longest training demo has 254 steps
|
| 66 |
+
TaskSuite.LIBERO_GOAL: 300, # longest training demo has 270 steps
|
| 67 |
+
TaskSuite.LIBERO_10: 520, # longest training demo has 505 steps
|
| 68 |
+
TaskSuite.LIBERO_90: 400, # longest training demo has 373 steps
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# Set up logging
|
| 73 |
+
logging.basicConfig(
|
| 74 |
+
level=logging.INFO,
|
| 75 |
+
format="%(asctime)s [%(levelname)s] %(message)s",
|
| 76 |
+
handlers=[logging.StreamHandler()],
|
| 77 |
+
)
|
| 78 |
+
logger = logging.getLogger(__name__)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@dataclass
|
| 83 |
+
class GenerateConfig:
|
| 84 |
+
# fmt: off
|
| 85 |
+
|
| 86 |
+
#################################################################################################################
|
| 87 |
+
# Model-specific parameters
|
| 88 |
+
#################################################################################################################
|
| 89 |
+
model_family: str = "openvla" # Model family
|
| 90 |
+
pretrained_checkpoint: Union[str, Path] = "" # Pretrained checkpoint path
|
| 91 |
+
use_l1_regression: bool = True # If True, uses continuous action head with L1 regression objective
|
| 92 |
+
use_minivlm: bool = True # If True, uses minivlm
|
| 93 |
+
num_diffusion_steps: int = 50 # (When `diffusion==True`) Number of diffusion steps for inference
|
| 94 |
+
use_film: bool = False # If True, uses FiLM to infuse language inputs into visual features
|
| 95 |
+
num_images_in_input: int = 2 # Number of images in the VLA input (default: 1)
|
| 96 |
+
use_proprio: bool = True # Whether to include proprio state in input
|
| 97 |
+
|
| 98 |
+
center_crop: bool = True # Center crop? (if trained w/ random crop image aug)
|
| 99 |
+
num_open_loop_steps: int = 8 # Number of actions to execute open-loop before requerying policy
|
| 100 |
+
unnorm_key: Union[str, Path] = "" # Action un-normalization key
|
| 101 |
+
|
| 102 |
+
load_in_8bit: bool = False # (For OpenVLA only) Load with 8-bit quantization
|
| 103 |
+
load_in_4bit: bool = False # (For OpenVLA only) Load with 4-bit quantization
|
| 104 |
+
|
| 105 |
+
#################################################################################################################
|
| 106 |
+
# LIBERO environment-specific parameters
|
| 107 |
+
#################################################################################################################
|
| 108 |
+
task_suite_name: str = TaskSuite.LIBERO_SPATIAL # Task suite
|
| 109 |
+
num_steps_wait: int = 10 # Number of steps to wait for objects to stabilize in sim
|
| 110 |
+
num_trials_per_task: int = 50 # Number of rollouts per task
|
| 111 |
+
initial_states_path: str = "DEFAULT" # "DEFAULT", or path to initial states JSON file
|
| 112 |
+
env_img_res: int = 256 # Resolution for environment images (not policy input resolution)
|
| 113 |
+
|
| 114 |
+
#################################################################################################################
|
| 115 |
+
# Utils
|
| 116 |
+
#################################################################################################################
|
| 117 |
+
run_id_note: Optional[str] = None # Extra note to add to end of run ID for logging
|
| 118 |
+
local_log_dir: str = "./experiments/logs" # Local directory for eval logs
|
| 119 |
+
|
| 120 |
+
use_wandb: bool = False # Whether to also log results in Weights & Biases
|
| 121 |
+
wandb_entity: str = "your-wandb-entity" # Name of WandB entity
|
| 122 |
+
wandb_project: str = "your-wandb-project" # Name of WandB project
|
| 123 |
+
|
| 124 |
+
seed: int = 7 # Random Seed (for reproducibility)
|
| 125 |
+
|
| 126 |
+
# fmt: on
|
| 127 |
+
save_version: str = "vla-adapter" # version of
|
| 128 |
+
use_pro_version: bool = True # encourage to use the pro models we released.
|
| 129 |
+
phase: str = "Inference"
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def validate_config(cfg: GenerateConfig) -> None:
|
| 134 |
+
"""Validate configuration parameters."""
|
| 135 |
+
assert cfg.pretrained_checkpoint is not None, "pretrained_checkpoint must not be None!"
|
| 136 |
+
|
| 137 |
+
if "image_aug" in str(cfg.pretrained_checkpoint):
|
| 138 |
+
assert cfg.center_crop, "Expecting `center_crop==True` because model was trained with image augmentations!"
|
| 139 |
+
|
| 140 |
+
assert not (cfg.load_in_8bit and cfg.load_in_4bit), "Cannot use both 8-bit and 4-bit quantization!"
|
| 141 |
+
|
| 142 |
+
# Validate task suite
|
| 143 |
+
assert cfg.task_suite_name in [suite.value for suite in TaskSuite], f"Invalid task suite: {cfg.task_suite_name}"
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def initialize_model(cfg: GenerateConfig):
|
| 148 |
+
"""Initialize model and associated components."""
|
| 149 |
+
# Load model
|
| 150 |
+
model = get_model(cfg)
|
| 151 |
+
model.set_version(cfg.save_version)
|
| 152 |
+
# Load proprio projector if needed
|
| 153 |
+
proprio_projector = None
|
| 154 |
+
if cfg.use_proprio:
|
| 155 |
+
proprio_projector = get_proprio_projector(
|
| 156 |
+
cfg,
|
| 157 |
+
model.llm_dim,
|
| 158 |
+
proprio_dim=8, # 8-dimensional proprio for LIBERO
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
# Load action head if needed
|
| 162 |
+
action_head = None
|
| 163 |
+
if cfg.use_l1_regression:
|
| 164 |
+
action_head = get_action_head(cfg, model.llm_dim)
|
| 165 |
+
|
| 166 |
+
# Load noisy action projector if using diffusion
|
| 167 |
+
noisy_action_projector = None
|
| 168 |
+
|
| 169 |
+
# Get OpenVLA processor if needed
|
| 170 |
+
processor = None
|
| 171 |
+
if cfg.model_family == "openvla":
|
| 172 |
+
processor = get_processor(cfg)
|
| 173 |
+
check_unnorm_key(cfg, model)
|
| 174 |
+
|
| 175 |
+
return model, action_head, proprio_projector, noisy_action_projector, processor
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def check_unnorm_key(cfg: GenerateConfig, model) -> None:
|
| 179 |
+
"""Check that the model contains the action un-normalization key."""
|
| 180 |
+
# Initialize unnorm_key
|
| 181 |
+
unnorm_key = cfg.task_suite_name
|
| 182 |
+
|
| 183 |
+
# In some cases, the key must be manually modified (e.g. after training on a modified version of the dataset
|
| 184 |
+
# with the suffix "_no_noops" in the dataset name)
|
| 185 |
+
if unnorm_key not in model.norm_stats and f"{unnorm_key}_no_noops" in model.norm_stats:
|
| 186 |
+
unnorm_key = f"{unnorm_key}_no_noops"
|
| 187 |
+
|
| 188 |
+
assert unnorm_key in model.norm_stats, f"Action un-norm key {unnorm_key} not found in VLA `norm_stats`!"
|
| 189 |
+
|
| 190 |
+
# Set the unnorm_key in cfg
|
| 191 |
+
cfg.unnorm_key = unnorm_key
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def setup_logging(cfg: GenerateConfig):
|
| 196 |
+
"""Set up logging to file and optionally to wandb."""
|
| 197 |
+
# Create run ID
|
| 198 |
+
run_id = f"EVAL-{cfg.task_suite_name}-{cfg.model_family}-{DATE_TIME}"
|
| 199 |
+
if cfg.run_id_note is not None:
|
| 200 |
+
run_id += f"--{cfg.run_id_note}"
|
| 201 |
+
|
| 202 |
+
# Set up local logging
|
| 203 |
+
os.makedirs(cfg.local_log_dir, exist_ok=True)
|
| 204 |
+
local_log_filepath = os.path.join(cfg.local_log_dir, run_id + ".txt")
|
| 205 |
+
log_file = open(local_log_filepath, "w")
|
| 206 |
+
logger.info(f"Logging to local log file: {local_log_filepath}")
|
| 207 |
+
|
| 208 |
+
# Initialize Weights & Biases logging if enabled
|
| 209 |
+
if cfg.use_wandb:
|
| 210 |
+
wandb.init(
|
| 211 |
+
entity=cfg.wandb_entity,
|
| 212 |
+
project=cfg.wandb_project,
|
| 213 |
+
name=run_id,
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
return log_file, local_log_filepath, run_id
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def log_message(message: str, log_file=None):
|
| 221 |
+
"""Log a message to console and optionally to a log file."""
|
| 222 |
+
logger.info(message)
|
| 223 |
+
if log_file:
|
| 224 |
+
log_file.write(message + "\n")
|
| 225 |
+
log_file.flush()
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def load_initial_states(cfg: GenerateConfig, task_suite, task_id: int, log_file=None):
|
| 230 |
+
"""Load initial states for the given task."""
|
| 231 |
+
# Get default initial states
|
| 232 |
+
initial_states = task_suite.get_task_init_states(task_id)
|
| 233 |
+
|
| 234 |
+
# If using custom initial states, load them from file
|
| 235 |
+
if cfg.initial_states_path != "DEFAULT":
|
| 236 |
+
with open(cfg.initial_states_path, "r") as f:
|
| 237 |
+
all_initial_states = json.load(f)
|
| 238 |
+
log_message(f"Using initial states from {cfg.initial_states_path}", log_file)
|
| 239 |
+
return initial_states, all_initial_states
|
| 240 |
+
else:
|
| 241 |
+
log_message("Using default initial states", log_file)
|
| 242 |
+
return initial_states, None
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def prepare_observation(obs, resize_size):
|
| 247 |
+
"""Prepare observation for policy input."""
|
| 248 |
+
# Get preprocessed images
|
| 249 |
+
img = get_libero_image(obs)
|
| 250 |
+
wrist_img = get_libero_wrist_image(obs)
|
| 251 |
+
|
| 252 |
+
# Resize images to size expected by model
|
| 253 |
+
img_resized = resize_image_for_policy(img, resize_size)
|
| 254 |
+
wrist_img_resized = resize_image_for_policy(wrist_img, resize_size)
|
| 255 |
+
|
| 256 |
+
# Prepare observations dict
|
| 257 |
+
observation = {
|
| 258 |
+
"full_image": img_resized,
|
| 259 |
+
"wrist_image": wrist_img_resized,
|
| 260 |
+
"state": np.concatenate(
|
| 261 |
+
(obs["robot0_eef_pos"], quat2axisangle(obs["robot0_eef_quat"]), obs["robot0_gripper_qpos"])
|
| 262 |
+
),
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
return observation, img # Return both processed observation and original image for replay
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def process_action(action, model_family):
|
| 270 |
+
"""Process action before sending to environment."""
|
| 271 |
+
# Normalize gripper action [0,1] -> [-1,+1] because the environment expects the latter
|
| 272 |
+
action = normalize_gripper_action(action, binarize=True)
|
| 273 |
+
|
| 274 |
+
# [OpenVLA] The dataloader flips the sign of the gripper action to align with other datasets
|
| 275 |
+
# (0 = close, 1 = open), so flip it back (-1 = open, +1 = close) before executing the action
|
| 276 |
+
if model_family == "openvla":
|
| 277 |
+
action = invert_gripper_action(action)
|
| 278 |
+
|
| 279 |
+
return action
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def run_episode(
|
| 284 |
+
cfg: GenerateConfig,
|
| 285 |
+
env,
|
| 286 |
+
task_description: str,
|
| 287 |
+
model,
|
| 288 |
+
resize_size,
|
| 289 |
+
processor=None,
|
| 290 |
+
action_head=None,
|
| 291 |
+
proprio_projector=None,
|
| 292 |
+
noisy_action_projector=None,
|
| 293 |
+
initial_state=None,
|
| 294 |
+
log_file=None,
|
| 295 |
+
):
|
| 296 |
+
"""Run a single episode in the environment."""
|
| 297 |
+
# Reset environment
|
| 298 |
+
env.reset()
|
| 299 |
+
|
| 300 |
+
# Set initial state if provided
|
| 301 |
+
if initial_state is not None:
|
| 302 |
+
obs = env.set_init_state(initial_state)
|
| 303 |
+
else:
|
| 304 |
+
obs = env.get_observation()
|
| 305 |
+
|
| 306 |
+
# Initialize action queue
|
| 307 |
+
if cfg.num_open_loop_steps != NUM_ACTIONS_CHUNK:
|
| 308 |
+
print(f"WARNING: cfg.num_open_loop_steps ({cfg.num_open_loop_steps}) does not match the NUM_ACTIONS_CHUNK "
|
| 309 |
+
"{NUM_ACTIONS_CHUNK} constant defined in prismatic.vla.constants! For best performance (in terms of "
|
| 310 |
+
"both speed and success rate), we recommend executing the full action chunk.")
|
| 311 |
+
action_queue = deque(maxlen=cfg.num_open_loop_steps)
|
| 312 |
+
|
| 313 |
+
# Setup
|
| 314 |
+
t = 0
|
| 315 |
+
replay_images = []
|
| 316 |
+
max_steps = TASK_MAX_STEPS[cfg.task_suite_name]
|
| 317 |
+
|
| 318 |
+
# Run episode
|
| 319 |
+
success = False
|
| 320 |
+
try:
|
| 321 |
+
while t < max_steps + cfg.num_steps_wait:
|
| 322 |
+
# Do nothing for the first few timesteps to let objects stabilize
|
| 323 |
+
if t < cfg.num_steps_wait:
|
| 324 |
+
obs, reward, done, info = env.step(get_libero_dummy_action(cfg.model_family))
|
| 325 |
+
t += 1
|
| 326 |
+
continue
|
| 327 |
+
|
| 328 |
+
# Prepare observation
|
| 329 |
+
observation, img = prepare_observation(obs, resize_size)
|
| 330 |
+
replay_images.append(img)
|
| 331 |
+
|
| 332 |
+
# If action queue is empty, requery model
|
| 333 |
+
if len(action_queue) == 0:
|
| 334 |
+
# Query model to get action
|
| 335 |
+
actions = get_action(
|
| 336 |
+
cfg,
|
| 337 |
+
model,
|
| 338 |
+
observation,
|
| 339 |
+
task_description,
|
| 340 |
+
processor=processor,
|
| 341 |
+
action_head=action_head,
|
| 342 |
+
proprio_projector=proprio_projector,
|
| 343 |
+
noisy_action_projector=noisy_action_projector,
|
| 344 |
+
use_film=cfg.use_film,
|
| 345 |
+
use_minivlm=cfg.use_minivlm
|
| 346 |
+
)
|
| 347 |
+
|
| 348 |
+
action_queue.extend(actions)
|
| 349 |
+
|
| 350 |
+
# Get action from queue
|
| 351 |
+
action = action_queue.popleft()
|
| 352 |
+
# action = actions[0]
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
# Process action
|
| 356 |
+
action = process_action(action, cfg.model_family)
|
| 357 |
+
|
| 358 |
+
# Execute action in environment
|
| 359 |
+
obs, reward, done, info = env.step(action.tolist())
|
| 360 |
+
if done:
|
| 361 |
+
success = True
|
| 362 |
+
break
|
| 363 |
+
t += 1
|
| 364 |
+
|
| 365 |
+
except Exception as e:
|
| 366 |
+
log_message(f"Episode error: {e}", log_file)
|
| 367 |
+
|
| 368 |
+
return success, replay_images
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
def run_task(
|
| 374 |
+
cfg: GenerateConfig,
|
| 375 |
+
task_suite,
|
| 376 |
+
task_id: int,
|
| 377 |
+
model,
|
| 378 |
+
resize_size,
|
| 379 |
+
processor=None,
|
| 380 |
+
action_head=None,
|
| 381 |
+
proprio_projector=None,
|
| 382 |
+
noisy_action_projector=None,
|
| 383 |
+
total_episodes=0,
|
| 384 |
+
total_successes=0,
|
| 385 |
+
log_file=None,
|
| 386 |
+
save_version=None
|
| 387 |
+
):
|
| 388 |
+
"""Run evaluation for a single task."""
|
| 389 |
+
# Get task
|
| 390 |
+
# task_id = 8
|
| 391 |
+
task = task_suite.get_task(task_id)
|
| 392 |
+
|
| 393 |
+
# Get initial states
|
| 394 |
+
initial_states, all_initial_states = load_initial_states(cfg, task_suite, task_id, log_file)
|
| 395 |
+
|
| 396 |
+
# Initialize environment and get task description
|
| 397 |
+
env, task_description = get_libero_env(task, cfg.model_family, resolution=cfg.env_img_res)
|
| 398 |
+
|
| 399 |
+
# Start episodes
|
| 400 |
+
task_episodes, task_successes = 0, 0
|
| 401 |
+
for episode_idx in tqdm.tqdm(range(cfg.num_trials_per_task)):
|
| 402 |
+
log_message(f"\nTask: {task_description}", log_file)
|
| 403 |
+
|
| 404 |
+
# Handle initial state
|
| 405 |
+
if cfg.initial_states_path == "DEFAULT":
|
| 406 |
+
# Use default initial state
|
| 407 |
+
initial_state = initial_states[episode_idx]
|
| 408 |
+
else:
|
| 409 |
+
# Get keys for fetching initial episode state from JSON
|
| 410 |
+
initial_states_task_key = task_description.replace(" ", "_")
|
| 411 |
+
episode_key = f"demo_{episode_idx}"
|
| 412 |
+
|
| 413 |
+
# Skip episode if expert demonstration failed to complete the task
|
| 414 |
+
if not all_initial_states[initial_states_task_key][episode_key]["success"]:
|
| 415 |
+
log_message(f"Skipping task {task_id} episode {episode_idx} due to failed expert demo!", log_file)
|
| 416 |
+
continue
|
| 417 |
+
|
| 418 |
+
# Get initial state
|
| 419 |
+
initial_state = np.array(all_initial_states[initial_states_task_key][episode_key]["initial_state"])
|
| 420 |
+
|
| 421 |
+
log_message(f"Starting episode {task_episodes + 1}...", log_file)
|
| 422 |
+
|
| 423 |
+
# Run episode
|
| 424 |
+
success, replay_images = run_episode(
|
| 425 |
+
cfg,
|
| 426 |
+
env,
|
| 427 |
+
task_description,
|
| 428 |
+
model,
|
| 429 |
+
resize_size,
|
| 430 |
+
processor,
|
| 431 |
+
action_head,
|
| 432 |
+
proprio_projector,
|
| 433 |
+
noisy_action_projector,
|
| 434 |
+
initial_state,
|
| 435 |
+
log_file,
|
| 436 |
+
)
|
| 437 |
+
|
| 438 |
+
# Update counters
|
| 439 |
+
task_episodes += 1
|
| 440 |
+
total_episodes += 1
|
| 441 |
+
if success:
|
| 442 |
+
task_successes += 1
|
| 443 |
+
total_successes += 1
|
| 444 |
+
|
| 445 |
+
# Save replay video
|
| 446 |
+
save_rollout_video(
|
| 447 |
+
replay_images, total_episodes, success=success, task_description=task_description, log_file=log_file, save_version=save_version
|
| 448 |
+
)
|
| 449 |
+
|
| 450 |
+
# Log results
|
| 451 |
+
log_message(f"Success: {success}", log_file)
|
| 452 |
+
log_message(f"# episodes completed so far: {total_episodes}", log_file)
|
| 453 |
+
log_message(f"# successes: {total_successes} ({total_successes / total_episodes * 100:.1f}%)", log_file)
|
| 454 |
+
|
| 455 |
+
# Log task results
|
| 456 |
+
task_success_rate = float(task_successes) / float(task_episodes) if task_episodes > 0 else 0
|
| 457 |
+
total_success_rate = float(total_successes) / float(total_episodes) if total_episodes > 0 else 0
|
| 458 |
+
|
| 459 |
+
log_message(f"Current task success rate: {task_success_rate}", log_file)
|
| 460 |
+
log_message(f"Current total success rate: {total_success_rate}", log_file)
|
| 461 |
+
|
| 462 |
+
# close env
|
| 463 |
+
env.close()
|
| 464 |
+
del env
|
| 465 |
+
|
| 466 |
+
# Log to wandb if enabled
|
| 467 |
+
if cfg.use_wandb:
|
| 468 |
+
wandb.log(
|
| 469 |
+
{
|
| 470 |
+
f"success_rate/{task_description}": task_success_rate,
|
| 471 |
+
f"num_episodes/{task_description}": task_episodes,
|
| 472 |
+
}
|
| 473 |
+
)
|
| 474 |
+
|
| 475 |
+
return total_episodes, total_successes
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
@draccus.wrap()
|
| 480 |
+
def eval_libero(cfg: GenerateConfig) -> float:
|
| 481 |
+
"""Main function to evaluate a trained policy on LIBERO benchmark tasks."""
|
| 482 |
+
# Validate configuration
|
| 483 |
+
validate_config(cfg)
|
| 484 |
+
|
| 485 |
+
# Set random seed
|
| 486 |
+
set_seed_everywhere(cfg.seed)
|
| 487 |
+
|
| 488 |
+
# Initialize model and components
|
| 489 |
+
model, action_head, proprio_projector, noisy_action_projector, processor = initialize_model(cfg)
|
| 490 |
+
|
| 491 |
+
# for name, param in model.named_parameters():
|
| 492 |
+
# if 'action_queries' in name:
|
| 493 |
+
# print(f"{name}: {param}")
|
| 494 |
+
|
| 495 |
+
# Get expected image dimensions
|
| 496 |
+
resize_size = get_image_resize_size(cfg)
|
| 497 |
+
|
| 498 |
+
# Setup logging
|
| 499 |
+
log_file, local_log_filepath, run_id = setup_logging(cfg)
|
| 500 |
+
|
| 501 |
+
# Initialize LIBERO task suite
|
| 502 |
+
benchmark_dict = benchmark.get_benchmark_dict()
|
| 503 |
+
task_suite = benchmark_dict[cfg.task_suite_name]()
|
| 504 |
+
num_tasks = task_suite.n_tasks
|
| 505 |
+
|
| 506 |
+
log_message(f"Task suite: {cfg.task_suite_name}", log_file)
|
| 507 |
+
|
| 508 |
+
# Start evaluation
|
| 509 |
+
total_episodes, total_successes = 0, 0
|
| 510 |
+
for task_id in tqdm.tqdm(range(num_tasks)):
|
| 511 |
+
total_episodes, total_successes = run_task(
|
| 512 |
+
cfg,
|
| 513 |
+
task_suite,
|
| 514 |
+
task_id,
|
| 515 |
+
model,
|
| 516 |
+
resize_size,
|
| 517 |
+
processor,
|
| 518 |
+
action_head,
|
| 519 |
+
proprio_projector,
|
| 520 |
+
noisy_action_projector,
|
| 521 |
+
total_episodes,
|
| 522 |
+
total_successes,
|
| 523 |
+
log_file,
|
| 524 |
+
cfg.save_version
|
| 525 |
+
)
|
| 526 |
+
|
| 527 |
+
# Calculate final success rate
|
| 528 |
+
final_success_rate = float(total_successes) / float(total_episodes) if total_episodes > 0 else 0
|
| 529 |
+
|
| 530 |
+
# Log final results
|
| 531 |
+
log_message("Final results:", log_file)
|
| 532 |
+
log_message(f"Total episodes: {total_episodes}", log_file)
|
| 533 |
+
log_message(f"Total successes: {total_successes}", log_file)
|
| 534 |
+
log_message(f"Overall success rate: {final_success_rate:.4f} ({final_success_rate * 100:.1f}%)", log_file)
|
| 535 |
+
|
| 536 |
+
# Log to wandb if enabled
|
| 537 |
+
if cfg.use_wandb:
|
| 538 |
+
wandb.log(
|
| 539 |
+
{
|
| 540 |
+
"success_rate/total": final_success_rate,
|
| 541 |
+
"num_episodes/total": total_episodes,
|
| 542 |
+
}
|
| 543 |
+
)
|
| 544 |
+
wandb.save(local_log_filepath)
|
| 545 |
+
|
| 546 |
+
# Close log file
|
| 547 |
+
if log_file:
|
| 548 |
+
log_file.close()
|
| 549 |
+
|
| 550 |
+
return final_success_rate
|
| 551 |
+
|
| 552 |
+
|
| 553 |
+
|
| 554 |
+
if __name__ == "__main__":
|
| 555 |
+
eval_libero()
|
VLA-Adapter-UAV/experiments/robot/libero/sample_libero_spatial_observation.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:326db6c78dd0a9d91c11f05af03b93fa3095338ee3cb5a5eb15adf3d87eb0109
|
| 3 |
+
size 301501
|
VLA-Adapter-UAV/experiments/robot/openvla_utils.py
ADDED
|
@@ -0,0 +1,850 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Utils for evaluating VLA-Adapter or fine-tuned VLA-Adapter policies."""
|
| 2 |
+
|
| 3 |
+
import filecmp
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import shutil
|
| 7 |
+
import time
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
| 11 |
+
|
| 12 |
+
import json_numpy
|
| 13 |
+
import numpy as np
|
| 14 |
+
import requests
|
| 15 |
+
import tensorflow as tf
|
| 16 |
+
import torch
|
| 17 |
+
from huggingface_hub import HfApi, hf_hub_download
|
| 18 |
+
from PIL import Image
|
| 19 |
+
from transformers import AutoConfig, AutoImageProcessor, AutoModelForVision2Seq, AutoProcessor
|
| 20 |
+
|
| 21 |
+
# Apply JSON numpy patch for serialization
|
| 22 |
+
json_numpy.patch()
|
| 23 |
+
|
| 24 |
+
from prismatic.extern.hf.configuration_prismatic import OpenVLAConfig
|
| 25 |
+
from prismatic.extern.hf.modeling_prismatic import OpenVLAForActionPrediction
|
| 26 |
+
from prismatic.extern.hf.processing_prismatic import PrismaticImageProcessor, PrismaticProcessor
|
| 27 |
+
from prismatic.models.action_heads import L1RegressionActionHead
|
| 28 |
+
from prismatic.models.film_vit_wrapper import FiLMedPrismaticVisionBackbone
|
| 29 |
+
from prismatic.models.projectors import NoisyActionProjector, ProprioProjector
|
| 30 |
+
from prismatic.vla.constants import (
|
| 31 |
+
ACTION_DIM,
|
| 32 |
+
ACTION_PROPRIO_NORMALIZATION_TYPE,
|
| 33 |
+
)
|
| 34 |
+
from prismatic.vla.datasets.rlds.utils.data_utils import NormalizationType
|
| 35 |
+
|
| 36 |
+
# Initialize important constants
|
| 37 |
+
DATE = time.strftime("%Y_%m_%d")
|
| 38 |
+
DATE_TIME = time.strftime("%Y_%m_%d-%H_%M_%S")
|
| 39 |
+
DEVICE = torch.device("cuda:0") if torch.cuda.is_available() else torch.device("cpu")
|
| 40 |
+
OPENVLA_IMAGE_SIZE = 224 # Standard image size expected by OpenVLA
|
| 41 |
+
|
| 42 |
+
# Configure NumPy print settings
|
| 43 |
+
np.set_printoptions(formatter={"float": lambda x: "{0:0.8f}".format(x)})
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def model_is_on_hf_hub(model_path: str) -> bool:
|
| 47 |
+
"""Checks whether a model path points to a model on Hugging Face Hub."""
|
| 48 |
+
# Local paths should never trigger a Hub lookup; otherwise each rank can block
|
| 49 |
+
# on a pointless network probe before training starts.
|
| 50 |
+
if os.path.exists(os.path.expanduser(model_path)):
|
| 51 |
+
return False
|
| 52 |
+
|
| 53 |
+
# If the API call below runs without error, the model is on the hub
|
| 54 |
+
try:
|
| 55 |
+
HfApi().model_info(model_path)
|
| 56 |
+
return True
|
| 57 |
+
except Exception:
|
| 58 |
+
return False
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def update_auto_map(pretrained_checkpoint: str) -> None:
|
| 62 |
+
"""
|
| 63 |
+
Update the AutoMap configuration in the checkpoint config.json file.
|
| 64 |
+
|
| 65 |
+
This loads the config.json file inside the checkpoint directory and overwrites
|
| 66 |
+
the AutoConfig and AutoModelForVision2Seq fields to use OpenVLA-specific classes.
|
| 67 |
+
|
| 68 |
+
Args:
|
| 69 |
+
pretrained_checkpoint: Path to the checkpoint directory
|
| 70 |
+
"""
|
| 71 |
+
if not os.path.isdir(pretrained_checkpoint):
|
| 72 |
+
return
|
| 73 |
+
|
| 74 |
+
config_path = os.path.join(pretrained_checkpoint, "config.json")
|
| 75 |
+
if not os.path.exists(config_path):
|
| 76 |
+
print(f"Warning: No config.json found at {config_path}")
|
| 77 |
+
return
|
| 78 |
+
|
| 79 |
+
# Create timestamped backup
|
| 80 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 81 |
+
backup_path = os.path.join(pretrained_checkpoint, f"config.json.back.{timestamp}")
|
| 82 |
+
shutil.copy2(config_path, backup_path)
|
| 83 |
+
print(f"Created backup of original config at: {os.path.abspath(backup_path)}")
|
| 84 |
+
|
| 85 |
+
# Read and update the config
|
| 86 |
+
with open(config_path, "r") as f:
|
| 87 |
+
config = json.load(f)
|
| 88 |
+
|
| 89 |
+
config["auto_map"] = {
|
| 90 |
+
"AutoConfig": "configuration_prismatic.OpenVLAConfig",
|
| 91 |
+
"AutoModelForVision2Seq": "modeling_prismatic.OpenVLAForActionPrediction",
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
# Write back the updated config
|
| 95 |
+
with open(config_path, "w") as f:
|
| 96 |
+
json.dump(config, f, indent=2)
|
| 97 |
+
|
| 98 |
+
print(f"Updated config.json at: {os.path.abspath(config_path)}")
|
| 99 |
+
print("Changes made:")
|
| 100 |
+
print(' - Set AutoConfig to "configuration_prismatic.OpenVLAConfig"')
|
| 101 |
+
print(' - Set AutoModelForVision2Seq to "modeling_prismatic.OpenVLAForActionPrediction"')
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def check_identical_files(path1: Union[str, Path], path2: Union[str, Path]) -> bool:
|
| 105 |
+
"""
|
| 106 |
+
Check if two files are identical in content.
|
| 107 |
+
|
| 108 |
+
Args:
|
| 109 |
+
path1: Path to the first file
|
| 110 |
+
path2: Path to the second file
|
| 111 |
+
|
| 112 |
+
Returns:
|
| 113 |
+
bool: True if files are identical, False otherwise
|
| 114 |
+
"""
|
| 115 |
+
path1, path2 = Path(path1), Path(path2)
|
| 116 |
+
|
| 117 |
+
# First check if file sizes match
|
| 118 |
+
if path1.stat().st_size != path2.stat().st_size:
|
| 119 |
+
return False
|
| 120 |
+
|
| 121 |
+
# Check if contents match
|
| 122 |
+
return filecmp.cmp(path1, path2, shallow=False)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def _handle_file_sync(curr_filepath: str, checkpoint_filepath: str, file_type: str) -> None:
|
| 126 |
+
"""
|
| 127 |
+
Handle syncing of files between current directory and checkpoint.
|
| 128 |
+
|
| 129 |
+
Creates backups if files exist but differ, and copies current versions to checkpoint.
|
| 130 |
+
|
| 131 |
+
Args:
|
| 132 |
+
curr_filepath: Path to the current file version
|
| 133 |
+
checkpoint_filepath: Path where the file should be in the checkpoint
|
| 134 |
+
file_type: Description of the file type for logging
|
| 135 |
+
"""
|
| 136 |
+
if os.path.exists(checkpoint_filepath):
|
| 137 |
+
# Check if existing files are identical
|
| 138 |
+
match = check_identical_files(curr_filepath, checkpoint_filepath)
|
| 139 |
+
|
| 140 |
+
if not match:
|
| 141 |
+
print(
|
| 142 |
+
"\n------------------------------------------------------------------------------------------------\n"
|
| 143 |
+
f"Found mismatch between:\n"
|
| 144 |
+
f"Current: {curr_filepath}\n"
|
| 145 |
+
f"Checkpoint: {checkpoint_filepath}\n"
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
# Create timestamped backup
|
| 149 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 150 |
+
backup_path = f"{checkpoint_filepath}.back.{timestamp}"
|
| 151 |
+
shutil.copy2(checkpoint_filepath, backup_path)
|
| 152 |
+
print(f"Created backup of original checkpoint file at: {os.path.abspath(backup_path)}")
|
| 153 |
+
|
| 154 |
+
# Copy current version to checkpoint directory
|
| 155 |
+
shutil.copy2(curr_filepath, checkpoint_filepath)
|
| 156 |
+
print(f"Copied current version to checkpoint at: {os.path.abspath(checkpoint_filepath)}")
|
| 157 |
+
print(
|
| 158 |
+
f"Changes complete. The checkpoint will now use the current version of {file_type}"
|
| 159 |
+
"\n------------------------------------------------------------------------------------------------\n"
|
| 160 |
+
)
|
| 161 |
+
else:
|
| 162 |
+
# If file doesn't exist in checkpoint directory, copy it
|
| 163 |
+
shutil.copy2(curr_filepath, checkpoint_filepath)
|
| 164 |
+
print(
|
| 165 |
+
"\n------------------------------------------------------------------------------------------------\n"
|
| 166 |
+
f"No {file_type} found in checkpoint directory.\n"
|
| 167 |
+
f"Copied current version from: {curr_filepath}\n"
|
| 168 |
+
f"To checkpoint location: {os.path.abspath(checkpoint_filepath)}"
|
| 169 |
+
"\n------------------------------------------------------------------------------------------------\n"
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def check_model_logic_mismatch(pretrained_checkpoint: str) -> None:
|
| 174 |
+
"""
|
| 175 |
+
Check and sync model logic files between current code and checkpoint.
|
| 176 |
+
|
| 177 |
+
Handles the relationship between current and checkpoint versions of both
|
| 178 |
+
modeling_prismatic.py and configuration_prismatic.py:
|
| 179 |
+
- If checkpoint file exists and differs: creates backup and copies current version
|
| 180 |
+
- If checkpoint file doesn't exist: copies current version
|
| 181 |
+
|
| 182 |
+
Args:
|
| 183 |
+
pretrained_checkpoint: Path to the checkpoint directory
|
| 184 |
+
"""
|
| 185 |
+
if not os.path.isdir(pretrained_checkpoint):
|
| 186 |
+
return
|
| 187 |
+
|
| 188 |
+
# Find current files
|
| 189 |
+
curr_files = {"modeling_prismatic.py": None, "configuration_prismatic.py": None}
|
| 190 |
+
|
| 191 |
+
for root, _, files in os.walk("./prismatic/"):
|
| 192 |
+
for filename in curr_files.keys():
|
| 193 |
+
if filename in files and curr_files[filename] is None:
|
| 194 |
+
curr_files[filename] = os.path.join(root, filename)
|
| 195 |
+
|
| 196 |
+
# Check and handle each file
|
| 197 |
+
for filename, curr_filepath in curr_files.items():
|
| 198 |
+
if curr_filepath is None:
|
| 199 |
+
print(f"WARNING: `{filename}` is not found anywhere in the current directory.")
|
| 200 |
+
continue
|
| 201 |
+
|
| 202 |
+
checkpoint_filepath = os.path.join(pretrained_checkpoint, filename)
|
| 203 |
+
_handle_file_sync(curr_filepath, checkpoint_filepath, filename)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def find_checkpoint_file(pretrained_checkpoint: str, file_pattern: str) -> str:
|
| 207 |
+
"""
|
| 208 |
+
Find a specific checkpoint file matching a pattern.
|
| 209 |
+
|
| 210 |
+
Args:
|
| 211 |
+
pretrained_checkpoint: Path to the checkpoint directory
|
| 212 |
+
file_pattern: String pattern to match in filenames
|
| 213 |
+
|
| 214 |
+
Returns:
|
| 215 |
+
str: Path to the matching checkpoint file
|
| 216 |
+
|
| 217 |
+
Raises:
|
| 218 |
+
AssertionError: If no files or multiple files match the pattern
|
| 219 |
+
"""
|
| 220 |
+
assert os.path.isdir(pretrained_checkpoint), f"Checkpoint path must be a directory: {pretrained_checkpoint}"
|
| 221 |
+
|
| 222 |
+
checkpoint_files = []
|
| 223 |
+
for filename in os.listdir(pretrained_checkpoint):
|
| 224 |
+
if file_pattern in filename and "checkpoint" in filename:
|
| 225 |
+
full_path = os.path.join(pretrained_checkpoint, filename)
|
| 226 |
+
checkpoint_files.append(full_path)
|
| 227 |
+
|
| 228 |
+
assert len(checkpoint_files) == 1, (
|
| 229 |
+
f"Expected exactly 1 {file_pattern} checkpoint but found {len(checkpoint_files)} in directory: {pretrained_checkpoint}"
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
return checkpoint_files[0]
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def load_component_state_dict(checkpoint_path: str) -> Dict[str, torch.Tensor]:
|
| 236 |
+
"""
|
| 237 |
+
Load a component's state dict from checkpoint and handle DDP prefix if present.
|
| 238 |
+
|
| 239 |
+
Args:
|
| 240 |
+
checkpoint_path: Path to the checkpoint file
|
| 241 |
+
|
| 242 |
+
Returns:
|
| 243 |
+
Dict: The processed state dictionary for loading
|
| 244 |
+
"""
|
| 245 |
+
state_dict = torch.load(checkpoint_path, weights_only=True)
|
| 246 |
+
|
| 247 |
+
# If the component was trained with DDP, elements in the state dict have prefix "module." which we must remove
|
| 248 |
+
new_state_dict = {}
|
| 249 |
+
for k, v in state_dict.items():
|
| 250 |
+
if k.startswith("module."):
|
| 251 |
+
new_state_dict[k[7:]] = v
|
| 252 |
+
else:
|
| 253 |
+
new_state_dict[k] = v
|
| 254 |
+
|
| 255 |
+
return new_state_dict
|
| 256 |
+
|
| 257 |
+
def load_component_state_dict_v1(checkpoint_path: str) -> Dict[str, torch.Tensor]:
|
| 258 |
+
"""
|
| 259 |
+
Load a component's state dict from checkpoint and handle DDP prefix if present.
|
| 260 |
+
|
| 261 |
+
Args:
|
| 262 |
+
checkpoint_path: Path to the checkpoint file
|
| 263 |
+
|
| 264 |
+
Returns:
|
| 265 |
+
Dict: The processed state dictionary for loading
|
| 266 |
+
"""
|
| 267 |
+
state_dict = torch.load(checkpoint_path, weights_only=True)
|
| 268 |
+
|
| 269 |
+
# If the component was trained with DDP, elements in the state dict have prefix "module." which we must remove
|
| 270 |
+
new_state_dict = {}
|
| 271 |
+
for k, v in state_dict.items():
|
| 272 |
+
new_state_dict[k] = v
|
| 273 |
+
|
| 274 |
+
return new_state_dict
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def get_vla(cfg: Any) -> torch.nn.Module:
|
| 278 |
+
"""
|
| 279 |
+
Load and initialize the VLA model from checkpoint.
|
| 280 |
+
|
| 281 |
+
Args:
|
| 282 |
+
cfg: Configuration object
|
| 283 |
+
|
| 284 |
+
Returns:
|
| 285 |
+
torch.nn.Module: The initialized VLA model
|
| 286 |
+
"""
|
| 287 |
+
print("Instantiating pretrained VLA policy...")
|
| 288 |
+
|
| 289 |
+
# If loading a locally stored pretrained checkpoint, check whether config or model files
|
| 290 |
+
# need to be synced so that any changes the user makes to the VLA modeling code will
|
| 291 |
+
# actually go into effect
|
| 292 |
+
# If loading a pretrained checkpoint from Hugging Face Hub, we just assume that the policy
|
| 293 |
+
# will be used as is, with its original modeling logic
|
| 294 |
+
if not model_is_on_hf_hub(cfg.pretrained_checkpoint):
|
| 295 |
+
# Register OpenVLA model to HF Auto Classes (not needed if the model is on HF Hub)
|
| 296 |
+
AutoConfig.register("openvla", OpenVLAConfig)
|
| 297 |
+
AutoImageProcessor.register(OpenVLAConfig, PrismaticImageProcessor)
|
| 298 |
+
AutoProcessor.register(OpenVLAConfig, PrismaticProcessor)
|
| 299 |
+
AutoModelForVision2Seq.register(OpenVLAConfig, OpenVLAForActionPrediction)
|
| 300 |
+
|
| 301 |
+
# Update config.json and sync model files
|
| 302 |
+
update_auto_map(cfg.pretrained_checkpoint)
|
| 303 |
+
check_model_logic_mismatch(cfg.pretrained_checkpoint)
|
| 304 |
+
|
| 305 |
+
# Load the model
|
| 306 |
+
vla = AutoModelForVision2Seq.from_pretrained(
|
| 307 |
+
cfg.pretrained_checkpoint,
|
| 308 |
+
# attn_implementation="flash_attention_2",
|
| 309 |
+
torch_dtype=torch.bfloat16,
|
| 310 |
+
load_in_8bit=cfg.load_in_8bit,
|
| 311 |
+
load_in_4bit=cfg.load_in_4bit,
|
| 312 |
+
low_cpu_mem_usage=False,
|
| 313 |
+
trust_remote_code=False,
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
# If using FiLM, wrap the vision backbone to allow for infusion of language inputs
|
| 317 |
+
if cfg.use_film:
|
| 318 |
+
vla = _apply_film_to_vla(vla, cfg)
|
| 319 |
+
|
| 320 |
+
# Set number of images in model input
|
| 321 |
+
vla.vision_backbone.set_num_images_in_input(cfg.num_images_in_input)
|
| 322 |
+
|
| 323 |
+
vla.eval()
|
| 324 |
+
|
| 325 |
+
# Move model to device if not using quantization
|
| 326 |
+
if not cfg.load_in_8bit and not cfg.load_in_4bit:
|
| 327 |
+
vla = vla.to(DEVICE)
|
| 328 |
+
|
| 329 |
+
# Load dataset stats for action normalization
|
| 330 |
+
_load_dataset_stats(vla, cfg.pretrained_checkpoint)
|
| 331 |
+
|
| 332 |
+
return vla
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def _apply_film_to_vla(vla: torch.nn.Module, cfg: Any) -> torch.nn.Module:
|
| 336 |
+
"""
|
| 337 |
+
Apply FiLM (Feature-wise Linear Modulation) to the VLA vision backbone.
|
| 338 |
+
|
| 339 |
+
Args:
|
| 340 |
+
vla: The VLA model
|
| 341 |
+
cfg: Configuration object with model parameters
|
| 342 |
+
|
| 343 |
+
Returns:
|
| 344 |
+
torch.nn.Module: VLA model with FiLM applied
|
| 345 |
+
"""
|
| 346 |
+
from peft import LoraConfig, get_peft_model
|
| 347 |
+
|
| 348 |
+
# Apply LoRA configuration
|
| 349 |
+
lora_config = LoraConfig(
|
| 350 |
+
r=32,
|
| 351 |
+
lora_alpha=16,
|
| 352 |
+
lora_dropout=0.0,
|
| 353 |
+
target_modules="all-linear",
|
| 354 |
+
init_lora_weights="gaussian",
|
| 355 |
+
)
|
| 356 |
+
vla = get_peft_model(vla, lora_config)
|
| 357 |
+
|
| 358 |
+
# Create and apply FiLMed vision backbone
|
| 359 |
+
new_vision_backbone = FiLMedPrismaticVisionBackbone(
|
| 360 |
+
vision_backbone=vla.vision_backbone, llm_dim=vla.llm_dim,
|
| 361 |
+
)
|
| 362 |
+
vla.model.vision_backbone = new_vision_backbone
|
| 363 |
+
|
| 364 |
+
# Load vision backbone checkpoint
|
| 365 |
+
checkpoint_path = find_checkpoint_file(cfg.pretrained_checkpoint, "vision_backbone")
|
| 366 |
+
state_dict = torch.load(checkpoint_path, weights_only=True)
|
| 367 |
+
vla.model.vision_backbone.load_state_dict(state_dict)
|
| 368 |
+
|
| 369 |
+
# Use the model component instead of wrapper and convert to bfloat16
|
| 370 |
+
vla = vla.model
|
| 371 |
+
vla.vision_backbone = vla.vision_backbone.to(torch.bfloat16)
|
| 372 |
+
|
| 373 |
+
return vla
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
def _load_dataset_stats(vla: torch.nn.Module, checkpoint_path: str) -> None:
|
| 377 |
+
"""
|
| 378 |
+
Load dataset statistics used during training for action normalization.
|
| 379 |
+
|
| 380 |
+
Args:
|
| 381 |
+
vla: The VLA model
|
| 382 |
+
checkpoint_path: Path to the checkpoint directory
|
| 383 |
+
"""
|
| 384 |
+
if model_is_on_hf_hub(checkpoint_path):
|
| 385 |
+
# Download dataset stats directly from HF Hub
|
| 386 |
+
dataset_statistics_path = hf_hub_download(
|
| 387 |
+
repo_id=checkpoint_path,
|
| 388 |
+
filename="dataset_statistics.json",
|
| 389 |
+
)
|
| 390 |
+
else:
|
| 391 |
+
dataset_statistics_path = os.path.join(checkpoint_path, "dataset_statistics.json")
|
| 392 |
+
if os.path.isfile(dataset_statistics_path):
|
| 393 |
+
with open(dataset_statistics_path, "r") as f:
|
| 394 |
+
norm_stats = json.load(f)
|
| 395 |
+
vla.norm_stats = norm_stats
|
| 396 |
+
else:
|
| 397 |
+
print(
|
| 398 |
+
"WARNING: No local dataset_statistics.json file found for current checkpoint.\n"
|
| 399 |
+
"You can ignore this if you are loading the base VLA (i.e. not fine-tuned) checkpoint."
|
| 400 |
+
"Otherwise, you may run into errors when trying to call `predict_action()` due to an absent `unnorm_key`."
|
| 401 |
+
)
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def get_processor(cfg: Any) -> AutoProcessor:
|
| 405 |
+
"""
|
| 406 |
+
Get the VLA model's Hugging Face processor.
|
| 407 |
+
|
| 408 |
+
Args:
|
| 409 |
+
cfg: Configuration object with model parameters
|
| 410 |
+
|
| 411 |
+
Returns:
|
| 412 |
+
AutoProcessor: The model's processor
|
| 413 |
+
"""
|
| 414 |
+
return AutoProcessor.from_pretrained(cfg.pretrained_checkpoint, trust_remote_code=False)
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
def get_proprio_projector(cfg: Any, llm_dim: int, proprio_dim: int) -> ProprioProjector:
|
| 418 |
+
"""
|
| 419 |
+
Get proprioception projector for the VLA model.
|
| 420 |
+
|
| 421 |
+
Args:
|
| 422 |
+
cfg: Configuration object with model parameters
|
| 423 |
+
llm_dim: Dimension of the language model
|
| 424 |
+
proprio_dim: Dimension of proprioception data
|
| 425 |
+
|
| 426 |
+
Returns:
|
| 427 |
+
ProprioProjector: The initialized proprio projector
|
| 428 |
+
"""
|
| 429 |
+
# Initialize projector and move to device
|
| 430 |
+
proprio_projector = ProprioProjector(
|
| 431 |
+
llm_dim=llm_dim,
|
| 432 |
+
proprio_dim=proprio_dim,
|
| 433 |
+
).to(DEVICE)
|
| 434 |
+
proprio_projector = proprio_projector.to(torch.bfloat16).to(DEVICE)
|
| 435 |
+
proprio_projector.eval()
|
| 436 |
+
|
| 437 |
+
# Find and load checkpoint (may be on Hugging Face Hub or stored locally)
|
| 438 |
+
if model_is_on_hf_hub(cfg.pretrained_checkpoint):
|
| 439 |
+
model_path_to_proprio_projector_name = {
|
| 440 |
+
"VLA-Adapter/LIBERO-Spatial-Pro": "proprio_projector--checkpoint.pt",
|
| 441 |
+
"VLA-Adapter/LIBERO-Object-Pro": "proprio_projector--checkpoint.pt",
|
| 442 |
+
"VLA-Adapter/LIBERO-Goal-Pro": "proprio_projector--checkpoint.pt",
|
| 443 |
+
"VLA-Adapter/LIBERO-Long-Pro": "proprio_projector--checkpoint.pt",
|
| 444 |
+
}
|
| 445 |
+
if cfg.pretrained_checkpoint not in model_path_to_proprio_projector_name.keys():
|
| 446 |
+
raise ValueError("Unsupported HF Hub pretrained checkpoint found!")
|
| 447 |
+
# Download proprio projector directly from HF Hub
|
| 448 |
+
proprio_projector_path = hf_hub_download(
|
| 449 |
+
repo_id=cfg.pretrained_checkpoint, filename=model_path_to_proprio_projector_name[cfg.pretrained_checkpoint]
|
| 450 |
+
)
|
| 451 |
+
state_dict = load_component_state_dict(proprio_projector_path)
|
| 452 |
+
proprio_projector.load_state_dict(state_dict)
|
| 453 |
+
else:
|
| 454 |
+
checkpoint_path = find_checkpoint_file(cfg.pretrained_checkpoint, "proprio_projector")
|
| 455 |
+
state_dict = load_component_state_dict(checkpoint_path)
|
| 456 |
+
proprio_projector.load_state_dict(state_dict)
|
| 457 |
+
|
| 458 |
+
return proprio_projector
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
def get_noisy_action_projector(cfg: Any, llm_dim: int) -> NoisyActionProjector:
|
| 462 |
+
"""
|
| 463 |
+
Get noisy action projector for diffusion-based action prediction.
|
| 464 |
+
|
| 465 |
+
Args:
|
| 466 |
+
cfg: Configuration object with model parameters
|
| 467 |
+
llm_dim: Dimension of the language model
|
| 468 |
+
|
| 469 |
+
Returns:
|
| 470 |
+
NoisyActionProjector: The initialized noisy action projector
|
| 471 |
+
"""
|
| 472 |
+
# Initialize projector and move to device
|
| 473 |
+
noisy_action_projector = NoisyActionProjector(
|
| 474 |
+
llm_dim=llm_dim,
|
| 475 |
+
).to(DEVICE)
|
| 476 |
+
noisy_action_projector = noisy_action_projector.to(torch.bfloat16).to(DEVICE)
|
| 477 |
+
noisy_action_projector.eval()
|
| 478 |
+
|
| 479 |
+
# Find and load checkpoint
|
| 480 |
+
checkpoint_path = find_checkpoint_file(cfg.pretrained_checkpoint, "noisy_action_projector")
|
| 481 |
+
state_dict = load_component_state_dict(checkpoint_path)
|
| 482 |
+
noisy_action_projector.load_state_dict(state_dict)
|
| 483 |
+
|
| 484 |
+
return noisy_action_projector
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
def get_action_head(cfg: Any, llm_dim: int) -> Union[L1RegressionActionHead]:
|
| 488 |
+
"""
|
| 489 |
+
Get action head for continuous value prediction.
|
| 490 |
+
|
| 491 |
+
Args:
|
| 492 |
+
cfg: Configuration object with model parameters
|
| 493 |
+
llm_dim: Dimension of the language model
|
| 494 |
+
|
| 495 |
+
Returns:
|
| 496 |
+
Union[L1RegressionActionHead, DiffusionActionHead]: The initialized action head
|
| 497 |
+
|
| 498 |
+
Raises:
|
| 499 |
+
AssertionError: If both L1 regression and diffusion are specified
|
| 500 |
+
"""
|
| 501 |
+
# assert not cfg.use_l1_regression, "Cannot use both L1 regression and diffusion action head!"
|
| 502 |
+
if not hasattr(cfg, "use_pro_version"):
|
| 503 |
+
if "Pro" in cfg.pretrained_checkpoint or "Pro" in cfg.save_version:
|
| 504 |
+
cfg.use_pro_version = True
|
| 505 |
+
else:
|
| 506 |
+
cfg.use_pro_version = False
|
| 507 |
+
|
| 508 |
+
# Initialize appropriate action head based on configuration
|
| 509 |
+
if cfg.use_l1_regression:
|
| 510 |
+
action_head = L1RegressionActionHead(
|
| 511 |
+
input_dim=llm_dim,
|
| 512 |
+
hidden_dim=llm_dim,
|
| 513 |
+
action_dim=ACTION_DIM,
|
| 514 |
+
use_pro_version=cfg.use_pro_version,
|
| 515 |
+
)
|
| 516 |
+
|
| 517 |
+
else:
|
| 518 |
+
raise ValueError("Either use_l1_regression or use_diffusion must be True")
|
| 519 |
+
|
| 520 |
+
action_head = action_head.to(torch.bfloat16).to(DEVICE)
|
| 521 |
+
action_head.eval()
|
| 522 |
+
|
| 523 |
+
# Find and load checkpoint (may be on Hugging Face Hub or stored locally)
|
| 524 |
+
if model_is_on_hf_hub(cfg.pretrained_checkpoint):
|
| 525 |
+
model_path_to_action_head_name = {
|
| 526 |
+
"VLA-Adapter/LIBERO-Spatial-Pro": "action_head--checkpoint.pt",
|
| 527 |
+
"VLA-Adapter/LIBERO-Object-Pro": "action_head--checkpoint.pt",
|
| 528 |
+
"VLA-Adapter/LIBERO-Goal-Pro": "action_head--checkpoint.pt",
|
| 529 |
+
"VLA-Adapter/LIBERO-Long-Pro": "action_head--checkpoint.pt",
|
| 530 |
+
}
|
| 531 |
+
if cfg.pretrained_checkpoint not in model_path_to_action_head_name.keys():
|
| 532 |
+
raise ValueError("Unsupported HF Hub pretrained checkpoint found!")
|
| 533 |
+
# Download proprio projector directly from HF Hub
|
| 534 |
+
action_head_path = hf_hub_download(
|
| 535 |
+
repo_id=cfg.pretrained_checkpoint, filename=model_path_to_action_head_name[cfg.pretrained_checkpoint]
|
| 536 |
+
)
|
| 537 |
+
state_dict = load_component_state_dict(action_head_path)
|
| 538 |
+
action_head.load_state_dict(state_dict)
|
| 539 |
+
else:
|
| 540 |
+
checkpoint_path = find_checkpoint_file(cfg.pretrained_checkpoint, "action_head")
|
| 541 |
+
state_dict = load_component_state_dict(checkpoint_path)
|
| 542 |
+
action_head.load_state_dict(state_dict)
|
| 543 |
+
|
| 544 |
+
return action_head
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
def resize_image_for_policy(img: np.ndarray, resize_size: Union[int, Tuple[int, int]]) -> np.ndarray:
|
| 548 |
+
"""
|
| 549 |
+
Resize an image to match the policy's expected input size.
|
| 550 |
+
|
| 551 |
+
Uses the same resizing scheme as in the training data pipeline for distribution matching.
|
| 552 |
+
|
| 553 |
+
Args:
|
| 554 |
+
img: Numpy array containing the image
|
| 555 |
+
resize_size: Target size as int (square) or (height, width) tuple
|
| 556 |
+
|
| 557 |
+
Returns:
|
| 558 |
+
np.ndarray: The resized image
|
| 559 |
+
"""
|
| 560 |
+
assert isinstance(resize_size, int) or isinstance(resize_size, tuple)
|
| 561 |
+
if isinstance(resize_size, int):
|
| 562 |
+
resize_size = (resize_size, resize_size)
|
| 563 |
+
|
| 564 |
+
# Resize using the same pipeline as in RLDS dataset builder
|
| 565 |
+
img = tf.image.encode_jpeg(img) # Encode as JPEG
|
| 566 |
+
img = tf.io.decode_image(img, expand_animations=False, dtype=tf.uint8) # Decode back
|
| 567 |
+
img = tf.image.resize(img, resize_size, method="lanczos3", antialias=True)
|
| 568 |
+
img = tf.cast(tf.clip_by_value(tf.round(img), 0, 255), tf.uint8)
|
| 569 |
+
|
| 570 |
+
return img.numpy()
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
def crop_and_resize(image: tf.Tensor, crop_scale: float, batch_size: int) -> tf.Tensor:
|
| 574 |
+
"""
|
| 575 |
+
Center-crop an image and resize it back to original dimensions.
|
| 576 |
+
|
| 577 |
+
Uses the same logic as in the training data pipeline for distribution matching.
|
| 578 |
+
|
| 579 |
+
Args:
|
| 580 |
+
image: TF Tensor of shape (batch_size, H, W, C) or (H, W, C) with values in [0,1]
|
| 581 |
+
crop_scale: Area of center crop relative to original image
|
| 582 |
+
batch_size: Batch size
|
| 583 |
+
|
| 584 |
+
Returns:
|
| 585 |
+
tf.Tensor: The cropped and resized image
|
| 586 |
+
"""
|
| 587 |
+
# Handle 3D inputs by adding batch dimension if needed
|
| 588 |
+
assert image.shape.ndims in (3, 4), "Image must be 3D or 4D tensor"
|
| 589 |
+
expanded_dims = False
|
| 590 |
+
if image.shape.ndims == 3:
|
| 591 |
+
image = tf.expand_dims(image, axis=0)
|
| 592 |
+
expanded_dims = True
|
| 593 |
+
|
| 594 |
+
# Calculate crop dimensions (note: we use sqrt(crop_scale) for h/w)
|
| 595 |
+
new_heights = tf.reshape(tf.clip_by_value(tf.sqrt(crop_scale), 0, 1), shape=(batch_size,))
|
| 596 |
+
new_widths = tf.reshape(tf.clip_by_value(tf.sqrt(crop_scale), 0, 1), shape=(batch_size,))
|
| 597 |
+
|
| 598 |
+
# Create bounding box for the crop
|
| 599 |
+
height_offsets = (1 - new_heights) / 2
|
| 600 |
+
width_offsets = (1 - new_widths) / 2
|
| 601 |
+
bounding_boxes = tf.stack(
|
| 602 |
+
[
|
| 603 |
+
height_offsets,
|
| 604 |
+
width_offsets,
|
| 605 |
+
height_offsets + new_heights,
|
| 606 |
+
width_offsets + new_widths,
|
| 607 |
+
],
|
| 608 |
+
axis=1,
|
| 609 |
+
)
|
| 610 |
+
|
| 611 |
+
# Apply crop and resize
|
| 612 |
+
image = tf.image.crop_and_resize(
|
| 613 |
+
image, bounding_boxes, tf.range(batch_size), (OPENVLA_IMAGE_SIZE, OPENVLA_IMAGE_SIZE)
|
| 614 |
+
)
|
| 615 |
+
|
| 616 |
+
# Remove batch dimension if it was added
|
| 617 |
+
if expanded_dims:
|
| 618 |
+
image = image[0]
|
| 619 |
+
|
| 620 |
+
return image
|
| 621 |
+
|
| 622 |
+
|
| 623 |
+
def center_crop_image(image: Union[np.ndarray, Image.Image]) -> Image.Image:
|
| 624 |
+
"""
|
| 625 |
+
Center crop an image to match training data distribution.
|
| 626 |
+
|
| 627 |
+
Args:
|
| 628 |
+
image: Input image (PIL or numpy array)
|
| 629 |
+
|
| 630 |
+
Returns:
|
| 631 |
+
Image.Image: Cropped PIL Image
|
| 632 |
+
"""
|
| 633 |
+
batch_size = 1
|
| 634 |
+
crop_scale = 0.9
|
| 635 |
+
|
| 636 |
+
# Convert to TF Tensor if needed
|
| 637 |
+
if not isinstance(image, tf.Tensor):
|
| 638 |
+
image = tf.convert_to_tensor(np.array(image))
|
| 639 |
+
|
| 640 |
+
orig_dtype = image.dtype
|
| 641 |
+
|
| 642 |
+
# Convert to float32 in range [0,1]
|
| 643 |
+
image = tf.image.convert_image_dtype(image, tf.float32)
|
| 644 |
+
|
| 645 |
+
# Apply center crop and resize
|
| 646 |
+
image = crop_and_resize(image, crop_scale, batch_size)
|
| 647 |
+
|
| 648 |
+
# Convert back to original data type
|
| 649 |
+
image = tf.clip_by_value(image, 0, 1)
|
| 650 |
+
image = tf.image.convert_image_dtype(image, orig_dtype, saturate=True)
|
| 651 |
+
|
| 652 |
+
# Convert to PIL Image
|
| 653 |
+
return Image.fromarray(image.numpy()).convert("RGB")
|
| 654 |
+
|
| 655 |
+
|
| 656 |
+
def check_image_format(image: Any) -> None:
|
| 657 |
+
"""
|
| 658 |
+
Validate input image format.
|
| 659 |
+
|
| 660 |
+
Args:
|
| 661 |
+
image: Image to check
|
| 662 |
+
|
| 663 |
+
Raises:
|
| 664 |
+
AssertionError: If image format is invalid
|
| 665 |
+
"""
|
| 666 |
+
is_numpy_array = isinstance(image, np.ndarray)
|
| 667 |
+
has_correct_shape = len(image.shape) == 3 and image.shape[-1] == 3
|
| 668 |
+
has_correct_dtype = image.dtype == np.uint8
|
| 669 |
+
|
| 670 |
+
assert is_numpy_array and has_correct_shape and has_correct_dtype, (
|
| 671 |
+
"Incorrect image format detected! Make sure that the input image is a "
|
| 672 |
+
"numpy array with shape (H, W, 3) and dtype np.uint8!"
|
| 673 |
+
)
|
| 674 |
+
|
| 675 |
+
|
| 676 |
+
def normalize_proprio(proprio: np.ndarray, norm_stats: Dict[str, Any]) -> np.ndarray:
|
| 677 |
+
"""
|
| 678 |
+
Normalize proprioception data to match training distribution.
|
| 679 |
+
|
| 680 |
+
Args:
|
| 681 |
+
proprio: Raw proprioception data
|
| 682 |
+
norm_stats: Normalization statistics
|
| 683 |
+
|
| 684 |
+
Returns:
|
| 685 |
+
np.ndarray: Normalized proprioception data
|
| 686 |
+
"""
|
| 687 |
+
if ACTION_PROPRIO_NORMALIZATION_TYPE == NormalizationType.BOUNDS:
|
| 688 |
+
mask = norm_stats.get("mask", np.ones_like(norm_stats["min"], dtype=bool))
|
| 689 |
+
proprio_high, proprio_low = np.array(norm_stats["max"]), np.array(norm_stats["min"])
|
| 690 |
+
elif ACTION_PROPRIO_NORMALIZATION_TYPE == NormalizationType.BOUNDS_Q99:
|
| 691 |
+
mask = norm_stats.get("mask", np.ones_like(norm_stats["q01"], dtype=bool))
|
| 692 |
+
proprio_high, proprio_low = np.array(norm_stats["q99"]), np.array(norm_stats["q01"])
|
| 693 |
+
else:
|
| 694 |
+
raise ValueError("Unsupported action/proprio normalization type detected!")
|
| 695 |
+
|
| 696 |
+
normalized_proprio = np.clip(
|
| 697 |
+
np.where(
|
| 698 |
+
mask,
|
| 699 |
+
2 * (proprio - proprio_low) / (proprio_high - proprio_low + 1e-8) - 1,
|
| 700 |
+
proprio,
|
| 701 |
+
),
|
| 702 |
+
a_min=-1.0,
|
| 703 |
+
a_max=1.0,
|
| 704 |
+
)
|
| 705 |
+
|
| 706 |
+
return normalized_proprio
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
def prepare_images_for_vla(images: List[np.ndarray], cfg: Any) -> List[Image.Image]:
|
| 710 |
+
"""
|
| 711 |
+
Prepare images for VLA input by resizing and cropping as needed.
|
| 712 |
+
|
| 713 |
+
Args:
|
| 714 |
+
images: List of input images as numpy arrays
|
| 715 |
+
cfg: Configuration object with parameters
|
| 716 |
+
|
| 717 |
+
Returns:
|
| 718 |
+
List[Image.Image]: Processed images ready for the model
|
| 719 |
+
"""
|
| 720 |
+
processed_images = []
|
| 721 |
+
|
| 722 |
+
for image in images:
|
| 723 |
+
# Validate format
|
| 724 |
+
check_image_format(image)
|
| 725 |
+
|
| 726 |
+
# Resize if needed
|
| 727 |
+
if image.shape != (OPENVLA_IMAGE_SIZE, OPENVLA_IMAGE_SIZE, 3):
|
| 728 |
+
image = resize_image_for_policy(image, OPENVLA_IMAGE_SIZE)
|
| 729 |
+
|
| 730 |
+
# Convert to PIL image
|
| 731 |
+
pil_image = Image.fromarray(image).convert("RGB")
|
| 732 |
+
|
| 733 |
+
# Apply center crop if configured
|
| 734 |
+
if cfg.center_crop:
|
| 735 |
+
pil_image = center_crop_image(pil_image)
|
| 736 |
+
|
| 737 |
+
processed_images.append(pil_image)
|
| 738 |
+
|
| 739 |
+
return processed_images
|
| 740 |
+
|
| 741 |
+
|
| 742 |
+
def get_vla_action(
|
| 743 |
+
cfg: Any,
|
| 744 |
+
vla: torch.nn.Module,
|
| 745 |
+
processor: Any,
|
| 746 |
+
obs: Dict[str, Any],
|
| 747 |
+
task_label: str,
|
| 748 |
+
action_head: Optional[torch.nn.Module] = None,
|
| 749 |
+
proprio_projector: Optional[torch.nn.Module] = None,
|
| 750 |
+
noisy_action_projector: Optional[torch.nn.Module] = None,
|
| 751 |
+
use_film: bool = False,
|
| 752 |
+
use_minivlm: bool = False,
|
| 753 |
+
) -> List[np.ndarray]:
|
| 754 |
+
"""
|
| 755 |
+
Generate action predictions with the VLA policy.
|
| 756 |
+
|
| 757 |
+
Args:
|
| 758 |
+
cfg: Configuration object with parameters
|
| 759 |
+
vla: The VLA model
|
| 760 |
+
processor: Model processor for inputs
|
| 761 |
+
obs: Observation dictionary
|
| 762 |
+
task_label: Text description of the task
|
| 763 |
+
action_head: Optional action head for continuous actions
|
| 764 |
+
proprio_projector: Optional proprioception projector
|
| 765 |
+
noisy_action_projector: Optional noisy action projector for diffusion
|
| 766 |
+
use_film: Whether to use FiLM
|
| 767 |
+
|
| 768 |
+
Returns:
|
| 769 |
+
List[np.ndarray]: Predicted actions
|
| 770 |
+
"""
|
| 771 |
+
with torch.inference_mode():
|
| 772 |
+
|
| 773 |
+
# Collect all input images
|
| 774 |
+
all_images = [obs["full_image"]]
|
| 775 |
+
if cfg.num_images_in_input > 1:
|
| 776 |
+
all_images.extend([obs[k] for k in obs.keys() if "wrist" in k])
|
| 777 |
+
|
| 778 |
+
# Process images
|
| 779 |
+
all_images = prepare_images_for_vla(all_images, cfg)
|
| 780 |
+
|
| 781 |
+
# Extract primary image and additional images
|
| 782 |
+
primary_image = all_images.pop(0)
|
| 783 |
+
|
| 784 |
+
# Build VLA prompt
|
| 785 |
+
if not use_minivlm:
|
| 786 |
+
prompt = f"In: What action should the robot take to {task_label.lower()}?\nOut:"
|
| 787 |
+
else:
|
| 788 |
+
prompt = f'<|im_start|>system\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\n<|im_start|>user\nWhat action should the robot take to {task_label.lower()}?<|im_end|>\n<|im_start|>assistant\n'
|
| 789 |
+
|
| 790 |
+
# Process primary image
|
| 791 |
+
inputs = processor(prompt, primary_image).to(DEVICE, dtype=torch.bfloat16)
|
| 792 |
+
|
| 793 |
+
# Process additional wrist images if any
|
| 794 |
+
if all_images:
|
| 795 |
+
all_wrist_inputs = [
|
| 796 |
+
processor(prompt, image_wrist).to(DEVICE, dtype=torch.bfloat16) for image_wrist in all_images
|
| 797 |
+
]
|
| 798 |
+
# Concatenate all images
|
| 799 |
+
primary_pixel_values = inputs["pixel_values"]
|
| 800 |
+
all_wrist_pixel_values = [wrist_inputs["pixel_values"] for wrist_inputs in all_wrist_inputs]
|
| 801 |
+
inputs["pixel_values"] = torch.cat([primary_pixel_values] + all_wrist_pixel_values, dim=1)
|
| 802 |
+
|
| 803 |
+
# Process proprioception data if used
|
| 804 |
+
proprio = None
|
| 805 |
+
if cfg.use_proprio:
|
| 806 |
+
proprio = obs["state"]
|
| 807 |
+
proprio_norm_stats = vla.norm_stats[cfg.unnorm_key]["proprio"]
|
| 808 |
+
obs["state"] = normalize_proprio(proprio, proprio_norm_stats)
|
| 809 |
+
proprio = obs["state"]
|
| 810 |
+
|
| 811 |
+
|
| 812 |
+
# Generate action
|
| 813 |
+
if action_head is None:
|
| 814 |
+
# Standard VLA output (single-image inputs, discrete actions)
|
| 815 |
+
action, _ = vla.predict_action(**inputs, unnorm_key=cfg.unnorm_key, do_sample=False)
|
| 816 |
+
else:
|
| 817 |
+
# Custom action head for continuous actions
|
| 818 |
+
action, _ = vla.predict_action(
|
| 819 |
+
**inputs,
|
| 820 |
+
unnorm_key=cfg.unnorm_key,
|
| 821 |
+
do_sample=False,
|
| 822 |
+
proprio=proprio,
|
| 823 |
+
proprio_projector=proprio_projector,
|
| 824 |
+
noisy_action_projector=noisy_action_projector,
|
| 825 |
+
action_head=action_head,
|
| 826 |
+
use_film=use_film,
|
| 827 |
+
)
|
| 828 |
+
|
| 829 |
+
# Extract subset of actions for open loop steps
|
| 830 |
+
return [action[i] for i in range(min(len(action), cfg.num_open_loop_steps))]
|
| 831 |
+
|
| 832 |
+
|
| 833 |
+
def get_action_from_server(
|
| 834 |
+
observation: Dict[str, Any], server_endpoint: str = "http://0.0.0.0:8777/act"
|
| 835 |
+
) -> Dict[str, Any]:
|
| 836 |
+
"""
|
| 837 |
+
Get VLA action from remote inference server.
|
| 838 |
+
|
| 839 |
+
Args:
|
| 840 |
+
observation: Observation data to send to server
|
| 841 |
+
server_endpoint: URL of the inference server
|
| 842 |
+
|
| 843 |
+
Returns:
|
| 844 |
+
Dict[str, Any]: Action response from server
|
| 845 |
+
"""
|
| 846 |
+
response = requests.post(
|
| 847 |
+
server_endpoint,
|
| 848 |
+
json=observation,
|
| 849 |
+
)
|
| 850 |
+
return response.json()
|
VLA-Adapter-UAV/experiments/robot/robot_utils.py
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Utils for evaluating robot policies in various environments."""
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import random
|
| 5 |
+
import time
|
| 6 |
+
from typing import Any, Dict, List, Optional, Union
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
from experiments.robot.openvla_utils import (
|
| 12 |
+
get_vla,
|
| 13 |
+
get_vla_action,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
# Initialize important constants
|
| 17 |
+
ACTION_DIM = 7
|
| 18 |
+
DATE = time.strftime("%Y_%m_%d")
|
| 19 |
+
DATE_TIME = time.strftime("%Y_%m_%d-%H_%M_%S")
|
| 20 |
+
DEVICE = torch.device("cuda:0") if torch.cuda.is_available() else torch.device("cpu")
|
| 21 |
+
|
| 22 |
+
# Configure NumPy print settings
|
| 23 |
+
np.set_printoptions(formatter={"float": lambda x: "{0:0.8f}".format(x)})
|
| 24 |
+
|
| 25 |
+
# Initialize system prompt for OpenVLA v0.1
|
| 26 |
+
OPENVLA_V01_SYSTEM_PROMPT = (
|
| 27 |
+
"A chat between a curious user and an artificial intelligence assistant. "
|
| 28 |
+
"The assistant gives helpful, detailed, and polite answers to the user's questions."
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
# Model image size configuration
|
| 32 |
+
MODEL_IMAGE_SIZES = {
|
| 33 |
+
"openvla": 224,
|
| 34 |
+
# Add other models as needed
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def set_seed_everywhere(seed: int) -> None:
|
| 39 |
+
"""
|
| 40 |
+
Set random seed for all random number generators for reproducibility.
|
| 41 |
+
|
| 42 |
+
Args:
|
| 43 |
+
seed: The random seed to use
|
| 44 |
+
"""
|
| 45 |
+
torch.manual_seed(seed)
|
| 46 |
+
torch.cuda.manual_seed_all(seed)
|
| 47 |
+
np.random.seed(seed)
|
| 48 |
+
random.seed(seed)
|
| 49 |
+
torch.backends.cudnn.deterministic = True
|
| 50 |
+
torch.backends.cudnn.benchmark = False
|
| 51 |
+
os.environ["PYTHONHASHSEED"] = str(seed)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def get_model(cfg: Any, wrap_diffusion_policy_for_droid: bool = False) -> torch.nn.Module:
|
| 55 |
+
"""
|
| 56 |
+
Load and initialize model for evaluation based on configuration.
|
| 57 |
+
|
| 58 |
+
Args:
|
| 59 |
+
cfg: Configuration object with model parameters
|
| 60 |
+
wrap_diffusion_policy_for_droid: Whether to wrap diffusion policy for DROID
|
| 61 |
+
|
| 62 |
+
Returns:
|
| 63 |
+
torch.nn.Module: The loaded model
|
| 64 |
+
|
| 65 |
+
Raises:
|
| 66 |
+
ValueError: If model family is not supported
|
| 67 |
+
"""
|
| 68 |
+
if cfg.model_family == "openvla":
|
| 69 |
+
model = get_vla(cfg)
|
| 70 |
+
else:
|
| 71 |
+
raise ValueError(f"Unsupported model family: {cfg.model_family}")
|
| 72 |
+
|
| 73 |
+
print(f"Loaded model: {type(model)}")
|
| 74 |
+
return model
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def get_image_resize_size(cfg: Any) -> Union[int, tuple]:
|
| 78 |
+
"""
|
| 79 |
+
Get image resize dimensions for a specific model.
|
| 80 |
+
|
| 81 |
+
If returned value is an int, the resized image will be a square.
|
| 82 |
+
If returned value is a tuple, the resized image will be a rectangle.
|
| 83 |
+
|
| 84 |
+
Args:
|
| 85 |
+
cfg: Configuration object with model parameters
|
| 86 |
+
|
| 87 |
+
Returns:
|
| 88 |
+
Union[int, tuple]: Image resize dimensions
|
| 89 |
+
|
| 90 |
+
Raises:
|
| 91 |
+
ValueError: If model family is not supported
|
| 92 |
+
"""
|
| 93 |
+
if cfg.model_family not in MODEL_IMAGE_SIZES:
|
| 94 |
+
raise ValueError(f"Unsupported model family: {cfg.model_family}")
|
| 95 |
+
|
| 96 |
+
return MODEL_IMAGE_SIZES[cfg.model_family]
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def get_action(
|
| 100 |
+
cfg: Any,
|
| 101 |
+
model: torch.nn.Module,
|
| 102 |
+
obs: Dict[str, Any],
|
| 103 |
+
task_label: str,
|
| 104 |
+
processor: Optional[Any] = None,
|
| 105 |
+
action_head: Optional[torch.nn.Module] = None,
|
| 106 |
+
proprio_projector: Optional[torch.nn.Module] = None,
|
| 107 |
+
noisy_action_projector: Optional[torch.nn.Module] = None,
|
| 108 |
+
use_film: bool = False,
|
| 109 |
+
use_minivlm: bool = False,
|
| 110 |
+
) -> Union[List[np.ndarray], np.ndarray]:
|
| 111 |
+
"""
|
| 112 |
+
Query the model to get action predictions.
|
| 113 |
+
|
| 114 |
+
Args:
|
| 115 |
+
cfg: Configuration object with model parameters
|
| 116 |
+
model: The loaded model
|
| 117 |
+
obs: Observation dictionary
|
| 118 |
+
task_label: Text description of the task
|
| 119 |
+
processor: Model processor for inputs
|
| 120 |
+
action_head: Optional action head for continuous actions
|
| 121 |
+
proprio_projector: Optional proprioception projector
|
| 122 |
+
noisy_action_projector: Optional noisy action projector for diffusion
|
| 123 |
+
use_film: Whether to use FiLM
|
| 124 |
+
|
| 125 |
+
Returns:
|
| 126 |
+
Union[List[np.ndarray], np.ndarray]: Predicted actions
|
| 127 |
+
|
| 128 |
+
Raises:
|
| 129 |
+
ValueError: If model family is not supported
|
| 130 |
+
"""
|
| 131 |
+
with torch.no_grad():
|
| 132 |
+
if cfg.model_family == "openvla":
|
| 133 |
+
action = get_vla_action(
|
| 134 |
+
cfg=cfg,
|
| 135 |
+
vla=model,
|
| 136 |
+
processor=processor,
|
| 137 |
+
obs=obs,
|
| 138 |
+
task_label=task_label,
|
| 139 |
+
action_head=action_head,
|
| 140 |
+
proprio_projector=proprio_projector,
|
| 141 |
+
noisy_action_projector=noisy_action_projector,
|
| 142 |
+
use_film=use_film,
|
| 143 |
+
use_minivlm=use_minivlm
|
| 144 |
+
)
|
| 145 |
+
else:
|
| 146 |
+
raise ValueError(f"Unsupported model family: {cfg.model_family}")
|
| 147 |
+
|
| 148 |
+
return action
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def normalize_gripper_action(action: np.ndarray, binarize: bool = True) -> np.ndarray:
|
| 152 |
+
"""
|
| 153 |
+
Normalize gripper action from [0,1] to [-1,+1] range.
|
| 154 |
+
|
| 155 |
+
This is necessary for some environments because the dataset wrapper
|
| 156 |
+
standardizes gripper actions to [0,1]. Note that unlike the other action
|
| 157 |
+
dimensions, the gripper action is not normalized to [-1,+1] by default.
|
| 158 |
+
|
| 159 |
+
Normalization formula: y = 2 * (x - orig_low) / (orig_high - orig_low) - 1
|
| 160 |
+
|
| 161 |
+
Args:
|
| 162 |
+
action: Action array with gripper action in the last dimension
|
| 163 |
+
binarize: Whether to binarize gripper action to -1 or +1
|
| 164 |
+
|
| 165 |
+
Returns:
|
| 166 |
+
np.ndarray: Action array with normalized gripper action
|
| 167 |
+
"""
|
| 168 |
+
# Create a copy to avoid modifying the original
|
| 169 |
+
normalized_action = action.copy()
|
| 170 |
+
|
| 171 |
+
# Normalize the last action dimension to [-1,+1]
|
| 172 |
+
orig_low, orig_high = 0.0, 1.0
|
| 173 |
+
normalized_action[..., -1] = 2 * (normalized_action[..., -1] - orig_low) / (orig_high - orig_low) - 1
|
| 174 |
+
|
| 175 |
+
if binarize:
|
| 176 |
+
# Binarize to -1 or +1
|
| 177 |
+
normalized_action[..., -1] = np.sign(normalized_action[..., -1])
|
| 178 |
+
|
| 179 |
+
return normalized_action
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def invert_gripper_action(action: np.ndarray) -> np.ndarray:
|
| 183 |
+
"""
|
| 184 |
+
Flip the sign of the gripper action (last dimension of action vector).
|
| 185 |
+
|
| 186 |
+
This is necessary for environments where -1 = open, +1 = close, since
|
| 187 |
+
the RLDS dataloader aligns gripper actions such that 0 = close, 1 = open.
|
| 188 |
+
|
| 189 |
+
Args:
|
| 190 |
+
action: Action array with gripper action in the last dimension
|
| 191 |
+
|
| 192 |
+
Returns:
|
| 193 |
+
np.ndarray: Action array with inverted gripper action
|
| 194 |
+
"""
|
| 195 |
+
# Create a copy to avoid modifying the original
|
| 196 |
+
inverted_action = action.copy()
|
| 197 |
+
|
| 198 |
+
# Invert the gripper action
|
| 199 |
+
inverted_action[..., -1] *= -1.0
|
| 200 |
+
|
| 201 |
+
return inverted_action
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
# -------- Msgpack for VLA: Start ----------
|
| 205 |
+
|
| 206 |
+
import msgpack
|
| 207 |
+
import msgpack_numpy
|
| 208 |
+
from requests.adapters import HTTPAdapter
|
| 209 |
+
from urllib3.util.retry import Retry
|
| 210 |
+
import requests
|
| 211 |
+
import logging
|
| 212 |
+
# Set up logging
|
| 213 |
+
logging.basicConfig(
|
| 214 |
+
level=logging.INFO,
|
| 215 |
+
format="%(asctime)s [%(levelname)s] %(message)s",
|
| 216 |
+
handlers=[logging.StreamHandler()],
|
| 217 |
+
)
|
| 218 |
+
logger = logging.getLogger(__name__)
|
| 219 |
+
|
| 220 |
+
class MsgPackHttpClientPolicy:
|
| 221 |
+
"""A client policy for communicating with a VLA server using MessagePack."""
|
| 222 |
+
|
| 223 |
+
def __init__(self, host: str, port: int=None):
|
| 224 |
+
"""
|
| 225 |
+
Initializes the client.
|
| 226 |
+
|
| 227 |
+
Args:
|
| 228 |
+
host (str): The server host address.
|
| 229 |
+
port (int): The server port.
|
| 230 |
+
"""
|
| 231 |
+
protocol = "https" if "nat-notebook-inspire" in host or "ngrok" in host else "http"
|
| 232 |
+
if host.startswith("http"):
|
| 233 |
+
base_url = host
|
| 234 |
+
else:
|
| 235 |
+
base_url = f"{protocol}://{host}:{port}"
|
| 236 |
+
|
| 237 |
+
self.infer_url = f"{base_url.rstrip('/')}/act"
|
| 238 |
+
self.session = requests.Session()
|
| 239 |
+
# Robust retries for occasional connection resets from server
|
| 240 |
+
retries = Retry(
|
| 241 |
+
total=3,
|
| 242 |
+
connect=3,
|
| 243 |
+
read=3,
|
| 244 |
+
backoff_factor=0.2,
|
| 245 |
+
status_forcelist=(502, 503, 504),
|
| 246 |
+
raise_on_status=False,
|
| 247 |
+
allowed_methods=frozenset(["POST", "GET"]),
|
| 248 |
+
)
|
| 249 |
+
adapter = HTTPAdapter(max_retries=retries)
|
| 250 |
+
self.session.mount("http://", adapter)
|
| 251 |
+
self.session.mount("https://", adapter)
|
| 252 |
+
self.session.headers.update({"Content-Type": "application/msgpack"})
|
| 253 |
+
print(f"Standalone MsgPack HTTP Client configured for: {self.infer_url}")
|
| 254 |
+
|
| 255 |
+
def infer(self, observation: Dict[str, Any], **kwargs) -> Dict[str, Any]:
|
| 256 |
+
"""
|
| 257 |
+
Sends an observation to the server and returns the predicted action.
|
| 258 |
+
|
| 259 |
+
Args:
|
| 260 |
+
observation (Dict[str, Any]): The observation dictionary.
|
| 261 |
+
|
| 262 |
+
Returns:
|
| 263 |
+
Dict[str, Any]: The action dictionary from the server.
|
| 264 |
+
"""
|
| 265 |
+
packed_observation = msgpack.packb(observation, default=msgpack_numpy.encode, use_bin_type=True)
|
| 266 |
+
try:
|
| 267 |
+
response = self.session.post(self.infer_url, data=packed_observation, timeout=30)
|
| 268 |
+
response.raise_for_status()
|
| 269 |
+
return msgpack.unpackb(response.content, object_hook=msgpack_numpy.decode, raw=False)
|
| 270 |
+
except requests.exceptions.RequestException as e:
|
| 271 |
+
logger.error(f"Inference request failed: {e}")
|
| 272 |
+
# Propagate exception to let the main loop handle it
|
| 273 |
+
raise e
|
| 274 |
+
except msgpack.UnpackException as e:
|
| 275 |
+
logger.error(f"Failed to unpack server response: {e}")
|
| 276 |
+
raise e
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
# -------- Msgpack for VLA: End ----------
|
VLA-Adapter-UAV/experiments/robot/server_deploy/deploy.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
deploy.py
|
| 3 |
+
|
| 4 |
+
Starts VLA server which the client can query to get robot actions.
|
| 5 |
+
"""
|
| 6 |
+
import logging
|
| 7 |
+
import traceback
|
| 8 |
+
from dataclasses import dataclass, field
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Any, Dict, Union
|
| 11 |
+
import time
|
| 12 |
+
import sys
|
| 13 |
+
|
| 14 |
+
import draccus
|
| 15 |
+
import msgpack
|
| 16 |
+
import torch
|
| 17 |
+
import uvicorn
|
| 18 |
+
import numpy as np
|
| 19 |
+
from fastapi import FastAPI, HTTPException, Request, Response
|
| 20 |
+
from PIL import Image
|
| 21 |
+
import msgpack_numpy
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# Append project root to sys.path
|
| 25 |
+
sys.path.append("../..")
|
| 26 |
+
|
| 27 |
+
from experiments.robot.openvla_utils import (
|
| 28 |
+
get_action_head,
|
| 29 |
+
get_processor,
|
| 30 |
+
get_proprio_projector,
|
| 31 |
+
)
|
| 32 |
+
from experiments.robot.robot_utils import (
|
| 33 |
+
get_action,
|
| 34 |
+
get_image_resize_size,
|
| 35 |
+
get_model,
|
| 36 |
+
set_seed_everywhere,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
# Set up logging to display timestamp, level, and message
|
| 41 |
+
logging.basicConfig(
|
| 42 |
+
level=logging.INFO,
|
| 43 |
+
format="%(asctime)s.%(msecs)03d [%(levelname)s] %(message)s",
|
| 44 |
+
datefmt="%Y-%m-%d %H:%M:%S",
|
| 45 |
+
handlers=[logging.StreamHandler()],
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@dataclass
|
| 50 |
+
class DeployConfig:
|
| 51 |
+
# fmt: off
|
| 52 |
+
|
| 53 |
+
# Server Configuration
|
| 54 |
+
host: str = "0.0.0.0" # Host IP Address
|
| 55 |
+
port: int = 8000 # Host Port
|
| 56 |
+
device: str = "cuda:0" # Device to run model on
|
| 57 |
+
|
| 58 |
+
#################################################################################################################
|
| 59 |
+
# Model-specific parameters
|
| 60 |
+
#################################################################################################################
|
| 61 |
+
model_family: str = "openvla" # Model family
|
| 62 |
+
pretrained_checkpoint: Union[str, Path] = "" # Pretrained checkpoint path
|
| 63 |
+
use_l1_regression: bool = True # If True, uses continuous action head with L1 regression objective
|
| 64 |
+
use_minivlm: bool = True # If True, uses minivlm
|
| 65 |
+
num_diffusion_steps: int = 50 # (When `diffusion==True`) Number of diffusion steps for inference
|
| 66 |
+
use_film: bool = False # If True, uses FiLM to infuse language inputs into visual features
|
| 67 |
+
num_images_in_input: int = 3 # Number of images in the VLA input (default: 1)
|
| 68 |
+
use_proprio: bool = True # Whether to include proprio state in input
|
| 69 |
+
|
| 70 |
+
center_crop: bool = True # Center crop? (if trained w/ random crop image aug)
|
| 71 |
+
num_open_loop_steps: int = 25 # Number of actions to execute open-loop before requerying policy
|
| 72 |
+
unnorm_key: Union[str, Path] = "" # Action un-normalization key
|
| 73 |
+
|
| 74 |
+
load_in_8bit: bool = False # (For OpenVLA only) Load with 8-bit quantization
|
| 75 |
+
load_in_4bit: bool = False # (For OpenVLA only) Load with 4-bit quantization
|
| 76 |
+
|
| 77 |
+
#################################################################################################################
|
| 78 |
+
# LIBERO environment-specific parameters
|
| 79 |
+
#################################################################################################################
|
| 80 |
+
num_steps_wait: int = 10 # Number of steps to wait for objects to stabilize in sim
|
| 81 |
+
num_trials_per_task: int = 50 # Number of rollouts per task
|
| 82 |
+
initial_states_path: str = "DEFAULT" # "DEFAULT", or path to initial states JSON file
|
| 83 |
+
env_img_res: int = 256 # Resolution for environment images (not policy input resolution)
|
| 84 |
+
|
| 85 |
+
#################################################################################################################
|
| 86 |
+
# Utils
|
| 87 |
+
#################################################################################################################
|
| 88 |
+
|
| 89 |
+
use_wandb: bool = False # Whether to also log results in Weights & Biases
|
| 90 |
+
wandb_entity: str = "your-wandb-entity" # Name of WandB entity
|
| 91 |
+
wandb_project: str = "your-wandb-project" # Name of WandB project
|
| 92 |
+
|
| 93 |
+
seed: int = 42 # Random Seed (for reproducibility)
|
| 94 |
+
|
| 95 |
+
# fmt: on
|
| 96 |
+
save_version: str = "vla-adapter" # version of
|
| 97 |
+
phase: str = "Inference"
|
| 98 |
+
use_pro_version: bool = True
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def initialize_model(cfg: DeployConfig):
|
| 103 |
+
"""Initialize model and associated components."""
|
| 104 |
+
# Load model
|
| 105 |
+
model = get_model(cfg)
|
| 106 |
+
model.set_version(cfg.save_version)
|
| 107 |
+
|
| 108 |
+
# Get number of vision patches
|
| 109 |
+
NUM_PATCHES = model.vision_backbone.get_num_patches() * model.vision_backbone.get_num_images_in_input()
|
| 110 |
+
# If we have proprio inputs, a single proprio embedding is appended to the end of the vision patch embeddings
|
| 111 |
+
if cfg.use_proprio:
|
| 112 |
+
NUM_PATCHES += 1
|
| 113 |
+
cfg.num_task_tokens=NUM_PATCHES
|
| 114 |
+
|
| 115 |
+
# Load proprio projector if needed
|
| 116 |
+
proprio_projector = None
|
| 117 |
+
if cfg.use_proprio:
|
| 118 |
+
proprio_projector = get_proprio_projector(
|
| 119 |
+
cfg,
|
| 120 |
+
model.llm_dim,
|
| 121 |
+
proprio_dim=14, # 14-dimensional proprio for aloha
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
# Load action head if needed
|
| 125 |
+
action_head = None
|
| 126 |
+
if cfg.use_l1_regression:
|
| 127 |
+
action_head = get_action_head(cfg, model.llm_dim)
|
| 128 |
+
|
| 129 |
+
# Get OpenVLA processor
|
| 130 |
+
processor = get_processor(cfg)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
return model, processor, action_head, proprio_projector
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class MsgPackResponse(Response):
|
| 137 |
+
"""Custom FastAPI Response class to automatically encode response data into MessagePack."""
|
| 138 |
+
|
| 139 |
+
media_type = "application/msgpack"
|
| 140 |
+
|
| 141 |
+
def render(self, content: Any) -> bytes:
|
| 142 |
+
return msgpack.packb(content, default=msgpack_numpy.encode, use_bin_type=True)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
# === Server Interface ===
|
| 146 |
+
class VLAServer:
|
| 147 |
+
def __init__(self, cfg: DeployConfig):
|
| 148 |
+
"""
|
| 149 |
+
A simple server for VLA models, exposing `/act` endpoint.
|
| 150 |
+
This server receives observations and instructions via MessagePack,
|
| 151 |
+
and returns predicted actions in MessagePack format.
|
| 152 |
+
"""
|
| 153 |
+
self.cfg = cfg
|
| 154 |
+
(
|
| 155 |
+
self.model,
|
| 156 |
+
self.processor,
|
| 157 |
+
self.action_head,
|
| 158 |
+
self.proprio_projector,
|
| 159 |
+
) = initialize_model(cfg)
|
| 160 |
+
self.resize_size = get_image_resize_size(cfg)
|
| 161 |
+
set_seed_everywhere(self.cfg.seed)
|
| 162 |
+
self.app = FastAPI()
|
| 163 |
+
|
| 164 |
+
@self.app.middleware("http")
|
| 165 |
+
async def log_requests(request: Request, call_next):
|
| 166 |
+
"""
|
| 167 |
+
Middleware to log request details including processing time.
|
| 168 |
+
"""
|
| 169 |
+
start_time = time.time()
|
| 170 |
+
response = await call_next(request)
|
| 171 |
+
process_time = (time.time() - start_time) * 1000 # in milliseconds
|
| 172 |
+
logging.info(f'"{request.method} {request.url.path}" {response.status_code} - {process_time:.2f}ms')
|
| 173 |
+
return response
|
| 174 |
+
|
| 175 |
+
self.app.post("/act", response_class=MsgPackResponse)(self.get_server_action)
|
| 176 |
+
|
| 177 |
+
async def get_server_action(self, request: Request) -> Dict[str, Any]:
|
| 178 |
+
"""Handles a single action prediction request using MessagePack."""
|
| 179 |
+
if request.headers.get("content-type") != "application/msgpack":
|
| 180 |
+
raise HTTPException(
|
| 181 |
+
status_code=415, detail="Unsupported Media Type. 'application/msgpack' is required."
|
| 182 |
+
)
|
| 183 |
+
try:
|
| 184 |
+
body = await request.body()
|
| 185 |
+
batch = msgpack.unpackb(body, object_hook=msgpack_numpy.decode, raw=False)
|
| 186 |
+
|
| 187 |
+
# Extract unnorm_key and instruction from the batch
|
| 188 |
+
unnorm_key = batch.pop("unnorm_key")
|
| 189 |
+
instruction = batch.pop("instruction")
|
| 190 |
+
|
| 191 |
+
# Update cfg with the unnorm_key from the client
|
| 192 |
+
self.cfg.unnorm_key = unnorm_key
|
| 193 |
+
|
| 194 |
+
# Use get_action to get model's prediction
|
| 195 |
+
actions = get_action(
|
| 196 |
+
self.cfg,
|
| 197 |
+
self.model,
|
| 198 |
+
batch,
|
| 199 |
+
instruction,
|
| 200 |
+
processor=self.processor,
|
| 201 |
+
action_head=self.action_head,
|
| 202 |
+
proprio_projector=self.proprio_projector,
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
return {"actions": np.array(actions).tolist()}
|
| 206 |
+
|
| 207 |
+
except msgpack.UnpackException:
|
| 208 |
+
raise HTTPException(status_code=400, detail="Invalid MessagePack data provided.")
|
| 209 |
+
except Exception:
|
| 210 |
+
logging.error(traceback.format_exc())
|
| 211 |
+
# Re-raise as a generic 500 error to avoid leaking implementation details.
|
| 212 |
+
raise HTTPException(status_code=500, detail="An internal server error occurred.")
|
| 213 |
+
|
| 214 |
+
def run(self) -> None:
|
| 215 |
+
"""Starts the Uvicorn server."""
|
| 216 |
+
uvicorn.run(self.app, host=self.cfg.host, port=self.cfg.port, access_log=False, timeout_keep_alive=120)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
@draccus.wrap()
|
| 220 |
+
def deploy(cfg: DeployConfig) -> None:
|
| 221 |
+
server = VLAServer(cfg)
|
| 222 |
+
server.run()
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
if __name__ == "__main__":
|
| 226 |
+
deploy()
|
VLA-Adapter-UAV/prismatic/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .models import available_model_names, available_models, get_model_description, load
|
VLA-Adapter-UAV/prismatic/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (273 Bytes). View file
|
|
|
VLA-Adapter-UAV/prismatic/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (278 Bytes). View file
|
|
|
VLA-Adapter-UAV/prismatic/conf/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .datasets import DatasetConfig, DatasetRegistry
|
| 2 |
+
from .models import ModelConfig, ModelRegistry
|
| 3 |
+
from .vla import VLAConfig, VLARegistry
|
VLA-Adapter-UAV/prismatic/conf/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (349 Bytes). View file
|
|
|
VLA-Adapter-UAV/prismatic/conf/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (356 Bytes). View file
|
|
|
VLA-Adapter-UAV/prismatic/conf/__pycache__/datasets.cpython-310.pyc
ADDED
|
Binary file (3.24 kB). View file
|
|
|
VLA-Adapter-UAV/prismatic/conf/__pycache__/datasets.cpython-312.pyc
ADDED
|
Binary file (5.02 kB). View file
|
|
|
VLA-Adapter-UAV/prismatic/conf/__pycache__/models.cpython-310.pyc
ADDED
|
Binary file (16.4 kB). View file
|
|
|
VLA-Adapter-UAV/prismatic/conf/__pycache__/vla.cpython-310.pyc
ADDED
|
Binary file (9.13 kB). View file
|
|
|
VLA-Adapter-UAV/prismatic/conf/datasets.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
datasets.py
|
| 3 |
+
|
| 4 |
+
Draccus Dataclass Definition for a DatasetConfig object, with various registered subclasses for each dataset variant
|
| 5 |
+
and processing scheme. A given dataset variant (e.g., `llava-lightning`) configures the following attributes:
|
| 6 |
+
- Dataset Variant (Identifier) --> e.g., "llava-v15"
|
| 7 |
+
- Align Stage Dataset Components (annotations, images)
|
| 8 |
+
- Finetune Stage Dataset Components (annotations, images)
|
| 9 |
+
- Dataset Root Directory (Path)
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from dataclasses import dataclass
|
| 13 |
+
from enum import Enum, unique
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from typing import Tuple
|
| 16 |
+
|
| 17 |
+
from draccus import ChoiceRegistry
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@dataclass
|
| 21 |
+
class DatasetConfig(ChoiceRegistry):
|
| 22 |
+
# fmt: off
|
| 23 |
+
dataset_id: str # Unique ID that fully specifies a dataset variant
|
| 24 |
+
|
| 25 |
+
# Dataset Components for each Stage in < align | finetune >
|
| 26 |
+
align_stage_components: Tuple[Path, Path] # Path to annotation file and images directory for `align` stage
|
| 27 |
+
finetune_stage_components: Tuple[Path, Path] # Path to annotation file and images directory for `finetune` stage
|
| 28 |
+
|
| 29 |
+
dataset_root_dir: Path # Path to dataset root directory; others paths are relative to root
|
| 30 |
+
# fmt: on
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# [Reproduction] LLaVa-v15 (exact dataset used in all public LLaVa-v15 models)
|
| 34 |
+
@dataclass
|
| 35 |
+
class LLaVa_V15_Config(DatasetConfig):
|
| 36 |
+
dataset_id: str = "llava-v15"
|
| 37 |
+
|
| 38 |
+
align_stage_components: Tuple[Path, Path] = (
|
| 39 |
+
Path("download/llava-laion-cc-sbu-558k/chat.json"),
|
| 40 |
+
Path("download/llava-laion-cc-sbu-558k/"),
|
| 41 |
+
)
|
| 42 |
+
finetune_stage_components: Tuple[Path, Path] = (
|
| 43 |
+
Path("download/llava-v1.5-instruct/llava_v1_5_mix665k.json"),
|
| 44 |
+
Path("download/llava-v1.5-instruct/"),
|
| 45 |
+
)
|
| 46 |
+
dataset_root_dir: Path = Path("/mnt/fsx/skaramcheti/datasets/prismatic-vlms")
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# [Multimodal-Only] LLava-v15 WITHOUT the Language-Only ShareGPT Data (No Co-Training)
|
| 50 |
+
@dataclass
|
| 51 |
+
class LLaVa_Multimodal_Only_Config(DatasetConfig):
|
| 52 |
+
dataset_id: str = "llava-multimodal"
|
| 53 |
+
|
| 54 |
+
align_stage_components: Tuple[Path, Path] = (
|
| 55 |
+
Path("download/llava-laion-cc-sbu-558k/chat.json"),
|
| 56 |
+
Path("download/llava-laion-cc-sbu-558k/"),
|
| 57 |
+
)
|
| 58 |
+
finetune_stage_components: Tuple[Path, Path] = (
|
| 59 |
+
Path("download/llava-v1.5-instruct/llava_v1_5_stripped625k.json"),
|
| 60 |
+
Path("download/llava-v1.5-instruct/"),
|
| 61 |
+
)
|
| 62 |
+
dataset_root_dir: Path = Path("/mnt/fsx/skaramcheti/datasets/prismatic-vlms")
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
# LLaVa-v15 + LVIS-Instruct-4V
|
| 66 |
+
@dataclass
|
| 67 |
+
class LLaVa_LVIS4V_Config(DatasetConfig):
|
| 68 |
+
dataset_id: str = "llava-lvis4v"
|
| 69 |
+
|
| 70 |
+
align_stage_components: Tuple[Path, Path] = (
|
| 71 |
+
Path("download/llava-laion-cc-sbu-558k/chat.json"),
|
| 72 |
+
Path("download/llava-laion-cc-sbu-558k/"),
|
| 73 |
+
)
|
| 74 |
+
finetune_stage_components: Tuple[Path, Path] = (
|
| 75 |
+
Path("download/llava-v1.5-instruct/llava_v1_5_lvis4v_mix888k.json"),
|
| 76 |
+
Path("download/llava-v1.5-instruct/"),
|
| 77 |
+
)
|
| 78 |
+
dataset_root_dir: Path = Path("/mnt/fsx/skaramcheti/datasets/prismatic-vlms")
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
# LLaVa-v15 + LRV-Instruct
|
| 82 |
+
@dataclass
|
| 83 |
+
class LLaVa_LRV_Config(DatasetConfig):
|
| 84 |
+
dataset_id: str = "llava-lrv"
|
| 85 |
+
|
| 86 |
+
align_stage_components: Tuple[Path, Path] = (
|
| 87 |
+
Path("download/llava-laion-cc-sbu-558k/chat.json"),
|
| 88 |
+
Path("download/llava-laion-cc-sbu-558k/"),
|
| 89 |
+
)
|
| 90 |
+
finetune_stage_components: Tuple[Path, Path] = (
|
| 91 |
+
Path("download/llava-v1.5-instruct/llava_v1_5_lrv_mix1008k.json"),
|
| 92 |
+
Path("download/llava-v1.5-instruct/"),
|
| 93 |
+
)
|
| 94 |
+
dataset_root_dir: Path = Path("/mnt/fsx/skaramcheti/datasets/prismatic-vlms")
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
# LLaVa-v15 + LVIS-Instruct-4V + LRV-Instruct
|
| 98 |
+
@dataclass
|
| 99 |
+
class LLaVa_LVIS4V_LRV_Config(DatasetConfig):
|
| 100 |
+
dataset_id: str = "llava-lvis4v-lrv"
|
| 101 |
+
|
| 102 |
+
align_stage_components: Tuple[Path, Path] = (
|
| 103 |
+
Path("download/llava-laion-cc-sbu-558k/chat.json"),
|
| 104 |
+
Path("download/llava-laion-cc-sbu-558k/"),
|
| 105 |
+
)
|
| 106 |
+
finetune_stage_components: Tuple[Path, Path] = (
|
| 107 |
+
Path("download/llava-v1.5-instruct/llava_v1_5_lvis4v_lrv_mix1231k.json"),
|
| 108 |
+
Path("download/llava-v1.5-instruct/"),
|
| 109 |
+
)
|
| 110 |
+
dataset_root_dir: Path = Path("/mnt/fsx/skaramcheti/datasets/prismatic-vlms")
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# === Define a Dataset Registry Enum for Reference & Validation =>> all *new* datasets must be added here! ===
|
| 114 |
+
@unique
|
| 115 |
+
class DatasetRegistry(Enum):
|
| 116 |
+
# === LLaVa v1.5 ===
|
| 117 |
+
LLAVA_V15 = LLaVa_V15_Config
|
| 118 |
+
|
| 119 |
+
LLAVA_MULTIMODAL_ONLY = LLaVa_Multimodal_Only_Config
|
| 120 |
+
|
| 121 |
+
LLAVA_LVIS4V = LLaVa_LVIS4V_Config
|
| 122 |
+
LLAVA_LRV = LLaVa_LRV_Config
|
| 123 |
+
|
| 124 |
+
LLAVA_LVIS4V_LRV = LLaVa_LVIS4V_LRV_Config
|
| 125 |
+
|
| 126 |
+
@property
|
| 127 |
+
def dataset_id(self) -> str:
|
| 128 |
+
return self.value.dataset_id
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
# Register Datasets in Choice Registry
|
| 132 |
+
for dataset_variant in DatasetRegistry:
|
| 133 |
+
DatasetConfig.register_subclass(dataset_variant.dataset_id, dataset_variant.value)
|
VLA-Adapter-UAV/prismatic/conf/models.py
ADDED
|
@@ -0,0 +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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
models.py
|
| 3 |
+
|
| 4 |
+
Draccus Dataclass Definition for a ModelConfig object, with various registered subclasses for each model family and
|
| 5 |
+
variant thereof. A given model variant configures the following attributes:
|
| 6 |
+
- Pretrained Visual Representation (e.g., OpenAI CLIP ViT-L/14) + Pretrained LLM Backbone (e.g., LLaMa-2 7B)
|
| 7 |
+
- VLM Configuration + Parameters (e.g., MLP Projector, Image Preprocessing, etc.)
|
| 8 |
+
- [Optional] Stage 1 (`align`) Optimization Hyperparameters
|
| 9 |
+
- Stage 2 (`finetune`) Optimization Hyperparameters
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from dataclasses import dataclass
|
| 13 |
+
from enum import Enum, unique
|
| 14 |
+
from typing import Optional
|
| 15 |
+
|
| 16 |
+
from draccus import ChoiceRegistry
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@dataclass
|
| 20 |
+
class ModelConfig(ChoiceRegistry):
|
| 21 |
+
# fmt: off
|
| 22 |
+
model_id: str # Unique Model ID that fully specifies a given variant
|
| 23 |
+
arch_specifier: str # Architecture specifier string (e.g., "gelu-mlp")
|
| 24 |
+
|
| 25 |
+
# Pretrained Backbones
|
| 26 |
+
vision_backbone_id: str # Pretrained Visual Featurizer (from TIMM) to load
|
| 27 |
+
llm_backbone_id: str # Pretrained LLM (from HF Transformers) to load
|
| 28 |
+
|
| 29 |
+
# Backbone Parameters
|
| 30 |
+
image_resize_strategy: str # Resizing strategy in < crop | letterbox | corner-pad >
|
| 31 |
+
llm_max_length: int # Maximum context length for LLM (can be < than max!)
|
| 32 |
+
image_sequence_len: int # Sequence length to use for the vision backbone
|
| 33 |
+
|
| 34 |
+
# === Multi-Stage Optimization Hyperparameters ===
|
| 35 |
+
# By default, we assume an AdamW optimizer with FSDP (Gradient Sharding or Full Sharding depending on stage)
|
| 36 |
+
|
| 37 |
+
# Align Stage Optimization Parameters
|
| 38 |
+
align_epochs: int # Epochs to Run (in case `max_steps` is not specified)
|
| 39 |
+
align_max_steps: Optional[int] # [Optional] Max Gradient Steps (overrides epochs)
|
| 40 |
+
align_save_every_n_steps: Optional[int]
|
| 41 |
+
align_global_batch_size: int # Global Batch Size (divided across processes)
|
| 42 |
+
align_per_device_batch_size: int # Per-Device Batch Size (per-process)
|
| 43 |
+
# => # of accumulation steps is auto-computed
|
| 44 |
+
|
| 45 |
+
align_learning_rate: float # Peak Learning Rate (lr_scheduler sets warmup/decay)
|
| 46 |
+
align_weight_decay: float # Weight Decay for AdamW Optimizer
|
| 47 |
+
align_max_grad_norm: float # Max Grad Norm (for global gradient clipping)
|
| 48 |
+
align_lr_scheduler_type: str # LR Scheduler (default: "linear-warmup+cosine-decay")
|
| 49 |
+
align_warmup_ratio: float # Fraction of total steps to warmup
|
| 50 |
+
|
| 51 |
+
align_train_strategy: str # Align Train Strategy (default: "fsdp-shard-grad-op")
|
| 52 |
+
|
| 53 |
+
# Finetune Stage Optimization Parameters
|
| 54 |
+
finetune_epochs: int # Epochs to Run (in case `max_steps` is not specified)
|
| 55 |
+
finetune_max_steps: Optional[int] # [Optional] Max Gradient Steps (overrides epochs)
|
| 56 |
+
finetune_save_every_n_steps: Optional[int]
|
| 57 |
+
finetune_global_batch_size: int # Global Batch Size (divided across processes)
|
| 58 |
+
finetune_per_device_batch_size: int # Per-Device Batch Size (per-process)
|
| 59 |
+
# => # of accumulation steps is auto-computed
|
| 60 |
+
|
| 61 |
+
finetune_learning_rate: float # Peak Learning Rate (lr_scheduler sets warmup/decay)
|
| 62 |
+
finetune_weight_decay: float # Weight Decay for AdamW Optimizer
|
| 63 |
+
finetune_max_grad_norm: float # Max Grad Norm (for global gradient clipping)
|
| 64 |
+
finetune_lr_scheduler_type: str # LR Scheduler (default: "linear-warmup+cosine-decay")
|
| 65 |
+
finetune_warmup_ratio: float # Fraction of total steps to warmup
|
| 66 |
+
|
| 67 |
+
finetune_train_strategy: str # Finetune Train Strategy (default: "fsdp-full-shard")
|
| 68 |
+
|
| 69 |
+
# Enable Gradient/Activation Checkpointing (for the LLM Backbone)
|
| 70 |
+
enable_gradient_checkpointing: bool = True
|
| 71 |
+
|
| 72 |
+
# Enable Traditional Mixed Precision Training via Torch Native AMP (`autocast`)
|
| 73 |
+
enable_mixed_precision_training: bool = True # Whether to enable mixed precision training
|
| 74 |
+
reduce_in_full_precision: bool = False # Whether to run gradient reduction in FP32
|
| 75 |
+
|
| 76 |
+
# fmt: on
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
# === LLaVa v1.5 Reproduction - Fully Specified Configurations ===
|
| 80 |
+
@dataclass
|
| 81 |
+
class LLaVa_v15_Reproduction_7B(ModelConfig):
|
| 82 |
+
model_id: str = "reproduction-llava-v15+7b"
|
| 83 |
+
arch_specifier: str = "gelu-mlp"
|
| 84 |
+
|
| 85 |
+
vision_backbone_id: str = "clip-vit-l-336px"
|
| 86 |
+
llm_backbone_id: str = "vicuna-v15-7b"
|
| 87 |
+
|
| 88 |
+
image_resize_strategy: str = "letterbox"
|
| 89 |
+
llm_max_length: int = 2048
|
| 90 |
+
image_sequence_len: int = 1
|
| 91 |
+
|
| 92 |
+
# Align Stage Optimization Parameters
|
| 93 |
+
align_epochs: int = 1
|
| 94 |
+
align_max_steps: Optional[int] = None
|
| 95 |
+
align_save_every_n_steps: int = 10000
|
| 96 |
+
align_global_batch_size: int = 96
|
| 97 |
+
align_per_device_batch_size: int = 16
|
| 98 |
+
|
| 99 |
+
align_learning_rate: float = 1e-3
|
| 100 |
+
align_weight_decay: float = 0.0
|
| 101 |
+
align_max_grad_norm: float = 1.0
|
| 102 |
+
align_lr_scheduler_type: str = "linear-warmup+cosine-decay"
|
| 103 |
+
align_warmup_ratio: float = 0.03
|
| 104 |
+
|
| 105 |
+
align_train_strategy: str = "fsdp-shard-grad-op"
|
| 106 |
+
|
| 107 |
+
# Finetune Stage Optimization Parameters
|
| 108 |
+
finetune_epochs: int = 1
|
| 109 |
+
finetune_max_steps: Optional[int] = None
|
| 110 |
+
finetune_save_every_n_steps: int = 10000
|
| 111 |
+
finetune_global_batch_size: int = 128
|
| 112 |
+
finetune_per_device_batch_size: int = 16
|
| 113 |
+
|
| 114 |
+
finetune_learning_rate: float = 2e-5
|
| 115 |
+
finetune_weight_decay: float = 0.1
|
| 116 |
+
finetune_max_grad_norm: float = 1.0
|
| 117 |
+
finetune_lr_scheduler_type: str = "linear-warmup+cosine-decay"
|
| 118 |
+
finetune_warmup_ratio: float = 0.03
|
| 119 |
+
|
| 120 |
+
finetune_train_strategy: str = "fsdp-full-shard"
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
@dataclass
|
| 124 |
+
class LLaVa_v15_Reproduction_13B(LLaVa_v15_Reproduction_7B):
|
| 125 |
+
model_id: str = "reproduction-llava-v15+13b"
|
| 126 |
+
llm_backbone_id: str = "vicuna-v15-13b"
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
# === Section 4.1 :: Optimization Procedure ===
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
# Section 4.1A :: 🚀 --> Necessity of Multi-Stage Training
|
| 133 |
+
@dataclass
|
| 134 |
+
class Exp_7B_One_Stage(LLaVa_v15_Reproduction_7B):
|
| 135 |
+
model_id: str = "one-stage+7b"
|
| 136 |
+
arch_specifier: str = "no-align+gelu-mlp"
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@dataclass
|
| 140 |
+
class Exp_13B_One_Stage(LLaVa_v15_Reproduction_13B):
|
| 141 |
+
model_id: str = "one-stage+13b"
|
| 142 |
+
arch_specifier: str = "no-align+gelu-mlp"
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
# Section 4.1B :: 🛠️ --> Full Finetuning through Visual Backbones
|
| 146 |
+
# =>> Note :: Run with `--stage full-finetune`
|
| 147 |
+
@dataclass
|
| 148 |
+
class Exp_7B_Full_Finetune_Multi_Stage(LLaVa_v15_Reproduction_7B):
|
| 149 |
+
model_id: str = "full-ft-multi-stage+7b"
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
@dataclass
|
| 153 |
+
class Exp_7B_Full_Finetune_One_Stage(Exp_7B_One_Stage):
|
| 154 |
+
model_id: str = "full-ft-one-stage+7b"
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
# === Section 4.2 :: Image Processing and Visual Representations ===
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
# Section 4.2A :: 📸 --> Choosing a Pretrained Representation
|
| 161 |
+
@dataclass
|
| 162 |
+
class Exp_7B_IN1K_ViT_L_p16_224px(Exp_7B_One_Stage):
|
| 163 |
+
model_id: str = "in1k-224px+7b"
|
| 164 |
+
vision_backbone_id: str = "in1k-vit-l"
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
@dataclass
|
| 168 |
+
class Exp_7B_DINOv2_ViT_L_p14_224px(Exp_7B_One_Stage):
|
| 169 |
+
model_id: str = "dinov2-224px+7b"
|
| 170 |
+
vision_backbone_id: str = "dinov2-vit-l"
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
@dataclass
|
| 174 |
+
class Exp_7B_CLIP_ViT_L_p14_224px(Exp_7B_One_Stage):
|
| 175 |
+
model_id: str = "clip-224px+7b"
|
| 176 |
+
vision_backbone_id: str = "clip-vit-l"
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
@dataclass
|
| 180 |
+
class Exp_7B_SigLIP_ViT_SO_p14_224px(Exp_7B_One_Stage):
|
| 181 |
+
model_id: str = "siglip-224px+7b"
|
| 182 |
+
vision_backbone_id: str = "siglip-vit-so400m"
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
# Section 4.2B :: 📐 --> Choosing an Image Preprocessing Strategy
|
| 186 |
+
@dataclass
|
| 187 |
+
class Exp_7B_CLIP_ViT_L_p14_336px_Resize_Crop(Exp_7B_One_Stage):
|
| 188 |
+
model_id: str = "clip-336px-resize-crop+7b"
|
| 189 |
+
image_resize_strategy: str = "resize-crop"
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
@dataclass
|
| 193 |
+
class Exp_7B_CLIP_ViT_L_p14_336px_Resize_Naive(Exp_7B_One_Stage):
|
| 194 |
+
model_id: str = "clip-336px-resize-naive+7b"
|
| 195 |
+
image_resize_strategy: str = "resize-naive"
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
@dataclass
|
| 199 |
+
class Exp_7B_SigLIP_ViT_SO_p14_384px_Letterbox(Exp_7B_One_Stage):
|
| 200 |
+
model_id: str = "siglip-384px-letterbox+7b"
|
| 201 |
+
vision_backbone_id: str = "siglip-vit-so400m-384px"
|
| 202 |
+
image_resize_strategy: str = "letterbox"
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
@dataclass
|
| 206 |
+
class Exp_7B_SigLIP_ViT_SO_p14_384px_Resize_Crop(Exp_7B_One_Stage):
|
| 207 |
+
model_id: str = "siglip-384px-resize-crop+7b"
|
| 208 |
+
vision_backbone_id: str = "siglip-vit-so400m-384px"
|
| 209 |
+
image_resize_strategy: str = "resize-crop"
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
@dataclass
|
| 213 |
+
class Exp_7B_SigLIP_ViT_SO_p14_384px_Resize_Naive(Exp_7B_One_Stage):
|
| 214 |
+
model_id: str = "siglip-384px-resize-naive+7b"
|
| 215 |
+
vision_backbone_id: str = "siglip-vit-so400m-384px"
|
| 216 |
+
image_resize_strategy: str = "resize-naive"
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
# Section 4.2D :: 🥞 --> Stacking/Ensembling Visual Representations
|
| 220 |
+
@dataclass
|
| 221 |
+
class Exp_7B_DINOCLIP_ViT_L_p14_336px_Letterbox(Exp_7B_One_Stage):
|
| 222 |
+
model_id: str = "dinoclip-336px-letterbox+7b"
|
| 223 |
+
vision_backbone_id: str = "dinoclip-vit-l-336px"
|
| 224 |
+
image_resize_strategy: str = "letterbox"
|
| 225 |
+
arch_specifier: str = "no-align+fused-gelu-mlp"
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
@dataclass
|
| 229 |
+
class Exp_7B_DINOCLIP_ViT_L_p14_336px_Resize_Naive(Exp_7B_One_Stage):
|
| 230 |
+
model_id: str = "dinoclip-336px-resize-naive+7b"
|
| 231 |
+
vision_backbone_id: str = "dinoclip-vit-l-336px"
|
| 232 |
+
image_resize_strategy: str = "resize-naive"
|
| 233 |
+
arch_specifier: str = "no-align+fused-gelu-mlp"
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
@dataclass
|
| 237 |
+
class Exp_7B_DINOSigLIP_ViT_L_p14_384px_Letterbox(Exp_7B_One_Stage):
|
| 238 |
+
model_id: str = "dinosiglip-384px-letterbox+7b"
|
| 239 |
+
vision_backbone_id: str = "dinosiglip-vit-so-384px"
|
| 240 |
+
image_resize_strategy: str = "letterbox"
|
| 241 |
+
arch_specifier: str = "no-align+fused-gelu-mlp"
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
@dataclass
|
| 245 |
+
class Exp_7B_DINOSigLIP_ViT_L_p14_384px_Resize_Naive(Exp_7B_One_Stage):
|
| 246 |
+
model_id: str = "dinosiglip-384px-resize-naive+7b"
|
| 247 |
+
vision_backbone_id: str = "dinosiglip-vit-so-384px"
|
| 248 |
+
image_resize_strategy: str = "resize-naive"
|
| 249 |
+
arch_specifier: str = "no-align+fused-gelu-mlp"
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
# === Section 4.3 :: Language Models ===
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
# Section 4.3A :: 📝 --> Base vs. Instruct-Tuned (Chat) LLMs
|
| 256 |
+
@dataclass
|
| 257 |
+
class Exp_7B_Llama2(Exp_7B_One_Stage):
|
| 258 |
+
model_id: str = "llama2+7b"
|
| 259 |
+
llm_backbone_id: str = "llama2-7b-pure"
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
@dataclass
|
| 263 |
+
class Exp_13B_Llama2(Exp_13B_One_Stage):
|
| 264 |
+
model_id: str = "llama2+13b"
|
| 265 |
+
llm_backbone_id: str = "llama2-13b-pure"
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
# ~ Additional LLM Backbones :: LLaMa-2 Chat, Mistral v0.1, Mistral v0.1 Instruct, Phi-2 ~
|
| 269 |
+
@dataclass
|
| 270 |
+
class Ext_Exp_7B_Llama2_Chat(Exp_7B_One_Stage):
|
| 271 |
+
model_id: str = "llama2-chat+7b"
|
| 272 |
+
llm_backbone_id: str = "llama2-7b-chat"
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
@dataclass
|
| 276 |
+
class Ext_Exp_13B_Llama2_Chat(Exp_13B_One_Stage):
|
| 277 |
+
model_id: str = "llama2-chat+13b"
|
| 278 |
+
llm_backbone_id: str = "llama2-13b-chat"
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
@dataclass
|
| 282 |
+
class Ext_Exp_7B_Mistral_V1(Exp_7B_One_Stage):
|
| 283 |
+
model_id: str = "mistral-v0.1+7b"
|
| 284 |
+
llm_backbone_id: str = "mistral-v0.1-7b-pure"
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
@dataclass
|
| 288 |
+
class Ext_Exp_7B_Mistral_Instruct_V1(Exp_7B_One_Stage):
|
| 289 |
+
model_id: str = "mistral-instruct-v0.1+7b"
|
| 290 |
+
llm_backbone_id: str = "mistral-v0.1-7b-instruct"
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
@dataclass
|
| 294 |
+
class Ext_Exp_3B_Phi_2(Exp_7B_One_Stage):
|
| 295 |
+
model_id: str = "phi-2+3b"
|
| 296 |
+
llm_backbone_id: str = "phi-2-3b"
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
# Section 4.3B :: ✌️ --> Co-training on Language-only Data
|
| 300 |
+
# =>> Note :: Run with `--dataset.type "llava-multimodal" (multimodal data only / no co-training)
|
| 301 |
+
@dataclass
|
| 302 |
+
class Exp_7B_Vicuna_No_Cotraining(Exp_7B_One_Stage):
|
| 303 |
+
model_id: str = "vicuna-no-cotraining+7b"
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
@dataclass
|
| 307 |
+
class Exp_7B_Llama2_No_Cotraining(Exp_7B_One_Stage):
|
| 308 |
+
model_id: str = "llama2-no-cotraining+7b"
|
| 309 |
+
llm_backbone_id: str = "llama2-7b-pure"
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
# === Section 4.4 :: Scaling Properties - Train Time & Data ===
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
# Section 4.4A :: ⏰ --> Scaling Train Time
|
| 316 |
+
@dataclass
|
| 317 |
+
class Exp_7B_1p25_Epochs(Exp_7B_One_Stage):
|
| 318 |
+
model_id: str = "train-1.25-epochs+7b"
|
| 319 |
+
finetune_max_steps: int = 6500
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
@dataclass
|
| 323 |
+
class Exp_7B_1p5_Epochs(Exp_7B_One_Stage):
|
| 324 |
+
model_id: str = "train-1.5-epochs+7b"
|
| 325 |
+
finetune_max_steps: int = 7800
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
@dataclass
|
| 329 |
+
class Exp_7B_2_Epochs(Exp_7B_One_Stage):
|
| 330 |
+
model_id: str = "train-2-epochs+7b"
|
| 331 |
+
finetune_epochs: int = 2
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
@dataclass
|
| 335 |
+
class Exp_7B_3_Epochs(Exp_7B_One_Stage):
|
| 336 |
+
model_id: str = "train-3-epochs+7b"
|
| 337 |
+
finetune_epochs: int = 3
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
# Section 4.4B :: 📚 --> Scaling Data
|
| 341 |
+
# =>> Note :: Run with `--dataset.type "llava-lvis4v"`
|
| 342 |
+
@dataclass
|
| 343 |
+
class Exp_7B_LLaVa_LVIS4V(Exp_7B_One_Stage):
|
| 344 |
+
model_id: str = "llava-lvis4v+7b"
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
# =>> Note :: Run with `--dataset.type "llava-lrv"`
|
| 348 |
+
@dataclass
|
| 349 |
+
class Exp_7B_LLaVa_LRV(Exp_7B_One_Stage):
|
| 350 |
+
model_id: str = "llava-lrv+7b"
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
# =>> Note :: Run with `--dataset.type "llava-lvis4v-lrv"`
|
| 354 |
+
@dataclass
|
| 355 |
+
class Exp_7B_LLaVa_LVIS4V_LRV(Exp_7B_One_Stage):
|
| 356 |
+
model_id: str = "llava-lvis4v-lrv+7b"
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
# === Section 5 :: Prisms ===
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
# Prism-CLIP
|
| 363 |
+
@dataclass
|
| 364 |
+
class Prism_7B_CLIP_Controlled(Exp_7B_One_Stage):
|
| 365 |
+
model_id: str = "prism-clip-controlled+7b"
|
| 366 |
+
vision_backbone_id: str = "clip-vit-l-336px"
|
| 367 |
+
image_resize_strategy: str = "resize-naive"
|
| 368 |
+
llm_backbone_id: str = "llama2-7b-pure"
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
@dataclass
|
| 372 |
+
class Prism_13B_CLIP_Controlled(Exp_13B_One_Stage):
|
| 373 |
+
model_id: str = "prism-clip-controlled+13b"
|
| 374 |
+
vision_backbone_id: str = "clip-vit-l-336px"
|
| 375 |
+
image_resize_strategy: str = "resize-naive"
|
| 376 |
+
llm_backbone_id: str = "llama2-13b-pure"
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
# =>> Note :: Run with `--dataset.type "llava-lvis4v-lrv"`
|
| 380 |
+
@dataclass
|
| 381 |
+
class Prism_7B_CLIP(Exp_7B_One_Stage):
|
| 382 |
+
model_id: str = "prism-clip+7b"
|
| 383 |
+
vision_backbone_id: str = "clip-vit-l-336px"
|
| 384 |
+
image_resize_strategy: str = "resize-naive"
|
| 385 |
+
llm_backbone_id: str = "llama2-7b-pure"
|
| 386 |
+
finetune_epochs: int = 2
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
# =>> Note :: Run with `--dataset.type "llava-lvis4v-lrv"`
|
| 390 |
+
@dataclass
|
| 391 |
+
class Prism_13B_CLIP(Exp_13B_One_Stage):
|
| 392 |
+
model_id: str = "prism-clip+13b"
|
| 393 |
+
vision_backbone_id: str = "clip-vit-l-336px"
|
| 394 |
+
image_resize_strategy: str = "resize-naive"
|
| 395 |
+
llm_backbone_id: str = "llama2-13b-pure"
|
| 396 |
+
finetune_epochs: int = 2
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
# Prism-SigLIP
|
| 400 |
+
@dataclass
|
| 401 |
+
class Prism_7B_SigLIP_Controlled(Exp_7B_One_Stage):
|
| 402 |
+
model_id: str = "prism-siglip-controlled+7b"
|
| 403 |
+
vision_backbone_id: str = "siglip-vit-so400m-384px"
|
| 404 |
+
image_resize_strategy: str = "resize-naive"
|
| 405 |
+
llm_backbone_id: str = "llama2-7b-pure"
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
@dataclass
|
| 409 |
+
class Prism_13B_SigLIP_Controlled(Exp_13B_One_Stage):
|
| 410 |
+
model_id: str = "prism-siglip-controlled+13b"
|
| 411 |
+
vision_backbone_id: str = "siglip-vit-so400m-384px"
|
| 412 |
+
image_resize_strategy: str = "resize-naive"
|
| 413 |
+
llm_backbone_id: str = "llama2-13b-pure"
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
# =>> Note :: Run with `--dataset.type "llava-lvis4v-lrv"`
|
| 417 |
+
@dataclass
|
| 418 |
+
class Prism_7B_SigLIP(Exp_7B_One_Stage):
|
| 419 |
+
model_id: str = "prism-siglip+7b"
|
| 420 |
+
vision_backbone_id: str = "siglip-vit-so400m-384px"
|
| 421 |
+
image_resize_strategy: str = "resize-naive"
|
| 422 |
+
llm_backbone_id: str = "llama2-7b-pure"
|
| 423 |
+
finetune_epochs: int = 2
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
# =>> Note :: Run with `--dataset.type "llava-lvis4v-lrv"`
|
| 427 |
+
@dataclass
|
| 428 |
+
class Prism_13B_SigLIP(Exp_13B_One_Stage):
|
| 429 |
+
model_id: str = "prism-siglip+13b"
|
| 430 |
+
vision_backbone_id: str = "clip-vit-l-336px"
|
| 431 |
+
image_resize_strategy: str = "resize-naive"
|
| 432 |
+
llm_backbone_id: str = "llama2-13b-pure"
|
| 433 |
+
finetune_epochs: int = 2
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
# Prism-DINOSigLIP
|
| 437 |
+
@dataclass
|
| 438 |
+
class Prism_7B_DINOSigLIP_Controlled(Exp_7B_One_Stage):
|
| 439 |
+
model_id: str = "prism-dinosiglip-controlled+7b"
|
| 440 |
+
vision_backbone_id: str = "dinosiglip-vit-so-384px"
|
| 441 |
+
image_resize_strategy: str = "resize-naive"
|
| 442 |
+
llm_backbone_id: str = "llama2-7b-pure"
|
| 443 |
+
arch_specifier: str = "no-align+fused-gelu-mlp"
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
@dataclass
|
| 447 |
+
class Prism_13B_DINOSigLIP_Controlled(Exp_13B_One_Stage):
|
| 448 |
+
model_id: str = "prism-dinosiglip-controlled+13b"
|
| 449 |
+
vision_backbone_id: str = "dinosiglip-vit-so-384px"
|
| 450 |
+
image_resize_strategy: str = "resize-naive"
|
| 451 |
+
llm_backbone_id: str = "llama2-13b-pure"
|
| 452 |
+
arch_specifier: str = "no-align+fused-gelu-mlp"
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
# =>> Note :: Run with `--dataset.type "llava-lvis4v-lrv"`
|
| 456 |
+
@dataclass
|
| 457 |
+
class Prism_7B_DINOSigLIP(Exp_7B_One_Stage):
|
| 458 |
+
model_id: str = "prism-dinosiglip+7b"
|
| 459 |
+
vision_backbone_id: str = "dinosiglip-vit-so-384px"
|
| 460 |
+
image_resize_strategy: str = "resize-naive"
|
| 461 |
+
llm_backbone_id: str = "llama2-7b-pure"
|
| 462 |
+
arch_specifier: str = "no-align+fused-gelu-mlp"
|
| 463 |
+
finetune_epochs: int = 2
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
# =>> Note :: Run with `--dataset.type "llava-lvis4v-lrv"`
|
| 467 |
+
@dataclass
|
| 468 |
+
class Prism_13B_DINOSigLIP(Exp_13B_One_Stage):
|
| 469 |
+
model_id: str = "prism-dinosiglip+13b"
|
| 470 |
+
vision_backbone_id: str = "dinosiglip-vit-so-384px"
|
| 471 |
+
image_resize_strategy: str = "resize-naive"
|
| 472 |
+
llm_backbone_id: str = "llama2-13b-pure"
|
| 473 |
+
arch_specifier: str = "no-align+fused-gelu-mlp"
|
| 474 |
+
finetune_epochs: int = 2
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
# [Inference-Optimized] 224px Prisms
|
| 478 |
+
@dataclass
|
| 479 |
+
class Opt_7B_DINOSigLIP_ViT_SO_p14_224px_Resize_Naive(Exp_7B_One_Stage):
|
| 480 |
+
model_id: str = "dinosiglip-224px-resize-naive+7b"
|
| 481 |
+
vision_backbone_id: str = "dinosiglip-vit-so-224px"
|
| 482 |
+
image_resize_strategy: str = "resize-naive"
|
| 483 |
+
arch_specifier: str = "no-align+fused-gelu-mlp"
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
@dataclass
|
| 487 |
+
class Prism_7B_DINOSigLIP_224px_Controlled(Exp_7B_One_Stage):
|
| 488 |
+
model_id: str = "prism-dinosiglip-224px-controlled+7b"
|
| 489 |
+
vision_backbone_id: str = "dinosiglip-vit-so-224px"
|
| 490 |
+
image_resize_strategy: str = "resize-naive"
|
| 491 |
+
llm_backbone_id: str = "llama2-7b-pure"
|
| 492 |
+
arch_specifier: str = "no-align+fused-gelu-mlp"
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
# =>> Note :: Run with `--dataset.type "llava-lvis4v-lrv"`
|
| 496 |
+
@dataclass
|
| 497 |
+
class Prism_7B_DINOSigLIP_224px(Exp_7B_One_Stage):
|
| 498 |
+
model_id: str = "prism-dinosiglip-224px+7b"
|
| 499 |
+
vision_backbone_id: str = "dinosiglip-vit-so-224px"
|
| 500 |
+
image_resize_strategy: str = "resize-naive"
|
| 501 |
+
llm_backbone_id: str = "llama2-7b-pure"
|
| 502 |
+
arch_specifier: str = "no-align+fused-gelu-mlp"
|
| 503 |
+
finetune_epochs: int = 2
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
# =>> Note :: Run with `--dataset.type "llava-lvis4v-lrv"`
|
| 507 |
+
@dataclass
|
| 508 |
+
class Prism_Qwen25_0_5B_DINOSigLIP_224px(Exp_7B_One_Stage):
|
| 509 |
+
model_id: str = "prism-qwen25-dinosiglip-224px+0_5b"
|
| 510 |
+
vision_backbone_id: str = "dinosiglip-vit-so-224px"
|
| 511 |
+
image_resize_strategy: str = "resize-naive"
|
| 512 |
+
llm_backbone_id: str = "qwen25-0_5b-pure"
|
| 513 |
+
arch_specifier: str = "no-align+fused-gelu-mlp"
|
| 514 |
+
finetune_epochs: int = 2
|
| 515 |
+
|
| 516 |
+
llm_max_length: int = 32768
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
# =>> Note :: Run with `--dataset.type "llava-lvis4v-lrv"`
|
| 520 |
+
@dataclass
|
| 521 |
+
class Prism_Qwen25_0_5B_Extra_DINOSigLIP_224px(Prism_Qwen25_0_5B_DINOSigLIP_224px):
|
| 522 |
+
model_id: str = "prism-qwen25-extra-dinosiglip-224px+0_5b"
|
| 523 |
+
llm_backbone_id: str = "qwen25-0_5b-extra"
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
# === Define a Model Registry Enum for Reference & Validation ===
|
| 527 |
+
@unique
|
| 528 |
+
class ModelRegistry(Enum):
|
| 529 |
+
# === LLaVa v1.5 Base Reproductions ===
|
| 530 |
+
REPRODUCTION_7B = LLaVa_v15_Reproduction_7B
|
| 531 |
+
REPRODUCTION_13B = LLaVa_v15_Reproduction_13B
|
| 532 |
+
|
| 533 |
+
# === Section 4.1 :: Optimization Procedure ===
|
| 534 |
+
EXP_ONE_STAGE_7B = Exp_7B_One_Stage
|
| 535 |
+
EXP_ONE_STAGE_13B = Exp_13B_One_Stage
|
| 536 |
+
|
| 537 |
+
EXP_FULL_FT_MULTI_STAGE = Exp_7B_Full_Finetune_Multi_Stage
|
| 538 |
+
EXP_FULL_FT_ONE_STAGE = Exp_7B_Full_Finetune_One_Stage
|
| 539 |
+
|
| 540 |
+
# === Section 4.2 :: Image Processing and Visual Representations ===
|
| 541 |
+
EXP_IN1K_224PX = Exp_7B_IN1K_ViT_L_p16_224px
|
| 542 |
+
EXP_DINOV2_224PX = Exp_7B_DINOv2_ViT_L_p14_224px
|
| 543 |
+
EXP_CLIP_224PX = Exp_7B_CLIP_ViT_L_p14_224px
|
| 544 |
+
EXP_SIGLIP_224PX = Exp_7B_SigLIP_ViT_SO_p14_224px
|
| 545 |
+
|
| 546 |
+
EXP_CLIP_336PX_RESIZE_CROP = Exp_7B_CLIP_ViT_L_p14_336px_Resize_Crop
|
| 547 |
+
EXP_CLIP_336PX_RESIZE_NAIVE = Exp_7B_CLIP_ViT_L_p14_336px_Resize_Naive
|
| 548 |
+
EXP_SIGLIP_384PX_LETTERBOX = Exp_7B_SigLIP_ViT_SO_p14_384px_Letterbox
|
| 549 |
+
EXP_SIGLIP_384PX_RESIZE_CROP = Exp_7B_SigLIP_ViT_SO_p14_384px_Resize_Crop
|
| 550 |
+
EXP_SIGLIP_384PX_RESIZE_NAIVE = Exp_7B_SigLIP_ViT_SO_p14_384px_Resize_Naive
|
| 551 |
+
|
| 552 |
+
EXP_DINOCLIP_336PX_LETTERBOX = Exp_7B_DINOCLIP_ViT_L_p14_336px_Letterbox
|
| 553 |
+
EXP_DINOCLIP_336PX_RESIZE_NAIVE = Exp_7B_DINOCLIP_ViT_L_p14_336px_Resize_Naive
|
| 554 |
+
EXP_DINOSIGLIP_384PX_LETTERBOX = Exp_7B_DINOSigLIP_ViT_L_p14_384px_Letterbox
|
| 555 |
+
EXP_DINOSIGLIP_384PX_RESIZE_NAIVE = Exp_7B_DINOSigLIP_ViT_L_p14_384px_Resize_Naive
|
| 556 |
+
|
| 557 |
+
# === Section 4.3 :: Language Models ===
|
| 558 |
+
EXP_LLAMA2_7B = Exp_7B_Llama2
|
| 559 |
+
EXP_LLAMA2_13B = Exp_13B_Llama2
|
| 560 |
+
|
| 561 |
+
# ~ Additional LLM Backbone Experiments :: LLaMa-2 Chat, Mistral v0.1, Mistral v0.1 Instruct ~
|
| 562 |
+
EXT_EXP_LLAMA2_CHAT_7B = Ext_Exp_7B_Llama2_Chat
|
| 563 |
+
EXT_EXP_LLAMA2_CHAT_13B = Ext_Exp_13B_Llama2_Chat
|
| 564 |
+
EXT_EXP_MISTRAL_V1_7B = Ext_Exp_7B_Mistral_V1
|
| 565 |
+
EXT_EXP_MISTRAL_INSTRUCT_V1_7B = Ext_Exp_7B_Mistral_Instruct_V1
|
| 566 |
+
EXT_EXP_PHI_2_3B = Ext_Exp_3B_Phi_2
|
| 567 |
+
|
| 568 |
+
# Cotraining w/ Unimodal Data
|
| 569 |
+
EXP_VICUNA_NO_COTRAINING_7B = Exp_7B_Vicuna_No_Cotraining
|
| 570 |
+
EXP_LLAMA2_NO_COTRAINING_7B = Exp_7B_Llama2_No_Cotraining
|
| 571 |
+
|
| 572 |
+
# === Section 4.4 :: Scaling Properties - Train Time & Data ===
|
| 573 |
+
EXP_1P25_EPOCHS = Exp_7B_1p25_Epochs
|
| 574 |
+
EXP_1P5_EPOCHS = Exp_7B_1p5_Epochs
|
| 575 |
+
EXP_2_EPOCHS = Exp_7B_2_Epochs
|
| 576 |
+
EXP_3_EPOCHS = Exp_7B_3_Epochs
|
| 577 |
+
|
| 578 |
+
EXP_LLAVA_LVIS4V = Exp_7B_LLaVa_LVIS4V
|
| 579 |
+
EXP_LLAVA_LRV = Exp_7B_LLaVa_LRV
|
| 580 |
+
EXP_LLAVA_LVIS4V_LRV = Exp_7B_LLaVa_LVIS4V_LRV
|
| 581 |
+
|
| 582 |
+
# === Section 5 :: Prisms ===
|
| 583 |
+
PRISM_CLIP_CONTROLLED_7B = Prism_7B_CLIP_Controlled
|
| 584 |
+
PRISM_CLIP_CONTROLLED_13B = Prism_13B_CLIP_Controlled
|
| 585 |
+
PRISM_CLIP_7B = Prism_7B_CLIP
|
| 586 |
+
PRISM_CLIP_13B = Prism_13B_CLIP
|
| 587 |
+
|
| 588 |
+
PRISM_SIGLIP_CONTROLLED_7B = Prism_7B_SigLIP_Controlled
|
| 589 |
+
PRISM_SIGLIP_CONTROLLED_13B = Prism_13B_SigLIP_Controlled
|
| 590 |
+
PRISM_SIGLIP_7B = Prism_7B_SigLIP
|
| 591 |
+
PRISM_SIGLIP_13B = Prism_13B_SigLIP
|
| 592 |
+
|
| 593 |
+
PRISM_DINOSIGLIP_CONTROLLED_7B = Prism_7B_DINOSigLIP_Controlled
|
| 594 |
+
PRISM_DINOSIGLIP_CONTROLLED_13B = Prism_13B_DINOSigLIP_Controlled
|
| 595 |
+
PRISM_DINOSIGLIP_7B = Prism_7B_DINOSigLIP
|
| 596 |
+
PRISM_DINOSIGLIP_13B = Prism_13B_DINOSigLIP
|
| 597 |
+
|
| 598 |
+
# === Inference Optimized :: 224px Prisms ===
|
| 599 |
+
OPT_DINOSIGLIP_224PX_RESIZE_NAIVE = Opt_7B_DINOSigLIP_ViT_SO_p14_224px_Resize_Naive
|
| 600 |
+
PRISM_DINOSIGLIP_224PX_CONTROLLED_7B = Prism_7B_DINOSigLIP_224px_Controlled
|
| 601 |
+
PRISM_DINOSIGLIP_224PX_7B = Prism_7B_DINOSigLIP_224px
|
| 602 |
+
|
| 603 |
+
# Qwen
|
| 604 |
+
PRISM_QWEN25_DINOSIGLIP_224PX_0_5B = Prism_Qwen25_0_5B_DINOSigLIP_224px
|
| 605 |
+
PRISM_QWEN25_EXTRA_DINOSIGLIP_224PX_0_5B = Prism_Qwen25_0_5B_Extra_DINOSigLIP_224px
|
| 606 |
+
|
| 607 |
+
@property
|
| 608 |
+
def model_id(self) -> str:
|
| 609 |
+
return self.value.model_id
|
| 610 |
+
|
| 611 |
+
|
| 612 |
+
# Register Models in Choice Registry
|
| 613 |
+
for model_variant in ModelRegistry:
|
| 614 |
+
ModelConfig.register_subclass(model_variant.model_id, model_variant.value)
|
VLA-Adapter-UAV/prismatic/conf/vla.py
ADDED
|
@@ -0,0 +1,319 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
vla.py
|
| 3 |
+
|
| 4 |
+
Draccus Dataclass Definition for a VLAConfig object, with various registered subclasses for each VLA experiment and
|
| 5 |
+
model configuration thereof. A given VLA model (`policy`) configures the following attributes:
|
| 6 |
+
- Data Mixture (e.g., Bridge, OXE_MAGIC_SOUP, etc.)
|
| 7 |
+
- Base VLM from Prismatic Registry (e.g., `prism-dinosiglip+7b`)
|
| 8 |
+
- VLA Model Architecture / Parameters (e.g., freeze vision encoder, last layer finetuning)
|
| 9 |
+
- Training / Optimization Hyperparameters
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from dataclasses import dataclass
|
| 13 |
+
from enum import Enum, unique
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from typing import Optional, Union
|
| 16 |
+
|
| 17 |
+
from draccus import ChoiceRegistry
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@dataclass
|
| 21 |
+
class VLAConfig(ChoiceRegistry):
|
| 22 |
+
# fmt: off
|
| 23 |
+
vla_id: str # Unique VLA Policy ID that fully specifies a configuration variant
|
| 24 |
+
base_vlm: Union[str, Path] # Base VLM as ID/Path to Run Directory (e.g., `prism-dinosiglip+7b`)
|
| 25 |
+
freeze_vision_backbone: bool # Freeze Vision Backbone Parameters (akin to pretraining)
|
| 26 |
+
freeze_llm_backbone: bool # Freeze LLM Backbone parameters
|
| 27 |
+
unfreeze_last_llm_layer: bool # Unfreeze final layer of LLM (only takes effect if LLM is frozen)
|
| 28 |
+
|
| 29 |
+
# Data Mixture Parameters
|
| 30 |
+
data_mix: str # Open-X Embodiment Dataset =>> Unique Mixture ID (e.g., `bridge`)
|
| 31 |
+
shuffle_buffer_size: int # Size of Shuffle Buffer (100K for Bridge, 1M for OXE)
|
| 32 |
+
|
| 33 |
+
# Optimization Parameters
|
| 34 |
+
epochs: int # Epochs to Run (in case `max_steps` is not specified)
|
| 35 |
+
max_steps: Optional[int] # [Optional] Max Gradient Steps to Run (overrides `epochs`)
|
| 36 |
+
save_every_n_steps: Optional[int]
|
| 37 |
+
|
| 38 |
+
expected_world_size: int # Expected # of GPUs =>> allows us to gate training on hardware
|
| 39 |
+
global_batch_size: int # Global Batch Size (divided across processes / world size)
|
| 40 |
+
per_device_batch_size: int # Per-Device Batch Size (per-process / individual GPU)
|
| 41 |
+
# =>> # of accumulation steps is auto-computed
|
| 42 |
+
|
| 43 |
+
learning_rate: float # Peak Learning Rate (`lr_scheduler_type` sets warmup/decay)
|
| 44 |
+
weight_decay: float # Weight Decay for AdamW Optimizer
|
| 45 |
+
max_grad_norm: float # Max Grad Norm (for global gradient clipping)
|
| 46 |
+
lr_scheduler_type: str # LR Scheduler (usually: "constant" | "linear-warmup+cosine-decay")
|
| 47 |
+
warmup_ratio: float # Fraction of Steps to Warmup (for warmup LR schedulers)
|
| 48 |
+
|
| 49 |
+
train_strategy: str # Train Strategy (default "fsdp-full-shard")
|
| 50 |
+
action_tokenizer: str
|
| 51 |
+
|
| 52 |
+
image_sequence_len: int
|
| 53 |
+
use_wrist_image: bool
|
| 54 |
+
|
| 55 |
+
# Enable Gradient/Activation Checkpointing (for the LLM Backbone)
|
| 56 |
+
enable_gradient_checkpointing: bool = True # Enable Gradient/Activation Checkpointing during Training
|
| 57 |
+
|
| 58 |
+
# Mixed Precision Training via Torch Native AMP (`autocast`)
|
| 59 |
+
enable_mixed_precision_training: bool = True # Enable Traditional BF16 Mixed Precision
|
| 60 |
+
reduce_in_full_precision: bool = True # Accumulate/Reduce All-Gather Gradients in FP32 Full Precision
|
| 61 |
+
|
| 62 |
+
# fmt: on
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
# === OpenVLA Training Configurations ===
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# = [8 GPU] Fast Iteration =>> SigLIP 224px + Bridge =
|
| 69 |
+
@dataclass
|
| 70 |
+
class Exp_SigLIP_224px_Bridge(VLAConfig):
|
| 71 |
+
vla_id: str = "siglip-224px+mx-bridge"
|
| 72 |
+
base_vlm: Union[str, Path] = "siglip-224px+7b"
|
| 73 |
+
|
| 74 |
+
image_sequence_len: int = 1
|
| 75 |
+
use_wrist_image: bool = False
|
| 76 |
+
|
| 77 |
+
freeze_vision_backbone: bool = False
|
| 78 |
+
freeze_llm_backbone: bool = False
|
| 79 |
+
unfreeze_last_llm_layer: bool = False
|
| 80 |
+
|
| 81 |
+
# Data Mixture Parameters
|
| 82 |
+
data_mix: str = "bridge"
|
| 83 |
+
shuffle_buffer_size: int = 256_000
|
| 84 |
+
|
| 85 |
+
# Optimization Parameters
|
| 86 |
+
epochs: int = 1000
|
| 87 |
+
max_steps: Optional[int] = None
|
| 88 |
+
save_every_n_steps: Optional[int] = 25000
|
| 89 |
+
|
| 90 |
+
expected_world_size: int = 8
|
| 91 |
+
global_batch_size: int = 256
|
| 92 |
+
per_device_batch_size: int = 32
|
| 93 |
+
|
| 94 |
+
learning_rate: float = 2e-5
|
| 95 |
+
weight_decay: float = 0.0
|
| 96 |
+
max_grad_norm: float = 1.0
|
| 97 |
+
lr_scheduler_type: str = "constant"
|
| 98 |
+
warmup_ratio: float = 0.0
|
| 99 |
+
|
| 100 |
+
train_strategy: str = "fsdp-full-shard"
|
| 101 |
+
action_tokenizer: str = "action_tokenizer"
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
# = [8 GPU] SigLIP 224px Frozen Vision Backbone + Bridge =
|
| 105 |
+
@dataclass
|
| 106 |
+
class Exp_FreezeVIT_SigLIP_224px_Bridge(Exp_SigLIP_224px_Bridge):
|
| 107 |
+
vla_id: str = "siglip-224px-icy+mx-bridge"
|
| 108 |
+
base_vlm: Union[str, Path] = "siglip-224px+7b"
|
| 109 |
+
freeze_vision_backbone: bool = True
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
# = [8 GPU] Fast Iteration =>> DINO-SigLIP 224px + Bridge =
|
| 113 |
+
@dataclass
|
| 114 |
+
class Exp_DinoSigLIP_224px_Bridge(Exp_SigLIP_224px_Bridge):
|
| 115 |
+
vla_id: str = "prism-dinosiglip-224px+mx-bridge"
|
| 116 |
+
base_vlm: Union[str, Path] = "prism-dinosiglip-224px+7b"
|
| 117 |
+
|
| 118 |
+
data_mix: str = "bridge"
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
# = [64 GPU] SigLIP 224px + OXE Magic Soup =
|
| 122 |
+
@dataclass
|
| 123 |
+
class Exp_SigLIP_224px_OXE_Magic_Soup(Exp_SigLIP_224px_Bridge):
|
| 124 |
+
vla_id: str = "siglip-224px+mx-oxe-magic-soup"
|
| 125 |
+
base_vlm: Union[str, Path] = "siglip-224px+7b"
|
| 126 |
+
|
| 127 |
+
data_mix: str = "oxe_magic_soup"
|
| 128 |
+
|
| 129 |
+
expected_world_size: int = 64
|
| 130 |
+
global_batch_size: int = 2048
|
| 131 |
+
per_device_batch_size: int = 32
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
# = [8 GPU] Qwen2.5 0.5B SigLIP 224px + OXE Magic Soup =
|
| 135 |
+
@dataclass
|
| 136 |
+
class Exp_Qwen25_DinoSigLIP_224px_0_5B_OXE_Magic_Soup(Exp_SigLIP_224px_Bridge):
|
| 137 |
+
vla_id: str = "prism-qwen25-dinosiglip-224px+0_5b+mx-oxe-magic-soup"
|
| 138 |
+
base_vlm: Union[str, Path] = "prism-qwen25-extra-dinosiglip-224px+0_5b"
|
| 139 |
+
|
| 140 |
+
data_mix: str = "oxe_magic_soup"
|
| 141 |
+
action_tokenizer: str = "extra_action_tokenizer"
|
| 142 |
+
|
| 143 |
+
expected_world_size: int = 8
|
| 144 |
+
global_batch_size: int = 256
|
| 145 |
+
per_device_batch_size: int = 32
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
@dataclass
|
| 149 |
+
class Exp_Qwen25_DinoSigLIP_224px_0_5B_LIBERO_90(Exp_Qwen25_DinoSigLIP_224px_0_5B_OXE_Magic_Soup):
|
| 150 |
+
vla_id: str = "prism-qwen25-dinosiglip-224px+0_5b+mx-libero-90"
|
| 151 |
+
|
| 152 |
+
data_mix: str = "libero_90"
|
| 153 |
+
|
| 154 |
+
expected_world_size: int = 8
|
| 155 |
+
global_batch_size: int = 256
|
| 156 |
+
per_device_batch_size: int = 32
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
@dataclass
|
| 160 |
+
class Exp_Qwen25_DinoSigLIP_224px_T2_0_5B_LIBERO_90(Exp_Qwen25_DinoSigLIP_224px_0_5B_LIBERO_90):
|
| 161 |
+
vla_id: str = "prism-qwen25-dinosiglip-224px-t2+0_5b+mx-libero-90"
|
| 162 |
+
image_sequence_len: int = 2
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
@dataclass
|
| 166 |
+
class Exp_Qwen25_DinoSigLIP_224px_wrist_0_5B_LIBERO_90(Exp_Qwen25_DinoSigLIP_224px_0_5B_LIBERO_90):
|
| 167 |
+
vla_id: str = "prism-qwen25-dinosiglip-224px-wrist+0_5b+mx-libero-90"
|
| 168 |
+
image_sequence_len: int = 2
|
| 169 |
+
use_wrist_image: bool = True
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
## bridge Qwen
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
@dataclass
|
| 176 |
+
class Exp_Qwen25_DinoSigLIP_224px_0_5B_Bridge(Exp_SigLIP_224px_Bridge):
|
| 177 |
+
vla_id: str = "prism-qwen25-dinosiglip-224px+0_5b+mx-bridge"
|
| 178 |
+
base_vlm: Union[str, Path] = "prism-qwen25-extra-dinosiglip-224px+0_5b"
|
| 179 |
+
|
| 180 |
+
data_mix: str = "bridge_dataset" # direct dataset
|
| 181 |
+
action_tokenizer: str = "extra_action_tokenizer"
|
| 182 |
+
|
| 183 |
+
expected_world_size: int = 8
|
| 184 |
+
global_batch_size: int = 256
|
| 185 |
+
per_device_batch_size: int = 32
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
@dataclass
|
| 189 |
+
class Exp_DinoSigLIP_224px_LIBERO_90(Exp_DinoSigLIP_224px_Bridge):
|
| 190 |
+
vla_id: str = "prism-dinosiglip-224px+mx-libero-90"
|
| 191 |
+
|
| 192 |
+
data_mix: str = "libero_90"
|
| 193 |
+
|
| 194 |
+
expected_world_size: int = 8
|
| 195 |
+
global_batch_size: int = 256
|
| 196 |
+
per_device_batch_size: int = 32
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
# = [64 GPU] DINO-SigLIP 224px + OXE Magic Soup++ =
|
| 200 |
+
@dataclass
|
| 201 |
+
class Exp_DinoSigLIP_224px_OXE_Magic_Soup_Plus(Exp_SigLIP_224px_Bridge):
|
| 202 |
+
vla_id: str = "prism-dinosiglip-224px+mx-oxe-magic-soup-plus"
|
| 203 |
+
base_vlm: Union[str, Path] = "prism-dinosiglip-224px+7b"
|
| 204 |
+
|
| 205 |
+
# Note =>> We adopt two stages, training on a mixture including DROID for 70% of training, before resampling!
|
| 206 |
+
# data_mix: str = "oxe_magic_soup_plus"
|
| 207 |
+
data_mix: str = "oxe_magic_soup_plus_minus"
|
| 208 |
+
|
| 209 |
+
expected_world_size: int = 64
|
| 210 |
+
global_batch_size: int = 2048
|
| 211 |
+
per_device_batch_size: int = 32
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
# === OpenVLA Fine-tuning Configurations ===
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
# = [8 GPU] SigLIP 224px + T-DROID =
|
| 218 |
+
@dataclass
|
| 219 |
+
class Exp_SigLIP_224px_TDROID_CarrotInBowl(Exp_SigLIP_224px_Bridge):
|
| 220 |
+
vla_id: str = "siglip-224px+mx-tdroid_carrot_in_bowl"
|
| 221 |
+
base_vlm: Union[str, Path] = "siglip-224px+7b"
|
| 222 |
+
|
| 223 |
+
data_mix: str = "tdroid_carrot_in_bowl"
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
@dataclass
|
| 227 |
+
class Exp_SigLIP_224px_TDROID_PourCornInPot(Exp_SigLIP_224px_Bridge):
|
| 228 |
+
vla_id: str = "siglip-224px+mx-tdroid_pour_corn_in_pot"
|
| 229 |
+
base_vlm: Union[str, Path] = "siglip-224px+7b"
|
| 230 |
+
|
| 231 |
+
data_mix: str = "tdroid_pour_corn_in_pot"
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
# = [8 GPU] SigLIP 224px + T-DROID -- Partial Finetuning =
|
| 235 |
+
@dataclass
|
| 236 |
+
class Exp_SigLIP_224px_Icy_TDROID_CarrotInBowl(Exp_SigLIP_224px_Bridge):
|
| 237 |
+
vla_id: str = "siglip-224px-icy+mx-tdroid_carrot_in_bowl"
|
| 238 |
+
base_vlm: Union[str, Path] = "siglip-224px+7b"
|
| 239 |
+
freeze_vision_backbone: bool = True
|
| 240 |
+
freeze_llm_backbone: bool = False
|
| 241 |
+
|
| 242 |
+
data_mix: str = "tdroid_carrot_in_bowl"
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
@dataclass
|
| 246 |
+
class Exp_SigLIP_224px_LastLayer_TDROID_CarrotInBowl(Exp_SigLIP_224px_Bridge):
|
| 247 |
+
vla_id: str = "siglip-224px-last_layer+mx-tdroid_carrot_in_bowl"
|
| 248 |
+
base_vlm: Union[str, Path] = "siglip-224px+7b"
|
| 249 |
+
freeze_vision_backbone: bool = True
|
| 250 |
+
freeze_llm_backbone: bool = True
|
| 251 |
+
unfreeze_last_llm_layer: bool = True
|
| 252 |
+
|
| 253 |
+
data_mix: str = "tdroid_carrot_in_bowl"
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
@dataclass
|
| 257 |
+
class Exp_SigLIP_224px_Sandwich_TDROID_CarrotInBowl(Exp_SigLIP_224px_Bridge):
|
| 258 |
+
vla_id: str = "siglip-224px-sandwich+mx-tdroid_carrot_in_bowl"
|
| 259 |
+
base_vlm: Union[str, Path] = "siglip-224px+7b"
|
| 260 |
+
freeze_vision_backbone: bool = False
|
| 261 |
+
freeze_llm_backbone: bool = True
|
| 262 |
+
unfreeze_last_llm_layer: bool = True
|
| 263 |
+
|
| 264 |
+
data_mix: str = "tdroid_carrot_in_bowl"
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
# === [8 GPU] SigLIP 224px + FrankaWipe ===
|
| 268 |
+
@dataclass
|
| 269 |
+
class Exp_SigLIP_224px_Droid_Wipe(Exp_SigLIP_224px_Bridge):
|
| 270 |
+
vla_id: str = "siglip-224px+mx-droid_wipe"
|
| 271 |
+
base_vlm: Union[str, Path] = "siglip-224px+7b"
|
| 272 |
+
|
| 273 |
+
data_mix: str = "droid_wipe"
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
# === Define a VLA Registry Enum for Reference & Validation ===
|
| 277 |
+
@unique
|
| 278 |
+
class VLARegistry(Enum):
|
| 279 |
+
# Sanity Check Configurations =>> BridgeV2
|
| 280 |
+
SIGLIP_224PX_MX_BRIDGE = Exp_SigLIP_224px_Bridge
|
| 281 |
+
DINOSIGLIP_224PX_MX_BRIDGE = Exp_DinoSigLIP_224px_Bridge
|
| 282 |
+
DINOSIGLIP_224PX_MX_LIBERO_90 = Exp_DinoSigLIP_224px_LIBERO_90
|
| 283 |
+
|
| 284 |
+
# SigLIP Frozen Backbone Experiment
|
| 285 |
+
FREEZE_SIGLIP_224PX_MX_BRIDGE = Exp_FreezeVIT_SigLIP_224px_Bridge
|
| 286 |
+
|
| 287 |
+
# [OpenVLA v0.1 7B] SigLIP 224px + OXE Magic Soup
|
| 288 |
+
SIGLIP_224PX_MX_OXE_MAGIC_SOUP = Exp_SigLIP_224px_OXE_Magic_Soup
|
| 289 |
+
|
| 290 |
+
# [OpenVLA 7B] DINO + SigLIP 224px + OXE Magic Soup++
|
| 291 |
+
DINOSIGLIP_224PX_MX_OXE_MAGIC_SOUP_PLUS = Exp_DinoSigLIP_224px_OXE_Magic_Soup_Plus
|
| 292 |
+
|
| 293 |
+
# [OpenVLA 0.5B] Qwen backbones
|
| 294 |
+
QWEN25_DINOSIGLIP_224PX_0_5B_MX_OXE_MAGIC_SOUP = Exp_Qwen25_DinoSigLIP_224px_0_5B_OXE_Magic_Soup
|
| 295 |
+
QWEN25_DINOSIGLIP_224PX_0_5B_LIBERO_90 = Exp_Qwen25_DinoSigLIP_224px_0_5B_LIBERO_90
|
| 296 |
+
QWEN25_DINOSIGLIP_224PX_T2_0_5B_LIBERO_90 = Exp_Qwen25_DinoSigLIP_224px_T2_0_5B_LIBERO_90
|
| 297 |
+
QWEN25_DINOSIGLIP_224PX_WRIST_0_5B_LIBERO_90 = Exp_Qwen25_DinoSigLIP_224px_wrist_0_5B_LIBERO_90
|
| 298 |
+
|
| 299 |
+
QWEN25_DINOSIGLIP_224PX_0_5B_BRIDGE = Exp_Qwen25_DinoSigLIP_224px_0_5B_Bridge
|
| 300 |
+
|
| 301 |
+
# === TDROID Fine-tuning Configs ===
|
| 302 |
+
SIGLIP_224PX_MX_TDROID_CARROT_IN_BOWL = Exp_SigLIP_224px_TDROID_CarrotInBowl
|
| 303 |
+
SIGLIP_224PX_MX_TDROID_POUR_CORN_IN_POT = Exp_SigLIP_224px_TDROID_PourCornInPot
|
| 304 |
+
|
| 305 |
+
SIGLIP_224PX_ICY_MX_TDROID_CARROT_IN_BOWL = Exp_SigLIP_224px_Icy_TDROID_CarrotInBowl
|
| 306 |
+
SIGLIP_224PX_LASTLAYER_MX_TDROID_CARROT_IN_BOWL = Exp_SigLIP_224px_LastLayer_TDROID_CarrotInBowl
|
| 307 |
+
SIGLIP_224PX_SANDWICH_MX_TDROID_CARROT_IN_BOWL = Exp_SigLIP_224px_Sandwich_TDROID_CarrotInBowl
|
| 308 |
+
|
| 309 |
+
# === DROID Fine-tuning Configs ===
|
| 310 |
+
SIGLIP_224PX_MX_DROID_WIPE = Exp_SigLIP_224px_Droid_Wipe
|
| 311 |
+
|
| 312 |
+
@property
|
| 313 |
+
def vla_id(self) -> str:
|
| 314 |
+
return self.value.vla_id
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
# Register VLAs in Choice Registry
|
| 318 |
+
for vla_variant in VLARegistry:
|
| 319 |
+
VLAConfig.register_subclass(vla_variant.vla_id, vla_variant.value)
|
VLA-Adapter-UAV/prismatic/extern/__init__.py
ADDED
|
File without changes
|
VLA-Adapter-UAV/prismatic/extern/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (154 Bytes). View file
|
|
|
VLA-Adapter-UAV/prismatic/extern/hf/__init__.py
ADDED
|
File without changes
|
VLA-Adapter-UAV/prismatic/extern/hf/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (157 Bytes). View file
|
|
|