diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..893678cfaf60377516a62a51c6d954ac0ce905d7
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,7 @@
+.runtime/
+__pycache__/
+*.pyc
+.DS_Store
+.env
+*.token
+.cache/
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..70de1be60431f58019fde4d996961e69b22b9102
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,23 @@
+.PHONY: help clean check autoformat
+.DEFAULT: help
+
+# Generates a useful overview/help message for various make features - add to this as necessary!
+help:
+ @echo "make clean"
+ @echo " Remove all temporary pyc/pycache files"
+ @echo "make check"
+ @echo " Run code style and linting (black, ruff) *without* changing files!"
+ @echo "make autoformat"
+ @echo " Run code styling (black, ruff) and update in place - committing with pre-commit also does this."
+
+clean:
+ find . -name "*.pyc" | xargs rm -f && \
+ find . -name "__pycache__" | xargs rm -rf
+
+check:
+ black --check .
+ ruff check --show-source .
+
+autoformat:
+ black .
+ ruff check --fix --show-fixes .
diff --git a/README_dinov3.md b/README_dinov3.md
new file mode 100644
index 0000000000000000000000000000000000000000..317f71034cd615b36b9b7b741779750ba3bd55bd
--- /dev/null
+++ b/README_dinov3.md
@@ -0,0 +1,882 @@
+:new: [2026-03-10] :fire: The [Canopy Height Maps v2 (CHMv2) model](https://arxiv.org/abs/2603.06382) and inference code are now available (more details on downloading the model weights and using the code [here](#canopy-height-maps-v2-chmv2)). The model weights are also available in [Hugging Face Hub](https://huggingface.co/facebook/dinov3-vitl16-chmv2-dpt-head) and [supported](https://github.com/huggingface/transformers/blob/main/docs/source/en/model_doc/chmv2.md) by the Hugging Face [Transformers](https://huggingface.co/docs/transformers/index) library. Building on our original high-resolution canopy height maps released in 2024, CHMv2 delivers substantial improvements in accuracy, detail, and global consistency by leveraging DINOv3.
+
+[2025-11-20] Distillation code and configurations for ConvNeXt backbones are now released!
+
+[2025-10-13] [Semantic segmentation](https://github.com/facebookresearch/dinov3?tab=readme-ov-file#linear-segmentation-with-data-augmentation-on-ade20k) (ADE20K) and [monocular depth estimation](https://github.com/facebookresearch/dinov3?tab=readme-ov-file#linear-depth-estimation-on-nyuv2-depth) (NYUv2-Depth) linear probing code are now released!
+
+[2025-09-17] DINOv3 backbones are now supported by the [PyTorch Image Models / timm](https://github.com/huggingface/pytorch-image-models/) library starting with version [1.0.20](https://github.com/huggingface/pytorch-image-models/releases/tag/v1.0.20)
+
+[2025-08-29] DINOv3 backbones are [supported](https://huggingface.co/docs/transformers/model_doc/dinov3) by released versions of the Hugging Face [Transformers](https://huggingface.co/docs/transformers/index) library starting with version [4.56.0](https://github.com/huggingface/transformers/releases/tag/v4.56.0)
+
+[2025-08-14] DINOv3 backbones are now available in [Hugging Face Hub](https://huggingface.co/collections/facebook/dinov3-68924841bd6b561778e31009) and [supported](https://huggingface.co/docs/transformers/model_doc/dinov3) by the [development](https://github.com/huggingface/transformers/) version of the Hugging Face [Transformers](https://huggingface.co/docs/transformers/index) library
+
+# DINOv3 🦖🦖🦖
+
+**[Meta AI Research, FAIR](https://ai.meta.com/research/)**
+
+Oriane Siméoni, Huy V. Vo, Maximilian Seitzer, Federico Baldassarre, Maxime Oquab,
+Cijo Jose, Vasil Khalidov, Marc Szafraniec, Seungeun Yi, Michaël Ramamonjisoa,
+Francisco Massa, Daniel Haziza, Luca Wehrstedt, Jianyuan Wang,
+Timothée Darcet, Théo Moutakanni, Leonel Sentana, Claire Roberts,
+Andrea Vedaldi, Jamie Tolan, John Brandt, Camille Couprie,
+Julien Mairal, Hervé Jégou, Patrick Labatut, Piotr Bojanowski
+
+[ :scroll: [`Paper`](https://arxiv.org/abs/2508.10104)] [ :newspaper: [`Blog`](https://ai.meta.com/blog/dinov3-self-supervised-vision-model/)] [ :globe_with_meridians: [`Website`](https://ai.meta.com/dinov3/)] [ :book: [`BibTeX`](#citing-dinov3)]
+
+Reference PyTorch implementation and models for DINOv3. For details, see the **[DINOv3](https://arxiv.org/abs/2508.10104)** paper.
+
+## Overview
+
+
+
+
+ High-resolution dense features. We visualize the cosine similarity maps obtained with DINOv3 output features between the patches marked with a red cross and all other patches.
+
+
+
+
+An extended family of versatile vision foundation models producing high-quality dense features and achieving outstanding performance on various vision tasks including outperforming the specialized state of the art across a broad range of settings, without fine-tuning
+
+## Pretrained models
+
+:information_source: Please follow the link provided below to get access to all the model weights: once accepted, an e-mail will be sent with the complete list of URLs pointing to all the available model weights (both backbones and adapters). These URLs can then be used to either:
+- download the model or adapter weights to a local filesystem and point `torch.hub.load()` to these local weights via the `weights` or `backbone_weights` parameters, or
+- directly invoke `torch.hub.load()` to download and load a backbone or an adapter from its URL via also the `weights` or `backbone_weights` parameters.
+
+See the example code snippets below.
+
+:warning: Please use `wget` instead of a web browser to download the weights.
+
+ViT models pretrained on web dataset (LVD-1689M):
+
+
+The (full) dino.txt model can be loaded via PyTorch Hub:
+
+```python
+import torch
+# DINOv3
+dinov3_vitl16_dinotxt_tet1280d20h24l, tokenizer = torch.hub.load(REPO_DIR, 'dinov3_vitl16_dinotxt_tet1280d20h24l', weights=, backbone_weights=)
+```
+
+
+## Installation
+
+The training and evaluation code requires PyTorch version >= 2.7.1 as well as a few other 3rd party packages. Note that the code has only been tested with the specified versions and also expects a Linux environment. To setup all the required dependencies for training and evaluation, please follow the instructions below:
+
+*[micromamba](https://mamba.readthedocs.io/en/latest/user_guide/micromamba.html)* **(Recommended)** - Clone the repository and then create and activate a `dinov3` conda environment using the provided environment definition:
+
+```shell
+micromamba env create -f conda.yaml
+micromamba activate dinov3
+```
+
+## Getting started
+
+Several notebooks are provided to get started applying DINOv3:
+- [PCA of patch features](notebooks/pca.ipynb): display the PCA of DINOv3 patch features on a foreground object (rainbow visualizations from the paper) [[Run in Google Colab]](https://colab.research.google.com/github/facebookresearch/dinov3/blob/main/notebooks/pca.ipynb)
+- [Foreground segmentation](notebooks/foreground_segmentation.ipynb): train a linear foreground segmentation model based on DINOv3 features [[Run in Google Colab]](https://colab.research.google.com/github/facebookresearch/dinov3/blob/main/notebooks/foreground_segmentation.ipynb)
+- [Dense and sparse matching](notebooks/dense_sparse_matching.ipynb): match patches from objects on two different images based on DINOv3 features [[Run in Google Colab]](https://colab.research.google.com/github/facebookresearch/dinov3/blob/main/notebooks/dense_sparse_matching.ipynb)
+- [Segmentation tracking](notebooks/segmentation_tracking.ipynb): video segmentation tracking using a non-parametric method based on DINOv3 features [[Run in Google Colab]](https://colab.research.google.com/github/facebookresearch/dinov3/blob/main/notebooks/segmentation_tracking.ipynb)
+- [Zero-shot segmentation with DINOv3-based dino.txt](notebooks/dinotxt_segmentation_inference.ipynb): compute the open-vocabulary segmentation results with dino.txt strategy.
+
+## Data preparation
+
+### ImageNet-1k
+
+The root directory of the dataset should hold the following contents:
+
+- `/test/ILSVRC2012_test_00000001.JPEG`
+- `/test/[..]`
+- `/test/ILSVRC2012_test_00100000.JPEG`
+- `/train/n01440764/n01440764_10026.JPEG`
+- `/train/[...]`
+- `/train/n15075141/n15075141_9993.JPEG`
+- `/val/n01440764/ILSVRC2012_val_00000293.JPEG`
+- `/val/[...]`
+- `/val/n15075141/ILSVRC2012_val_00049174.JPEG`
+- `/labels.txt`
+
+The provided dataset implementation expects a few additional metadata files to be present under the extra directory:
+
+- `/class-ids-TRAIN.npy`
+- `/class-ids-VAL.npy`
+- `/class-names-TRAIN.npy`
+- `/class-names-VAL.npy`
+- `/entries-TEST.npy`
+- `/entries-TRAIN.npy`
+- `/entries-VAL.npy`
+
+These metadata files can be generated (once) with the following lines of Python code:
+
+```python
+from dinov3.data.datasets import ImageNet
+
+for split in ImageNet.Split:
+ dataset = ImageNet(split=split, root="", extra="")
+ dataset.dump_extra()
+```
+
+Note that the root and extra directories do not have to be distinct directories.
+
+### ImageNet-22k
+
+Please adapt the [dataset class](dinov3/data/datasets/image_net_22k.py) to match your local setup.
+
+
+
+:warning: To execute the commands provided in the next sections for training and evaluation, the `dinov3` package should be included in the Python module search path, i.e. simply prefix the command to run with `PYTHONPATH=.`.
+
+## Training
+
+### Fast setup: training DINOv3 ViT-L/16 on ImageNet-1k
+
+Run DINOv3 pre-training on 4 H100-80GB nodes (32 GPUs) in a SLURM cluster environment with submitit:
+
+```shell
+ PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/train/train.py \
+ --nodes 4 \
+ --config-file dinov3/configs/train/vitl_im1k_lin834.yaml \
+ --output-dir \
+ train.dataset_path=ImageNet22k:root=:extra=
+```
+Training time is approximately 14 hours and the resulting checkpoint should reach 82.0% on k-NN eval and 83.5% on linear eval.
+
+The training code saves the weights of the teacher in the eval folder every 12500 iterations for evaluation.
+
+### Exact DINOv3 setup: training DINOv3 ViT-7B/16
+
+DINOv3 ViT-7B/16 is trained on a private dataset. The training involves 3 stages:
+- Pretraining
+- Gram anchoring
+- High resolution adaptation
+
+#### Pretraining
+
+Launch DINOV3 ViT-7B/16 pretraining on 32 nodes (256 GPUs) in a SLURM cluster environment with submitit.
+
+```shell
+PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/train/train.py \
+ --nodes 32 \
+ --config-file dinov3/configs/train/dinov3_vit7b16_pretrain.yaml \
+ --output-dir \
+ train.dataset_path=:root=:extra=
+```
+
+#### Gram anchoring
+
+```shell
+PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/train/train.py \
+ --nodes 32 \
+ --config-file dinov3/configs/train/dinov3_vit7b16_gram_anchor.yaml \
+ --output-dir \
+ train.dataset_path=:root=:extra= \
+ gram.ckpt=
+```
+
+#### High-resolution adaptation
+
+
+```shell
+PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/train/train.py \
+ --nodes 32 \
+ --config-file dinov3/configs/train/dinov3_vit7b16_high_res_adapt.yaml \
+ --output-dir \
+ train.dataset_path=:root=:extra= \
+ gram.ckpt= \
+ student.resume_from_teacher_chkpt=
+```
+
+## Multi-distillation
+
+### Test setup:
+
+```shell
+PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/train/train.py \
+ --nodes 1 \
+ --config-file dinov3/configs/train/multi_distillation_test.yaml \
+ --output-dir \
+ --multi-distillation \
+ train.dataset_path=:root=:extra=
+```
+
+## Evaluation
+
+The training code regularly saves the teacher weights. In order to evaluate the model, run the following evaluation on a single node:
+
+
+### Logistic regression classification on ImageNet-1k
+
+```shell
+PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/eval/log_regression.py \
+ model.config_file=/config.yaml \
+ model.pretrained_weights=/teacher_checkpoint.pth \
+ output_dir= \
+ train.dataset=ImageNet:split=TRAIN:root=:extra= \
+ eval.test_dataset=ImageNet:split=VAL:root=:extra=
+```
+
+### k-NN classification on ImageNet-1k
+
+```shell
+PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/eval/knn.py \
+ model.config_file=/config.yaml \
+ model.pretrained_weights=/teacher_checkpoint.pth \
+ output_dir= \
+ train.dataset=ImageNet:split=TRAIN:root=:extra= \
+ eval.test_dataset=ImageNet:split=VAL:root=:extra=
+```
+
+### Linear classification with data augmentation on ImageNet-1k
+
+```shell
+PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/eval/linear.py \
+ model.config_file=/config.yaml \
+ model.pretrained_weights=/teacher_checkpoint.pth \
+ output_dir= \
+ train.dataset=ImageNet:split=TRAIN:root=:extra= \
+ train.val_dataset=ImageNet:split=VAL:root=:extra=
+```
+
+### Linear segmentation with data augmentation on ADE20K
+
+```shell
+PYTHONPATH=. python -m dinov3.run.submit dinov3/eval/segmentation/run.py \
+model.dino_hub=dinov3_vit7b16 \
+config=dinov3/eval/segmentation/configs/config-ade20k-linear-training.yaml \
+datasets.root= \
+--output-dir
+```
+
+After the job completes, you will find in the output path directory you specified
+- `segmentation_config.yaml` that contains the config you trained the model with;
+- `model_final.pth`, the final linear head checkpoint at the end of training; and
+- `results-semantic-segmentation.csv` with the final metrics.
+
+
+#### Linear depth estimation on NYUv2 Depth
+```shell
+PYTHONPATH=. python -m dinov3.run.submit dinov3/eval/depth/run.py \
+ model.dino_hub=dinov3_vit7b16 \
+ config=dinov3/eval/depth/configs/config-nyu.yaml \
+ datasets.root= \
+ --output-dir
+```
+
+After the job completes, you will find in the output path directory you specified
+- `depth_config.yaml` that contains the config you trained the model with;
+- `model_final.pth`, the final linear head checkpoint at the end of training; and
+- `results-depth.csv` with the final metrics.
+
+### Text alignment on DINOv3 using dino.txt
+
+Text alignment can be done following the method from `dino.txt` aka [DINOv2 Meets Text](https://arxiv.org/abs/2412.16334).
+
+```shell
+PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/eval/text/train_dinotxt.py \
+ --nodes 4 \
+ # An example config for text alignment is here: dinov3/eval/text/configs/dinov3_vitl_text.yaml \
+ trainer_config_file="" \
+ output-dir=
+```
+Launching the above trains text alignment on 4 nodes with 8 gpus each (32 gpus in total).
+Please note that the text alignment model in the DINOv3 paper was trained on a private dataset and here we have given an example config in ```dinov3/eval/text/configs/dinov3_vitl_text.yaml``` using ```CocoCaptions``` dataset for illustration purposes.
+Please adapt the provided ```CocoCaptions``` dataset class, the dataset can be found [here](https://www.kaggle.com/datasets/nikhil7280/coco-image-caption)
+
+
+## Canopy Height Maps v2 (CHMv2)
+
+John Brandt, Seungeun Yi, Jamie Tolan, Xinyuan Li, Peter Potapov,
+Jessica Ertel, Justine Spore, Huy V. Vo, Michaël Ramamonjisoa, Patrick Labatut,
+Piotr Bojanowski, Camille Couprie
+
+[ :scroll: [`Paper`](https://arxiv.org/abs/2603.06382)] [ :newspaper: [`Blog`](http://ai.meta.com/blog/world-resources-institute-dino-canopy-height-maps-v2)]
+
+### CHMv2 model loading (via PyTorch [Hub](https://docs.pytorch.org/docs/stable/hub.html))
+
+:information_source: Please follow the link provided below to get access to the CHMv2 model weights: once accepted, an e-mail will be sent with the URL pointing to the available model weights. The URL can then be used to either:
+- download the model weights to a local filesystem and point `torch.hub.load()` to these local weights via the `weights` parameters, or
+- directly invoke `torch.hub.load()` to download and load a backbone from its URL.
+
+CHMv2 uses the DINOv3 ViT-L/16 satellite as the backbone, available after requesting access [here](https://ai.meta.com/resources/models-and-libraries/dinov3-downloads/).
+
+:warning: Please use `wget` instead of a web browser to download the weights.
+
+Download link: https://ai.meta.com/resources/models-and-libraries/chmv2-downloads/
+
+```python
+import torch
+from dinov3.hub.backbones import Weights
+
+REPO_DIR =
+
+chmv2_model = torch.hub.load(
+ REPO_DIR,
+ 'dinov3_vitl16_chmv2',
+ source="local",
+ weights="",
+ backbone_weights=Weights.SAT493M, # or
+)
+```
+
+Refer to this [notebook](notebooks/chmv2_inference.ipynb) for an example of how to use the DINOv3 + CHMv2 model.
+
+This [notebook](notebooks/chmv2_dataset_exploration.ipynb) can be used to download inference data from the existing global dataset stored on aws.
+
+### CHMv2 model loading (via Hugging Face [Transformers](https://huggingface.co/docs/transformers/))
+
+The CHMv2 model is also available on [Hugging Face Hub](https://huggingface.co/facebook/dinov3-vitl16-chmv2-dpt-head) and supported via the Hugging Face [Transformers](https://huggingface.co/docs/transformers/index) library. Please refer to the corresponding documentation for usage, but below is a short example that demonstrates how to obtain canopy height predictions on a sample image.
+
+```python
+from PIL import Image
+import torch
+
+from transformers import AutoModelForDepthEstimation, AutoImageProcessor
+
+processor = AutoImageProcessor.from_pretrained("facebook/dinov3-vitl16-chmv2-dpt-head")
+model = AutoModelForDepthEstimation.from_pretrained("facebook/dinov3-vitl16-chmv2-dpt-head")
+
+image = Image.open("image.tif")
+inputs = processor(images=image, return_tensors="pt")
+
+with torch.no_grad():
+ outputs = model(**inputs)
+
+depth = processor.post_process_depth_estimation(
+ outputs, target_sizes=[(image.height, image.width)]
+)[0]["predicted_depth"]
+```
+
+## License
+
+DINOv3 code and model weights are released under the DINOv3 License. See [LICENSE.md](LICENSE.md) for additional details.
+
+## Contributing
+
+See [contributing](CONTRIBUTING.md) and the [code of conduct](CODE_OF_CONDUCT.md).
+
+## Citing DINOv3
+
+If you find this repository useful, please consider giving a star :star: and citation :t-rex::
+
+```
+@misc{simeoni2025dinov3,
+ title={{DINOv3}},
+ author={Sim{\'e}oni, Oriane and Vo, Huy V. and Seitzer, Maximilian and Baldassarre, Federico and Oquab, Maxime and Jose, Cijo and Khalidov, Vasil and Szafraniec, Marc and Yi, Seungeun and Ramamonjisoa, Micha{\"e}l and Massa, Francisco and Haziza, Daniel and Wehrstedt, Luca and Wang, Jianyuan and Darcet, Timoth{\'e}e and Moutakanni, Th{\'e}o and Sentana, Leonel and Roberts, Claire and Vedaldi, Andrea and Tolan, Jamie and Brandt, John and Couprie, Camille and Mairal, Julien and J{\'e}gou, Herv{\'e} and Labatut, Patrick and Bojanowski, Piotr},
+ year={2025},
+ eprint={2508.10104},
+ archivePrefix={arXiv},
+ primaryClass={cs.CV},
+ url={https://arxiv.org/abs/2508.10104},
+}
+```
diff --git a/README_starVLA.md b/README_starVLA.md
new file mode 100644
index 0000000000000000000000000000000000000000..981d5dba0ad90d950067920bb8fa8489fb8b16d9
--- /dev/null
+++ b/README_starVLA.md
@@ -0,0 +1,446 @@
+# StarVLA: A Lego-like Codebase for Vision-Language-Action Model Developing
+
+
+[](https://huggingface.co/StarVLA) [](assets/starVLA_wechat.jpg)
+
+**[205/12/25]** We've simultaneously established pipelines for [Behavior-1K](examples/Behavior), [RoboTwin 2.0](examples/Robotwin), and CALVIN. We'd love to collaborate and share baseline results for more benchs with the community!
+
+**[205/12/25]** We've released RoboCasa evaluation support, which trained **without pretraining and reach SOTA performance**. Check out more details in [examples/Robocasa_tabletop](examples/Robocasa_tabletop).
+
+**[2025/12/15]** Completed a release regression check to ensure the public code runs smoothly. Routine updates—including recent support for the LeRobot dataset v3.0 and DeepSpeed ZeRO-3—will continue to appear in the [🚧 Daily Development Log](https://github.com/starVLA/starVLA/issues/64#issue-3727060165).
+
+**[2025/12/09]** Be the first open-source repository that can train with [train your vlm](starVLA/training/train_starvlm.py), [train your vla](starVLA/training/train_starvla.py), and [train your vla with vlm](starVLA/training/train_starvla_cotrain.py). Check out how to co-train your VLA with multimodal data in [examples/CoTrainVLM](examples/CoTrainVLM/README.md).
+
+
+ Historical Milestones
+
+**[2025/11/12]** We now support [Florence-2](https://github.com/anyantudre/Florence-2-Vision-Language-Model) as a smaller VLM for resource-constrained development. StarVLA can now run on a single A100 GPU. See the [🚀Train with a smaller VLM](#train-smaller-vlm) section for more details.
+
+
+**[2025/10/30]:** We released the LIBERO Training & Evaluation README. Results are very promising. More detail are in [examples/LIBERO](examples/LIBERO).
+
+**[2025/10/25]:** We fixed several script links and so everything is smoother now. Thanks to the community for the feedback.
+
+
+
+---
+
+StarVLA is a modular and flexible codebase for developing Vision-Language Model (VLM) to Vision-Language-Action (VLA) models.
+In StarVLA (also a pun on “start VLA” ), each functional component (model, data, trainer, config, evaluation, etc.) follows a top-down, intuitive separation and high cohesion and low coupling principle, which enabling plug-and-play design, rapid prototyping, and independent debugging.
+
+
+
+
+*Modules with solid borders are supported; borderless ones are coming soon.
+
+## Projects Based on StarVLA
+
+**NeuroVLA**: [*A Brain-like Embodied Intelligence for Fluid and Fast Reflexive Robotics Control*](https://github.com/guoweiyu/NeuroVLA)
+
+**PhysBrain**: [*Human Egocentric Data as a Bridge from Vision Language Models to Physical Intelligence*](https://zgc-embodyai.github.io/PhysBrain)
+
+
+## 🔥 Key Features
+
+
+
+
+Various VLA Frameworks
+
+- [x] **Qwen-FAST**: Utilizes Qwen2.5-VL-3B with a fast tokenizer to autoregressively generate discrete action tokens conditioned on visual and linguistic inputs (in line with π₀-fast).
+- [x] **Qwen-OFT**: Combines Qwen2.5-VL-3B with an MLP action head to perform parallel decoding of continuous actions, regressed from the hidden states of predefined special action tokens (in line with OpenVLA-OFT/EO).
+- [x] **Qwen-PI**: Integrates the Flow-Matching (FM) action expert with Qwen2.5-VL-3B, adopting a diffusion-based approach for continuous action prediction (in line with π₀).
+- [x] **Qwen-GR00T**: Implements a dual-system VLA architecture, where Qwen2.5-VL-3B serves as System2 for high-level vision-language reasoning, while the Flow-Matching module acts as System1 for rapid action prediction (in line with GR00T).
+
+
+ Results on SimplerEnv
+
+
+
+
+
+
+
+
+
+ Results on RoboCasa GR1
+
+
+
+
+
+
+
+
+ Results on LIBERO
+
+
+
+
+
+
+
+
+
+
+We have more results for RoboCasa, RoboTwin 2.0, Behavior-1k, Calvin. See our [🍀 Overleaf](https://www.overleaf.com/read/qqtwrnprctkf#d5bdce), which continuously presents our real-time experimental results.
+
+
+
+
+
+### 📈 Model Zoo
+We release a series of modified models and finetuning checkpoints to facilitate reproduction and downstream use.
+
+#### ✅ Available Modified Models
+
+| Model | Description | Link |
+|-------|-------------|------|
+| **Qwen2.5-VL-3B-Action** | Extend Qwen2.5-VL's vocabulary with Fast Tokens | [🤗 Hugging Face](https://huggingface.co/StarVLA/Qwen2.5-VL-3B-Instruct-Action) |
+| **Qwen3-VL-4B-Action** | Extend Qwen3-VL's vocabulary with Fast Tokens | [🤗 Hugging Face](https://huggingface.co/StarVLA/Qwen3-VL-4B-Instruct-Action) |
+
+#### ✅ Available Finetuning Checkpoints
+| Model | Description | WidowX | Link |
+|-------|-------------|------|------|
+| **QWen2.5-FAST-Bridge-RT-1** | Training on [Bridge](https://huggingface.co/datasets/IPEC-COMMUNITY/bridge_orig_lerobot) and [Fractal](https://huggingface.co/datasets/IPEC-COMMUNITY/fractal20220817_data_lerobot) | 58.6 | [🤗 Hugging Face](https://huggingface.co/StarVLA/Qwen-FAST-Bridge-RT-1) |
+| **QWen2.5-OFT-Bridge-RT-1** | Training on [Bridge](https://huggingface.co/datasets/IPEC-COMMUNITY/bridge_orig_lerobot) and [Fractal](https://huggingface.co/datasets/IPEC-COMMUNITY/fractal20220817_data_lerobot) | 41.8 | [🤗 Hugging Face](https://huggingface.co/StarVLA/Qwen-OFT-Bridge-RT-1) |
+| **QWen2.5-PI-Bridge-RT-1** | Training on [Bridge](https://huggingface.co/datasets/IPEC-COMMUNITY/bridge_orig_lerobot) and [Fractal](https://huggingface.co/datasets/IPEC-COMMUNITY/fractal20220817_data_lerobot) | 62.5 | [🤗 Hugging Face](https://huggingface.co/StarVLA/Qwen-FM-Bridge-RT-1) |
+| **QWen2.5-GR00T-Bridge-RT-1** | Training on [Bridge](https://huggingface.co/datasets/IPEC-COMMUNITY/bridge_orig_lerobot) and [Fractal](https://huggingface.co/datasets/IPEC-COMMUNITY/fractal20220817_data_lerobot) | 63.6 | [🤗 Hugging Face](https://huggingface.co/StarVLA/Qwen-PI-Bridge-RT-1) |
+| **QWen-GR00T-Bridge** | Training only on [Bridge](https://huggingface.co/datasets/IPEC-COMMUNITY/bridge_orig_lerobot) | 71.4 | [🤗 Hugging Face](https://huggingface.co/StarVLA/Qwen-GR00T-Bridge) |
+| **QWen3VL-OFT-Bridge-RT-1** | Training on [Bridge](https://huggingface.co/datasets/IPEC-COMMUNITY/bridge_orig_lerobot) and [Fractal](https://huggingface.co/datasets/IPEC-COMMUNITY/fractal20220817_data_lerobot) | 42.7 | [🤗 Hugging Face](https://huggingface.co/StarVLA/Qwen3VL-OFT-Bridge-RT-1) |
+| **QWen3VL-GR00T-Bridge-RT-1** | Training on [Bridge](https://huggingface.co/datasets/IPEC-COMMUNITY/bridge_orig_lerobot) and [Fractal](https://huggingface.co/datasets/IPEC-COMMUNITY/fractal20220817_data_lerobot) | 65.3 | [🤗 Hugging Face](https://huggingface.co/StarVLA/Qwen3VL-GR00T-Bridge-RT-1) |
+
+---
+
+
+
+Various Simulation Benchmarks
+
+
+- [x] **SimplerEnV**
+- [x] **LIBERO**
+- [x] **Robocasa**
+- [x] **RoboTwin**
+- [x] **BEHAVIOR**
+- [ ] **SO101**
+- [ ] **Calvin**
+- [ ] **RLBench**
+
+
+
+
+
+ Various Training Strategies
+
+* [x] Single Imitation Learning
+* [x] Multimodal Multitasks Co-training
+* [ ] Reinforcement Learning Adaption
+
+
+
+---
+
+## 🚀 Quick Start
+
+
+🛠 Environment Setup
+
+
+
+
+```bash
+# Clone the repo
+git clone https://github.com/starVLA/starVLA
+
+# Create conda environment
+conda create -n starVLA python=3.10 -y
+conda activate starVLA
+
+# Install requirements
+pip install -r requirements.txt
+
+# Install FlashAttention2
+pip install flash-attn --no-build-isolation
+
+# Install starVLA
+pip install -e .
+```
+
+
+⚠️ **Common Issues**
+flash-attn can be tricky to install because it must match your system’s CUDA toolkit (nvcc) and PyTorch versions. The `--no-build-isolation` flag resolves most issues, but on newer systems you may need to manually choose a compatible flash-attn version. Ensure your CUDA driver/toolkit and torch versions are aligned. Check your environment:
+
+```bash
+nvcc -V
+pip list | grep -E 'torch|transformers|flash-attn'
+```
+
+If issues persist, pick a flash-attn release that matches your versions (CUDA and torch) or ask chatGPT with searching function for help with the outputs above.
+
+We have verified that `flash-attn==2.7.4.post1` works well with nvcc versions `12.0` and `12.4`.
+
+
+
+
+👀 Quick Check StarVLA
+
+
+
+
+```bash
+# check framework with fake examples
+python starVLA/model/framework/QwenGR00T.py
+```
+
+
+You should download [Qwen3-VL-4B-Instruct](https://huggingface.co/Qwen/Qwen3-VL-4B-Instruct) and put it as `./playground/Pretrained_models/Qwen3-VL-4B-Instruct`. It should build successfully and `print(model)`. You can also call `model.forward(fake_data)` and obtain unnormalized actions via `model.predict_action(fake_data)`.
+
+
+
+
+🧪 Evaluate Existing Models
+
+We publish benchmark-specific evaluation guides inside each folder under [examples](examples).
+
+**Recommended quick start: LIBERO simulator**
+
+1. Download [Qwen2.5-VL-GR00T-LIBERO-4in1](https://huggingface.co/StarVLA/Qwen2.5-VL-GR00T-LIBERO-4in1).
+2. Follow the [LIBERO Eval](https://github.com/starVLA/starVLA/tree/starVLA/examples/LIBERO#-1-environment-setup) instructions to prepare the Python environment.
+3. Set the environment variables at the top of [`eval_libero.sh`](examples/LIBERO/eval_files/eval_libero.sh) and [`run_policy_server.sh`](examples/LIBERO/eval_files/run_policy_server.sh).
+4. Run:
+
+```bash
+bash examples/LIBERO/eval_files/run_policy_server.sh &
+bash examples/LIBERO/eval_files/eval_libero.sh
+```
+
+⚠️ **Common issue**
+If `NotImplementedError: Framework QwenGR00T is not implemented` appears, run `python starVLA/model/framework/QwenGR00T.py` to verify your environment.
+
+
+
+
+🚀 Train Your Own Model
+
+We ship benchmark-specific training scripts under [examples](examples). We recommend starting with the [LIBERO suite](examples/LIBERO/train_files):
+
+1. Edit `run_libero_train.sh` to point to your checkpoint, dataset root, and desired output directory.
+2. Launch training:
+
+```bash
+bash examples/LIBERO/train_files/run_libero_train.sh
+```
+
+⚠️ **Note:** Ensure all absolute paths inside `run_libero_train.sh` match your local environment before launching.
+
+
+
+
+
+## 🌟 How does starVLA make model development Lego-like again?
+👇 StarVLA achieves “Lego-like” development via the following designs:
+
+
+1. Smoke test any submodule
+
+StarVLA emphasizes a modular model design. Each major framework file can be run standalone for rapid debugging and smoke test your code. For example:
+
+```bash
+# model
+python starVLA/model/framework/QwenOFT.py --config_yaml starvla_cotrain_oxe.yaml
+# dataloader
+python starVLA/dataloader/lerobot_datasets.py --config_yaml starvla_cotrain_oxe.yaml
+
+```
+Note: `starVLA/model/framework/yourframework.py` is the single external API surface of the model; it should mirror (be structurally isomorphic to) the framework diagram in your paper.
+
+
+
+2. Explicit model boundaries
+
+StarVLA follows top‑down decomposition and the principle of high cohesion & low coupling.
+
+For example:
+- Dataloader
+ - Returns a raw, model‑agnostic dict only; no model‑specific preprocessing (e.g., tokenizer, image encoding).
+ - A single sample should include (add/remove as needed):
+ - image: list[PIL.Image] | np.ndarray
+ - lang: str
+ - action: np.ndarray[T, action_dim]
+ - state: Optional[np.ndarray[..., state_dim]]
+
+Both `framework.forward()` and `framework.predict_action()` operate directly on raw inputs, keeping train/test boundaries explicit and easy to hack.
+
+
+
+3. Flexible configuration system
+
+StarVLA uses a single global configuration object
+Parameters are passed primarily via extensible dicts, allowing overrides and controlled redundancy.
+
+
+
+
+🧪 *To self‑test and iterate on StarVLA’s usability, we re‑implemented several representative VLA frameworks. Our have done a beta test: an internal developer can stand up a new VLA framework in under half a day (leat then 3 hours), and an new user can build their first custom VLA framework within a single day. More design insights for each item can be found in [assets/intro_v1.md](assets/intro_v1.md).*
+
+
+---
+
+
+## 📖 FAQ
+
+
+Q: Why not put preprocessing in the dataloader?
+
+A: We profiled it: data preprocessing takes <1% time. Keeping it inside the Framework is acceptable and allows model‑specific flexible handling.
+
+
+
+
+Q: Can I use a backbone other than Qwen2.5-VL?
+
+A: Yes. Implement new vision + language modules and compose them inside a Framework; any other existing models can be swapped in. Yet, due to the framework processing raw action data, it is very easy to swap in.
+
+
+Q: Why isn't there an abstract interface for the vision tower?
+
+A: We believe that VLM will become the base model and will inherently possess its own native vision tower.
+
+
+
+
+
+Q: Can I override or add parameters via the terminal?
+
+A: Yes. We use OmegaConf.load(args.config_yaml) as the single configuration entry; standalone debugging also uses args.config_yaml. Parameters may be intentionally redundant; you can freely add or override them via the CLI.
+
+Examples:
+```bash
+accelerate launch \
+ --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \
+ --num_processes 8 \
+ starVLA/training/train_internvla.py \
+ --config_yaml ./starVLA/config/training/starvla_cotrain_oxe.yaml \
+ --framework.qwenvl.base_vlm Qwen/Qwen2.5-VL-7B-Instruct \ # override framework choice
+ --framework.qwenvl.base_vlm Qwen/Qwen2.5-VL-7B-Instruct \ # override framework choice
+ --framework.action_model.new_module ${module_name} \ # plug-in a new module to action model
+```
+
+⚠️: `framework.action_model.new_module` only adds to the global config; its behavior is on your framework.
+
+
+
+
+
+Q: Can I freeze the VLM via parameters?
+
+A: Yes. StarVLA uses a regex / name list to control freezing. Example:
+```
+--trainer.freeze_modules "qwen_vl_interface.model.model.visual,dino_encoder" \
+```
+Tips: You can ``print(your_model)`` first to check the relative paths of your modules and list them as comma-separated values.
+(implementation in `TrainerUtils.freeze_backbones`.)
+
+
+
+
+Q: Can I set different learning rates for different modules?
+
+A: Yes, starVLA also uses name: value dict to control learning group. Config example:
+```yaml
+trainer:
+ learning_rate:
+ base: 1e-05 # other modules
+ qwen_vl_interface: 1.0e-05
+ action_model: 1.0e-04
+```
+(Also referenced in `trainer_tools.build_param_lr_groups`.)
+
+
+
+Q: Can I resume training from a checkpoint?
+
+A: Yes, somehow can. Specify the latest checkpoint path in `config.yaml`, e.g.:
+```yaml
+trainer:
+ pretrained_checkpoint: path_to_steps_10000.pt
+ reload_modules: "action_model"
+```
+Empty `reload_modules` means full load all model. However, starVLA does not save `optimizer state`. It requires a lot of memory/disk and bring limited benefit.
+
+
+
+
+🚀 Train with a smaller VLM
+
+```bash
+ accelerate launch \
+ --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \
+ --main_process_ip $MASTER_ADDR \
+ --main_process_port $MASTER_PORT \
+ --machine_rank $SLURM_PROCID \
+ --num_machines $SLURM_NNODES \
+ --num_processes=${TOTAL_GPUS} \
+ starVLA/training/train_starvla.py \
+ --config_yaml ./starVLA/config/training/starvla_cotrain_oxe.yaml \
+ --framework.framework_py QwenGR00T \
+ --framework.qwenvl.base_vlm microsoft/Florence-2-large \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project your_project \
+ --wandb_entity your_name
+```
+
+Note: To ensure better compatibility with already released checkpoints, we are continuing to use `--framework.qwenvl`. This parameter will be unified in the next release.
+
+
+
+
+
+## ✍️ Citation & Copyright
+
+
+StarVLA is released under the MIT License, which permits commercial use, modification, distribution, and private use. Rebases are allowed for forks and feature branches; when rebasing from upstream StarVLA, use descriptive commit messages (e.g., "chore: rebase from StarVLA") and keep at least the two latest upstream commits as separate. See [License](LICENSE) for details.
+
+
+```
+@misc{starvla2025,
+ title = {StarVLA: A Lego-like Codebase for Vision-Language-Action Model Developing},
+ author = {starVLA Community},
+ url = {https://github.com/starVLA/starVLA}
+ year = {2025}
+}
+```
+
+
+## 🤝 Contributing
+
+
+1) If you find an issue, please open an Issue first. If it persists or needs clarification, start a Discussion and we’ll follow up.
+
+2) If you have ideas to improve StarVLA, feel free to open a PR. To make sure we will accept your effect, please align scope and design first via an Issue or by booking a short sync with this [Cooperation Form](https://forms.gle/R4VvgiVveULibTCCA).
+
+3) If you’re blocked or want to brainstorm, please fill out the [Cooperation Form](https://forms.gle/R4VvgiVveULibTCCA). We host office hours every Friday afternoon for live discussion.
+
+Tip: Before submitting a PR, run make check locally to pass formatting and lint.
+
+
+## 🙏 Acknowledgements
+This project draws inspiration and references from several notable open-source initiatives, including:
+- [LeRobot](https://github.com/huggingface/lerobot)
+- [GR00T](https://github.com/NVIDIA/Isaac-GR00T/tree/main)
+- [DeepSpeed](https://github.com/deepspeedai/DeepSpeed)
+- [Qwen-VL](https://github.com/QwenLM/Qwen3-VL/tree/main)
+- [InternVL](https://github.com/OpenGVLab/InternVL)
+
+The codebase was originally forked from [InternVLA-M1](https://github.com/InternRobotics/InternVLA-M1).
+
+
+
+# Star History
+Here's how our community has grown over time:
+
+[](https://www.star-history.com/#starVLA/starVLA&type=date&legend=bottom-right)
+
+
+
\ No newline at end of file
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
new file mode 100644
index 0000000000000000000000000000000000000000..becd78fb2d1499ec5c1820405153d32f17f20276
--- /dev/null
+++ b/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,25 @@
+# Third-Party Sources
+
+This directory is a private reproducibility archive, not a declaration that
+all upstream code, weights, and assets have one common license.
+
+- RoboCasa: original license is retained at `third_party/robocasa/LICENSE`.
+- RoboSuite: upstream license is retained at `third_party/robosuite/LICENSE`.
+ Its collection source is recorded in
+ `provenance/runtime_versions_and_licenses.json`.
+- pykdl_utils and hrl_geom: original `package.xml` and source copyright
+ headers are retained; both package manifests declare BSD. No standalone
+ LICENSE file was found in the copied upstream roots. Resolve the complete
+ applicable license text before public redistribution.
+- Orocos KDL / PyKDL 1.5.4: the recovered source and its original notices,
+ including `orocos_kdl/COPYING`, are vendored. Its pybind11 source/notices
+ are also retained. See `provenance/kdl_source.json` for the source revision.
+- GR1 robot geometry and RoboCasa object assets: preserve all embedded
+ notices; their redistribution rights must be reviewed separately.
+- Original starVLA, NVIDIA simulation wrappers, VJEPA, model metadata, and
+ other source headers/notices are preserved. Backbone weight licenses must
+ also be reviewed before distribution; do not relicense them as project code.
+
+The owner authorized a private Hugging Face archive. This does not authorize
+public redistribution. No public-distribution license or permission has been
+inferred from local access to these resources.
diff --git a/TRAINING_PROVENANCE.md b/TRAINING_PROVENANCE.md
new file mode 100644
index 0000000000000000000000000000000000000000..defa903709c3616ae67d24dc040fc2e8e2562411
--- /dev/null
+++ b/TRAINING_PROVENANCE.md
@@ -0,0 +1,54 @@
+# Training Provenance
+
+## What Was Recovered
+
+- Run-saved `provenance/training/run_yzh_cosmos25_perceiver_vjepa2_ac_resume.sh`.
+- The run's saved `config.yaml`, `dataset_statistics.json`, and
+ `summary.jsonl`, under `provenance/training/`.
+- Trainer source `starVLA/training/train_starvla.py` and data/model source.
+- Per-file source hashes and original modification times in
+ `provenance/source_snapshot.json`.
+
+The current project and its `_back` copy were compared during collection;
+the selected code contents were identical. A backup directory name is not
+evidence of a separate historical version. Original notebook checkpoints,
+where present, are retained as evidence, not substituted automatically.
+
+## Run Identity
+
+- Model run: `cosmopredict25_vjepa_ImageLatent/robocasa_06-28-13-10`.
+- Selected released checkpoint step: 280000.
+- Dataset mixture: `robocasa_teleop_ee`, original root
+ `/mnt/workspace/datasets/`.
+- Dataset files were NOT migrated. The saved normalization statistics were.
+- Final run configuration takes precedence over stale comments or today's
+ example launch scripts.
+
+WM4A resumes from
+`robocasa_06-26-16-51/checkpoints/steps_180000_pytorch_model.pt`.
+The selected 280000-step checkpoint is from the resumed run.
+
+Initialization resources in the archived script:
+
+- Cosmos-Predict2.5-2B-Post-Trained, revision
+ `diffusers/base/post-trained`.
+- VJEPA2-AC `vjepa2-ac-vitg.pt` and the vendored VJEPA repository.
+- The preceding 180000-step policy checkpoint.
+
+The archived script's comment says 25000/50000 steps and loss 0.05, but its
+actual arguments and saved config specify 180000-step resume, 300000 target
+steps, and future-latent loss weight 0.01. Do not use that comment as protocol.
+Saved per-device batch size is 14, checkpoint interval 20000, warmup 2000.
+
+## Limits And Safe Use
+
+Exact training reproduction is NOT validated. No training was launched.
+The archived scripts contain historical absolute paths and eight-GPU defaults;
+they are evidence, not safe one-click commands for a shared host. Update paths,
+obtain an explicit allocation, and set `CUDA_VISIBLE_DEVICES` before adapting
+them. Required datasets, initialization weights, and any optimizer/resume
+states have not been bundled or proven complete.
+
+The evaluation preparer reconstructs initialization files from the FINAL
+policy checkpoint. These files are suitable for loading that policy, not for
+reconstructing its original training initialization.
diff --git a/VALIDATION.md b/VALIDATION.md
new file mode 100644
index 0000000000000000000000000000000000000000..6ee0ebdecb264248b58f3348051791197e97e75a
--- /dev/null
+++ b/VALIDATION.md
@@ -0,0 +1,222 @@
+# Validation Status
+
+Diagnostic date: September 26, 2026 (Asia/Shanghai).
+
+## Current Result
+
+The full migrated RoboCasa benchmark was STOPPED at the user's request at
+2026-09-25T16:21:29Z (September 26, 00:21:29 Asia/Shanghai).
+Closed-loop effectiveness has NOT been reproduced. The completed first task,
+cup-to-drawer-close, scored 0/50 versus the historical 11/50. The next task
+was interrupted and must not be counted as a finished result.
+No new complete 24-task mean success rate is available.
+
+- Host: exact SSH alias `perdon-hou`, verified hostname `nb-5pl2apckdj-0`.
+- Checkpoint: step 280000; original pinned SHA-256 verified.
+- Strict checkpoint load passed in both the precheck and the full-run process.
+- Policy GPU: 0; simulation CUDA/EGL GPU: 1.
+- Stopped full-run coordinator PID: 538455; its recorded children also exited.
+- Full-run output: `/mnt/workspace/users/maxiangkai/migrations/MaskWAM_WM4A_perdon_hou_20260925T143800Z/WM4A/.runtime/full_01`.
+- Historical mean (reference only, NOT a new result): 56.17%.
+
+## Open-Loop Diagnostics
+
+36 fixed demonstration windows from 9 episodes and 3 tasks were tested with
+the original checkpoint normalization statistics and per-window seeds.
+The original project/initialization paths and the migrated paths produced
+bitwise-identical predictions for both tested input pipelines (72 paired
+predictions, maximum absolute difference 0).
+
+| Input Pipeline | Active-Dimension Action MAE |
+| --- | ---: |
+| Evaluation client inputs | 0.03853773 |
+| Dataset EE state instead of client FK | 0.03853773 |
+| Subtask prompt instead of Task prompt | 0.03840540 |
+| Dataset EE state, Subtask prompt, PIL resize | 0.03988905 |
+
+Metrics use the first 12 executed actions, 27 active normalized dimensions.
+These are demonstration diagnostics, not held-out success rates.
+FK versus preconverted EE states has maximum position discrepancy below
+4e-8 m. Changing only the state to dataset EE values changes predicted
+actions by at most 3.19e-6, not exactly zero.
+
+Ground-truth EE actions passed 864 IK checks with no residual exceeding
+1 mm or 0.01 rad. Predicted actions exceeded that threshold on 12/864
+checks (3 cup, 9 potato). Four fixed-seed tests with future-image generation
+enabled showed no change to the current or subsequent action prediction.
+Three reset-only simulator observations were captured without policy steps;
+their images are not blank, and the inspected frame has the expected
+orientation and cropped/padded camera layout.
+
+This does NOT establish the cause of the 0/50 regression or prove July
+runtime equivalence. The source-path A/B used today's available original
+code and the same current policy environment, not an immutable July runtime.
+The 222 vendored RoboSuite source files match the collected
+`robocasa_liao` source; differences in another editable RoboSuite checkout
+are not evidence that the migrated evaluation used it.
+
+Detailed evidence and runnable diagnostic scripts:
+`provenance/validation/wm4a_openloop_20260925T163212Z/`.
+The WM4A full evaluation remains stopped. No model weights, training code,
+simulator source, shared environment, or driver were modified by these tests.
+
+## Controlled Follow-Up
+
+Evidence: `provenance/validation/wm4a_followup_20260925T170412Z/REPORT.md`.
+The historical effectiveness regression remains unresolved. The full sweep
+was not restarted, and no experimental IK change was promoted to default.
+
+The original cup demonstration (LeRobot episode 0 / HDF5 demo_245) was restored
+with bitwise-identical initial simulator state. Recorded joint actions and
+recorded EE actions through the actual WM4A client/IK both completed the task
+from step 213. Model-driven execution from that same state failed after
+720 steps. This validates that particular demonstration/control path, not
+all scenes or historical runtime equivalence.
+
+In a separate fixed-constructor-seed scene, the baseline, per-chunk IK-cache
+reset, and bounded 5 mm approximate IK fallback all failed. Their initial
+state, scene XML and first prediction were identical. IK residual misses
+at the common 1 mm / 0.01 rad threshold were 429, 317 and 427 out of 1440.
+No transient successful substep was omitted by the legacy aggregation in
+the five model-driven diagnostic episodes.
+
+The controlled BF16 implementation matched all 36 prior open-loop outputs
+bitwise. Restoring action-head weights in FP32 changed MAE only from
+0.03853773 to 0.03852874. All 901 Diffusers and 2347 Transformers Python
+files compared against the June 16 environment archive matched.
+
+The diagnostic now distinguishes clipped actuator tracking error from raw
+hand-command differences, and explicitly seeds RoboSuite's constructor.
+Merely calling reset(seed) does not seed its separate RNG. These corrections
+are isolated diagnostic changes; the release's general --seed path is not
+certified for multi-episode determinism.
+
+All 1505 sealed source hashes and four release unit tests passed. The
+diagnostic server and rollout processes exited; MaskWAM and unrelated jobs
+were not signaled. The evidence preserves scripts, predictions, simulator
+states, source frames, execution records, and checksums.
+
+## Conditioning And Replanning
+
+Evidence: `provenance/validation/wm4a_conditioning_20260925T175334Z/REPORT.md`.
+No repair was promoted and the full benchmark remains stopped.
+
+The 36 fixed windows were tested with seven paired conditions. Baseline
+outputs again match the prior predictions bitwise. Image, language, and state
+interventions change internal features and actions; no entire input branch
+was found disconnected. Normalized MAE was 0.03854 at baseline, 0.16592 with
+black images, 0.16410 with other-task images, 0.05666 with other-task language,
+and 0.27769 with other-task states. These interventions are not realistic
+evaluation conditions or proof of correct task understanding.
+
+At the matched demonstration start, replacing the recorded frame with the
+reconstructed frame changes target positions by only 3.61/2.89 mm on average
+for left/right arms and slightly improves this window's error. This is not
+a validation of all subsequent rendered observations.
+
+Six-step rather than twelve-step execution was tested in two paired scenes,
+with initial simulator state, XML, first input and prediction all identical.
+Model seeds were aligned at shared physical timesteps. Both episodes failed
+after 720 steps. IK misses changed from 386 to 187 in demo_245 and from 429
+to zero in the seeded random scene, out of 1440 calls each. Thus IK failure
+alone does not explain every unsuccessful episode.
+
+A further oracle-conditioned replay used the original demonstration images
+and states for all 19 model calls. Its predicted actions failed over the
+demonstration's 228 transitions, while both recorded-action controls succeeded
+from step 213. Mean EE target errors were 4.55/2.78 cm and mean orientation
+errors 0.167/0.178 rad. This is not autonomous evaluation, and recorded future
+inputs can become inconsistent with the evolving scene. It shows that
+correcting the input distribution alone was insufficient in this case.
+
+The v1 diagnostic's all-dimension `hold_state` metric is invalid because hand
+observations and action commands use different conventions. It is preserved
+but explicitly excluded in `conditioning/metrics_corrected.json` and
+`comparison.json`. Only the direct EE XYZ hold baseline is used.
+
+All experiments were bounded and their processes exited. The sealed model
+and simulator sources, checkpoints, shared environments, and other jobs were
+not changed. The historical effectiveness discrepancy remains unresolved.
+
+## Action Components And Sampling
+
+Evidence: `provenance/validation/wm4a_action_components_20260925T184142Z/REPORT.md`.
+No repair was promoted; the full benchmark remains stopped.
+
+Six component replays used the same demonstration, 19 recorded-input model
+calls, and 228 executed transitions. Actual restored simulator states match
+bitwise, as do all untouched action channels. The unchanged model reproduces
+the prior failed replay exactly. Replacing only both arms' Cartesian XYZ with
+recorded targets succeeds from step 215. Full recorded actions and recorded
+complete EE poses succeed from steps 213 and 216. Replacing only rotations or
+hand commands still fails. These are oracle-action interventions on one scene,
+not autonomous evaluation or a validated repair.
+
+The real collected training transforms and mixture sample assembly were
+exercised on 55 windows without constructing shared caches. Layout and masks
+match the expected 64-state/32-action padded schema; all 36 prior training
+images and prompts match exactly. FP16 intermediate casting changes 83/3520
+state elements after BF16 conversion. Independently merging the current
+24-dataset min/max statistics exactly reproduces the checkpoint's state and
+action bounds. This is not immutable historical training-source validation.
+
+Nineteen baseline predictions and their isolated head replays match bitwise.
+With fixed backbone/VAE features, eight independent head draws have conditional
+XYZ spread of 0.945/0.688 cm RMS versus finite-sample mean errors of
+5.424/3.483 cm RMS against the demonstration. This weakens a pure head-noise
+explanation on these windows, not every possible source of randomness.
+
+Four inference variants were replayed without replacing action targets:
+eight-draw XYZ averaging, 80 instead of 20 integration steps, training state
+casting only, and complete current training inputs. All fail and none brings
+the cup into the drawer. XYZ averaging and denser integration reduce maximum
+cup lift to about 1.21 and 0.71 cm. Small normalized-MAE improvements do not
+justify adopting a candidate.
+
+CPU-only state-encoder comparisons across five checkpoints are consistent
+with the current padded input layout, but cannot prove historical semantics.
+All diagnostic jobs exited. One failed CPU-only launcher path attempt is
+retained alongside its successful retry. All 1505 sealed source hashes and
+four release tests passed locally and remotely. No original weights, sealed
+sources, dataset metadata, shared environment, or unrelated jobs were changed.
+
+## Completed Precheck
+
+The cutting-board-to-pan task completed one whole episode: 60 finite action
+chunks of shape [1, 12, 29], with up to 12 simulator steps per chunk and a
+720-step episode cap.
+The task outcome was 0/1; elapsed simulation time was
+130.46 seconds. This single episode is a runtime
+check, not an estimate of the 24-task mean.
+
+The first attempt used GPU 0 for both policy and rendering and aborted in MuJoCo read_pixels after 40 action calls. No new kernel Xid was observed. The successful end-to-end retest kept policy inference on GPU 0 and moved simulation CUDA/EGL to GPU 1 through the archived host-only sim-python-render1 wrapper. The original failed evidence is retained; no model or task source was changed.
+
+## Protocol And Environment
+
+The stopped sweep requested 24 tasks with 50 episodes each, n_envs=1,
+720 maximum simulator steps, action chunks of 12, shift=5.0, and
+the historical top-level inference argument of 5. The action head actually
+uses its saved `num_inference_timesteps=20`; the top-level argument is not
+forwarded to that action branch. As in the original scripts, no seed was
+applied. Independent unseeded reruns are not bitwise-identical reproductions.
+
+Full-run video encoding was disabled. Camera observation rendering and
+future-image inference were enabled. Precheck videos remain on the server.
+
+The repository's sealed sources and the 44,901 simulation asset files were
+verified. The pinned policy and simulation environments passed their CPU
+doctor checks. Simulation uses the rebuilt KDL/PyKDL 1.5.4 rather than this
+host's system KDL 1.5.1. Host-native NVIDIA EGL libraries are used; no driver
+reset, replacement, or other user's process management was performed.
+
+Code was copied from the latest case-safe Mac release. Existing checkpoints,
+backbone caches, environments, and simulation assets were reused on the shared
+filesystem, with new per-host runtime configs in an isolated directory.
+
+Initial evidence is in `provenance/validation/perdon_hou_20260925T143800Z/`.
+Its original status snapshots predate the user-requested stop; the new
+open-loop evidence contains the stop record and updated process snapshot.
+Incomplete runs must not be reported as the full benchmark.
+
+Clean-machine installation remains unvalidated. The owner has now authorized
+private publication; upload completion is recorded separately in publication receipts.
diff --git a/checkpoints/README.md b/checkpoints/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..0575b4021a2998c82be7a77c698840be2182d82d
--- /dev/null
+++ b/checkpoints/README.md
@@ -0,0 +1,9 @@
+# Selected Checkpoint
+
+Filename: `steps_280000_pytorch_model.pt`.
+
+Bytes: 24232783701
+
+SHA-256: `eeba9505f715b582a054baac1ef5b599f1da225cabcc060631c23f2f47affe6c`
+
+Included in private repository `mxk1998/WM4A`. Run `hf download mxk1998/WM4A --local-dir WM4A` to download code, metadata, assets, and weights together. Original source provenance is retained in `release_manifest.json`.
diff --git a/deployment/__init__.py b/deployment/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/deployment/model_server/README.md b/deployment/model_server/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..e14aa352b71b39cb34149e20885b6a9de7c7d651
--- /dev/null
+++ b/deployment/model_server/README.md
@@ -0,0 +1,22 @@
+
+# start policy server
+
+
+```bash
+
+your_ckpt=./results/Checkpoints/1003_qwenfast/checkpoints/steps_50000_pytorch_model.pt
+
+python deployment/model_server/server_policy.py \
+ --ckpt_path ${your_ckpt} \
+ --port 10093 \
+ --use_bf16
+```
+
+
+# connect to policy server for debug
+
+```bash
+python deployment/model_server/debug_server_policy.py
+
+# plus server_policy.py into your vla controler by ref to debug_server_policy.py
+```
\ No newline at end of file
diff --git a/deployment/model_server/__init__.py b/deployment/model_server/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/deployment/model_server/server_policy.py b/deployment/model_server/server_policy.py
new file mode 100644
index 0000000000000000000000000000000000000000..4596e376821a84c0121dca56290e58081503b93b
--- /dev/null
+++ b/deployment/model_server/server_policy.py
@@ -0,0 +1,70 @@
+# Copyright 2025 starVLA community. All rights reserved.
+# Licensed under the MIT License, Version 1.0 (the "License");
+# Implemented by [Jinhui YE / HKUST University] in [2025].
+
+import logging
+import socket
+import argparse
+from deployment.model_server.tools.websocket_policy_server import WebsocketPolicyServer
+from starVLA.model.framework.base_framework import baseframework
+import torch, os
+
+
+def main(args) -> None:
+ # Example usage:
+ # policy = YourPolicyClass() # Replace with your actual policy class
+ # server = WebsocketPolicyServer(policy, host="localhost", port=10091)
+ # server.serve_forever()
+
+ vla = baseframework.from_pretrained( # TODO should auto detect framework from model path
+ args.ckpt_path,
+ )
+
+ if args.use_bf16: # False
+ vla = vla.to(torch.bfloat16)
+ vla = vla.to("cuda").eval()
+
+ hostname = socket.gethostname()
+ local_ip = socket.gethostbyname(hostname)
+ logging.info("Creating server (host: %s, ip: %s)", hostname, local_ip)
+
+ # start websocket server
+ server = WebsocketPolicyServer(
+ policy=vla,
+ host="0.0.0.0",
+ port=args.port,
+ idle_timeout=args.idle_timeout,
+ metadata={"env": "simpler_env"},
+ )
+ logging.info("server running ...")
+ server.serve_forever()
+
+
+def build_argparser():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--ckpt_path", type=str, default="Qwen/Qwen2.5-VL-3B-Instruct")
+ parser.add_argument("--port", type=int, default=10093)
+ parser.add_argument("--use_bf16", action="store_true")
+ parser.add_argument("--idle_timeout" , type=int, default=1800, help="Idle timeout in seconds, -1 means never close")
+ return parser
+
+
+def start_debugpy_once():
+ """start debugpy once"""
+ import debugpy
+ if getattr(start_debugpy_once, "_started", False):
+ return
+ debugpy.listen(("0.0.0.0", 10095))
+ print("🔍 Waiting for VSCode attach on 0.0.0.0:10095 ...")
+ debugpy.wait_for_client()
+ start_debugpy_once._started = True
+
+
+if __name__ == "__main__":
+ logging.basicConfig(level=logging.INFO, force=True)
+ parser = build_argparser()
+ args = parser.parse_args()
+ if os.getenv("DEBUG", False):
+ print("🔍 DEBUGPY is enabled")
+ start_debugpy_once()
+ main(args)
\ No newline at end of file
diff --git a/deployment/model_server/tools/__init__.py b/deployment/model_server/tools/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/deployment/model_server/tools/debug_server_policy.py b/deployment/model_server/tools/debug_server_policy.py
new file mode 100644
index 0000000000000000000000000000000000000000..5af00c7c01bc66a8f5b303c25d9226c5df94ac0c
--- /dev/null
+++ b/deployment/model_server/tools/debug_server_policy.py
@@ -0,0 +1,91 @@
+"""
+Debug / smoke-test client for deployment/model_server/server_policy.py.
+
+Purpose:
+ - Establish a WebSocket connection to the policy server.
+ - Initialize device on the server side.
+ - Optionally run a very simple inference request to verify end-to-end transport
+ (serialization + server handling).
+
+Usage example:
+ python debug_server_policy.py --host 127.0.0.1 --port 10093 --device cuda --test infer
+
+Notes:
+ - The random observation is synthetic and only meant to validate the interface.
+ - Adjust keys (e.g. 'images', 'task_description') to match the server's expected schema.
+"""
+
+import argparse
+import logging
+import numpy as np
+
+
+from tools.websocket_policy_client import WebsocketClientPolicy
+
+
+def _build_argparser() -> argparse.ArgumentParser:
+ ap = argparse.ArgumentParser(description="WebSocket policy client smoke test (msgpack protocol)")
+ ap.add_argument("--host", default="127.0.0.1", help="server hostname/IP (do not use 0.0.0.0)")
+ ap.add_argument("--port", type=int, default=10093, help="server port")
+ ap.add_argument("--api_key", default="", help="optional: API key for authentication")
+ ap.add_argument("--device", default="cuda", choices=["cuda", "cpu"], help="initialize device")
+ ap.add_argument(
+ "--test", choices=["init", "infer"], default="infer", help="test mode: only initialize, or try simple inference"
+ )
+ ap.add_argument("--log_level", default="INFO")
+ return ap
+
+
+def _main():
+ args = _build_argparser().parse_args()
+ logging.basicConfig(level=getattr(logging, args.log_level.upper(), logging.INFO), force=True)
+
+ client = WebsocketClientPolicy(host=args.host, port=args.port, api_key=(args.api_key or None))
+ logging.info("Connected. Server metadata: %s", client.get_server_metadata())
+
+ # 1) device initialization
+ init_ret = client.init_device(args.device) # here to set some things on the server
+ logging.info("Init device resp: %s", init_ret)
+
+ # 2) optional: try one simple inference
+ if args.test == "infer":
+ try:
+ # build observation aligned with model API
+ H, W = 224, 224
+ img = np.random.randint(0, 256, (H, W, 3), dtype=np.uint8)
+ wrist_img = np.random.randint(0, 256, (H, W, 3), dtype=np.uint8)
+ state = np.zeros((7,), dtype=np.float32) # [x,y,z, ax,ay,az, gripper]
+
+ observation = { # key to align with model API
+ "request_id": "smoke-test",
+ "observation.primary": np.expand_dims(img, axis=0), # (1,H,W,C), uint8 0-255
+ "observation.wrist_image": np.expand_dims(wrist_img, axis=0), # (1,H,W,C)
+ "observation.state": np.expand_dims(state, axis=0), # (1,7), float32
+ "instruction": ["debug: pick up the red block"], # single element list
+ }
+
+ image_path = "assets/table.jpeg"
+ # read image as PIL
+ from PIL import Image
+ image_primary = Image.open(image_path).convert("RGB")
+ # Convert PIL -> numpy uint8 (H,W,3)
+ image_primary_np = np.asarray(image_primary, dtype=np.uint8)
+
+ instruction_lang="pick up the red block"
+ obs = {
+ "request_id": "smoke-test",
+ "batch_images": [[image_primary_np]],
+ "instructions": [instruction_lang], # assume batch task description
+ }
+
+ infer_ret = client.infer(obs)
+ logging.info("Infer resp: %s", infer_ret)
+ except Exception as e:
+ logging.error("Infer error (this still proves transport OK): %s", e)
+
+ client.close()
+ logging.info("Smoke test done.")
+
+
+if __name__ == "__main__":
+ _main()
diff --git a/deployment/model_server/tools/image_tools.py b/deployment/model_server/tools/image_tools.py
new file mode 100644
index 0000000000000000000000000000000000000000..a725d317243cf62cc5e971d46fa273351423e5b7
--- /dev/null
+++ b/deployment/model_server/tools/image_tools.py
@@ -0,0 +1,119 @@
+import numpy as np
+from PIL import Image
+
+
+def convert_to_uint8(img: np.ndarray) -> np.ndarray:
+ """Converts an image to uint8 if it is a float image.
+
+ This is important for reducing the size of the image when sending it over the network.
+ """
+ if np.issubdtype(img.dtype, np.floating):
+ img = (255 * img).astype(np.uint8)
+ return img
+
+
+def resize_with_pad(images: np.ndarray, height: int, width: int, method=Image.BILINEAR) -> np.ndarray:
+ """Replicates tf.image.resize_with_pad for multiple images using PIL. Resizes a batch of images to a target height.
+
+ Args:
+ images: A batch of images in [..., height, width, channel] format.
+ height: The target height of the image.
+ width: The target width of the image.
+ method: The interpolation method to use. Default is bilinear.
+
+ Returns:
+ The resized images in [..., height, width, channel].
+ """
+ # If the images are already the correct size, return them as is.
+ if images.shape[-3:-1] == (height, width):
+ return images
+
+ original_shape = images.shape
+
+ images = images.reshape(-1, *original_shape[-3:])
+ resized = np.stack([_resize_with_pad_pil(Image.fromarray(im), height, width, method=method) for im in images])
+ return resized.reshape(*original_shape[:-3], *resized.shape[-3:])
+
+
+def _resize_with_pad_pil(image: Image.Image, height: int, width: int, method: int) -> Image.Image:
+ """Replicates tf.image.resize_with_pad for one image using PIL. Resizes an image to a target height and
+ width without distortion by padding with zeros.
+
+ Unlike the jax version, note that PIL uses [width, height, channel] ordering instead of [batch, h, w, c].
+ """
+ cur_width, cur_height = image.size
+ if cur_width == width and cur_height == height:
+ return image # No need to resize if the image is already the correct size.
+
+ ratio = max(cur_width / width, cur_height / height)
+ resized_height = int(cur_height / ratio)
+ resized_width = int(cur_width / ratio)
+ resized_image = image.resize((resized_width, resized_height), resample=method)
+
+ zero_image = Image.new(resized_image.mode, (width, height), 0)
+ pad_height = max(0, int((height - resized_height) / 2))
+ pad_width = max(0, int((width - resized_width) / 2))
+ zero_image.paste(resized_image, (pad_width, pad_height))
+ assert zero_image.size == (width, height)
+ return zero_image
+
+from typing import Sequence, Union, List, Tuple, Any
+def to_pil_preserve(images: Any, scale_float: bool = True):
+ """
+ Convert (possibly nested) numpy image arrays back to PIL.Image WITHOUT changing spatial shape
+ or nesting structure.
+
+ Accepts:
+ - np.ndarray with shape (H, W, C), C in {1,3,4}, dtype uint8 or float
+ - PIL.Image.Image (returned as-is)
+ - Nested list / tuple structures containing the above
+
+ Guarantees:
+ - No resize / pad / crop performed
+ - Returns an object with the SAME nesting layout (list -> list, tuple -> tuple)
+ - Only dtype (float -> uint8) and channel-mode adaptation may happen
+ * float arrays assumed in [0,1] if scale_float=True (scaled *255 + clip)
+ Args:
+ images: input object / sequence
+ scale_float: whether to scale float images in [0,1] to uint8
+ Returns:
+ Mirrored structure with all leaf nodes as PIL.Image.Image
+ """
+ def _convert(obj):
+ # Nested containers
+ if isinstance(obj, list):
+ return [ _convert(x) for x in obj ]
+ if isinstance(obj, tuple):
+ return tuple(_convert(x) for x in obj)
+
+ # PIL stays
+ if isinstance(obj, Image.Image):
+ return obj
+
+ # numpy -> PIL
+ if isinstance(obj, np.ndarray):
+ arr = obj
+ if arr.ndim != 3:
+ raise ValueError(f"Expected 3D array (H,W,C), got shape={arr.shape}")
+ if arr.shape[2] not in (1,3,4):
+ raise ValueError(f"Channel count must be 1/3/4, got {arr.shape[2]}")
+ if np.issubdtype(arr.dtype, np.floating):
+ if scale_float:
+ arr = np.clip(arr, 0.0, 1.0)
+ arr = (arr * 255.0 + 0.5).astype(np.uint8)
+ else:
+ raise TypeError("Float array provided but scale_float=False")
+ elif arr.dtype != np.uint8:
+ arr = arr.astype(np.uint8)
+
+ # Single channel -> 'L'
+ if arr.shape[2] == 1:
+ arr = arr[:, :, 0]
+ return Image.fromarray(arr, mode="L")
+ # 3 channels -> RGB, 4 -> RGBA
+ mode = "RGB" if arr.shape[2] == 3 else "RGBA"
+ return Image.fromarray(arr, mode=mode)
+
+ raise TypeError(f"Unsupported element type: {type(obj)}")
+
+ return _convert(images)
\ No newline at end of file
diff --git a/deployment/model_server/tools/msgpack_numpy.py b/deployment/model_server/tools/msgpack_numpy.py
new file mode 100644
index 0000000000000000000000000000000000000000..007f755edf54565579376b077eec7f7f715e1b96
--- /dev/null
+++ b/deployment/model_server/tools/msgpack_numpy.py
@@ -0,0 +1,57 @@
+"""Adds NumPy array support to msgpack.
+
+msgpack is good for (de)serializing data over a network for multiple reasons:
+- msgpack is secure (as opposed to pickle/dill/etc which allow for arbitrary code execution)
+- msgpack is widely used and has good cross-language support
+- msgpack does not require a schema (as opposed to protobuf/flatbuffers/etc) which is convenient in dynamically typed
+ languages like Python and JavaScript
+- msgpack is fast and efficient (as opposed to readable formats like JSON/YAML/etc); I found that msgpack was ~4x faster
+ than pickle for serializing large arrays using the below strategy
+
+The code below is adapted from https://github.com/lebedov/msgpack-numpy. The reason not to use that library directly is
+that it falls back to pickle for object arrays.
+"""
+
+import functools
+
+import msgpack
+import numpy as np
+
+
+def pack_array(obj):
+ if (isinstance(obj, (np.ndarray, np.generic))) and obj.dtype.kind in ("V", "O", "c"):
+ raise ValueError(f"Unsupported dtype: {obj.dtype}")
+
+ if isinstance(obj, np.ndarray):
+ return {
+ b"__ndarray__": True,
+ b"data": obj.tobytes(),
+ b"dtype": obj.dtype.str,
+ b"shape": obj.shape,
+ }
+
+ if isinstance(obj, np.generic):
+ return {
+ b"__npgeneric__": True,
+ b"data": obj.item(),
+ b"dtype": obj.dtype.str,
+ }
+
+ return obj
+
+
+def unpack_array(obj):
+ if b"__ndarray__" in obj:
+ return np.ndarray(buffer=obj[b"data"], dtype=np.dtype(obj[b"dtype"]), shape=obj[b"shape"])
+
+ if b"__npgeneric__" in obj:
+ return np.dtype(obj[b"dtype"]).type(obj[b"data"])
+
+ return obj
+
+
+Packer = functools.partial(msgpack.Packer, default=pack_array)
+packb = functools.partial(msgpack.packb, default=pack_array)
+
+Unpacker = functools.partial(msgpack.Unpacker, object_hook=unpack_array)
+unpackb = functools.partial(msgpack.unpackb, object_hook=unpack_array)
diff --git a/deployment/model_server/tools/websocket_policy_client.py b/deployment/model_server/tools/websocket_policy_client.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b1291acf41e9e745b80920d41ef82235a1558b7
--- /dev/null
+++ b/deployment/model_server/tools/websocket_policy_client.py
@@ -0,0 +1,77 @@
+# Copyright 2025 starVLA community. All rights reserved.
+# Licensed under the MIT License, Version 1.0 (the "License");
+# Implemented by [Jinhui YE / HKUST University] in [2025].
+
+import logging, argparse
+import time, os
+from typing import Dict, Optional, Tuple
+
+from typing_extensions import override
+import websockets.sync.client
+
+from . import msgpack_numpy
+
+
+class WebsocketClientPolicy:
+ """Implements the Policy interface by communicating with a server over websocket.
+
+ See WebsocketPolicyServer for a corresponding server implementation.
+ """
+
+ def __init__(self, host: str = "127.0.0.1", port: Optional[int] = 10093, api_key: Optional[str] = None) -> None:
+ # 0.0.0.0 cannot be used as a connection target, here default 127.0.0.1
+ self._uri = f"ws://{host}"
+ if port is not None:
+ self._uri += f":{port}"
+ self._packer = msgpack_numpy.Packer()
+ self._api_key = api_key
+ self._ws, self._server_metadata = self._wait_for_server()
+
+ def get_server_metadata(self) -> Dict:
+ return self._server_metadata
+
+ def _wait_for_server(self, timeout: float = 300) -> Tuple[websockets.sync.client.ClientConnection, Dict]:
+ logging.info(f"Waiting for server at {self._uri}...")
+ start_time = time.time()
+
+ for k in ("HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"):
+ os.environ.pop(k, None)
+
+ while True:
+ if time.time() - start_time > timeout:
+ raise TimeoutError(f"Failed to connect to server within {timeout} seconds")
+
+ try:
+ headers = {"Authorization": f"Api-Key {self._api_key}"} if self._api_key else None
+ conn = websockets.sync.client.connect(
+ self._uri,
+ compression=None,
+ max_size=None,
+ additional_headers=headers,
+ open_timeout=150,
+ ping_interval=20,
+ ping_timeout=20,
+ )
+ metadata = msgpack_numpy.unpackb(conn.recv())
+ return conn, metadata
+ except ConnectionRefusedError:
+ logging.info(f"Still waiting for server {self._uri} ...")
+ time.sleep(2)
+
+ def close(self) -> None:
+ try:
+ self._ws.close()
+ except Exception:
+ pass
+
+ @override
+ def predict_action(self, query_info: Dict) -> Dict:
+ data = self._packer.pack(query_info)
+ self._ws.send(data)
+ response = self._ws.recv()
+ if isinstance(response, str):
+ raise RuntimeError(f"Error in inference server:\n{response}")
+ return msgpack_numpy.unpackb(response)
+
+
+
diff --git a/deployment/model_server/tools/websocket_policy_server.py b/deployment/model_server/tools/websocket_policy_server.py
new file mode 100644
index 0000000000000000000000000000000000000000..b93af67407a6f1b146a8ab95d8934a892793fd59
--- /dev/null
+++ b/deployment/model_server/tools/websocket_policy_server.py
@@ -0,0 +1,179 @@
+# Copyright 2025 starVLA community. All rights reserved.
+# Licensed under the MIT License, Version 1.0 (the "License");
+# Implemented by [Jinhui YE / HKUST University] in [2025].
+
+import asyncio
+import logging
+import traceback
+import time
+
+import numpy as np
+import torch
+import websockets.asyncio.server
+import websockets.frames
+from PIL import Image
+
+# from openpi_client import base_policy as _base_policy
+from . import msgpack_numpy
+
+class WebsocketPolicyServer:
+ """Serves a policy using the websocket protocol. See websocket_client_policy.py for a client implementation.
+
+ Currently only implements the `load` and `infer` methods.
+ """
+
+ def __init__(
+ self,
+ policy,
+ host: str = "0.0.0.0",
+ port: int = 10093,
+ idle_timeout: int = -1, # 新增参数,单位秒,-1表示永不关闭
+ metadata: dict | None = None,
+
+ ) -> None:
+ self._policy = policy #
+ self._host = host
+ self._port = port
+ self._metadata = metadata or {}
+ self._idle_timeout = idle_timeout
+ self._last_active = time.time()
+ logging.getLogger("websockets.server").setLevel(logging.INFO)
+
+ def serve_forever(self) -> None:
+ asyncio.run(self.run())
+
+ @staticmethod
+ def _make_msgpack_safe(obj):
+ """Convert common model outputs into msgpack-serializable objects."""
+ if isinstance(obj, Image.Image):
+ return np.asarray(obj.convert("RGB"))
+ if isinstance(obj, torch.Tensor):
+ return obj.detach().cpu().numpy()
+ if isinstance(obj, dict):
+ return {key: WebsocketPolicyServer._make_msgpack_safe(value) for key, value in obj.items()}
+ if isinstance(obj, list):
+ return [WebsocketPolicyServer._make_msgpack_safe(value) for value in obj]
+ if isinstance(obj, tuple):
+ return tuple(WebsocketPolicyServer._make_msgpack_safe(value) for value in obj)
+ return obj
+
+ async def run(self):
+ async with websockets.asyncio.server.serve(
+ self._handler,
+ self._host,
+ self._port,
+ compression=None,
+ max_size=None,
+ ) as server:
+ if self._idle_timeout > 0:
+ await self._idle_watchdog(server)
+ else:
+ await server.serve_forever()
+
+ async def _idle_watchdog(self, server):
+ """监控空闲时间,超时则关闭服务器"""
+ while True:
+ await asyncio.sleep(5)
+ if time.time() - self._last_active > self._idle_timeout:
+ logging.info(f"Idle timeout ({self._idle_timeout}s) reached, shutting down server.")
+ server.close()
+ await server.wait_closed()
+ break
+
+ async def _handler(self, websocket: websockets.asyncio.server.ServerConnection):
+ logging.info(f"Connection from {websocket.remote_address} opened")
+ packer = msgpack_numpy.Packer()
+
+ await websocket.send(packer.pack(self._metadata))
+
+ while True:
+ try:
+ msg = msgpack_numpy.unpackb(await websocket.recv())
+ self._last_active = time.time() # 每次收到消息刷新活跃时间
+ ret = self._route_message(msg) # route message
+ await websocket.send(packer.pack(ret))
+ except websockets.ConnectionClosed:
+ logging.info(f"Connection from {websocket.remote_address} closed")
+ break
+ except Exception:
+ await websocket.send(traceback.format_exc())
+ await websocket.close(
+ code=websockets.frames.CloseCode.INTERNAL_ERROR,
+ reason="Internal server error. Traceback included in previous frame.",
+ )
+ raise
+
+ # route logic: recognize request from client
+ def _route_message(self, msg: dict) -> dict:
+ """
+ Route rules (fault-tolerant):
+ - Supports messages of form:
+ {"type": "ping|init|infer|reset", "request_id": "...", "payload": {...}}
+ or a flat dict (will be treated as payload).
+ - Does NOT raise inside this function: all exceptions are caught and encoded in response.
+ """
+ req_id = msg.get("request_id", "default")
+ mtype = msg.get("type", "infer") # default = infer
+ msg # when no explicit payload, treat top-level as payload
+
+ # ping
+ if mtype == "ping":
+ return {"status": "ok", "ok": True, "type": "ping", "request_id": req_id}
+
+ # infer --> framework.predict_action
+ elif mtype == "infer" or mtype == "predict_action":
+ # Basic payload sanity
+ if not isinstance(msg, dict):
+ return {
+ "status": "error",
+ "ok": False,
+ "type": "inference_result",
+ "request_id": req_id,
+ "error": {"message": "Payload must be a dict", "payload_type": str(type(payload))}
+ }
+ try:
+
+ ouput_dict = self._policy.predict_action(**msg)
+ except Exception as e:
+ logging.exception("Policy inference error (request_id=%s)", req_id)
+ logging.exception(e)
+
+ return {
+ "status": "error",
+ "ok": False,
+ "type": "inference_result",
+ "request_id": req_id,
+ "error": {
+ "message": str(e),
+ # "traceback": traceback.format_exc(),
+ },
+ }
+ data = self._make_msgpack_safe(ouput_dict)
+ return {
+ "status": "ok",
+ "ok": True,
+ "type": "inference_result",
+ "request_id": req_id,
+ "data": data,
+ }
+
+ # unknow request type
+ else:
+ return {
+ "status": "error",
+ "ok": False,
+ "type": "unknown",
+ "request_id": req_id,
+ "error": {"message": f"Unsupported message type '{mtype}'"},
+ }
+
+
+if __name__ == "__main__":
+ logging.basicConfig(level=logging.INFO, force=True)
+ # Example usage:
+ # policy = YourPolicyClass() # Replace with your actual policy class
+ # server = WebsocketPolicyServer(policy, host="localhost", port=10091)
+ # server.serve_forever()
+ raise NotImplementedError("This module is not intended to be run directly.")
+#
+# Instead, it should be imported and used in a server context.
diff --git a/deployment/readme-deployment.md b/deployment/readme-deployment.md
new file mode 100644
index 0000000000000000000000000000000000000000..1c48b7693ca62266d8a4aa108064d4e8240dc1fa
--- /dev/null
+++ b/deployment/readme-deployment.md
@@ -0,0 +1,11 @@
+sudo ip addr add 172.16.0.100/24 dev enx207bd51a3217
+sudo ip link set enx207bd51a3217 up
+ping 172.16.0.2
+
+
+python -m real_deployment.model_controller_del_ee
+
+
+## install frankx
+conda install frankx
+unzip frankx.zip
\ No newline at end of file
diff --git a/deployment/real_infer/open_loop_eval.py b/deployment/real_infer/open_loop_eval.py
new file mode 100644
index 0000000000000000000000000000000000000000..33ecdf84e122b65301c2e1d5ff7196471b84a901
--- /dev/null
+++ b/deployment/real_infer/open_loop_eval.py
@@ -0,0 +1,315 @@
+import os
+import sys
+import time
+from pathlib import Path
+from dataclasses import dataclass, field
+from typing import Dict, List, Optional
+
+import numpy as np
+import matplotlib.pyplot as plt
+import torch
+from omegaconf import OmegaConf
+import tyro
+
+# ====== 你项目里的 import(按你现有路径保留)======
+from starVLA.dataloader.lerobot_datasets import get_vla_dataset, collate_fn
+from starVLA.model.framework.base_framework import baseframework
+from starVLA.model.framework.share_tools import read_mode_config
+
+
+# -----------------------------
+# 1) 你已有的归一化/反归一化逻辑(原封不动)
+# -----------------------------
+def _minmax_to_minus1_1(x: np.ndarray, stats: dict, eps: float = 1e-6) -> np.ndarray:
+ lo = np.asarray(stats["min"], dtype=np.float32)
+ hi = np.asarray(stats["max"], dtype=np.float32)
+ denom = np.maximum(hi - lo, eps)
+ x01 = (x - lo) / denom
+ xn = x01 * 2.0 - 1.0
+ return xn.astype(np.float32)
+
+
+def unnormalize_actions(normalized_actions: np.ndarray, action_norm_stats: Dict[str, np.ndarray]) -> np.ndarray:
+ mask = action_norm_stats.get("mask", np.ones_like(action_norm_stats["min"], dtype=bool))
+ action_high, action_low = np.array(action_norm_stats["max"]), np.array(action_norm_stats["min"])
+ normalized_actions = np.clip(normalized_actions, -1, 1)
+ actions = np.where(
+ mask,
+ (normalized_actions + 1) / 2 * (action_high - action_low) + action_low,
+ normalized_actions,
+ )
+ return actions
+
+
+# -----------------------------
+# 2) Args(按你 server 的 Args 简化必要项)
+# -----------------------------
+@dataclass
+class Args:
+ ckpt_path: str = "outputs/suqian_post_train_w_state/checkpoints/steps_80000_pytorch_model.pt"
+ unnorm_key: str = "agibot_genie1"
+ gripper_threshold: float = 0.5
+
+
+def _build_policy(args: Args):
+ vla = baseframework.from_pretrained(args.ckpt_path)
+ vla = vla.to("cuda").eval()
+
+ cfg, norm_stats = read_mode_config(Path(args.ckpt_path))
+ unnorm_key = args.unnorm_key
+ cfg = OmegaConf.create(cfg)
+
+ vla.action_norm_stats = norm_stats[unnorm_key]["action"]
+ vla.state_norm_stats = norm_stats[unnorm_key]["state"]
+ return vla, cfg
+
+
+def _infer_single(policy, obs: Dict, args: Args, gripper_th: float) -> Dict:
+ prompt = obs.get("prompt", "")
+
+ state = np.asarray(obs["observation/state"], dtype=np.float32)
+ if state.ndim == 1:
+ state = state[None, :]
+ elif state.ndim != 2:
+ raise ValueError(f"Unexpected state shape: {state.shape}")
+
+ state_norm = _minmax_to_minus1_1(state, policy.state_norm_stats)
+
+ fake_data = {
+ "image": [
+ obs["observation/image"],
+ obs["observation/wrist_left_image"],
+ obs["observation/wrist_right_image"],
+ ],
+ "lang": prompt,
+ "state": state_norm,
+ }
+
+ t0 = time.perf_counter()
+ with torch.inference_mode():
+ out = policy.predict_action(fake_data)
+ infer_ms = (time.perf_counter() - t0) * 1000
+
+ na = out["normalized_actions"] # (1, 16, D)
+ na2 = na[0] # (16, D)
+
+ raw2 = unnormalize_actions(na2, policy.action_norm_stats) # (16, D)
+ actions = raw2[None, ...] # (1, 16, D)
+
+ return {"actions": actions, "policy_timing": {"infer_ms": infer_ms}}
+
+
+# -----------------------------
+# 3) 从 single_ds.get_step_data 组装 obs / gt_chunk
+# -----------------------------
+def build_obs_from_step_data(step_data: dict, single_ds) -> dict:
+ """
+ step_data: single_ds.get_step_data(traj_id, base_index) 的 RAW 输出
+ 返回:_infer_single 所需的 obs dict
+ """
+ video_keys = single_ds.modality_keys["video"]
+ if len(video_keys) < 3:
+ raise ValueError(f"Need 3 cameras, got video_keys={video_keys}")
+
+ head = step_data[video_keys[0]][0]
+ left = step_data[video_keys[1]][0]
+ right = step_data[video_keys[2]][0]
+
+ # state concat: (T, D_total) -> 取第 0 帧对应 base step
+ state_parts = [step_data[k] for k in single_ds.modality_keys["state"]]
+ state = np.concatenate(state_parts, axis=1)
+ state0 = state[0]
+
+ # language(通常是 annotation.xxx),get_language 返回 list[str]
+ lang_key = single_ds.modality_keys["language"][0]
+ lang = step_data[lang_key][0]
+ if isinstance(lang, list):
+ lang = lang[0]
+
+ obs = {
+ "observation/image": head,
+ "observation/wrist_left_image": left,
+ "observation/wrist_right_image": right,
+ "observation/state": state0,
+ "prompt": lang,
+ }
+ return obs
+
+
+def get_gt_action_chunk(step_data: dict, single_ds) -> np.ndarray:
+ action_parts = [step_data[k] for k in single_ds.modality_keys["action"]]
+ gt = np.concatenate(action_parts, axis=1) # (H, D)
+ return gt
+
+
+# -----------------------------
+# 4) rollout:拼整段 pred/gt(像 gr00t open-loop eval)
+# -----------------------------
+def rollout_open_loop(
+ single_ds,
+ pi0_policy,
+ args: Args,
+ traj_id: int,
+ steps: int = 200,
+ action_horizon: int = 16,
+):
+ """
+ 返回:
+ pred_action_across_time: (actual_steps, D)
+ gt_action_across_time: (actual_steps, D)
+ infer_ms_list: 每次推理耗时
+ """
+ traj_len = int(single_ds.trajectory_lengths[single_ds.get_trajectory_index(traj_id)])
+ actual_steps = min(steps, traj_len)
+
+ pred_list = []
+ gt_list = []
+ infer_ms_list = []
+
+ # 每 action_horizon 步推理一次,把 chunk 展开 append
+ for t in range(0, actual_steps, action_horizon):
+ step_data = single_ds.get_step_data(traj_id, t)
+
+ obs = build_obs_from_step_data(step_data, single_ds)
+ pred = _infer_single(pi0_policy, obs, args, args.gripper_threshold)
+
+ pred_chunk = pred["actions"][0] # (H, D)
+ gt_chunk = get_gt_action_chunk(step_data, single_ds) # (H, D)
+
+ # 可能最后一段不足 action_horizon(如果 traj 尾巴短),这里裁一下
+ remain = actual_steps - t
+ pred_chunk = pred_chunk[:remain]
+ gt_chunk = gt_chunk[:remain]
+
+ pred_list.append(pred_chunk)
+ gt_list.append(gt_chunk)
+ infer_ms_list.append(pred["policy_timing"]["infer_ms"])
+
+ pred_action_across_time = np.concatenate(pred_list, axis=0)
+ gt_action_across_time = np.concatenate(gt_list, axis=0)
+
+ assert pred_action_across_time.shape == gt_action_across_time.shape, (
+ f"pred={pred_action_across_time.shape}, gt={gt_action_across_time.shape}"
+ )
+ return pred_action_across_time, gt_action_across_time, infer_ms_list
+
+
+# -----------------------------
+# 5) 画图(整段轨迹)
+# -----------------------------
+def plot_action_curves(
+ gt: np.ndarray,
+ pred: np.ndarray,
+ save_path: str,
+ dims: Optional[List[int]] = None,
+ title: str = "",
+):
+ """
+ 画每个维度一张子图(很多维会很长,但 debug 很直观)
+ """
+ T, D = gt.shape
+ if dims is None:
+ dims = list(range(D))
+
+ n = len(dims)
+ fig, axes = plt.subplots(nrows=n, ncols=1, figsize=(10, 2.2 * n))
+ if n == 1:
+ axes = [axes]
+
+ fig.suptitle(title, fontsize=14)
+
+ x = np.arange(T)
+ for i, d in enumerate(dims):
+ ax = axes[i]
+ ax.plot(x, gt[:, d], label="gt")
+ ax.plot(x, pred[:, d], label="pred")
+ ax.set_ylabel(f"dim {d}")
+ ax.legend(loc="upper right")
+
+ axes[-1].set_xlabel("time step")
+ plt.tight_layout()
+ Path(save_path).parent.mkdir(parents=True, exist_ok=True)
+ plt.savefig(save_path, dpi=150)
+ plt.close(fig)
+
+
+def plot_error_over_time(gt: np.ndarray, pred: np.ndarray, save_path: str, title: str = ""):
+ """
+ 画每个时间步的 L2/MSE(按维度平均) 和 MAE(按维度平均)
+ """
+ err = pred - gt
+ mse_t = np.mean(err**2, axis=1)
+ mae_t = np.mean(np.abs(err), axis=1)
+
+ x = np.arange(len(mse_t))
+ fig = plt.figure(figsize=(10, 4))
+ plt.plot(x, mse_t, label="MSE per step")
+ plt.plot(x, mae_t, label="MAE per step")
+ plt.title(title)
+ plt.xlabel("time step")
+ plt.ylabel("error")
+ plt.legend()
+ plt.tight_layout()
+ Path(save_path).parent.mkdir(parents=True, exist_ok=True)
+ plt.savefig(save_path, dpi=150)
+ plt.close(fig)
+
+
+# -----------------------------
+# 6) main:把 dataset + policy 接起来
+# -----------------------------
+def main(args: Args):
+ # ===== 2) load policy =====
+ pi0_policy, cfg = _build_policy(args)
+ print("policy loaded")
+
+ # ===== 1) 载入训练 yaml,复用你的 dataset 配置 =====
+ vla_dataset_cfg = cfg.datasets.vla_data
+ vla_dataset_cfg.task_id = "all" # 或者某个 task_id
+ # vla_dataset_cfg.data_mix = "suqian_test"
+
+ dataset = get_vla_dataset(data_cfg=vla_dataset_cfg)
+
+ # get_vla_dataset 可能返回 mixture(里面有 datasets 列表)
+ single_ds = dataset.datasets[0] if hasattr(dataset, "datasets") else dataset
+
+ # 选一条 traj
+ traj_id = int(single_ds.trajectory_ids[0])
+ print("Using traj_id:", traj_id)
+
+ # ===== 3) rollout open-loop =====
+ pred, gt, infer_ms_list = rollout_open_loop(
+ single_ds,
+ pi0_policy,
+ args,
+ traj_id=traj_id,
+ steps=200,
+ action_horizon=30,
+ )
+
+ mse = np.mean((pred - gt) ** 2)
+ mae = np.mean(np.abs(pred - gt))
+ print(f"Open-loop MSE={mse:.6f}, MAE={mae:.6f}")
+ print(f"Infer ms: mean={np.mean(infer_ms_list):.2f}, p95={np.percentile(infer_ms_list, 95):.2f}")
+
+ out_dir = Path("outputs/open_loop_eval")
+ out_dir.mkdir(parents=True, exist_ok=True)
+
+ # ===== 4) 画图 =====
+ plot_action_curves(
+ gt, pred,
+ save_path=str(out_dir / f"traj{traj_id}_action_curves.png"),
+ # dims=list(range(min(gt.shape[1], 18))), # 你想只看前 18 维就开这行
+ title=f"traj {traj_id} action curves (T={gt.shape[0]}, D={gt.shape[1]})",
+ )
+ plot_error_over_time(
+ gt, pred,
+ save_path=str(out_dir / f"traj{traj_id}_error.png"),
+ title=f"traj {traj_id} error over time",
+ )
+
+ print("Saved plots to:", out_dir)
+
+
+if __name__ == "__main__":
+ main(tyro.cli(Args))
diff --git a/deployment/real_infer/server.py b/deployment/real_infer/server.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c2897a4ef9b83877d368fd6d035d1884ecc184a
--- /dev/null
+++ b/deployment/real_infer/server.py
@@ -0,0 +1,332 @@
+"""
+Pi0 WebSocket 推理服务端,兼容 openpi-client 客户端协议。
+
+- 使用 websockets.asyncio.server,客户端用 WebsocketClientPolicy 连接。
+- 首次连接发送 metadata(简单字典)。
+- 收到 obs 后,调用 Pi0 推理并返回 {"actions": np.ndarray, "policy_timing": {"infer_ms": ...}}。
+
+支持 joint_position 和 camera_position(通过 state 维度判断:16 -> joint,14 -> camera)。
+"""
+
+import asyncio
+import http
+import os
+import sys
+import time
+import traceback
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Dict, List, Literal, Optional
+
+import numpy as np
+import tyro
+import websockets.asyncio.server as ws_server
+import websockets.frames
+
+import torch
+
+# 兼容 protobuf 版本
+os.environ.setdefault("PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION", "python")
+
+# 路径设置
+_current_dir = Path(__file__).resolve().parent
+_project_root = _current_dir.parent
+if str(_project_root) not in sys.path:
+ sys.path.insert(0, str(_project_root))
+
+_openpi_client_src = _project_root / "workspace" / "openpi-client" / "src"
+if _openpi_client_src.exists() and str(_openpi_client_src) not in sys.path:
+ sys.path.insert(0, str(_openpi_client_src))
+
+from starVLA.model.framework.base_framework import baseframework
+from starVLA.model.framework.share_tools import read_mode_config
+from openpi_client import msgpack_numpy
+
+
+@dataclass
+class Args:
+ host: str = "0.0.0.0"
+ port: int = 8000
+
+ ckpt_path: str = "/mnt/workspace/users/yuanzhihao/code/starVLA/outputs/suqian_post_train_no_pretrain/checkpoints/steps_15000_pytorch_model.pt"
+ data_statistics_path: str = "/workspace/niejunnan/VLAPipeline_RL_BY_Niejunnan/output_train/agibot/benchmark_pro_max/ds_stats.json"
+ language_tokenizer_path: Optional[str] = "/workspace/paligemma-3b-pt-224"
+ unnorm_key: Optional[str] = "agibot_genie1"
+ policy_setup: str = "agibot_genie1"
+ obs_camera_name: List[str] = field(default_factory=lambda: ["head_color", "hand_left", "hand_right"])
+ action_scale: float = 1.0
+ use_filter: bool = False
+ use_multi_action_head: str = "raw"
+ use_arm_pose_type: str = "euler"
+ use_paligemma_original_vocab_size: bool = True
+ n_action_steps: Optional[int] = None
+ inference_mode: str = "synchronous"
+ # 兼容 pi0inference 期望的其他开关
+ use_distillation_distribution: bool = False
+ use_embodiment_id: bool = False
+ use_vit_for_action_head: bool = False
+ use_distillation: bool = False
+ use_best_of_n: bool = False
+ best_of_n: int = 32
+ use_step_action_mask_for_q: bool = False
+
+ gripper_threshold: float = 0.5
+
+
+# def _build_policy(args: Args) -> LerobotPiFastInference:
+# if not args.data_statistics_path:
+# raise ValueError("需要 --data_statistics_path")
+
+# return LerobotPiFastInference(
+# args=args,
+# saved_model_path=args.ckpt_path,
+# policy_setup=args.policy_setup,
+# action_scale=args.action_scale,
+# use_filter=args.use_filter,
+# image_name_list=args.obs_camera_name,
+# data_statistics_path=args.data_statistics_path,
+# language_tokenlizer_path=args.language_tokenizer_path,
+# unnorm_key=args.unnorm_key,
+# use_multi_action_head=args.use_multi_action_head,
+# use_arm_pose_type=args.use_arm_pose_type,
+# inference_mode=args.inference_mode,
+# )
+
+
+def _minmax_to_minus1_1(x: np.ndarray, stats: dict, eps: float = 1e-6) -> np.ndarray:
+ """
+ x: (..., D)
+ stats: contains "min" and "max" (D,)
+ return: (..., D) in [-1, 1]
+ """
+ lo = np.asarray(stats["min"], dtype=np.float32)
+ hi = np.asarray(stats["max"], dtype=np.float32)
+ denom = np.maximum(hi - lo, eps)
+ x01 = (x - lo) / denom
+ xn = x01 * 2.0 - 1.0
+ return xn.astype(np.float32)
+
+def _sincos_state(x: np.ndarray) -> np.ndarray:
+ """
+ x: (B, D) or (D,)
+ return: (B, 2D) in [-1, 1]
+ """
+ x = np.asarray(x, dtype=np.float32)
+ if x.ndim == 1:
+ x = x[None, :] # (1, D)
+ elif x.ndim != 2:
+ raise ValueError(f"Unexpected state shape: {x.shape}")
+
+ sin_x = np.sin(x)
+ cos_x = np.cos(x)
+ return np.concatenate([sin_x, cos_x], axis=-1).astype(np.float32) # (B, 2D)
+
+
+def unnormalize_actions(normalized_actions: np.ndarray, action_norm_stats: Dict[str, np.ndarray]) -> np.ndarray:
+ """
+ Args:
+ normalized_actions: shape (B, chunk, D) (chunk, D)
+ action_norm_stats:
+ Returns:
+ actions
+ """
+ mask = action_norm_stats.get("mask", np.ones_like(action_norm_stats["min"], dtype=bool))
+ action_high, action_low = np.array(action_norm_stats["max"]), np.array(action_norm_stats["min"])
+
+ normalized_actions = np.clip(normalized_actions, -1, 1)
+
+ actions = np.where(
+ mask,
+ (normalized_actions + 1) / 2 * (action_high - action_low) + action_low,
+ normalized_actions,
+ )
+
+ return actions
+
+
+def _build_policy(args: Args):
+ vla = baseframework.from_pretrained(args.ckpt_path)
+ vla = vla.to("cuda").eval()
+
+ _, norm_stats = read_mode_config(Path(args.ckpt_path))
+ unnorm_key = args.unnorm_key
+
+ # ✅ action stats(你原来就有)
+ vla.action_norm_stats = norm_stats[unnorm_key]["action"]
+
+ # ✅ state stats(新增:用于输入归一化,训练一致)
+ vla.state_norm_stats = norm_stats[unnorm_key]["state"]
+
+ return vla
+
+
+def _infer_single(policy, obs: Dict, args: Args, gripper_th: float) -> Dict:
+ prompt = obs.get("prompt", "")
+ print("prompt", prompt)
+
+ # -------- state: raw -> normalized (min_max to [-1,1]) --------
+ state = np.asarray(obs["observation/state"], dtype=np.float32)
+ print('state', state.shape, state)
+ if state.ndim == 1:
+ state = state[None, :] # (1, D)
+ elif state.ndim != 2:
+ raise ValueError(f"Unexpected state shape: {state.shape}")
+
+ # ✅ 训练一致:min_max 归一化
+ state_norm = _minmax_to_minus1_1(state, policy.state_norm_stats)
+
+ fake_data = {
+ "image": [
+ obs["observation/image"],
+ obs["observation/wrist_left_image"],
+ obs["observation/wrist_right_image"],
+ ],
+ "lang": prompt,
+ "state": state_norm, # ✅ 用归一化后的 state
+ }
+
+ print('img', obs["observation/image"].shape)
+ raw = state
+ sn = state_norm
+ print("state raw min/max:", raw.min(), raw.max())
+ print("state_norm min/max:", sn.min(), sn.max(), "clip_ratio:", np.mean((sn <= -0.999) | (sn >= 0.999)))
+
+ t0 = time.perf_counter()
+ with torch.inference_mode():
+ out = policy.predict_action(fake_data)
+ infer_ms = (time.perf_counter() - t0) * 1000
+
+ # out 来自 predict_action
+ na = out["normalized_actions"] # (1, 16, 18) numpy
+
+ # 1️⃣ 去掉 batch 维
+ na2 = na[0] # (16, 18)
+
+ # 2️⃣ 用 numpy 版 unnormalize(CPU)
+ raw2 = unnormalize_actions(
+ na2,
+ policy.action_norm_stats,
+ ) # (16, 18)
+
+ # 3️⃣ 如有需要再加回 batch 维
+ actions = raw2[None, ...] # (1, 16, 18)
+ print(actions[0, 0])
+
+ return {"actions": actions, "policy_timing": {"infer_ms": infer_ms}}
+
+def _health_check(connection: ws_server.ServerConnection, request: ws_server.Request):
+ """健康检查端点"""
+ if request.path == "/healthz":
+ return connection.respond(http.HTTPStatus.OK, "OK\n")
+ return None
+
+
+class Pi0PolicyServer:
+ """Pi0 WebSocket 推理服务端"""
+
+ def __init__(self, pi0_policy, args: Args):
+ self._policy = pi0_policy
+ self._args = args
+ self._metadata = {
+ "status": "ok",
+ "policy": "pi0",
+ "obs_cameras": args.obs_camera_name,
+ "action_dim": 14,
+ }
+ self._packer = msgpack_numpy.Packer()
+
+ def serve_forever(self) -> None:
+ """阻塞式启动服务"""
+ asyncio.run(self._run())
+
+ async def _run(self):
+ """异步运行服务"""
+ async with ws_server.serve(
+ self._handler,
+ self._args.host,
+ self._args.port,
+ compression=None,
+ max_size=None,
+ process_request=_health_check,
+ ) as server:
+ print("✓ 服务已启动,等待客户端连接...")
+ await server.serve_forever()
+
+ async def _handler(self, websocket: ws_server.ServerConnection):
+ """处理单个客户端连接"""
+ print(f"[连接] 客户端 {websocket.remote_address} 已连接")
+
+ # 发送 metadata
+ await websocket.send(self._packer.pack(self._metadata))
+
+ while True:
+ try:
+ data = await websocket.recv()
+ if isinstance(data, str):
+ await websocket.send(f"Invalid data type: {type(data)}")
+ continue
+
+ obs = msgpack_numpy.unpackb(data)
+ result = _infer_single(self._policy, obs, self._args, self._args.gripper_threshold)
+ await websocket.send(self._packer.pack(result))
+
+ except websockets.ConnectionClosed:
+ print(f"[断开] 客户端 {websocket.remote_address} 已断开")
+ break
+ except Exception:
+ error_msg = traceback.format_exc()
+ print(f"[错误] {error_msg}")
+ await websocket.send(error_msg)
+ await websocket.close(
+ code=websockets.frames.CloseCode.INTERNAL_ERROR,
+ reason="Internal server error",
+ )
+ raise
+
+
+def serve(args: Args):
+ print("=" * 60)
+ print("Pi0 WebSocket 推理服务端 (openpi-client 兼容)")
+ print("=" * 60)
+ print(f" 监听: ws://{args.host}:{args.port}")
+ print(f" 权重: {args.ckpt_path}")
+ print(f" 数据统计: {args.data_statistics_path}")
+ print(f" 相机键: {args.obs_camera_name}")
+ print(f" unnorm_key: {args.unnorm_key}")
+ print(f" tokenizer: {args.language_tokenizer_path}")
+ print("=" * 60)
+
+ print("[1/2] 初始化模型...")
+ pi0_policy = _build_policy(args)
+ print("✓ 模型就绪")
+
+
+ # ===== 在这里加 =====
+ print("Has predict_action:", hasattr(pi0_policy, "predict_action"))
+ print("Has __call__:", callable(pi0_policy))
+ print("Action-related methods:",
+ [m for m in dir(pi0_policy) if "action" in m.lower()])
+
+ am = pi0_policy.action_model
+ print("past_action_window_size:", getattr(pi0_policy, "past_action_window_size", None))
+ print("future_action_window_size:", getattr(pi0_policy, "future_action_window_size", None))
+ print("action_model:", type(am))
+ print("action_model attrs (state):", [x for x in dir(am) if "state" in x.lower()])
+
+ # ===================
+
+ print("[2/2] 启动 WebSocket 服务...")
+ server = Pi0PolicyServer(pi0_policy, args)
+
+ try:
+ server.serve_forever()
+ except KeyboardInterrupt:
+ print("\n[退出] 收到中断信号,正在关闭服务...")
+
+
+def main():
+ serve(tyro.cli(Args))
+
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/deployment/upload/push_model_to_hf.py b/deployment/upload/push_model_to_hf.py
new file mode 100644
index 0000000000000000000000000000000000000000..646ca535c4f266653adb214842dd6671c6d9358f
--- /dev/null
+++ b/deployment/upload/push_model_to_hf.py
@@ -0,0 +1,12 @@
+from huggingface_hub import create_repo, HfApi
+
+# 1. create repository
+hf_name = "StarVLA/Qwen3-VL-OFT-LIBERO-4in1"
+create_repo(hf_name, repo_type="model", exist_ok=True)
+
+# 2. initialize API
+api = HfApi()
+
+# 3. upload large folder
+folder_path = "/mnt/petrelfs/yejinhui/Projects/starVLA/results/Checkpoints/1_need/Qwen3-VL-OFT-LIBERO-4in1"
+api.upload_large_folder(folder_path=folder_path, repo_id=hf_name, repo_type="model")
diff --git a/deployment_robotwin/__init__.py b/deployment_robotwin/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/deployment_robotwin/model_server/README.md b/deployment_robotwin/model_server/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..e14aa352b71b39cb34149e20885b6a9de7c7d651
--- /dev/null
+++ b/deployment_robotwin/model_server/README.md
@@ -0,0 +1,22 @@
+
+# start policy server
+
+
+```bash
+
+your_ckpt=./results/Checkpoints/1003_qwenfast/checkpoints/steps_50000_pytorch_model.pt
+
+python deployment/model_server/server_policy.py \
+ --ckpt_path ${your_ckpt} \
+ --port 10093 \
+ --use_bf16
+```
+
+
+# connect to policy server for debug
+
+```bash
+python deployment/model_server/debug_server_policy.py
+
+# plus server_policy.py into your vla controler by ref to debug_server_policy.py
+```
\ No newline at end of file
diff --git a/deployment_robotwin/model_server/__init__.py b/deployment_robotwin/model_server/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/deployment_robotwin/model_server/server_policy.py b/deployment_robotwin/model_server/server_policy.py
new file mode 100644
index 0000000000000000000000000000000000000000..619425ef59c5fcaa6a1da0ad4504dba609f68626
--- /dev/null
+++ b/deployment_robotwin/model_server/server_policy.py
@@ -0,0 +1,91 @@
+# Copyright 2025 starVLA community. All rights reserved.
+# Licensed under the MIT License, Version 1.0 (the "License");
+# Implemented by [Jinhui YE / HKUST University] in [2025].
+
+import logging
+import socket
+import argparse
+import random
+import numpy as np
+from deployment_robotwin.model_server.tools.websocket_policy_server import WebsocketPolicyServer
+from starVLA.model.framework.base_framework import baseframework
+import torch, os
+
+
+def set_seed(seed: int) -> None:
+ """Fix all possible random seeds for reproducibility.
+
+ Args:
+ seed: Random seed to use.
+ """
+ random.seed(seed)
+ np.random.seed(seed)
+ torch.manual_seed(seed)
+ torch.cuda.manual_seed(seed)
+ torch.cuda.manual_seed_all(seed)
+ torch.backends.cudnn.deterministic = True
+ torch.backends.cudnn.benchmark = False
+
+
+def main(args) -> None:
+ # Set random seeds for reproducibility
+ set_seed(args.seed)
+
+ # Example usage:
+ # policy = YourPolicyClass() # Replace with your actual policy class
+ # server = WebsocketPolicyServer(policy, host="localhost", port=10091)
+ # server.serve_forever()
+
+ vla = baseframework.from_pretrained( # TODO should auto detect framework from model path
+ args.ckpt_path,
+ )
+
+ if args.use_bf16: # False
+ vla = vla.to(torch.bfloat16)
+ vla = vla.to("cuda").eval()
+
+ hostname = socket.gethostname()
+ local_ip = socket.gethostbyname(hostname)
+ logging.info("Creating server (host: %s, ip: %s)", hostname, local_ip)
+
+ # start websocket server
+ server = WebsocketPolicyServer(
+ policy=vla,
+ host="0.0.0.0",
+ port=args.port,
+ idle_timeout=args.idle_timeout,
+ metadata={"env": "simpler_env"},
+ )
+ logging.info("server running ...")
+ server.serve_forever()
+
+
+def build_argparser():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--ckpt_path", type=str, default="Qwen/Qwen2.5-VL-3B-Instruct")
+ parser.add_argument("--port", type=int, default=10093)
+ parser.add_argument("--use_bf16", action="store_true")
+ parser.add_argument("--idle_timeout" , type=int, default=1800, help="Idle timeout in seconds, -1 means never close")
+ parser.add_argument("--seed", type=int, default=42, help="Random seed for reproducibility")
+ return parser
+
+
+def start_debugpy_once():
+ """start debugpy once"""
+ import debugpy
+ if getattr(start_debugpy_once, "_started", False):
+ return
+ debugpy.listen(("0.0.0.0", 10095))
+ print("🔍 Waiting for VSCode attach on 0.0.0.0:10095 ...")
+ debugpy.wait_for_client()
+ start_debugpy_once._started = True
+
+
+if __name__ == "__main__":
+ logging.basicConfig(level=logging.INFO, force=True)
+ parser = build_argparser()
+ args = parser.parse_args()
+ if os.getenv("DEBUG", False):
+ print("🔍 DEBUGPY is enabled")
+ start_debugpy_once()
+ main(args)
\ No newline at end of file
diff --git a/deployment_robotwin/model_server/tools/.ipynb_checkpoints/websocket_policy_client-checkpoint.py b/deployment_robotwin/model_server/tools/.ipynb_checkpoints/websocket_policy_client-checkpoint.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc3f8874dcdbdd11ff8939db7c535e4f922ed861
--- /dev/null
+++ b/deployment_robotwin/model_server/tools/.ipynb_checkpoints/websocket_policy_client-checkpoint.py
@@ -0,0 +1,149 @@
+# Copyright 2025 starVLA community. All rights reserved.
+# Licensed under the MIT License, Version 1.0 (the "License");
+# Implemented by [Jinhui YE / HKUST University] in [2025].
+
+import logging
+import os
+import time
+from typing import Dict, Optional, Tuple, Any
+
+from typing_extensions import override
+import websockets
+import websockets.sync.client
+
+from . import msgpack_numpy
+
+
+class WebsocketClientPolicy:
+ """Implements the Policy interface by communicating with a server over websocket.
+
+ See WebsocketPolicyServer for a corresponding server implementation.
+ """
+
+ def __init__(
+ self,
+ host: str = "127.0.0.1",
+ port: Optional[int] = 10093,
+ api_key: Optional[str] = None,
+ connect_timeout: float = 300.0,
+ open_timeout: float = 150.0,
+ ping_interval: Optional[float] = 30.0,
+ ping_timeout: Optional[float] = 300.0,
+ reconnect_max_attempts: int = 5,
+ ) -> None:
+ # 0.0.0.0 cannot be used as a connection target, here default 127.0.0.1
+ self._uri = f"ws://{host}"
+ if port is not None:
+ self._uri += f":{port}"
+
+ self._packer = msgpack_numpy.Packer()
+ self._api_key = api_key
+
+ self._connect_timeout = connect_timeout
+ self._open_timeout = open_timeout
+ self._ping_interval = ping_interval
+ self._ping_timeout = ping_timeout
+ self._reconnect_max_attempts = reconnect_max_attempts
+
+ self._ws, self._server_metadata = self._wait_for_server(timeout=self._connect_timeout)
+
+ def get_server_metadata(self) -> Dict:
+ return self._server_metadata
+
+ def close(self) -> None:
+ try:
+ if getattr(self, "_ws", None) is not None:
+ self._ws.close()
+ except Exception:
+ pass
+
+ def _drop_proxy_env(self) -> None:
+ # Some environments set proxies that break ws://127.0.0.1
+ for k in ("HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"):
+ os.environ.pop(k, None)
+
+ def _connect_once(self) -> Tuple[websockets.sync.client.ClientConnection, Dict[str, Any]]:
+ headers = {"Authorization": f"Api-Key {self._api_key}"} if self._api_key else None
+ conn = websockets.sync.client.connect(
+ self._uri,
+ compression=None,
+ max_size=None,
+ additional_headers=headers,
+ open_timeout=self._open_timeout,
+ ping_interval=self._ping_interval,
+ ping_timeout=self._ping_timeout,
+ close_timeout=10,
+ )
+ # First frame: metadata
+ metadata = msgpack_numpy.unpackb(conn.recv())
+ if not isinstance(metadata, dict):
+ raise RuntimeError(f"Server metadata must be dict, got: {type(metadata)}")
+ return conn, metadata
+
+ def _wait_for_server(self, timeout: float = 300.0) -> Tuple[websockets.sync.client.ClientConnection, Dict]:
+ logging.info(f"Waiting for server at {self._uri}...")
+ start_time = time.time()
+
+ self._drop_proxy_env()
+
+ backoff = 0.5 # seconds
+ while True:
+ if time.time() - start_time > timeout:
+ raise TimeoutError(f"Failed to connect to server within {timeout} seconds")
+
+ try:
+ conn, metadata = self._connect_once()
+ return conn, metadata
+ except ConnectionRefusedError:
+ logging.info(f"Still waiting for server {self._uri} ...")
+ except Exception as e:
+ logging.warning(f"Connect failed: {repr(e)}")
+
+ time.sleep(backoff)
+ backoff = min(backoff * 1.5, 5.0)
+
+ def _reconnect(self) -> None:
+ """Reconnect with limited attempts. Keeps it synchronous and simple."""
+ self.close()
+ last_err = None
+ for attempt in range(1, self._reconnect_max_attempts + 1):
+ try:
+ self._ws, self._server_metadata = self._wait_for_server(timeout=60.0)
+ return
+ except Exception as e:
+ last_err = e
+ logging.warning(f"Reconnect attempt {attempt}/{self._reconnect_max_attempts} failed: {repr(e)}")
+ raise RuntimeError(f"Failed to reconnect after {self._reconnect_max_attempts} attempts") from last_err
+
+ @override
+ def predict_action(self, query_info: Dict) -> Dict:
+ """
+ Sends a request to server. Supports both:
+ - legacy payload dict (query_info)
+ - or query_info already containing {type, request_id, payload}
+ """
+ data = self._packer.pack(query_info)
+
+ try:
+ self._ws.send(data)
+ response = self._ws.recv()
+ except websockets.exceptions.ConnectionClosedError as e:
+ logging.warning(f"WebSocket closed, reconnecting once... ({e})")
+ self._reconnect()
+ self._ws.send(data)
+ response = self._ws.recv()
+
+ if isinstance(response, str):
+ # server sent traceback text frame
+ raise RuntimeError(f"Error in inference server:\n{response}")
+
+ ret = msgpack_numpy.unpackb(response)
+ if not isinstance(ret, dict):
+ raise RuntimeError(f"Invalid response type: {type(ret)}")
+
+ # Optional: normalize error replies
+ if ret.get("ok") is False and ret.get("status") == "error":
+ err = ret.get("error", {})
+ raise RuntimeError(f"Server error: {err}")
+
+ return ret
diff --git a/deployment_robotwin/model_server/tools/.ipynb_checkpoints/websocket_policy_server-checkpoint.py b/deployment_robotwin/model_server/tools/.ipynb_checkpoints/websocket_policy_server-checkpoint.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c254a59b05f431582464d7cec74a4234e19209a
--- /dev/null
+++ b/deployment_robotwin/model_server/tools/.ipynb_checkpoints/websocket_policy_server-checkpoint.py
@@ -0,0 +1,207 @@
+# Copyright 2025 starVLA community. All rights reserved.
+# Licensed under the MIT License, Version 1.0 (the "License");
+# Implemented by [Jinhui YE / HKUST University] in [2025].
+
+import asyncio
+import logging
+import threading
+import time
+import traceback
+from typing import Any, Dict, Optional
+
+import numpy as np
+import websockets
+import websockets.asyncio.server
+import websockets.frames
+
+from . import msgpack_numpy
+
+
+def _to_serializable(obj: Any) -> Any:
+ """Recursively convert non-serializable objects (e.g. PIL Image) into
+ msgpack-friendly types so the response can be packed by msgpack_numpy.
+
+ PIL Image objects are converted to numpy arrays (which msgpack_numpy
+ supports) and the downstream client uses ``np.asarray`` on them anyway.
+ """
+ # Lazy import to avoid a hard dependency if PIL is unavailable.
+ try:
+ from PIL import Image as _PILImage
+ except Exception: # pragma: no cover - PIL should be available
+ _PILImage = None
+
+ if _PILImage is not None and isinstance(obj, _PILImage.Image):
+ return np.asarray(obj)
+ if isinstance(obj, dict):
+ return {key: _to_serializable(value) for key, value in obj.items()}
+ if isinstance(obj, (list, tuple)):
+ return [_to_serializable(item) for item in obj]
+ return obj
+
+
+class WebsocketPolicyServer:
+ """Serves a policy using the websocket protocol. See websocket_client_policy.py for a client implementation.
+
+ Currently only implements the `load` and `infer` methods.
+ """
+
+ def __init__(
+ self,
+ policy,
+ host: str = "0.0.0.0",
+ port: int = 10093,
+ idle_timeout: int = -1, # seconds; -1 means never shutdown
+ metadata: Optional[dict] = None,
+ ping_interval: Optional[float] = 30.0,
+ ping_timeout: Optional[float] = 300.0,
+ ) -> None:
+ self._policy = policy
+ self._host = host
+ self._port = port
+ self._metadata = metadata or {}
+ self._idle_timeout = idle_timeout
+ self._last_active = time.time()
+
+ # WebSocket keepalive tuning (server side!)
+ self._ping_interval = ping_interval
+ self._ping_timeout = ping_timeout
+
+ # Thread lock for concurrent inference protection
+ self._inference_lock = threading.Lock()
+
+ logging.getLogger("websockets.server").setLevel(logging.INFO)
+
+ def serve_forever(self) -> None:
+ asyncio.run(self.run())
+
+ async def run(self) -> None:
+ async with websockets.asyncio.server.serve(
+ self._handler,
+ self._host,
+ self._port,
+ compression=None,
+ max_size=None,
+ ping_interval=self._ping_interval,
+ ping_timeout=self._ping_timeout,
+ close_timeout=10,
+ ) as server:
+ if self._idle_timeout > 0:
+ await self._idle_watchdog(server)
+ else:
+ await server.serve_forever()
+
+ async def _idle_watchdog(self, server: websockets.asyncio.server.Server) -> None:
+ """Monitor server-level idle time; if no requests for idle_timeout seconds, shut down server."""
+ while True:
+ await asyncio.sleep(5)
+ if time.time() - self._last_active > self._idle_timeout:
+ logging.info(f"Idle timeout ({self._idle_timeout}s) reached, shutting down server.")
+ server.close()
+ await server.wait_closed()
+ break
+
+ async def _handler(self, websocket: websockets.asyncio.server.ServerConnection) -> None:
+ logging.info(f"Connection from {websocket.remote_address} opened")
+ packer = msgpack_numpy.Packer()
+
+ # Send metadata as first binary frame
+ await websocket.send(packer.pack(self._metadata))
+
+ while True:
+ try:
+ raw = await websocket.recv()
+ msg = msgpack_numpy.unpackb(raw)
+ self._last_active = time.time()
+
+ # ★ CRITICAL: do NOT block event loop with inference
+ ret = await asyncio.to_thread(self._route_message, msg)
+
+ await websocket.send(packer.pack(ret))
+ except websockets.ConnectionClosed:
+ logging.info(f"Connection from {websocket.remote_address} closed")
+ break
+ except Exception:
+ # Send traceback as text, then close with 1011
+ tb = traceback.format_exc()
+ try:
+ await websocket.send(tb)
+ except Exception:
+ pass
+ try:
+ await websocket.close(
+ code=websockets.frames.CloseCode.INTERNAL_ERROR,
+ reason="Internal server error. Traceback included in previous frame.",
+ )
+ except Exception:
+ pass
+ raise
+
+ def _route_message(self, msg: Any) -> Dict[str, Any]:
+ """
+ Fault-tolerant routing:
+ Accepts either:
+ 1) protocol envelope:
+ {"type": "ping|infer|reset|...", "request_id": "...", "payload": {...}}
+ 2) legacy style:
+ { ...payload... } (treated as infer)
+ """
+ # Normalize
+ if isinstance(msg, dict):
+ req_id = msg.get("request_id", "default")
+ mtype = msg.get("type", "infer")
+ payload = msg.get("payload", msg) # if no payload wrapper, treat whole dict as payload
+ else:
+ req_id = "default"
+ mtype = "infer"
+ payload = msg
+
+ # ping
+ if mtype == "ping":
+ return {"status": "ok", "ok": True, "type": "ping", "request_id": req_id}
+
+ # infer / predict_action
+ if mtype in ("infer", "predict_action"):
+ if not isinstance(payload, dict):
+ return {
+ "status": "error",
+ "ok": False,
+ "type": "inference_result",
+ "request_id": req_id,
+ "error": {"message": "Payload must be a dict", "payload_type": str(type(payload))},
+ }
+
+ try:
+ # IMPORTANT: only pass payload into policy, not control fields
+ # Use lock to ensure thread-safe concurrent inference
+ with self._inference_lock:
+ output_dict = self._policy.predict_action(**payload, is_run_parallel_eval_mxk=True)
+ return {
+ "status": "ok",
+ "ok": True,
+ "type": "inference_result",
+ "request_id": req_id,
+ "data": _to_serializable(output_dict),
+ }
+ except Exception as e:
+ logging.exception("Policy inference error (request_id=%s)", req_id)
+ return {
+ "status": "error",
+ "ok": False,
+ "type": "inference_result",
+ "request_id": req_id,
+ "error": {"message": str(e)},
+ }
+
+ # unknown request type
+ return {
+ "status": "error",
+ "ok": False,
+ "type": "unknown",
+ "request_id": req_id,
+ "error": {"message": f"Unsupported message type '{mtype}'"},
+ }
+
+
+if __name__ == "__main__":
+ logging.basicConfig(level=logging.INFO, force=True)
+ raise NotImplementedError("This module is not intended to be run directly.")
diff --git a/deployment_robotwin/model_server/tools/__init__.py b/deployment_robotwin/model_server/tools/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/deployment_robotwin/model_server/tools/debug_server_policy.py b/deployment_robotwin/model_server/tools/debug_server_policy.py
new file mode 100644
index 0000000000000000000000000000000000000000..1872432815c2bd21f750609da10010d55139fc4a
--- /dev/null
+++ b/deployment_robotwin/model_server/tools/debug_server_policy.py
@@ -0,0 +1,91 @@
+"""
+Debug / smoke-test client for deployment_robotwin/model_server/server_policy.py.
+
+Purpose:
+ - Establish a WebSocket connection to the policy server.
+ - Initialize device on the server side.
+ - Optionally run a very simple inference request to verify end-to-end transport
+ (serialization + server handling).
+
+Usage example:
+ python debug_server_policy.py --host 127.0.0.1 --port 10093 --device cuda --test infer
+
+Notes:
+ - The random observation is synthetic and only meant to validate the interface.
+ - Adjust keys (e.g. 'images', 'task_description') to match the server's expected schema.
+"""
+
+import argparse
+import logging
+import numpy as np
+
+
+from tools.websocket_policy_client import WebsocketClientPolicy
+
+
+def _build_argparser() -> argparse.ArgumentParser:
+ ap = argparse.ArgumentParser(description="WebSocket policy client smoke test (msgpack protocol)")
+ ap.add_argument("--host", default="127.0.0.1", help="server hostname/IP (do not use 0.0.0.0)")
+ ap.add_argument("--port", type=int, default=10093, help="server port")
+ ap.add_argument("--api_key", default="", help="optional: API key for authentication")
+ ap.add_argument("--device", default="cuda", choices=["cuda", "cpu"], help="initialize device")
+ ap.add_argument(
+ "--test", choices=["init", "infer"], default="infer", help="test mode: only initialize, or try simple inference"
+ )
+ ap.add_argument("--log_level", default="INFO")
+ return ap
+
+
+def _main():
+ args = _build_argparser().parse_args()
+ logging.basicConfig(level=getattr(logging, args.log_level.upper(), logging.INFO), force=True)
+
+ client = WebsocketClientPolicy(host=args.host, port=args.port, api_key=(args.api_key or None))
+ logging.info("Connected. Server metadata: %s", client.get_server_metadata())
+
+ # 1) device initialization
+ init_ret = client.init_device(args.device) # here to set some things on the server
+ logging.info("Init device resp: %s", init_ret)
+
+ # 2) optional: try one simple inference
+ if args.test == "infer":
+ try:
+ # build observation aligned with model API
+ H, W = 224, 224
+ img = np.random.randint(0, 256, (H, W, 3), dtype=np.uint8)
+ wrist_img = np.random.randint(0, 256, (H, W, 3), dtype=np.uint8)
+ state = np.zeros((7,), dtype=np.float32) # [x,y,z, ax,ay,az, gripper]
+
+ observation = { # key to align with model API
+ "request_id": "smoke-test",
+ "observation.primary": np.expand_dims(img, axis=0), # (1,H,W,C), uint8 0-255
+ "observation.wrist_image": np.expand_dims(wrist_img, axis=0), # (1,H,W,C)
+ "observation.state": np.expand_dims(state, axis=0), # (1,7), float32
+ "instruction": ["debug: pick up the red block"], # single element list
+ }
+
+ image_path = "assets/table.jpeg"
+ # read image as PIL
+ from PIL import Image
+ image_primary = Image.open(image_path).convert("RGB")
+ # Convert PIL -> numpy uint8 (H,W,3)
+ image_primary_np = np.asarray(image_primary, dtype=np.uint8)
+
+ instruction_lang="pick up the red block"
+ obs = {
+ "request_id": "smoke-test",
+ "batch_images": [[image_primary_np]],
+ "instructions": [instruction_lang], # assume batch task description
+ }
+
+ infer_ret = client.infer(obs)
+ logging.info("Infer resp: %s", infer_ret)
+ except Exception as e:
+ logging.error("Infer error (this still proves transport OK): %s", e)
+
+ client.close()
+ logging.info("Smoke test done.")
+
+
+if __name__ == "__main__":
+ _main()
diff --git a/deployment_robotwin/model_server/tools/image_tools.py b/deployment_robotwin/model_server/tools/image_tools.py
new file mode 100644
index 0000000000000000000000000000000000000000..a725d317243cf62cc5e971d46fa273351423e5b7
--- /dev/null
+++ b/deployment_robotwin/model_server/tools/image_tools.py
@@ -0,0 +1,119 @@
+import numpy as np
+from PIL import Image
+
+
+def convert_to_uint8(img: np.ndarray) -> np.ndarray:
+ """Converts an image to uint8 if it is a float image.
+
+ This is important for reducing the size of the image when sending it over the network.
+ """
+ if np.issubdtype(img.dtype, np.floating):
+ img = (255 * img).astype(np.uint8)
+ return img
+
+
+def resize_with_pad(images: np.ndarray, height: int, width: int, method=Image.BILINEAR) -> np.ndarray:
+ """Replicates tf.image.resize_with_pad for multiple images using PIL. Resizes a batch of images to a target height.
+
+ Args:
+ images: A batch of images in [..., height, width, channel] format.
+ height: The target height of the image.
+ width: The target width of the image.
+ method: The interpolation method to use. Default is bilinear.
+
+ Returns:
+ The resized images in [..., height, width, channel].
+ """
+ # If the images are already the correct size, return them as is.
+ if images.shape[-3:-1] == (height, width):
+ return images
+
+ original_shape = images.shape
+
+ images = images.reshape(-1, *original_shape[-3:])
+ resized = np.stack([_resize_with_pad_pil(Image.fromarray(im), height, width, method=method) for im in images])
+ return resized.reshape(*original_shape[:-3], *resized.shape[-3:])
+
+
+def _resize_with_pad_pil(image: Image.Image, height: int, width: int, method: int) -> Image.Image:
+ """Replicates tf.image.resize_with_pad for one image using PIL. Resizes an image to a target height and
+ width without distortion by padding with zeros.
+
+ Unlike the jax version, note that PIL uses [width, height, channel] ordering instead of [batch, h, w, c].
+ """
+ cur_width, cur_height = image.size
+ if cur_width == width and cur_height == height:
+ return image # No need to resize if the image is already the correct size.
+
+ ratio = max(cur_width / width, cur_height / height)
+ resized_height = int(cur_height / ratio)
+ resized_width = int(cur_width / ratio)
+ resized_image = image.resize((resized_width, resized_height), resample=method)
+
+ zero_image = Image.new(resized_image.mode, (width, height), 0)
+ pad_height = max(0, int((height - resized_height) / 2))
+ pad_width = max(0, int((width - resized_width) / 2))
+ zero_image.paste(resized_image, (pad_width, pad_height))
+ assert zero_image.size == (width, height)
+ return zero_image
+
+from typing import Sequence, Union, List, Tuple, Any
+def to_pil_preserve(images: Any, scale_float: bool = True):
+ """
+ Convert (possibly nested) numpy image arrays back to PIL.Image WITHOUT changing spatial shape
+ or nesting structure.
+
+ Accepts:
+ - np.ndarray with shape (H, W, C), C in {1,3,4}, dtype uint8 or float
+ - PIL.Image.Image (returned as-is)
+ - Nested list / tuple structures containing the above
+
+ Guarantees:
+ - No resize / pad / crop performed
+ - Returns an object with the SAME nesting layout (list -> list, tuple -> tuple)
+ - Only dtype (float -> uint8) and channel-mode adaptation may happen
+ * float arrays assumed in [0,1] if scale_float=True (scaled *255 + clip)
+ Args:
+ images: input object / sequence
+ scale_float: whether to scale float images in [0,1] to uint8
+ Returns:
+ Mirrored structure with all leaf nodes as PIL.Image.Image
+ """
+ def _convert(obj):
+ # Nested containers
+ if isinstance(obj, list):
+ return [ _convert(x) for x in obj ]
+ if isinstance(obj, tuple):
+ return tuple(_convert(x) for x in obj)
+
+ # PIL stays
+ if isinstance(obj, Image.Image):
+ return obj
+
+ # numpy -> PIL
+ if isinstance(obj, np.ndarray):
+ arr = obj
+ if arr.ndim != 3:
+ raise ValueError(f"Expected 3D array (H,W,C), got shape={arr.shape}")
+ if arr.shape[2] not in (1,3,4):
+ raise ValueError(f"Channel count must be 1/3/4, got {arr.shape[2]}")
+ if np.issubdtype(arr.dtype, np.floating):
+ if scale_float:
+ arr = np.clip(arr, 0.0, 1.0)
+ arr = (arr * 255.0 + 0.5).astype(np.uint8)
+ else:
+ raise TypeError("Float array provided but scale_float=False")
+ elif arr.dtype != np.uint8:
+ arr = arr.astype(np.uint8)
+
+ # Single channel -> 'L'
+ if arr.shape[2] == 1:
+ arr = arr[:, :, 0]
+ return Image.fromarray(arr, mode="L")
+ # 3 channels -> RGB, 4 -> RGBA
+ mode = "RGB" if arr.shape[2] == 3 else "RGBA"
+ return Image.fromarray(arr, mode=mode)
+
+ raise TypeError(f"Unsupported element type: {type(obj)}")
+
+ return _convert(images)
\ No newline at end of file
diff --git a/deployment_robotwin/model_server/tools/msgpack_numpy.py b/deployment_robotwin/model_server/tools/msgpack_numpy.py
new file mode 100644
index 0000000000000000000000000000000000000000..007f755edf54565579376b077eec7f7f715e1b96
--- /dev/null
+++ b/deployment_robotwin/model_server/tools/msgpack_numpy.py
@@ -0,0 +1,57 @@
+"""Adds NumPy array support to msgpack.
+
+msgpack is good for (de)serializing data over a network for multiple reasons:
+- msgpack is secure (as opposed to pickle/dill/etc which allow for arbitrary code execution)
+- msgpack is widely used and has good cross-language support
+- msgpack does not require a schema (as opposed to protobuf/flatbuffers/etc) which is convenient in dynamically typed
+ languages like Python and JavaScript
+- msgpack is fast and efficient (as opposed to readable formats like JSON/YAML/etc); I found that msgpack was ~4x faster
+ than pickle for serializing large arrays using the below strategy
+
+The code below is adapted from https://github.com/lebedov/msgpack-numpy. The reason not to use that library directly is
+that it falls back to pickle for object arrays.
+"""
+
+import functools
+
+import msgpack
+import numpy as np
+
+
+def pack_array(obj):
+ if (isinstance(obj, (np.ndarray, np.generic))) and obj.dtype.kind in ("V", "O", "c"):
+ raise ValueError(f"Unsupported dtype: {obj.dtype}")
+
+ if isinstance(obj, np.ndarray):
+ return {
+ b"__ndarray__": True,
+ b"data": obj.tobytes(),
+ b"dtype": obj.dtype.str,
+ b"shape": obj.shape,
+ }
+
+ if isinstance(obj, np.generic):
+ return {
+ b"__npgeneric__": True,
+ b"data": obj.item(),
+ b"dtype": obj.dtype.str,
+ }
+
+ return obj
+
+
+def unpack_array(obj):
+ if b"__ndarray__" in obj:
+ return np.ndarray(buffer=obj[b"data"], dtype=np.dtype(obj[b"dtype"]), shape=obj[b"shape"])
+
+ if b"__npgeneric__" in obj:
+ return np.dtype(obj[b"dtype"]).type(obj[b"data"])
+
+ return obj
+
+
+Packer = functools.partial(msgpack.Packer, default=pack_array)
+packb = functools.partial(msgpack.packb, default=pack_array)
+
+Unpacker = functools.partial(msgpack.Unpacker, object_hook=unpack_array)
+unpackb = functools.partial(msgpack.unpackb, object_hook=unpack_array)
diff --git a/deployment_robotwin/model_server/tools/websocket_policy_client.py b/deployment_robotwin/model_server/tools/websocket_policy_client.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc3f8874dcdbdd11ff8939db7c535e4f922ed861
--- /dev/null
+++ b/deployment_robotwin/model_server/tools/websocket_policy_client.py
@@ -0,0 +1,149 @@
+# Copyright 2025 starVLA community. All rights reserved.
+# Licensed under the MIT License, Version 1.0 (the "License");
+# Implemented by [Jinhui YE / HKUST University] in [2025].
+
+import logging
+import os
+import time
+from typing import Dict, Optional, Tuple, Any
+
+from typing_extensions import override
+import websockets
+import websockets.sync.client
+
+from . import msgpack_numpy
+
+
+class WebsocketClientPolicy:
+ """Implements the Policy interface by communicating with a server over websocket.
+
+ See WebsocketPolicyServer for a corresponding server implementation.
+ """
+
+ def __init__(
+ self,
+ host: str = "127.0.0.1",
+ port: Optional[int] = 10093,
+ api_key: Optional[str] = None,
+ connect_timeout: float = 300.0,
+ open_timeout: float = 150.0,
+ ping_interval: Optional[float] = 30.0,
+ ping_timeout: Optional[float] = 300.0,
+ reconnect_max_attempts: int = 5,
+ ) -> None:
+ # 0.0.0.0 cannot be used as a connection target, here default 127.0.0.1
+ self._uri = f"ws://{host}"
+ if port is not None:
+ self._uri += f":{port}"
+
+ self._packer = msgpack_numpy.Packer()
+ self._api_key = api_key
+
+ self._connect_timeout = connect_timeout
+ self._open_timeout = open_timeout
+ self._ping_interval = ping_interval
+ self._ping_timeout = ping_timeout
+ self._reconnect_max_attempts = reconnect_max_attempts
+
+ self._ws, self._server_metadata = self._wait_for_server(timeout=self._connect_timeout)
+
+ def get_server_metadata(self) -> Dict:
+ return self._server_metadata
+
+ def close(self) -> None:
+ try:
+ if getattr(self, "_ws", None) is not None:
+ self._ws.close()
+ except Exception:
+ pass
+
+ def _drop_proxy_env(self) -> None:
+ # Some environments set proxies that break ws://127.0.0.1
+ for k in ("HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"):
+ os.environ.pop(k, None)
+
+ def _connect_once(self) -> Tuple[websockets.sync.client.ClientConnection, Dict[str, Any]]:
+ headers = {"Authorization": f"Api-Key {self._api_key}"} if self._api_key else None
+ conn = websockets.sync.client.connect(
+ self._uri,
+ compression=None,
+ max_size=None,
+ additional_headers=headers,
+ open_timeout=self._open_timeout,
+ ping_interval=self._ping_interval,
+ ping_timeout=self._ping_timeout,
+ close_timeout=10,
+ )
+ # First frame: metadata
+ metadata = msgpack_numpy.unpackb(conn.recv())
+ if not isinstance(metadata, dict):
+ raise RuntimeError(f"Server metadata must be dict, got: {type(metadata)}")
+ return conn, metadata
+
+ def _wait_for_server(self, timeout: float = 300.0) -> Tuple[websockets.sync.client.ClientConnection, Dict]:
+ logging.info(f"Waiting for server at {self._uri}...")
+ start_time = time.time()
+
+ self._drop_proxy_env()
+
+ backoff = 0.5 # seconds
+ while True:
+ if time.time() - start_time > timeout:
+ raise TimeoutError(f"Failed to connect to server within {timeout} seconds")
+
+ try:
+ conn, metadata = self._connect_once()
+ return conn, metadata
+ except ConnectionRefusedError:
+ logging.info(f"Still waiting for server {self._uri} ...")
+ except Exception as e:
+ logging.warning(f"Connect failed: {repr(e)}")
+
+ time.sleep(backoff)
+ backoff = min(backoff * 1.5, 5.0)
+
+ def _reconnect(self) -> None:
+ """Reconnect with limited attempts. Keeps it synchronous and simple."""
+ self.close()
+ last_err = None
+ for attempt in range(1, self._reconnect_max_attempts + 1):
+ try:
+ self._ws, self._server_metadata = self._wait_for_server(timeout=60.0)
+ return
+ except Exception as e:
+ last_err = e
+ logging.warning(f"Reconnect attempt {attempt}/{self._reconnect_max_attempts} failed: {repr(e)}")
+ raise RuntimeError(f"Failed to reconnect after {self._reconnect_max_attempts} attempts") from last_err
+
+ @override
+ def predict_action(self, query_info: Dict) -> Dict:
+ """
+ Sends a request to server. Supports both:
+ - legacy payload dict (query_info)
+ - or query_info already containing {type, request_id, payload}
+ """
+ data = self._packer.pack(query_info)
+
+ try:
+ self._ws.send(data)
+ response = self._ws.recv()
+ except websockets.exceptions.ConnectionClosedError as e:
+ logging.warning(f"WebSocket closed, reconnecting once... ({e})")
+ self._reconnect()
+ self._ws.send(data)
+ response = self._ws.recv()
+
+ if isinstance(response, str):
+ # server sent traceback text frame
+ raise RuntimeError(f"Error in inference server:\n{response}")
+
+ ret = msgpack_numpy.unpackb(response)
+ if not isinstance(ret, dict):
+ raise RuntimeError(f"Invalid response type: {type(ret)}")
+
+ # Optional: normalize error replies
+ if ret.get("ok") is False and ret.get("status") == "error":
+ err = ret.get("error", {})
+ raise RuntimeError(f"Server error: {err}")
+
+ return ret
diff --git a/deployment_robotwin/model_server/tools/websocket_policy_server.py b/deployment_robotwin/model_server/tools/websocket_policy_server.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c254a59b05f431582464d7cec74a4234e19209a
--- /dev/null
+++ b/deployment_robotwin/model_server/tools/websocket_policy_server.py
@@ -0,0 +1,207 @@
+# Copyright 2025 starVLA community. All rights reserved.
+# Licensed under the MIT License, Version 1.0 (the "License");
+# Implemented by [Jinhui YE / HKUST University] in [2025].
+
+import asyncio
+import logging
+import threading
+import time
+import traceback
+from typing import Any, Dict, Optional
+
+import numpy as np
+import websockets
+import websockets.asyncio.server
+import websockets.frames
+
+from . import msgpack_numpy
+
+
+def _to_serializable(obj: Any) -> Any:
+ """Recursively convert non-serializable objects (e.g. PIL Image) into
+ msgpack-friendly types so the response can be packed by msgpack_numpy.
+
+ PIL Image objects are converted to numpy arrays (which msgpack_numpy
+ supports) and the downstream client uses ``np.asarray`` on them anyway.
+ """
+ # Lazy import to avoid a hard dependency if PIL is unavailable.
+ try:
+ from PIL import Image as _PILImage
+ except Exception: # pragma: no cover - PIL should be available
+ _PILImage = None
+
+ if _PILImage is not None and isinstance(obj, _PILImage.Image):
+ return np.asarray(obj)
+ if isinstance(obj, dict):
+ return {key: _to_serializable(value) for key, value in obj.items()}
+ if isinstance(obj, (list, tuple)):
+ return [_to_serializable(item) for item in obj]
+ return obj
+
+
+class WebsocketPolicyServer:
+ """Serves a policy using the websocket protocol. See websocket_client_policy.py for a client implementation.
+
+ Currently only implements the `load` and `infer` methods.
+ """
+
+ def __init__(
+ self,
+ policy,
+ host: str = "0.0.0.0",
+ port: int = 10093,
+ idle_timeout: int = -1, # seconds; -1 means never shutdown
+ metadata: Optional[dict] = None,
+ ping_interval: Optional[float] = 30.0,
+ ping_timeout: Optional[float] = 300.0,
+ ) -> None:
+ self._policy = policy
+ self._host = host
+ self._port = port
+ self._metadata = metadata or {}
+ self._idle_timeout = idle_timeout
+ self._last_active = time.time()
+
+ # WebSocket keepalive tuning (server side!)
+ self._ping_interval = ping_interval
+ self._ping_timeout = ping_timeout
+
+ # Thread lock for concurrent inference protection
+ self._inference_lock = threading.Lock()
+
+ logging.getLogger("websockets.server").setLevel(logging.INFO)
+
+ def serve_forever(self) -> None:
+ asyncio.run(self.run())
+
+ async def run(self) -> None:
+ async with websockets.asyncio.server.serve(
+ self._handler,
+ self._host,
+ self._port,
+ compression=None,
+ max_size=None,
+ ping_interval=self._ping_interval,
+ ping_timeout=self._ping_timeout,
+ close_timeout=10,
+ ) as server:
+ if self._idle_timeout > 0:
+ await self._idle_watchdog(server)
+ else:
+ await server.serve_forever()
+
+ async def _idle_watchdog(self, server: websockets.asyncio.server.Server) -> None:
+ """Monitor server-level idle time; if no requests for idle_timeout seconds, shut down server."""
+ while True:
+ await asyncio.sleep(5)
+ if time.time() - self._last_active > self._idle_timeout:
+ logging.info(f"Idle timeout ({self._idle_timeout}s) reached, shutting down server.")
+ server.close()
+ await server.wait_closed()
+ break
+
+ async def _handler(self, websocket: websockets.asyncio.server.ServerConnection) -> None:
+ logging.info(f"Connection from {websocket.remote_address} opened")
+ packer = msgpack_numpy.Packer()
+
+ # Send metadata as first binary frame
+ await websocket.send(packer.pack(self._metadata))
+
+ while True:
+ try:
+ raw = await websocket.recv()
+ msg = msgpack_numpy.unpackb(raw)
+ self._last_active = time.time()
+
+ # ★ CRITICAL: do NOT block event loop with inference
+ ret = await asyncio.to_thread(self._route_message, msg)
+
+ await websocket.send(packer.pack(ret))
+ except websockets.ConnectionClosed:
+ logging.info(f"Connection from {websocket.remote_address} closed")
+ break
+ except Exception:
+ # Send traceback as text, then close with 1011
+ tb = traceback.format_exc()
+ try:
+ await websocket.send(tb)
+ except Exception:
+ pass
+ try:
+ await websocket.close(
+ code=websockets.frames.CloseCode.INTERNAL_ERROR,
+ reason="Internal server error. Traceback included in previous frame.",
+ )
+ except Exception:
+ pass
+ raise
+
+ def _route_message(self, msg: Any) -> Dict[str, Any]:
+ """
+ Fault-tolerant routing:
+ Accepts either:
+ 1) protocol envelope:
+ {"type": "ping|infer|reset|...", "request_id": "...", "payload": {...}}
+ 2) legacy style:
+ { ...payload... } (treated as infer)
+ """
+ # Normalize
+ if isinstance(msg, dict):
+ req_id = msg.get("request_id", "default")
+ mtype = msg.get("type", "infer")
+ payload = msg.get("payload", msg) # if no payload wrapper, treat whole dict as payload
+ else:
+ req_id = "default"
+ mtype = "infer"
+ payload = msg
+
+ # ping
+ if mtype == "ping":
+ return {"status": "ok", "ok": True, "type": "ping", "request_id": req_id}
+
+ # infer / predict_action
+ if mtype in ("infer", "predict_action"):
+ if not isinstance(payload, dict):
+ return {
+ "status": "error",
+ "ok": False,
+ "type": "inference_result",
+ "request_id": req_id,
+ "error": {"message": "Payload must be a dict", "payload_type": str(type(payload))},
+ }
+
+ try:
+ # IMPORTANT: only pass payload into policy, not control fields
+ # Use lock to ensure thread-safe concurrent inference
+ with self._inference_lock:
+ output_dict = self._policy.predict_action(**payload, is_run_parallel_eval_mxk=True)
+ return {
+ "status": "ok",
+ "ok": True,
+ "type": "inference_result",
+ "request_id": req_id,
+ "data": _to_serializable(output_dict),
+ }
+ except Exception as e:
+ logging.exception("Policy inference error (request_id=%s)", req_id)
+ return {
+ "status": "error",
+ "ok": False,
+ "type": "inference_result",
+ "request_id": req_id,
+ "error": {"message": str(e)},
+ }
+
+ # unknown request type
+ return {
+ "status": "error",
+ "ok": False,
+ "type": "unknown",
+ "request_id": req_id,
+ "error": {"message": f"Unsupported message type '{mtype}'"},
+ }
+
+
+if __name__ == "__main__":
+ logging.basicConfig(level=logging.INFO, force=True)
+ raise NotImplementedError("This module is not intended to be run directly.")
diff --git a/deployment_robotwin/readme-deployment.md b/deployment_robotwin/readme-deployment.md
new file mode 100644
index 0000000000000000000000000000000000000000..1c48b7693ca62266d8a4aa108064d4e8240dc1fa
--- /dev/null
+++ b/deployment_robotwin/readme-deployment.md
@@ -0,0 +1,11 @@
+sudo ip addr add 172.16.0.100/24 dev enx207bd51a3217
+sudo ip link set enx207bd51a3217 up
+ping 172.16.0.2
+
+
+python -m real_deployment.model_controller_del_ee
+
+
+## install frankx
+conda install frankx
+unzip frankx.zip
\ No newline at end of file
diff --git a/deployment_robotwin/real_infer/open_loop_eval.py b/deployment_robotwin/real_infer/open_loop_eval.py
new file mode 100644
index 0000000000000000000000000000000000000000..3089281ac7d8ed37204b92ee7082b4f865aa3689
--- /dev/null
+++ b/deployment_robotwin/real_infer/open_loop_eval.py
@@ -0,0 +1,418 @@
+import os
+import sys
+import time
+from pathlib import Path
+from dataclasses import dataclass
+from typing import Dict, List, Optional
+
+import numpy as np
+import matplotlib.pyplot as plt
+import torch
+from omegaconf import OmegaConf
+import tyro
+
+# ====== 你项目里的 import(按你现有路径保留)======
+from starVLA.dataloader.lerobot_datasets import get_vla_dataset
+from starVLA.model.framework.base_framework import baseframework
+from starVLA.model.framework.share_tools import read_mode_config
+
+# ✅ 关键:导入你训练用的 VideoResizePad(按你项目实际路径改这里)
+from starVLA.dataloader.gr00t_lerobot.transform.video import VideoResizePad
+
+
+# -----------------------------
+# 0) 图像:单张图复用 VideoResizePad(resize longest edge -> pad 到 224)
+# -----------------------------
+def _img_to_torch_nchw(img) -> torch.Tensor:
+ """
+ Convert input image to torch float tensor [1,C,H,W] in [0,1].
+ Supports: np.ndarray(H,W,C) uint8/float, torch.Tensor, PIL.Image
+ """
+ if isinstance(img, torch.Tensor):
+ x = img
+ if x.ndim == 3 and x.shape[-1] in (1, 3, 4) and x.shape[0] not in (1, 3, 4):
+ x = x.permute(2, 0, 1) # HWC -> CHW
+ if x.ndim == 2:
+ x = x.unsqueeze(0)
+ if x.ndim != 3:
+ raise ValueError(f"Unexpected torch image shape: {x.shape}")
+ x = x.float()
+ if x.max() > 1.5:
+ x = x / 255.0
+ return x.unsqueeze(0) # [1,C,H,W]
+
+ if isinstance(img, np.ndarray):
+ x = torch.from_numpy(img)
+ if x.ndim == 3 and x.shape[-1] in (1, 3, 4): # HWC
+ x = x.permute(2, 0, 1) # -> CHW
+ elif x.ndim == 2:
+ x = x.unsqueeze(0)
+ if x.ndim != 3:
+ raise ValueError(f"Unexpected numpy image shape: {img.shape}")
+ x = x.float()
+ if x.max() > 1.5:
+ x = x / 255.0
+ return x.unsqueeze(0)
+
+ # 避免强依赖 PIL:只有你真的传 PIL.Image 才需要
+ try:
+ from PIL import Image
+ if isinstance(img, Image.Image):
+ x = torch.from_numpy(np.array(img))
+ if x.ndim == 2:
+ x = x.unsqueeze(-1)
+ x = x.permute(2, 0, 1).float()
+ if x.max() > 1.5:
+ x = x / 255.0
+ return x.unsqueeze(0)
+ except Exception:
+ pass
+
+ raise TypeError(f"Unsupported image type: {type(img)}")
+
+
+def _torch_chw_to_uint8_hwc(x: torch.Tensor) -> np.ndarray:
+ """
+ x: torch.Tensor [C,H,W] float [0,1]
+ return: np.uint8 [H,W,C]
+ """
+ x = (x.clamp(0, 1) * 255.0).to(torch.uint8)
+ x = x.permute(1, 2, 0).cpu().numpy()
+ return x
+
+
+class OpenLoopVideoResizePadWrapper:
+ """
+ 复用训练同款 VideoResizePad 的 torchvision resize+pad 逻辑,
+ 但输入/输出是“单张图”。
+ """
+
+ def __init__(self, resize_pad_transform: VideoResizePad, return_numpy_uint8_hwc: bool = True):
+ self.t = resize_pad_transform
+ self.return_numpy_uint8_hwc = return_numpy_uint8_hwc
+
+ def __call__(self, img):
+ # 单图 -> [1,C,H,W]
+ x = _img_to_torch_nchw(img)
+ # 复用类内部 torchvision resize+pad
+ y = self.t._torchvision_resize_pad(x) # [1,C,S,S]
+ y = y.squeeze(0) # [C,S,S]
+ if self.return_numpy_uint8_hwc:
+ return _torch_chw_to_uint8_hwc(y) # [S,S,C] uint8,最保险(兼容你现有 predict_action)
+ return y # torch [C,S,S]
+
+
+# -----------------------------
+# 1) 你已有的归一化/反归一化逻辑(原封不动)
+# -----------------------------
+def _minmax_to_minus1_1(x: np.ndarray, stats: dict, eps: float = 1e-6) -> np.ndarray:
+ lo = np.asarray(stats["min"], dtype=np.float32)
+ hi = np.asarray(stats["max"], dtype=np.float32)
+ denom = np.maximum(hi - lo, eps)
+ x01 = (x - lo) / denom
+ xn = x01 * 2.0 - 1.0
+ return xn.astype(np.float32)
+
+
+def unnormalize_actions(normalized_actions: np.ndarray, action_norm_stats: Dict[str, np.ndarray]) -> np.ndarray:
+ mask = action_norm_stats.get("mask", np.ones_like(action_norm_stats["min"], dtype=bool))
+ action_high, action_low = np.array(action_norm_stats["max"]), np.array(action_norm_stats["min"])
+ normalized_actions = np.clip(normalized_actions, -1, 1)
+ actions = np.where(
+ mask,
+ (normalized_actions + 1) / 2 * (action_high - action_low) + action_low,
+ normalized_actions,
+ )
+ return actions
+
+
+# -----------------------------
+# 2) Args(按你 server 的 Args 简化必要项)
+# -----------------------------
+@dataclass
+class Args:
+ ckpt_path: str = "outputs/suqian_post_train_w_state/checkpoints/steps_80000_pytorch_model.pt"
+ unnorm_key: str = "agibot_genie1"
+ gripper_threshold: float = 0.5
+
+ # ✅ 关键:对齐训练图像预处理
+ image_size: int = 224
+ image_interpolation: str = "linear"
+ image_fill_value: float = 0.0
+
+
+def _build_policy(args: Args):
+ vla = baseframework.from_pretrained(args.ckpt_path)
+ vla = vla.to("cuda").eval()
+
+ cfg, norm_stats = read_mode_config(Path(args.ckpt_path))
+ unnorm_key = args.unnorm_key
+ cfg = OmegaConf.create(cfg)
+
+ vla.action_norm_stats = norm_stats[unnorm_key]["action"]
+ vla.state_norm_stats = norm_stats[unnorm_key]["state"]
+ return vla, cfg
+
+
+def _infer_single(policy, obs: Dict, args: Args, gripper_th: float) -> Dict:
+ prompt = obs.get("prompt", "")
+
+ state = np.asarray(obs["observation/state"], dtype=np.float32)
+ if state.ndim == 1:
+ state = state[None, :]
+ elif state.ndim != 2:
+ raise ValueError(f"Unexpected state shape: {state.shape}")
+
+ state_norm = _minmax_to_minus1_1(state, policy.state_norm_stats)
+
+ # padding 到 64
+ cur_dim = state_norm.shape[-1]
+ if cur_dim < 64:
+ pad_width = 64 - cur_dim
+ state_norm = np.pad(
+ state_norm,
+ pad_width=((0, 0), (0, pad_width)),
+ mode="constant",
+ constant_values=0.0,
+ )
+
+ fake_data = {
+ "image": [
+ obs["observation/image"],
+ obs["observation/wrist_left_image"],
+ obs["observation/wrist_right_image"],
+ ],
+ "lang": prompt,
+ "state": state_norm,
+ }
+
+ t0 = time.perf_counter()
+ with torch.inference_mode():
+ out = policy.predict_action(fake_data)
+ infer_ms = (time.perf_counter() - t0) * 1000
+
+ na = out["normalized_actions"] # (1, H, D)
+ na2 = na[0, :, :18] # (H, D) 你原逻辑保留
+
+ raw2 = unnormalize_actions(na2, policy.action_norm_stats) # (H, D)
+ actions = raw2[None, ...] # (1, H, D)
+
+ return {"actions": actions, "policy_timing": {"infer_ms": infer_ms}}
+
+
+# -----------------------------
+# 3) 从 single_ds.get_step_data 组装 obs / gt_chunk
+# -----------------------------
+def build_obs_from_step_data(step_data: dict, single_ds, img_proc: Optional[callable] = None) -> dict:
+ """
+ step_data: single_ds.get_step_data(traj_id, base_index) 的 RAW 输出
+ 返回:_infer_single 所需的 obs dict
+ """
+ video_keys = single_ds.modality_keys["video"]
+ if len(video_keys) < 3:
+ raise ValueError(f"Need 3 cameras, got video_keys={video_keys}")
+
+ head = step_data[video_keys[0]][0]
+ left = step_data[video_keys[1]][0]
+ right = step_data[video_keys[2]][0]
+
+ # ✅ 对齐训练:resize+pad 到 224(或 args.image_size)
+ if img_proc is not None:
+ head = img_proc(head)
+ left = img_proc(left)
+ right = img_proc(right)
+
+ # state concat: (T, D_total) -> 取第 0 帧对应 base step
+ state_parts = [step_data[k] for k in single_ds.modality_keys["state"]]
+ state = np.concatenate(state_parts, axis=1)
+ state0 = state[0]
+
+ # language
+ lang_key = single_ds.modality_keys["language"][0]
+ lang = step_data[lang_key][0]
+ if isinstance(lang, list):
+ lang = lang[0]
+
+ obs = {
+ "observation/image": head,
+ "observation/wrist_left_image": left,
+ "observation/wrist_right_image": right,
+ "observation/state": state0,
+ "prompt": lang,
+ }
+ return obs
+
+
+def get_gt_action_chunk(step_data: dict, single_ds) -> np.ndarray:
+ action_parts = [step_data[k] for k in single_ds.modality_keys["action"]]
+ gt = np.concatenate(action_parts, axis=1) # (H, D)
+ return gt
+
+
+# -----------------------------
+# 4) rollout:拼整段 pred/gt(像 gr00t open-loop eval)
+# -----------------------------
+def rollout_open_loop(
+ single_ds,
+ pi0_policy,
+ args: Args,
+ traj_id: int,
+ steps: int = 200,
+ action_horizon: int = 16,
+ img_proc: Optional[callable] = None,
+):
+ traj_len = int(single_ds.trajectory_lengths[single_ds.get_trajectory_index(traj_id)])
+ actual_steps = min(steps, traj_len)
+
+ pred_list = []
+ gt_list = []
+ infer_ms_list = []
+
+ for t in range(0, actual_steps, action_horizon):
+ step_data = single_ds.get_step_data(traj_id, t)
+
+ obs = build_obs_from_step_data(step_data, single_ds, img_proc=img_proc)
+ pred = _infer_single(pi0_policy, obs, args, args.gripper_threshold)
+
+ pred_chunk = pred["actions"][0] # (H, D)
+ gt_chunk = get_gt_action_chunk(step_data, single_ds) # (H, D)
+
+ remain = actual_steps - t
+ pred_chunk = pred_chunk[:remain]
+ gt_chunk = gt_chunk[:remain]
+
+ pred_list.append(pred_chunk)
+ gt_list.append(gt_chunk)
+ infer_ms_list.append(pred["policy_timing"]["infer_ms"])
+
+ pred_action_across_time = np.concatenate(pred_list, axis=0)
+ gt_action_across_time = np.concatenate(gt_list, axis=0)
+
+ assert pred_action_across_time.shape == gt_action_across_time.shape, (
+ f"pred={pred_action_across_time.shape}, gt={gt_action_across_time.shape}")
+ return pred_action_across_time, gt_action_across_time, infer_ms_list
+
+
+# -----------------------------
+# 5) 画图(整段轨迹)
+# -----------------------------
+def plot_action_curves(
+ gt: np.ndarray,
+ pred: np.ndarray,
+ save_path: str,
+ dims: Optional[List[int]] = None,
+ title: str = "",
+):
+ T, D = gt.shape
+ if dims is None:
+ dims = list(range(D))
+
+ n = len(dims)
+ fig, axes = plt.subplots(nrows=n, ncols=1, figsize=(10, 2.2 * n))
+ if n == 1:
+ axes = [axes]
+
+ fig.suptitle(title, fontsize=14)
+
+ x = np.arange(T)
+ for i, d in enumerate(dims):
+ ax = axes[i]
+ ax.plot(x, gt[:, d], label="gt")
+ ax.plot(x, pred[:, d], label="pred")
+ ax.set_ylabel(f"dim {d}")
+ ax.legend(loc="upper right")
+
+ axes[-1].set_xlabel("time step")
+ plt.tight_layout()
+ Path(save_path).parent.mkdir(parents=True, exist_ok=True)
+ plt.savefig(save_path, dpi=150)
+ plt.close(fig)
+
+
+def plot_error_over_time(gt: np.ndarray, pred: np.ndarray, save_path: str, title: str = ""):
+ err = pred - gt
+ mse_t = np.mean(err**2, axis=1)
+ mae_t = np.mean(np.abs(err), axis=1)
+
+ x = np.arange(len(mse_t))
+ fig = plt.figure(figsize=(10, 4))
+ plt.plot(x, mse_t, label="MSE per step")
+ plt.plot(x, mae_t, label="MAE per step")
+ plt.title(title)
+ plt.xlabel("time step")
+ plt.ylabel("error")
+ plt.legend()
+ plt.tight_layout()
+ Path(save_path).parent.mkdir(parents=True, exist_ok=True)
+ plt.savefig(save_path, dpi=150)
+ plt.close(fig)
+
+
+# -----------------------------
+# 6) main:把 dataset + policy 接起来
+# -----------------------------
+def main(args: Args):
+ # ===== load policy =====
+ pi0_policy, cfg = _build_policy(args)
+ print("policy loaded")
+
+ # ===== 构造与训练一致的 VideoResizePad =====
+ # 训练时写的是 VideoResizePad(apply_to=[video_key], size=224, interpolation="linear", fill_value=0.0)
+ # 这里我们直接复用其内部 torchvision resize+pad 实现
+ resize_pad = VideoResizePad(
+ apply_to=["video"], # 占位即可
+ size=args.image_size,
+ interpolation=args.image_interpolation,
+ fill_value=args.image_fill_value,
+ backend="torchvision", # 确保走 torchvision
+ )
+ img_proc = OpenLoopVideoResizePadWrapper(resize_pad, return_numpy_uint8_hwc=True)
+
+ # ===== 载入训练 yaml 的 dataset 配置 =====
+ vla_dataset_cfg = cfg.datasets.vla_data
+ vla_dataset_cfg.task_id = "all"
+ dataset = get_vla_dataset(data_cfg=vla_dataset_cfg)
+ single_ds = dataset.datasets[0] if hasattr(dataset, "datasets") else dataset
+
+ # 选一条 traj
+ traj_id = int(single_ds.trajectory_ids[0])
+ print("Using traj_id:", traj_id)
+
+ # ===== rollout open-loop =====
+ pred, gt, infer_ms_list = rollout_open_loop(
+ single_ds,
+ pi0_policy,
+ args,
+ traj_id=traj_id,
+ steps=200,
+ action_horizon=30,
+ img_proc=img_proc, # ✅ 关键:评测也做 resize+pad
+ )
+
+ mse = np.mean((pred - gt)**2)
+ mae = np.mean(np.abs(pred - gt))
+ print(f"Open-loop MSE={mse:.6f}, MAE={mae:.6f}")
+ print(f"Infer ms: mean={np.mean(infer_ms_list):.2f}, p95={np.percentile(infer_ms_list, 95):.2f}")
+
+ out_dir = Path("outputs/open_loop_eval")
+ out_dir.mkdir(parents=True, exist_ok=True)
+
+ plot_action_curves(
+ gt,
+ pred,
+ save_path=str(out_dir / f"traj{traj_id}_action_curves.png"),
+ # dims=list(range(min(gt.shape[1], 18))), # 只看前 18 维就打开
+ title=f"traj {traj_id} action curves (T={gt.shape[0]}, D={gt.shape[1]})",
+ )
+ plot_error_over_time(
+ gt,
+ pred,
+ save_path=str(out_dir / f"traj{traj_id}_error.png"),
+ title=f"traj {traj_id} error over time",
+ )
+
+ print("Saved plots to:", out_dir)
+
+
+if __name__ == "__main__":
+ main(tyro.cli(Args))
diff --git a/deployment_robotwin/real_infer/server.py b/deployment_robotwin/real_infer/server.py
new file mode 100644
index 0000000000000000000000000000000000000000..d0ca5898d46270bdd33aece5fcc20580e5cacae7
--- /dev/null
+++ b/deployment_robotwin/real_infer/server.py
@@ -0,0 +1,375 @@
+"""
+Pi0 WebSocket 推理服务端,兼容 openpi-client 客户端协议。
+
+- 使用 websockets.asyncio.server,客户端用 WebsocketClientPolicy 连接。
+- 首次连接发送 metadata(简单字典)。
+- 收到 obs 后,调用 Pi0 推理并返回 {"actions": np.ndarray, "policy_timing": {"infer_ms": ...}}。
+
+支持 joint_position 和 camera_position(通过 state 维度判断:16 -> joint,14 -> camera)。
+"""
+
+import asyncio
+import http
+import os
+import sys
+import time
+import traceback
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Dict, List, Literal, Optional
+
+import numpy as np
+import tyro
+import websockets.asyncio.server as ws_server
+import websockets.frames
+
+import torch
+import cv2 as cv
+
+# 兼容 protobuf 版本
+os.environ.setdefault("PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION", "python")
+
+# 路径设置
+_current_dir = Path(__file__).resolve().parent
+_project_root = _current_dir.parent
+if str(_project_root) not in sys.path:
+ sys.path.insert(0, str(_project_root))
+
+# openpi-client 在当前目录下
+_openpi_client_src = _current_dir / "openpi-client" / "src"
+if _openpi_client_src.exists() and str(_openpi_client_src) not in sys.path:
+ sys.path.insert(0, str(_openpi_client_src))
+
+from starVLA.model.framework.base_framework import baseframework
+from starVLA.model.framework.share_tools import read_mode_config
+from openpi_client import msgpack_numpy
+
+
+@dataclass
+class Args:
+ host: str = "0.0.0.0"
+ port: int = 8000
+ ckpt_path: str = "/mnt/workspace/users/yuanzhihao/code/starVLA/outputs/suqian_post_train_no_pretrain/checkpoints/steps_15000_pytorch_model.pt"
+ data_statistics_path: str = "/workspace/niejunnan/VLAPipeline_RL_BY_Niejunnan/output_train/agibot/benchmark_pro_max/ds_stats.json"
+ language_tokenizer_path: Optional[str] = "/workspace/paligemma-3b-pt-224"
+ unnorm_key: Optional[str] = "agibot_genie1"
+ policy_setup: str = "agibot_genie1"
+ obs_camera_name: List[str] = field(default_factory=lambda: ["head_color", "hand_left", "hand_right"])
+ action_scale: float = 1.0
+ use_filter: bool = False
+ use_multi_action_head: str = "raw"
+ use_arm_pose_type: str = "euler"
+ use_paligemma_original_vocab_size: bool = True
+ n_action_steps: Optional[int] = None
+ inference_mode: str = "synchronous"
+ # 兼容 pi0inference 期望的其他开关
+ use_distillation_distribution: bool = False
+ use_embodiment_id: bool = False
+ use_vit_for_action_head: bool = False
+ use_distillation: bool = False
+ use_best_of_n: bool = False
+ best_of_n: int = 32
+ use_step_action_mask_for_q: bool = False
+ image_size: int = 224
+ gripper_threshold: float = 0.5
+
+
+def resizepad_longest_edge_cv2(
+ image: np.ndarray,
+ target_size: int = 224,
+ fill_value: int = 0,
+) -> np.ndarray:
+ """
+ Resize longest edge to target_size, keep aspect ratio, then center-pad to (target_size, target_size).
+ Input: image HWC (H,W,C) or HW (H,W)
+ Output: uint8 HWC (target_size,target_size,C) or (target_size,target_size) for grayscale
+ """
+ if not isinstance(image, np.ndarray):
+ image = np.asarray(image)
+
+ if image.ndim == 2:
+ H, W = image.shape
+ C = None
+ elif image.ndim == 3:
+ H, W, C = image.shape
+ else:
+ raise ValueError(f"Unexpected image shape: {image.shape}")
+
+ # Avoid degenerate
+ if H <= 0 or W <= 0:
+ raise ValueError(f"Invalid image size: H={H}, W={W}")
+
+ # scale longest edge -> target_size
+ scale = target_size / float(max(H, W))
+ new_h = max(1, int(round(H * scale)))
+ new_w = max(1, int(round(W * scale)))
+
+ # choose interpolation
+ interp = cv.INTER_AREA if scale < 1.0 else cv.INTER_LINEAR
+
+ resized = cv.resize(image, (new_w, new_h), interpolation=interp)
+
+ pad_h = target_size - new_h
+ pad_w = target_size - new_w
+ pad_top = pad_h // 2
+ pad_bottom = pad_h - pad_top
+ pad_left = pad_w // 2
+ pad_right = pad_w - pad_left
+
+ # padding value
+ if resized.ndim == 2:
+ border_value = fill_value
+ else:
+ # OpenCV expects scalar or tuple; tuple is safer for multi-channel
+ border_value = (fill_value,) * resized.shape[2]
+
+ padded = cv.copyMakeBorder(
+ resized,
+ pad_top,
+ pad_bottom,
+ pad_left,
+ pad_right,
+ borderType=cv.BORDER_CONSTANT,
+ value=border_value,
+ )
+
+ # safety: enforce exact target size
+ if padded.shape[0] != target_size or padded.shape[1] != target_size:
+ padded = padded[:target_size, :target_size]
+
+ return padded
+
+
+def _minmax_to_minus1_1(x: np.ndarray, stats: dict, eps: float = 1e-6) -> np.ndarray:
+ """
+ x: (..., D)
+ stats: contains "min" and "max" (D,)
+ return: (..., D) in [-1, 1]
+ """
+ lo = np.asarray(stats["min"], dtype=np.float32)
+ hi = np.asarray(stats["max"], dtype=np.float32)
+ denom = np.maximum(hi - lo, eps)
+ x01 = (x - lo) / denom
+ xn = x01 * 2.0 - 1.0
+ return xn.astype(np.float32)
+
+
+def unnormalize_actions(normalized_actions: np.ndarray, action_norm_stats: Dict[str, np.ndarray]) -> np.ndarray:
+ """
+ Args:
+ normalized_actions: shape (B, chunk, D) (chunk, D)
+ action_norm_stats:
+ Returns:
+ actions
+ """
+ mask = action_norm_stats.get("mask", np.ones_like(action_norm_stats["min"], dtype=bool))
+ action_high, action_low = np.array(action_norm_stats["max"]), np.array(action_norm_stats["min"])
+
+ normalized_actions = np.clip(normalized_actions, -1, 1)
+
+ actions = np.where(
+ mask,
+ (normalized_actions + 1) / 2 * (action_high - action_low) + action_low,
+ normalized_actions,
+ )
+
+ return actions
+
+
+def _build_policy(args: Args):
+ vla = baseframework.from_pretrained(args.ckpt_path)
+ vla = vla.to("cuda").eval()
+
+ _, norm_stats = read_mode_config(Path(args.ckpt_path))
+ unnorm_key = args.unnorm_key
+
+ # ✅ action stats(你原来就有)
+ vla.action_norm_stats = norm_stats[unnorm_key]["action"]
+
+ # ✅ state stats(新增:用于输入归一化,训练一致)
+ vla.state_norm_stats = norm_stats[unnorm_key]["state"]
+
+ return vla
+
+
+def _infer_single(policy, obs: Dict, args: Args, gripper_th: float) -> Dict:
+ prompt = obs.get("prompt", "")
+ print("prompt", prompt)
+
+ # -------- state: raw -> normalized (min_max to [-1,1]) --------
+ state = np.asarray(obs["observation/state"], dtype=np.float32)
+ # print('state', state.shape, state)
+ if state.ndim == 1:
+ state = state[None, :] # (1, D)
+ elif state.ndim != 2:
+ raise ValueError(f"Unexpected state shape: {state.shape}")
+
+ # ✅ 训练一致:min_max 归一化
+ state_norm = _minmax_to_minus1_1(state, policy.state_norm_stats)
+
+ # padding 到 58
+ cur_dim = state_norm.shape[-1]
+ if cur_dim < 64:
+ pad_width = 64 - cur_dim
+ state_norm = np.pad(
+ state_norm,
+ pad_width=((0, 0), (0, pad_width)),
+ mode="constant",
+ constant_values=0.0,
+ )
+
+ head = resizepad_longest_edge_cv2(obs["observation/image"], target_size=args.image_size, fill_value=0)
+ left = resizepad_longest_edge_cv2(obs["observation/wrist_left_image"], target_size=args.image_size, fill_value=0)
+ right = resizepad_longest_edge_cv2(obs["observation/wrist_right_image"], target_size=args.image_size, fill_value=0)
+
+ fake_data = {
+ "image": [head, left, right],
+ "lang": prompt,
+ "state": state_norm,
+ }
+
+ print('img', obs["observation/image"].shape)
+ # raw = state
+ # sn = state_norm
+ # print("state raw min/max:", raw.min(), raw.max())
+ # print("state_norm min/max:", sn.min(), sn.max(), "clip_ratio:", np.mean((sn <= -0.999) | (sn >= 0.999)))
+
+ t0 = time.perf_counter()
+ with torch.inference_mode():
+ out = policy.predict_action(fake_data)
+ infer_ms = (time.perf_counter() - t0) * 1000
+
+ # out 来自 predict_action
+ na = out["normalized_actions"] # (1, 16, 18) numpy
+
+ # 1️⃣ 去掉 batch 维
+ na2 = na[0, :, :18] # (H, D) 你原逻辑保留
+
+ # 2️⃣ 用 numpy 版 unnormalize(CPU)
+ raw2 = unnormalize_actions(
+ na2,
+ policy.action_norm_stats,
+ ) # (16, 18)
+
+ # 3️⃣ 如有需要再加回 batch 维
+ actions = raw2[None, ...] # (1, 16, 18)
+ actions = raw2
+ print(actions[0, 0])
+
+ return {"actions": actions, "policy_timing": {"infer_ms": infer_ms}}
+
+
+def _health_check(connection: ws_server.ServerConnection, request: ws_server.Request):
+ """健康检查端点"""
+ if request.path == "/healthz":
+ return connection.respond(http.HTTPStatus.OK, "OK\n")
+ return None
+
+
+class Pi0PolicyServer:
+ """Pi0 WebSocket 推理服务端"""
+
+ def __init__(self, pi0_policy, args: Args):
+ self._policy = pi0_policy
+ self._args = args
+ self._metadata = {
+ "status": "ok",
+ "policy": "pi0",
+ "obs_cameras": args.obs_camera_name,
+ "action_dim": 14,
+ }
+ self._packer = msgpack_numpy.Packer()
+
+ def serve_forever(self) -> None:
+ """阻塞式启动服务"""
+ asyncio.run(self._run())
+
+ async def _run(self):
+ """异步运行服务"""
+ async with ws_server.serve(
+ self._handler,
+ self._args.host,
+ self._args.port,
+ compression=None,
+ max_size=None,
+ process_request=_health_check,
+ ) as server:
+ print("✓ 服务已启动,等待客户端连接...")
+ await server.serve_forever()
+
+ async def _handler(self, websocket: ws_server.ServerConnection):
+ """处理单个客户端连接"""
+ print(f"[连接] 客户端 {websocket.remote_address} 已连接")
+
+ # 发送 metadata
+ await websocket.send(self._packer.pack(self._metadata))
+
+ while True:
+ try:
+ data = await websocket.recv()
+ if isinstance(data, str):
+ await websocket.send(f"Invalid data type: {type(data)}")
+ continue
+
+ obs = msgpack_numpy.unpackb(data)
+ result = _infer_single(self._policy, obs, self._args, self._args.gripper_threshold)
+ await websocket.send(self._packer.pack(result))
+
+ except websockets.ConnectionClosed:
+ print(f"[断开] 客户端 {websocket.remote_address} 已断开")
+ break
+ except Exception:
+ error_msg = traceback.format_exc()
+ print(f"[错误] {error_msg}")
+ await websocket.send(error_msg)
+ await websocket.close(
+ code=websockets.frames.CloseCode.INTERNAL_ERROR,
+ reason="Internal server error",
+ )
+ raise
+
+
+def serve(args: Args):
+ print("=" * 60)
+ print("Pi0 WebSocket 推理服务端 (openpi-client 兼容)")
+ print("=" * 60)
+ print(f" 监听: ws://{args.host}:{args.port}")
+ print(f" 权重: {args.ckpt_path}")
+ print(f" 数据统计: {args.data_statistics_path}")
+ print(f" 相机键: {args.obs_camera_name}")
+ print(f" unnorm_key: {args.unnorm_key}")
+ print(f" tokenizer: {args.language_tokenizer_path}")
+ print("=" * 60)
+
+ print("[1/2] 初始化模型...")
+ pi0_policy = _build_policy(args)
+ print("✓ 模型就绪")
+
+ # ===== 在这里加 =====
+ print("Has predict_action:", hasattr(pi0_policy, "predict_action"))
+ print("Has __call__:", callable(pi0_policy))
+ print("Action-related methods:", [m for m in dir(pi0_policy) if "action" in m.lower()])
+
+ am = pi0_policy.action_model
+ print("past_action_window_size:", getattr(pi0_policy, "past_action_window_size", None))
+ print("future_action_window_size:", getattr(pi0_policy, "future_action_window_size", None))
+ print("action_model:", type(am))
+ print("action_model attrs (state):", [x for x in dir(am) if "state" in x.lower()])
+
+ # ===================
+
+ print("[2/2] 启动 WebSocket 服务...")
+ server = Pi0PolicyServer(pi0_policy, args)
+
+ try:
+ server.serve_forever()
+ except KeyboardInterrupt:
+ print("\n[退出] 收到中断信号,正在关闭服务...")
+
+
+def main():
+ serve(tyro.cli(Args))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/deployment_robotwin/upload/push_model_to_hf.py b/deployment_robotwin/upload/push_model_to_hf.py
new file mode 100644
index 0000000000000000000000000000000000000000..646ca535c4f266653adb214842dd6671c6d9358f
--- /dev/null
+++ b/deployment_robotwin/upload/push_model_to_hf.py
@@ -0,0 +1,12 @@
+from huggingface_hub import create_repo, HfApi
+
+# 1. create repository
+hf_name = "StarVLA/Qwen3-VL-OFT-LIBERO-4in1"
+create_repo(hf_name, repo_type="model", exist_ok=True)
+
+# 2. initialize API
+api = HfApi()
+
+# 3. upload large folder
+folder_path = "/mnt/petrelfs/yejinhui/Projects/starVLA/results/Checkpoints/1_need/Qwen3-VL-OFT-LIBERO-4in1"
+api.upload_large_folder(folder_path=folder_path, repo_id=hf_name, repo_type="model")
diff --git a/docs/WM4A.md b/docs/WM4A.md
new file mode 100644
index 0000000000000000000000000000000000000000..f0e203b7c23a21f96b3a6ca8157ef6cf0bf11042
--- /dev/null
+++ b/docs/WM4A.md
@@ -0,0 +1,154 @@
+# WM4A: World Model for Action
+
+WM4A repurposes **pretrained video-generation world models** as visual encoders for
+robot action prediction. Instead of using a Vision-Language Model (VLM) backbone,
+WM4A feeds images through a **Diffusion Transformer (DiT)** — the same architecture
+used for video prediction — and attaches a lightweight action head on top of its
+intermediate representations.
+
+## Motivation
+
+Video prediction models learn rich spatiotemporal representations of physics,
+object permanence, and dynamics. WM4A exploits these representations directly:
+
+```
+VLM approach: Image → VLM encoder → language-aligned features → Action Head
+WM4A approach: Image → Video DiT encoder → physics-aligned features → Action Head
+```
+
+## Supported Backbones
+
+| Backbone | Params | Layers | Hidden Dim | Source |
+|----------|--------|--------|------------|--------|
+| **Cosmos-Predict2-2B** | 2B | 28 | 2048 | NVIDIA Cosmos |
+| **Wan2.2-T2V** | 5B | 30 | 3072 | Alibaba Wan |
+
+## Architecture
+
+```
+Input: {images: [PIL], instruction: str, actions: [T, action_dim]}
+ │
+ ├─ Text Encoder (T5 / UMT5)
+ │ instruction → [B, L_text, text_hidden]
+ │
+ ├─ VAE Encoder
+ │ images → latents [B, 16, T_latent, H/8, W/8]
+ │
+ └─ DiT Transformer (frozen or fine-tuned)
+ latents + text_embeds → hidden_states [B, N_tokens, hidden_dim]
+ │
+ └─ Action Head (one of three variants below)
+ → predicted actions [B, chunk_len, action_dim]
+```
+
+## Action Head Variants
+
+Each backbone can be paired with three action head types:
+
+| Variant | Action Head | What it uses | Speed | Frameworks |
+|---------|------------|--------------|-------|------------|
+| **OFT** | MLP regression | Last layer only | Fastest | `CosmoPredict2OFT`, `WanOFT` |
+| **GR00T** | Flow-matching diffusion (single-layer) | Last layer only | Medium | `CosmoPredict2GR00T`, `WanGR00T` |
+| **PI** | Layer-wise cross-attention DiT | All transformer layers | Slowest | `CosmoPredict2PI`, `WanPI` |
+
+This gives **7 framework combinations** (including a generic `WM4A_OFT`).
+
+## Quick Start: Inspect the Data Flow
+
+Run the built-in demo to see the full forward pass (training + inference):
+
+```bash
+python starVLA/model/framework/WM4A/CosmoPredict2GR00T.py
+```
+
+This script:
+1. Loads a config and instantiates the `CosmoPredict2_GR00T` model
+2. Creates a synthetic batch with multi-view images and random actions
+3. Runs the **training forward** and prints the action loss
+4. Runs the **inference forward** and prints the predicted actions
+
+> **Note:** You need the Cosmos-Predict2-2B weights downloaded locally.
+> Set the path in the script or download via:
+> ```bash
+> huggingface-cli download nvidia/Cosmos-Predict2-2B-Video2World \
+> --local-dir ./playground/Pretrained_models/nvidia/Cosmos-Predict2-2B-Video2World
+> ```
+
+## Training
+
+### Recommended: LIBERO with CosmoPredict2OFT
+
+The simplest way to train a WM4A model is with the OFT (MLP) action head on
+the LIBERO benchmark:
+
+```bash
+# From the starVLA project root
+bash examples/LIBERO/train_files/run_libero_train.sh
+```
+
+Before running, edit the script to set your local paths:
+
+```bash
+Framework_name=CosmoPredict2OFT # or CosmoPredict2GR00T, WanOFT, etc.
+base_wm=nvidia/Cosmos-Predict2-2B-Video2World> # still needed for tokenizer/processor
+config_yaml=./examples/LIBERO/train_files/starvla_cotrain_libero.yaml
+libero_data_root=
+data_mix=libero_all # or libero_goal
+```
+
+Key training arguments:
+
+| Argument | Description | Recommended |
+|----------|-------------|-------------|
+| `--framework.name` | Framework class name | `CosmoPredict2OFT` |
+| `--framework.action_model.future_action_window_size` | Action prediction horizon | 7 |
+| `--datasets.vla_data.per_device_batch_size` | Per-GPU batch size | 16 (OFT) / 8 (GR00T) |
+| `--trainer.max_train_steps` | Total training steps | 80000 |
+| `--trainer.save_interval` | Checkpoint save frequency | 10000 |
+
+### Switching Backbones
+
+To use Wan instead of Cosmos, simply change the framework name:
+
+```bash
+Framework_name=WanOFT # or WanGR00T, WanPI
+```
+
+The config YAML remains the same — the framework class handles backbone loading
+automatically based on its registered name.
+
+## Code Structure
+
+```
+starVLA/model/
+├── framework/
+│ └── WM4A/
+│ ├── CosmoPredict2GR00T.py # Cosmos + flow-matching head
+│ ├── CosmoPredict2OFT.py # Cosmos + MLP head
+│ ├── CosmoPredict2PI.py # Cosmos + layer-wise cross-DiT head
+│ ├── WanGR00T.py # Wan + flow-matching head
+│ ├── WanOFT.py # Wan + MLP head
+│ ├── WanPI.py # Wan + layer-wise cross-DiT head
+│ └── WM4A_OFT.py # Generic WM backend + MLP head
+└── modules/
+ ├── world_model/
+ │ └── CosmoPredict2.py # Cosmos backbone wrapper (VAE + T5 + DiT)
+ └── action_model/
+ ├── MLP_ActionHeader.py # OFT action head
+ ├── flow_matching_head/ # GR00T action head (single-layer FM)
+ └── LayerwiseFM_ActionHeader.py # PI action head (layer-wise FM)
+```
+
+## Key Implementation Details
+
+- **Precision**: DiT forward runs in `bfloat16` for speed; action head runs in
+ `float32` for numerical stability.
+- **Feature extraction**: Uses PyTorch hooks on selected DiT blocks to capture
+ intermediate hidden states without modifying the backbone code.
+- **Timestep trick**: Sets `timestep=0` during feature extraction — this extracts
+ representations at the near-clean noise level rather than denoising.
+- **Shape reshaping**: DiT outputs `[B, C, T, H, W]` video tensors, which are
+ reshaped to `[B, T*H*W, C]` token sequences for the action head.
+- **Framework registry**: All WM4A classes register themselves via
+ `@FRAMEWORK_REGISTRY.register("FrameworkName")` and are auto-discovered at
+ import time — no manual imports needed.
diff --git a/environment/README.md b/environment/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..f5fa819db20ed1e1191e4734270e81695260ad3f
--- /dev/null
+++ b/environment/README.md
@@ -0,0 +1,67 @@
+# Evaluation Environments
+
+The Mac contains portable source, model metadata, and simulation assets, not a
+native macOS policy runtime. Run evaluation on a Linux x86_64 NVIDIA GPU machine.
+Policy inference and simulation use separate Python 3.10 environments, as in
+the historical evaluation.
+
+## Validated Source Selection
+
+The launcher prepends only this repository and its vendored packages to
+`PYTHONPATH`. It disables user-site imports and online model downloads.
+Do not use the machine's editable RoboCasa installation: it can point to
+another user's modified checkout.
+
+- RoboCasa: historical `liao` checkout, Git base
+ `4840e671596f93ca03651524b9f72ffb1aadfeff`, including its modified `tabletop.py`.
+- RoboSuite: version 1.5.1 source and matching assets are vendored.
+- GR1 kinematics: exact historical URDF and `gr1_pos_transform_new.py`.
+- `pykdl_utils` and `hrl_geom`: local source copies, not unresolved editable paths.
+- Orocos KDL / PyKDL 1.5.4: vendored source at
+ `third_party/orocos_kinematics_dynamics`, Git commit
+ `fb840b0edb3e9905c354276d6513dddf4fd4ac1b`. The setup recipe builds this
+ version rather than substituting a Conda KDL 1.5.1 package.
+- No new GR00T policy or newer RoboCasa task set is substituted.
+
+## Environment Recreation
+
+Run `bash environment/create_linux_envs.sh /absolute/empty/environment/prefix`.
+This creates new environments and refuses to overwrite existing ones.
+The setup script is a recreation recipe; clean-machine installation is a
+separate validation from tests using the original server's environments.
+
+The NVIDIA driver and an EGL-capable rendering installation must be supplied
+by the host/container. FlashAttention compilation additionally requires an
+appropriate CUDA toolkit and C++ compiler. The launcher accepts
+`EGL_LIBRARY_PATH` when the host's EGL driver libraries need an explicit path;
+it does not embed the original server's library directory.
+
+Important runtime versions:
+
+| Component | Policy | Simulation |
+| --- | --- | --- |
+| Python | 3.10.19 | 3.10.18 |
+| PyTorch | 2.8.0 + CUDA 12.8 | 2.5.1 + CUDA 12.4 |
+| TorchVision | 0.23.0 | 0.20.1 |
+| NumPy | 2.2.6 | 1.26.4 |
+| Gymnasium | not used for simulation | 1.0.0 |
+| MuJoCo | not used for simulation | 3.2.6 |
+| Transformers | 5.8.1 | not needed by the portable simulation entry |
+| Diffusers | 0.38.0 | not needed by the portable simulation entry |
+| FlashAttention | 2.8.3 | not needed |
+| PyKDL | not used | 1.5.4 |
+| PyAV | 12.3.0 | 12.3.0 |
+
+`*.observed.json` retains all installed distribution metadata as found during
+migration. The old simulation environment contains duplicate distribution
+metadata, including Torch 2.5.1/2.8.0 and Gymnasium 1.0.0/1.2.1. Actual imported
+runtime versions take precedence over those stale metadata entries.
+
+The simulation client uses a lightweight metadata reader with the same YAML
+and statistics semantics as the original helper; it no longer imports the
+entire model registry just to read normalization values.
+
+Clean-install validation was attempted on September 25, 2026 but the authorized
+server could not reach `conda.anaconda.org:443` (network unreachable). The setup
+recipe must not be described as clean-install validated. Forward tests using
+the preserved environments are recorded separately in `../VALIDATION.md`.
diff --git a/environment/build_kdl.sh b/environment/build_kdl.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b4fa44d7fb4461170392ebc333813ef9fd66e4a0
--- /dev/null
+++ b/environment/build_kdl.sh
@@ -0,0 +1,27 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+PYTHON="${1:?Pass the absolute simulation Python path}"
+PREFIX="${2:?Pass an installation prefix owned by this release setup}"
+SOURCE="$ROOT/third_party/orocos_kinematics_dynamics"
+BUILD="$PREFIX/.kdl-build"
+[[ "$PREFIX" = /* && "$PYTHON" = /* ]] || { echo "Use absolute paths." >&2; exit 2; }
+[[ ! -e "$BUILD" ]] || { echo "Refusing to overwrite an existing KDL build." >&2; exit 2; }
+VERSION="$("$PYTHON" -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')"
+[[ "$VERSION" = 3.10 ]] || { echo "Use the pinned Python 3.10 interpreter." >&2; exit 2; }
+export PATH="$PREFIX/bin:$PATH"
+cmake -S "$SOURCE/orocos_kdl" -B "$BUILD/core" \
+ -DCMAKE_INSTALL_PREFIX="$PREFIX" -DCMAKE_BUILD_TYPE=Release \
+ -DCMAKE_PREFIX_PATH="$PREFIX" -DBUILD_TESTING=OFF
+cmake --build "$BUILD/core" --parallel "${MAX_JOBS:-2}"
+cmake --install "$BUILD/core"
+cmake -S "$SOURCE/python_orocos_kdl" -B "$BUILD/python" \
+ -DCMAKE_INSTALL_PREFIX="$PREFIX" -DCMAKE_BUILD_TYPE=Release \
+ -DCMAKE_PREFIX_PATH="$PREFIX" -DPython3_EXECUTABLE="$PYTHON" \
+ -DPYTHON_SITE_PACKAGES_INSTALL_DIR="$PREFIX/lib/python3.10/site-packages" \
+ -DCMAKE_INSTALL_RPATH="$PREFIX/lib"
+cmake --build "$BUILD/python" --parallel "${MAX_JOBS:-2}"
+cmake --install "$BUILD/python"
+PYTHONPATH="$PREFIX/lib/python3.10/site-packages" "$PYTHON" -c \
+ 'import PyKDL; assert PyKDL.__version__ == "1.5.4"; print(PyKDL.__file__, PyKDL.__version__)'
diff --git a/environment/create_linux_envs.sh b/environment/create_linux_envs.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e0fa89459e5f371840733612f04cfc45abf9f90b
--- /dev/null
+++ b/environment/create_linux_envs.sh
@@ -0,0 +1,31 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+if [[ "$(uname -s)" != Linux || "$(uname -m)" != x86_64 ]]; then
+ echo "Evaluation requires a Linux x86_64 NVIDIA CUDA host. The Mac copy is the portable source archive." >&2
+ exit 2
+fi
+command -v conda >/dev/null || { echo "Install Miniforge/Conda first." >&2; exit 2; }
+PREFIX="${1:-$ROOT/.runtime/envs}"
+POLICY="$PREFIX/policy"
+SIM="$PREFIX/simulation"
+if [[ -e "$POLICY" || -e "$SIM" ]]; then
+ echo "Refusing to alter existing environments. Choose a new empty prefix." >&2
+ exit 2
+fi
+conda create -y -p "$POLICY" -c conda-forge python=3.10.19 pip
+"$POLICY/bin/python" -m pip install torch==2.8.0 torchvision==0.23.0 \
+ --index-url https://download.pytorch.org/whl/cu128
+"$POLICY/bin/python" -m pip install -r "$ROOT/environment/policy.requirements.txt"
+"$POLICY/bin/python" -m pip install packaging ninja
+MAX_JOBS="${MAX_JOBS:-4}" "$POLICY/bin/python" -m pip install flash-attn==2.8.3 --no-build-isolation
+
+conda create -y -p "$SIM" -c conda-forge python=3.10.18 pip cmake eigen cxx-compiler
+"$SIM/bin/python" -m pip install torch==2.5.1 torchvision==0.20.1 \
+ --index-url https://download.pytorch.org/whl/cu124
+"$SIM/bin/python" -m pip install -r "$ROOT/environment/simulation.requirements.txt"
+bash "$ROOT/environment/build_kdl.sh" "$SIM/bin/python" "$SIM"
+echo "POLICY_PYTHON=$POLICY/bin/python"
+echo "SIM_PYTHON=$SIM/bin/python"
+echo "Source packages are selected through release.evaluate's isolated PYTHONPATH."
diff --git a/environment/policy.requirements.txt b/environment/policy.requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..93dd50c673edc79475054645d739ca5234ad6fcd
--- /dev/null
+++ b/environment/policy.requirements.txt
@@ -0,0 +1,24 @@
+accelerate==1.5.2
+av==12.3.0
+diffusers==0.38.0
+einops==0.8.1
+easydict==1.13
+huggingface-hub==1.15.0
+matplotlib==3.10.8
+msgpack==1.1.2
+msgpack-numpy==0.4.8
+numpy==2.2.6
+omegaconf==2.3.0
+opencv-python-headless==4.11.0.86
+pillow==12.0.0
+pydantic==2.10.6
+qwen-vl-utils==0.0.14
+rich==14.2.0
+safetensors==0.8.0rc0
+scipy==1.15.3
+sentencepiece==0.2.1
+setuptools==80.9.0
+timm==1.0.22
+transformers==5.8.1
+tyro==1.0.3
+websockets==15.0.1
diff --git a/environment/robocasa.observed.json b/environment/robocasa.observed.json
new file mode 100644
index 0000000000000000000000000000000000000000..daac0a0334fde29def815d08feb7ba6937c5e69f
--- /dev/null
+++ b/environment/robocasa.observed.json
@@ -0,0 +1,1288 @@
+{
+ "python": "3.10.18 | packaged by conda-forge | (main, Jun 4 2025, 14:45:41) [GCC 13.3.0]",
+ "packages": [
+ {
+ "name": "Farama-Notifications",
+ "version": "0.0.4",
+ "direct_url": null
+ },
+ {
+ "name": "PyOpenGL",
+ "version": "3.1.7",
+ "direct_url": null
+ },
+ {
+ "name": "PyOpenGL-accelerate",
+ "version": "3.1.7",
+ "direct_url": null
+ },
+ {
+ "name": "PyYAML",
+ "version": "6.0.2",
+ "direct_url": null
+ },
+ {
+ "name": "PyYAML",
+ "version": "6.0.3",
+ "direct_url": null
+ },
+ {
+ "name": "TorchCodec",
+ "version": "0.1.0",
+ "direct_url": null
+ },
+ {
+ "name": "absl-py",
+ "version": "2.3.1",
+ "direct_url": null
+ },
+ {
+ "name": "accelerate",
+ "version": "1.2.1",
+ "direct_url": null
+ },
+ {
+ "name": "aiosignal",
+ "version": "1.4.0",
+ "direct_url": null
+ },
+ {
+ "name": "albucore",
+ "version": "0.0.17",
+ "direct_url": null
+ },
+ {
+ "name": "albumentations",
+ "version": "1.4.18",
+ "direct_url": null
+ },
+ {
+ "name": "annotated-types",
+ "version": "0.7.0",
+ "direct_url": null
+ },
+ {
+ "name": "antlr4-python3-runtime",
+ "version": "4.9.3",
+ "direct_url": null
+ },
+ {
+ "name": "anytree",
+ "version": "2.13.0",
+ "direct_url": null
+ },
+ {
+ "name": "astunparse",
+ "version": "1.6.3",
+ "direct_url": null
+ },
+ {
+ "name": "attrs",
+ "version": "25.4.0",
+ "direct_url": null
+ },
+ {
+ "name": "av",
+ "version": "12.3.0",
+ "direct_url": null
+ },
+ {
+ "name": "blessings",
+ "version": "1.7",
+ "direct_url": null
+ },
+ {
+ "name": "cachetools",
+ "version": "6.2.0",
+ "direct_url": null
+ },
+ {
+ "name": "catkin-pkg",
+ "version": "1.1.0",
+ "direct_url": null
+ },
+ {
+ "name": "certifi",
+ "version": "2025.10.5",
+ "direct_url": null
+ },
+ {
+ "name": "charset-normalizer",
+ "version": "3.4.3",
+ "direct_url": null
+ },
+ {
+ "name": "click",
+ "version": "8.3.0",
+ "direct_url": null
+ },
+ {
+ "name": "cloudpickle",
+ "version": "3.1.1",
+ "direct_url": null
+ },
+ {
+ "name": "cmeel",
+ "version": "0.59.0",
+ "direct_url": null
+ },
+ {
+ "name": "cmeel-assimp",
+ "version": "6.0.2",
+ "direct_url": null
+ },
+ {
+ "name": "cmeel-boost",
+ "version": "1.89.0",
+ "direct_url": null
+ },
+ {
+ "name": "cmeel-console-bridge",
+ "version": "1.0.2.3",
+ "direct_url": null
+ },
+ {
+ "name": "cmeel-octomap",
+ "version": "1.10.0",
+ "direct_url": null
+ },
+ {
+ "name": "cmeel-qhull",
+ "version": "8.0.2.1",
+ "direct_url": null
+ },
+ {
+ "name": "cmeel-tinyxml2",
+ "version": "10.0.0",
+ "direct_url": null
+ },
+ {
+ "name": "cmeel-urdfdom",
+ "version": "4.0.1",
+ "direct_url": null
+ },
+ {
+ "name": "cmeel-zlib",
+ "version": "1.3.1",
+ "direct_url": null
+ },
+ {
+ "name": "coal",
+ "version": "3.0.2",
+ "direct_url": null
+ },
+ {
+ "name": "contourpy",
+ "version": "1.3.2",
+ "direct_url": null
+ },
+ {
+ "name": "cramjam",
+ "version": "2.11.0",
+ "direct_url": null
+ },
+ {
+ "name": "cycler",
+ "version": "0.12.1",
+ "direct_url": null
+ },
+ {
+ "name": "datasets",
+ "version": "4.8.4",
+ "direct_url": null
+ },
+ {
+ "name": "debugpy",
+ "version": "1.8.19",
+ "direct_url": null
+ },
+ {
+ "name": "decord",
+ "version": "0.6.0",
+ "direct_url": null
+ },
+ {
+ "name": "diffusers",
+ "version": "0.30.2",
+ "direct_url": null
+ },
+ {
+ "name": "dill",
+ "version": "0.4.1",
+ "direct_url": null
+ },
+ {
+ "name": "dm-tree",
+ "version": "0.1.8",
+ "direct_url": null
+ },
+ {
+ "name": "docker-pycreds",
+ "version": "0.4.0",
+ "direct_url": null
+ },
+ {
+ "name": "docstring_parser",
+ "version": "0.17.0",
+ "direct_url": null
+ },
+ {
+ "name": "docutils",
+ "version": "0.22.3",
+ "direct_url": null
+ },
+ {
+ "name": "eigenpy",
+ "version": "3.12.0",
+ "direct_url": null
+ },
+ {
+ "name": "einops",
+ "version": "0.8.1",
+ "direct_url": null
+ },
+ {
+ "name": "etils",
+ "version": "1.13.0",
+ "direct_url": null
+ },
+ {
+ "name": "eval_type_backport",
+ "version": "0.2.2",
+ "direct_url": null
+ },
+ {
+ "name": "evdev",
+ "version": "1.9.2",
+ "direct_url": null
+ },
+ {
+ "name": "exceptiongroup",
+ "version": "1.3.0",
+ "direct_url": null
+ },
+ {
+ "name": "fastparquet",
+ "version": "2024.11.0",
+ "direct_url": null
+ },
+ {
+ "name": "filelock",
+ "version": "3.20.0",
+ "direct_url": null
+ },
+ {
+ "name": "flatbuffers",
+ "version": "25.9.23",
+ "direct_url": null
+ },
+ {
+ "name": "fonttools",
+ "version": "4.60.1",
+ "direct_url": null
+ },
+ {
+ "name": "frozenlist",
+ "version": "1.8.0",
+ "direct_url": null
+ },
+ {
+ "name": "fsspec",
+ "version": "2025.9.0",
+ "direct_url": null
+ },
+ {
+ "name": "fvcore",
+ "version": "0.1.5.post20221221",
+ "direct_url": null
+ },
+ {
+ "name": "gast",
+ "version": "0.6.0",
+ "direct_url": null
+ },
+ {
+ "name": "gitdb",
+ "version": "4.0.12",
+ "direct_url": null
+ },
+ {
+ "name": "GitPython",
+ "version": "3.1.45",
+ "direct_url": null
+ },
+ {
+ "name": "glfw",
+ "version": "2.10.0",
+ "direct_url": null
+ },
+ {
+ "name": "google-auth",
+ "version": "2.41.1",
+ "direct_url": null
+ },
+ {
+ "name": "google-auth-oauthlib",
+ "version": "1.2.2",
+ "direct_url": null
+ },
+ {
+ "name": "google-pasta",
+ "version": "0.2.0",
+ "direct_url": null
+ },
+ {
+ "name": "gr00t",
+ "version": "1.1.0",
+ "direct_url": {
+ "dir_info": {
+ "editable": true
+ },
+ "url": "file:///mnt/workspace/users/zhangtianle/others/Isaac-GR00T"
+ }
+ },
+ {
+ "name": "grpcio",
+ "version": "1.75.1",
+ "direct_url": null
+ },
+ {
+ "name": "gymnasium",
+ "version": "1.0.0",
+ "direct_url": null
+ },
+ {
+ "name": "gymnasium",
+ "version": "1.2.1",
+ "direct_url": null
+ },
+ {
+ "name": "h5py",
+ "version": "3.12.1",
+ "direct_url": null
+ },
+ {
+ "name": "h5py",
+ "version": "3.14.0",
+ "direct_url": null
+ },
+ {
+ "name": "hf-xet",
+ "version": "1.1.10",
+ "direct_url": null
+ },
+ {
+ "name": "hidapi",
+ "version": "0.14.0.post4",
+ "direct_url": null
+ },
+ {
+ "name": "hrl_geom",
+ "version": "0.1.0",
+ "direct_url": {
+ "dir_info": {
+ "editable": true
+ },
+ "url": "file:///mnt/workspace/users/zhangtianle/others/hrl_geom"
+ }
+ },
+ {
+ "name": "huggingface-hub",
+ "version": "0.35.3",
+ "direct_url": null
+ },
+ {
+ "name": "hydra-core",
+ "version": "1.3.2",
+ "direct_url": null
+ },
+ {
+ "name": "idna",
+ "version": "3.10",
+ "direct_url": null
+ },
+ {
+ "name": "imageio",
+ "version": "2.34.2",
+ "direct_url": null
+ },
+ {
+ "name": "imageio",
+ "version": "2.37.0",
+ "direct_url": null
+ },
+ {
+ "name": "imageio-ffmpeg",
+ "version": "0.6.0",
+ "direct_url": null
+ },
+ {
+ "name": "importlib_metadata",
+ "version": "8.7.0",
+ "direct_url": null
+ },
+ {
+ "name": "importlib_resources",
+ "version": "6.5.2",
+ "direct_url": null
+ },
+ {
+ "name": "iniconfig",
+ "version": "2.1.0",
+ "direct_url": null
+ },
+ {
+ "name": "inquirerpy",
+ "version": "0.3.4",
+ "direct_url": null
+ },
+ {
+ "name": "iopath",
+ "version": "0.1.10",
+ "direct_url": null
+ },
+ {
+ "name": "Jinja2",
+ "version": "3.1.6",
+ "direct_url": null
+ },
+ {
+ "name": "jsonschema",
+ "version": "4.25.1",
+ "direct_url": null
+ },
+ {
+ "name": "jsonschema-specifications",
+ "version": "2025.9.1",
+ "direct_url": null
+ },
+ {
+ "name": "keras",
+ "version": "2.15.0",
+ "direct_url": null
+ },
+ {
+ "name": "kiwisolver",
+ "version": "1.4.9",
+ "direct_url": null
+ },
+ {
+ "name": "kornia",
+ "version": "0.7.4",
+ "direct_url": null
+ },
+ {
+ "name": "kornia_rs",
+ "version": "0.1.9",
+ "direct_url": null
+ },
+ {
+ "name": "lazy_loader",
+ "version": "0.4",
+ "direct_url": null
+ },
+ {
+ "name": "lerobot",
+ "version": "0.4.4",
+ "direct_url": null
+ },
+ {
+ "name": "libclang",
+ "version": "18.1.1",
+ "direct_url": null
+ },
+ {
+ "name": "libcoal",
+ "version": "3.0.2",
+ "direct_url": null
+ },
+ {
+ "name": "libero",
+ "version": "0.1.0",
+ "direct_url": {
+ "dir_info": {
+ "editable": true
+ },
+ "url": "file:///mnt/workspace/users/zlk/openpi/third_party/LIBERO"
+ }
+ },
+ {
+ "name": "libpinocchio",
+ "version": "3.9.0",
+ "direct_url": null
+ },
+ {
+ "name": "llvmlite",
+ "version": "0.44.0",
+ "direct_url": null
+ },
+ {
+ "name": "lxml",
+ "version": "6.0.2",
+ "direct_url": null
+ },
+ {
+ "name": "Markdown",
+ "version": "3.9",
+ "direct_url": null
+ },
+ {
+ "name": "markdown-it-py",
+ "version": "4.0.0",
+ "direct_url": null
+ },
+ {
+ "name": "MarkupSafe",
+ "version": "3.0.3",
+ "direct_url": null
+ },
+ {
+ "name": "matplotlib",
+ "version": "3.10.0",
+ "direct_url": null
+ },
+ {
+ "name": "mdurl",
+ "version": "0.1.2",
+ "direct_url": null
+ },
+ {
+ "name": "mink",
+ "version": "0.0.5",
+ "direct_url": null
+ },
+ {
+ "name": "ml-dtypes",
+ "version": "0.2.0",
+ "direct_url": null
+ },
+ {
+ "name": "mpmath",
+ "version": "1.3.0",
+ "direct_url": null
+ },
+ {
+ "name": "msgpack",
+ "version": "1.1.2",
+ "direct_url": null
+ },
+ {
+ "name": "msgpack-numpy",
+ "version": "0.4.8",
+ "direct_url": null
+ },
+ {
+ "name": "mujoco",
+ "version": "3.2.6",
+ "direct_url": null
+ },
+ {
+ "name": "multiprocess",
+ "version": "0.70.19",
+ "direct_url": null
+ },
+ {
+ "name": "networkx",
+ "version": "3.4.2",
+ "direct_url": null
+ },
+ {
+ "name": "nlopt",
+ "version": "2.10.0",
+ "direct_url": null
+ },
+ {
+ "name": "numba",
+ "version": "0.61.2",
+ "direct_url": null
+ },
+ {
+ "name": "numpy",
+ "version": "1.26.4",
+ "direct_url": null
+ },
+ {
+ "name": "numpydantic",
+ "version": "1.6.7",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-cublas-cu12",
+ "version": "12.4.5.8",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-cublas-cu12",
+ "version": "12.8.4.1",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-cuda-cupti-cu12",
+ "version": "12.4.127",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-cuda-cupti-cu12",
+ "version": "12.8.90",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-cuda-nvrtc-cu12",
+ "version": "12.4.127",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-cuda-nvrtc-cu12",
+ "version": "12.8.93",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-cuda-runtime-cu12",
+ "version": "12.4.127",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-cuda-runtime-cu12",
+ "version": "12.8.90",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-cudnn-cu12",
+ "version": "9.1.0.70",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-cudnn-cu12",
+ "version": "9.10.2.21",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-cufft-cu12",
+ "version": "11.2.1.3",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-cufft-cu12",
+ "version": "11.3.3.83",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-cufile-cu12",
+ "version": "1.13.1.3",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-curand-cu12",
+ "version": "10.3.5.147",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-curand-cu12",
+ "version": "10.3.9.90",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-cusolver-cu12",
+ "version": "11.6.1.9",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-cusolver-cu12",
+ "version": "11.7.3.90",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-cusparse-cu12",
+ "version": "12.3.1.170",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-cusparse-cu12",
+ "version": "12.5.8.93",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-cusparselt-cu12",
+ "version": "0.7.1",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-ml-py",
+ "version": "13.580.82",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-nccl-cu12",
+ "version": "2.21.5",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-nccl-cu12",
+ "version": "2.27.3",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-nvjitlink-cu12",
+ "version": "12.4.127",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-nvjitlink-cu12",
+ "version": "12.8.93",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-nvtx-cu12",
+ "version": "12.4.127",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-nvtx-cu12",
+ "version": "12.8.90",
+ "direct_url": null
+ },
+ {
+ "name": "oauthlib",
+ "version": "3.3.1",
+ "direct_url": null
+ },
+ {
+ "name": "omegaconf",
+ "version": "2.3.0",
+ "direct_url": null
+ },
+ {
+ "name": "onnx",
+ "version": "1.17.0",
+ "direct_url": null
+ },
+ {
+ "name": "opencv-python",
+ "version": "4.11.0.86",
+ "direct_url": null
+ },
+ {
+ "name": "opencv-python",
+ "version": "4.8.0.74",
+ "direct_url": null
+ },
+ {
+ "name": "opencv-python-headless",
+ "version": "4.11.0.86",
+ "direct_url": null
+ },
+ {
+ "name": "opt_einsum",
+ "version": "3.4.0",
+ "direct_url": null
+ },
+ {
+ "name": "packaging",
+ "version": "25.0",
+ "direct_url": null
+ },
+ {
+ "name": "pandas",
+ "version": "2.2.3",
+ "direct_url": null
+ },
+ {
+ "name": "peft",
+ "version": "0.17.0",
+ "direct_url": null
+ },
+ {
+ "name": "pettingzoo",
+ "version": "1.25.0",
+ "direct_url": null
+ },
+ {
+ "name": "pfzy",
+ "version": "0.3.4",
+ "direct_url": null
+ },
+ {
+ "name": "pillow",
+ "version": "11.3.0",
+ "direct_url": null
+ },
+ {
+ "name": "pin",
+ "version": "3.9.0",
+ "direct_url": null
+ },
+ {
+ "name": "pip",
+ "version": "25.3",
+ "direct_url": null
+ },
+ {
+ "name": "pipablepytorch3d",
+ "version": "0.7.6",
+ "direct_url": null
+ },
+ {
+ "name": "platformdirs",
+ "version": "4.5.0",
+ "direct_url": null
+ },
+ {
+ "name": "pluggy",
+ "version": "1.6.0",
+ "direct_url": null
+ },
+ {
+ "name": "portalocker",
+ "version": "3.2.0",
+ "direct_url": null
+ },
+ {
+ "name": "prompt_toolkit",
+ "version": "3.0.52",
+ "direct_url": null
+ },
+ {
+ "name": "protobuf",
+ "version": "3.20.3",
+ "direct_url": null
+ },
+ {
+ "name": "protobuf",
+ "version": "6.32.1",
+ "direct_url": null
+ },
+ {
+ "name": "psutil",
+ "version": "7.1.0",
+ "direct_url": null
+ },
+ {
+ "name": "pyarrow",
+ "version": "14.0.1",
+ "direct_url": null
+ },
+ {
+ "name": "pyasn1",
+ "version": "0.6.1",
+ "direct_url": null
+ },
+ {
+ "name": "pyasn1_modules",
+ "version": "0.4.2",
+ "direct_url": null
+ },
+ {
+ "name": "pybind11",
+ "version": "3.0.2a0",
+ "direct_url": {
+ "dir_info": {},
+ "url": "file:///vla/users/lijiayi/code/robot_retarget/retarget/body_retarget/pybind11"
+ }
+ },
+ {
+ "name": "pydantic",
+ "version": "2.10.6",
+ "direct_url": null
+ },
+ {
+ "name": "pydantic_core",
+ "version": "2.27.2",
+ "direct_url": null
+ },
+ {
+ "name": "pygame",
+ "version": "2.6.1",
+ "direct_url": null
+ },
+ {
+ "name": "Pygments",
+ "version": "2.19.2",
+ "direct_url": null
+ },
+ {
+ "name": "pykdl_utils",
+ "version": "0.1.0",
+ "direct_url": {
+ "dir_info": {
+ "editable": true
+ },
+ "url": "file:///mnt/workspace/users/zhangtianle/others/pykdl_utils"
+ }
+ },
+ {
+ "name": "pynput",
+ "version": "1.8.1",
+ "direct_url": null
+ },
+ {
+ "name": "pyparsing",
+ "version": "3.2.5",
+ "direct_url": null
+ },
+ {
+ "name": "pyperclip",
+ "version": "1.11.0",
+ "direct_url": null
+ },
+ {
+ "name": "pytest",
+ "version": "8.4.2",
+ "direct_url": null
+ },
+ {
+ "name": "python-dateutil",
+ "version": "2.9.0.post0",
+ "direct_url": null
+ },
+ {
+ "name": "python-xlib",
+ "version": "0.33",
+ "direct_url": null
+ },
+ {
+ "name": "pytransform3d",
+ "version": "3.14.4",
+ "direct_url": null
+ },
+ {
+ "name": "pytz",
+ "version": "2025.2",
+ "direct_url": null
+ },
+ {
+ "name": "pyzmq",
+ "version": "27.1.0",
+ "direct_url": null
+ },
+ {
+ "name": "qpsolvers",
+ "version": "4.8.1",
+ "direct_url": null
+ },
+ {
+ "name": "quadprog",
+ "version": "0.1.13",
+ "direct_url": null
+ },
+ {
+ "name": "qwen-vl-utils",
+ "version": "0.0.14",
+ "direct_url": null
+ },
+ {
+ "name": "ray",
+ "version": "2.40.0",
+ "direct_url": null
+ },
+ {
+ "name": "referencing",
+ "version": "0.36.2",
+ "direct_url": null
+ },
+ {
+ "name": "regex",
+ "version": "2025.9.18",
+ "direct_url": null
+ },
+ {
+ "name": "requests",
+ "version": "2.32.3",
+ "direct_url": null
+ },
+ {
+ "name": "requests-oauthlib",
+ "version": "2.0.0",
+ "direct_url": null
+ },
+ {
+ "name": "rich",
+ "version": "14.2.0",
+ "direct_url": null
+ },
+ {
+ "name": "robocasa",
+ "version": "0.2.0",
+ "direct_url": {
+ "dir_info": {
+ "editable": true
+ },
+ "url": "file:///mnt/workspace/users/zhangtianle/others/robocasa-gr1-tabletop-tasks"
+ }
+ },
+ {
+ "name": "robosuite",
+ "version": "1.5.1",
+ "direct_url": {
+ "dir_info": {
+ "editable": true
+ },
+ "url": "file:///mnt/workspace/users/zhangtianle/others/robosuite"
+ }
+ },
+ {
+ "name": "robosuite_models",
+ "version": "1.0.0",
+ "direct_url": null
+ },
+ {
+ "name": "rpds-py",
+ "version": "0.27.1",
+ "direct_url": null
+ },
+ {
+ "name": "rsa",
+ "version": "4.9.1",
+ "direct_url": null
+ },
+ {
+ "name": "safetensors",
+ "version": "0.6.2",
+ "direct_url": null
+ },
+ {
+ "name": "sapien",
+ "version": "3.0.1",
+ "direct_url": null
+ },
+ {
+ "name": "scikit-image",
+ "version": "0.25.2",
+ "direct_url": null
+ },
+ {
+ "name": "scipy",
+ "version": "1.15.3",
+ "direct_url": null
+ },
+ {
+ "name": "sentry-sdk",
+ "version": "2.41.0",
+ "direct_url": null
+ },
+ {
+ "name": "setproctitle",
+ "version": "1.3.7",
+ "direct_url": null
+ },
+ {
+ "name": "setuptools",
+ "version": "80.9.0",
+ "direct_url": null
+ },
+ {
+ "name": "shtab",
+ "version": "1.7.2",
+ "direct_url": null
+ },
+ {
+ "name": "six",
+ "version": "1.17.0",
+ "direct_url": null
+ },
+ {
+ "name": "smmap",
+ "version": "5.0.2",
+ "direct_url": null
+ },
+ {
+ "name": "sympy",
+ "version": "1.13.1",
+ "direct_url": null
+ },
+ {
+ "name": "sympy",
+ "version": "1.14.0",
+ "direct_url": null
+ },
+ {
+ "name": "tabulate",
+ "version": "0.9.0",
+ "direct_url": null
+ },
+ {
+ "name": "tensorboard",
+ "version": "2.15.2",
+ "direct_url": null
+ },
+ {
+ "name": "tensorboard",
+ "version": "2.20.0",
+ "direct_url": null
+ },
+ {
+ "name": "tensorboard-data-server",
+ "version": "0.7.2",
+ "direct_url": null
+ },
+ {
+ "name": "tensorflow",
+ "version": "2.15.0",
+ "direct_url": null
+ },
+ {
+ "name": "tensorflow-estimator",
+ "version": "2.15.0",
+ "direct_url": null
+ },
+ {
+ "name": "tensorflow-io-gcs-filesystem",
+ "version": "0.37.1",
+ "direct_url": null
+ },
+ {
+ "name": "termcolor",
+ "version": "3.1.0",
+ "direct_url": null
+ },
+ {
+ "name": "tianshou",
+ "version": "0.5.1",
+ "direct_url": null
+ },
+ {
+ "name": "tifffile",
+ "version": "2025.5.10",
+ "direct_url": null
+ },
+ {
+ "name": "timm",
+ "version": "1.0.14",
+ "direct_url": null
+ },
+ {
+ "name": "tokenizers",
+ "version": "0.21.4",
+ "direct_url": null
+ },
+ {
+ "name": "tomli",
+ "version": "2.3.0",
+ "direct_url": null
+ },
+ {
+ "name": "torch",
+ "version": "2.5.1",
+ "direct_url": null
+ },
+ {
+ "name": "torch",
+ "version": "2.8.0",
+ "direct_url": null
+ },
+ {
+ "name": "torchvision",
+ "version": "0.20.1",
+ "direct_url": null
+ },
+ {
+ "name": "tqdm",
+ "version": "4.67.1",
+ "direct_url": null
+ },
+ {
+ "name": "transformers",
+ "version": "4.51.3",
+ "direct_url": null
+ },
+ {
+ "name": "transforms3d",
+ "version": "0.4.2",
+ "direct_url": null
+ },
+ {
+ "name": "triton",
+ "version": "3.1.0",
+ "direct_url": null
+ },
+ {
+ "name": "triton",
+ "version": "3.4.0",
+ "direct_url": null
+ },
+ {
+ "name": "typeguard",
+ "version": "4.4.2",
+ "direct_url": null
+ },
+ {
+ "name": "typing_extensions",
+ "version": "4.12.2",
+ "direct_url": null
+ },
+ {
+ "name": "typing_extensions",
+ "version": "4.15.0",
+ "direct_url": null
+ },
+ {
+ "name": "tyro",
+ "version": "0.9.17",
+ "direct_url": null
+ },
+ {
+ "name": "tzdata",
+ "version": "2025.2",
+ "direct_url": null
+ },
+ {
+ "name": "urdf_parser_py",
+ "version": "0.0.4",
+ "direct_url": null
+ },
+ {
+ "name": "urllib3",
+ "version": "2.5.0",
+ "direct_url": null
+ },
+ {
+ "name": "wandb",
+ "version": "0.18.0",
+ "direct_url": null
+ },
+ {
+ "name": "wcwidth",
+ "version": "0.2.14",
+ "direct_url": null
+ },
+ {
+ "name": "websockets",
+ "version": "15.0.1",
+ "direct_url": null
+ },
+ {
+ "name": "Werkzeug",
+ "version": "3.1.3",
+ "direct_url": null
+ },
+ {
+ "name": "wheel",
+ "version": "0.45.1",
+ "direct_url": null
+ },
+ {
+ "name": "wrapt",
+ "version": "1.14.2",
+ "direct_url": null
+ },
+ {
+ "name": "yacs",
+ "version": "0.1.8",
+ "direct_url": null
+ },
+ {
+ "name": "zipp",
+ "version": "3.23.0",
+ "direct_url": null
+ },
+ {
+ "name": "hrl_geom",
+ "version": "0.1.0",
+ "direct_url": null
+ },
+ {
+ "name": "pykdl_utils",
+ "version": "0.1.0",
+ "direct_url": null
+ }
+ ]
+}
diff --git a/environment/simulation.requirements.txt b/environment/simulation.requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..ed8f08b25f7efde77ba58fa795c5ac56dbcbb041
--- /dev/null
+++ b/environment/simulation.requirements.txt
@@ -0,0 +1,31 @@
+accelerate==1.2.1
+av==12.3.0
+gymnasium==1.0.0
+h5py==3.12.1
+hidapi==0.14.0.post4
+imageio==2.34.2
+lxml==6.0.2
+matplotlib==3.10.0
+msgpack==1.1.2
+msgpack-numpy==0.4.8
+mujoco==3.2.6
+numba==0.61.2
+numpy==1.26.4
+omegaconf==2.3.0
+opencv-python-headless==4.11.0.86
+pandas==2.2.3
+pillow==11.3.0
+pydantic==2.10.6
+pygame==2.6.1
+PyOpenGL==3.1.7
+pynput==1.8.1
+pyyaml==6.0.2
+rich==14.2.0
+scipy==1.15.3
+termcolor==3.1.0
+tqdm==4.67.1
+transforms3d==0.4.2
+tyro==0.9.17
+urdf-parser-py==0.0.4
+websockets==15.0.1
+quadprog==0.1.13
diff --git a/environment/starVLA_1.observed.json b/environment/starVLA_1.observed.json
new file mode 100644
index 0000000000000000000000000000000000000000..ab7fb1b5525de8bc4692b64fbd87b39e8087fbdd
--- /dev/null
+++ b/environment/starVLA_1.observed.json
@@ -0,0 +1,1309 @@
+{
+ "python": "3.10.19 (main, Oct 21 2025, 16:43:05) [GCC 11.2.0]",
+ "packages": [
+ {
+ "name": "MarkupSafe",
+ "version": "2.1.5",
+ "direct_url": null
+ },
+ {
+ "name": "absl-py",
+ "version": "2.3.1",
+ "direct_url": null
+ },
+ {
+ "name": "albucore",
+ "version": "0.0.17",
+ "direct_url": null
+ },
+ {
+ "name": "albumentations",
+ "version": "1.4.18",
+ "direct_url": null
+ },
+ {
+ "name": "annotated-types",
+ "version": "0.7.0",
+ "direct_url": null
+ },
+ {
+ "name": "antlr4-python3-runtime",
+ "version": "4.9.3",
+ "direct_url": null
+ },
+ {
+ "name": "anyio",
+ "version": "4.12.0",
+ "direct_url": null
+ },
+ {
+ "name": "av",
+ "version": "12.3.0",
+ "direct_url": null
+ },
+ {
+ "name": "certifi",
+ "version": "2025.11.12",
+ "direct_url": null
+ },
+ {
+ "name": "charset-normalizer",
+ "version": "3.4.4",
+ "direct_url": null
+ },
+ {
+ "name": "click",
+ "version": "8.3.1",
+ "direct_url": null
+ },
+ {
+ "name": "conda-pack",
+ "version": "0.8.1",
+ "direct_url": {
+ "dir_info": {},
+ "url": "file:///home/conda/feedstock_root/build_artifacts/conda-pack_1734292804024/work"
+ }
+ },
+ {
+ "name": "contourpy",
+ "version": "1.3.2",
+ "direct_url": null
+ },
+ {
+ "name": "cramjam",
+ "version": "2.11.0",
+ "direct_url": null
+ },
+ {
+ "name": "cycler",
+ "version": "0.12.1",
+ "direct_url": null
+ },
+ {
+ "name": "decord",
+ "version": "0.6.0",
+ "direct_url": null
+ },
+ {
+ "name": "deepspeed",
+ "version": "0.18.3",
+ "direct_url": null
+ },
+ {
+ "name": "docstring_parser",
+ "version": "0.17.0",
+ "direct_url": null
+ },
+ {
+ "name": "einops",
+ "version": "0.8.1",
+ "direct_url": null
+ },
+ {
+ "name": "eva-decord",
+ "version": "0.6.1",
+ "direct_url": null
+ },
+ {
+ "name": "eval_type_backport",
+ "version": "0.3.1",
+ "direct_url": null
+ },
+ {
+ "name": "exceptiongroup",
+ "version": "1.3.1",
+ "direct_url": null
+ },
+ {
+ "name": "fastparquet",
+ "version": "2024.11.0",
+ "direct_url": null
+ },
+ {
+ "name": "filelock",
+ "version": "3.20.0",
+ "direct_url": null
+ },
+ {
+ "name": "fonttools",
+ "version": "4.61.1",
+ "direct_url": null
+ },
+ {
+ "name": "fsspec",
+ "version": "2025.12.0",
+ "direct_url": null
+ },
+ {
+ "name": "fvcore",
+ "version": "0.1.5.post20221221",
+ "direct_url": null
+ },
+ {
+ "name": "gevent",
+ "version": "25.9.1",
+ "direct_url": null
+ },
+ {
+ "name": "gitdb",
+ "version": "4.0.12",
+ "direct_url": null
+ },
+ {
+ "name": "GitPython",
+ "version": "3.1.46",
+ "direct_url": null
+ },
+ {
+ "name": "greenlet",
+ "version": "3.3.0",
+ "direct_url": null
+ },
+ {
+ "name": "grpcio",
+ "version": "1.76.0",
+ "direct_url": null
+ },
+ {
+ "name": "h11",
+ "version": "0.16.0",
+ "direct_url": null
+ },
+ {
+ "name": "hjson",
+ "version": "3.1.0",
+ "direct_url": null
+ },
+ {
+ "name": "httpcore",
+ "version": "1.0.9",
+ "direct_url": null
+ },
+ {
+ "name": "httpx",
+ "version": "0.28.1",
+ "direct_url": null
+ },
+ {
+ "name": "idna",
+ "version": "3.11",
+ "direct_url": null
+ },
+ {
+ "name": "ImageIO",
+ "version": "2.37.2",
+ "direct_url": null
+ },
+ {
+ "name": "importlib_metadata",
+ "version": "8.7.1",
+ "direct_url": null
+ },
+ {
+ "name": "iopath",
+ "version": "0.1.10",
+ "direct_url": null
+ },
+ {
+ "name": "Jinja2",
+ "version": "3.1.6",
+ "direct_url": null
+ },
+ {
+ "name": "kiwisolver",
+ "version": "1.4.9",
+ "direct_url": null
+ },
+ {
+ "name": "lazy_loader",
+ "version": "0.4",
+ "direct_url": null
+ },
+ {
+ "name": "Markdown",
+ "version": "3.10",
+ "direct_url": null
+ },
+ {
+ "name": "markdown-it-py",
+ "version": "4.0.0",
+ "direct_url": null
+ },
+ {
+ "name": "matplotlib",
+ "version": "3.10.8",
+ "direct_url": null
+ },
+ {
+ "name": "mdurl",
+ "version": "0.1.2",
+ "direct_url": null
+ },
+ {
+ "name": "mpmath",
+ "version": "1.3.0",
+ "direct_url": null
+ },
+ {
+ "name": "msgpack",
+ "version": "1.1.2",
+ "direct_url": null
+ },
+ {
+ "name": "networkx",
+ "version": "3.4.2",
+ "direct_url": null
+ },
+ {
+ "name": "ninja",
+ "version": "1.13.0",
+ "direct_url": null
+ },
+ {
+ "name": "numpydantic",
+ "version": "1.6.9",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-cublas-cu12",
+ "version": "12.8.4.1",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-cuda-cupti-cu12",
+ "version": "12.8.90",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-cuda-nvrtc-cu12",
+ "version": "12.8.93",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-cuda-runtime-cu12",
+ "version": "12.8.90",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-cudnn-cu12",
+ "version": "9.10.2.21",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-cufft-cu12",
+ "version": "11.3.3.83",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-cufile-cu12",
+ "version": "1.13.1.3",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-curand-cu12",
+ "version": "10.3.9.90",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-cusolver-cu12",
+ "version": "11.7.3.90",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-cusparse-cu12",
+ "version": "12.5.8.93",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-cusparselt-cu12",
+ "version": "0.7.1",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-nccl-cu12",
+ "version": "2.27.3",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-nvjitlink-cu12",
+ "version": "12.8.93",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-nvtx-cu12",
+ "version": "12.8.90",
+ "direct_url": null
+ },
+ {
+ "name": "omegaconf",
+ "version": "2.3.0",
+ "direct_url": null
+ },
+ {
+ "name": "opencv-python-headless",
+ "version": "4.11.0.86",
+ "direct_url": null
+ },
+ {
+ "name": "packaging",
+ "version": "25.0",
+ "direct_url": null
+ },
+ {
+ "name": "pandas",
+ "version": "2.3.3",
+ "direct_url": null
+ },
+ {
+ "name": "pillow",
+ "version": "12.0.0",
+ "direct_url": null
+ },
+ {
+ "name": "pipablepytorch3d",
+ "version": "0.7.6",
+ "direct_url": null
+ },
+ {
+ "name": "platformdirs",
+ "version": "4.5.1",
+ "direct_url": null
+ },
+ {
+ "name": "portalocker",
+ "version": "3.2.0",
+ "direct_url": null
+ },
+ {
+ "name": "protobuf",
+ "version": "6.33.2",
+ "direct_url": null
+ },
+ {
+ "name": "psutil",
+ "version": "7.2.1",
+ "direct_url": null
+ },
+ {
+ "name": "py-cpuinfo",
+ "version": "9.0.0",
+ "direct_url": null
+ },
+ {
+ "name": "pydantic",
+ "version": "2.10.6",
+ "direct_url": null
+ },
+ {
+ "name": "pydantic_core",
+ "version": "2.27.2",
+ "direct_url": null
+ },
+ {
+ "name": "Pygments",
+ "version": "2.19.2",
+ "direct_url": null
+ },
+ {
+ "name": "pyparsing",
+ "version": "3.3.1",
+ "direct_url": null
+ },
+ {
+ "name": "python-dateutil",
+ "version": "2.9.0.post0",
+ "direct_url": null
+ },
+ {
+ "name": "pytz",
+ "version": "2025.2",
+ "direct_url": null
+ },
+ {
+ "name": "PyYAML",
+ "version": "6.0.3",
+ "direct_url": null
+ },
+ {
+ "name": "qwen-vl-utils",
+ "version": "0.0.14",
+ "direct_url": null
+ },
+ {
+ "name": "regex",
+ "version": "2025.11.3",
+ "direct_url": null
+ },
+ {
+ "name": "requests",
+ "version": "2.32.5",
+ "direct_url": null
+ },
+ {
+ "name": "rich",
+ "version": "14.2.0",
+ "direct_url": null
+ },
+ {
+ "name": "scikit-image",
+ "version": "0.25.2",
+ "direct_url": null
+ },
+ {
+ "name": "scipy",
+ "version": "1.15.3",
+ "direct_url": null
+ },
+ {
+ "name": "sentry-sdk",
+ "version": "2.48.0",
+ "direct_url": null
+ },
+ {
+ "name": "setuptools",
+ "version": "80.9.0",
+ "direct_url": null
+ },
+ {
+ "name": "six",
+ "version": "1.17.0",
+ "direct_url": null
+ },
+ {
+ "name": "smmap",
+ "version": "5.0.2",
+ "direct_url": null
+ },
+ {
+ "name": "sympy",
+ "version": "1.14.0",
+ "direct_url": null
+ },
+ {
+ "name": "tabulate",
+ "version": "0.9.0",
+ "direct_url": null
+ },
+ {
+ "name": "tensorboard",
+ "version": "2.20.0",
+ "direct_url": null
+ },
+ {
+ "name": "tensorboard-data-server",
+ "version": "0.7.2",
+ "direct_url": null
+ },
+ {
+ "name": "termcolor",
+ "version": "3.3.0",
+ "direct_url": null
+ },
+ {
+ "name": "tifffile",
+ "version": "2025.5.10",
+ "direct_url": null
+ },
+ {
+ "name": "tiktoken",
+ "version": "0.12.0",
+ "direct_url": null
+ },
+ {
+ "name": "timm",
+ "version": "1.0.22",
+ "direct_url": null
+ },
+ {
+ "name": "torch",
+ "version": "2.8.0+cu128",
+ "direct_url": null
+ },
+ {
+ "name": "torchaudio",
+ "version": "2.8.0+cu128",
+ "direct_url": null
+ },
+ {
+ "name": "torchvision",
+ "version": "0.23.0+cu128",
+ "direct_url": null
+ },
+ {
+ "name": "tqdm",
+ "version": "4.67.1",
+ "direct_url": null
+ },
+ {
+ "name": "transformers-stream-generator",
+ "version": "0.0.5",
+ "direct_url": null
+ },
+ {
+ "name": "triton",
+ "version": "3.4.0",
+ "direct_url": null
+ },
+ {
+ "name": "typeguard",
+ "version": "4.4.4",
+ "direct_url": null
+ },
+ {
+ "name": "typing_extensions",
+ "version": "4.15.0",
+ "direct_url": null
+ },
+ {
+ "name": "tyro",
+ "version": "1.0.3",
+ "direct_url": null
+ },
+ {
+ "name": "tzdata",
+ "version": "2025.3",
+ "direct_url": null
+ },
+ {
+ "name": "urllib3",
+ "version": "2.6.2",
+ "direct_url": null
+ },
+ {
+ "name": "wandb",
+ "version": "0.23.1",
+ "direct_url": null
+ },
+ {
+ "name": "websocket",
+ "version": "0.2.1",
+ "direct_url": null
+ },
+ {
+ "name": "websocket-client",
+ "version": "1.8.0",
+ "direct_url": null
+ },
+ {
+ "name": "websockets",
+ "version": "15.0.1",
+ "direct_url": null
+ },
+ {
+ "name": "Werkzeug",
+ "version": "3.1.4",
+ "direct_url": null
+ },
+ {
+ "name": "wheel",
+ "version": "0.45.1",
+ "direct_url": null
+ },
+ {
+ "name": "yacs",
+ "version": "0.1.8",
+ "direct_url": null
+ },
+ {
+ "name": "zipp",
+ "version": "3.23.0",
+ "direct_url": null
+ },
+ {
+ "name": "zope.event",
+ "version": "6.1",
+ "direct_url": null
+ },
+ {
+ "name": "zope.interface",
+ "version": "8.1.1",
+ "direct_url": null
+ },
+ {
+ "name": "flash_attn",
+ "version": "2.8.3",
+ "direct_url": null
+ },
+ {
+ "name": "wrapt",
+ "version": "2.0.1",
+ "direct_url": null
+ },
+ {
+ "name": "svgwrite",
+ "version": "1.4.3",
+ "direct_url": null
+ },
+ {
+ "name": "attrs",
+ "version": "25.4.0",
+ "direct_url": null
+ },
+ {
+ "name": "Tree",
+ "version": "0.2.4",
+ "direct_url": null
+ },
+ {
+ "name": "dm-tree",
+ "version": "0.1.9",
+ "direct_url": null
+ },
+ {
+ "name": "debugpy",
+ "version": "1.8.19",
+ "direct_url": null
+ },
+ {
+ "name": "nvidia-ml-py",
+ "version": "13.590.44",
+ "direct_url": null
+ },
+ {
+ "name": "wcwidth",
+ "version": "0.2.14",
+ "direct_url": null
+ },
+ {
+ "name": "blessed",
+ "version": "1.25.0",
+ "direct_url": null
+ },
+ {
+ "name": "gpustat",
+ "version": "1.1.1",
+ "direct_url": null
+ },
+ {
+ "name": "pure_eval",
+ "version": "0.2.3",
+ "direct_url": null
+ },
+ {
+ "name": "ptyprocess",
+ "version": "0.7.0",
+ "direct_url": null
+ },
+ {
+ "name": "traitlets",
+ "version": "5.14.3",
+ "direct_url": null
+ },
+ {
+ "name": "tomli",
+ "version": "2.3.0",
+ "direct_url": null
+ },
+ {
+ "name": "prompt_toolkit",
+ "version": "3.0.52",
+ "direct_url": null
+ },
+ {
+ "name": "pexpect",
+ "version": "4.9.0",
+ "direct_url": null
+ },
+ {
+ "name": "parso",
+ "version": "0.8.5",
+ "direct_url": null
+ },
+ {
+ "name": "executing",
+ "version": "2.2.1",
+ "direct_url": null
+ },
+ {
+ "name": "decorator",
+ "version": "5.2.1",
+ "direct_url": null
+ },
+ {
+ "name": "asttokens",
+ "version": "3.0.1",
+ "direct_url": null
+ },
+ {
+ "name": "stack-data",
+ "version": "0.6.3",
+ "direct_url": null
+ },
+ {
+ "name": "matplotlib-inline",
+ "version": "0.2.1",
+ "direct_url": null
+ },
+ {
+ "name": "jedi",
+ "version": "0.19.2",
+ "direct_url": null
+ },
+ {
+ "name": "ipython",
+ "version": "8.38.0",
+ "direct_url": null
+ },
+ {
+ "name": "ipdb",
+ "version": "0.13.13",
+ "direct_url": null
+ },
+ {
+ "name": "json-numpy",
+ "version": "2.1.1",
+ "direct_url": null
+ },
+ {
+ "name": "accelerate",
+ "version": "1.5.2",
+ "direct_url": null
+ },
+ {
+ "name": "h5py",
+ "version": "3.15.1",
+ "direct_url": null
+ },
+ {
+ "name": "pip",
+ "version": "26.0.1",
+ "direct_url": null
+ },
+ {
+ "name": "docutils",
+ "version": "0.22.4",
+ "direct_url": null
+ },
+ {
+ "name": "catkin-pkg",
+ "version": "1.1.0",
+ "direct_url": null
+ },
+ {
+ "name": "pykdl_utils",
+ "version": "0.1.0",
+ "direct_url": {
+ "dir_info": {
+ "editable": true
+ },
+ "url": "file:///mnt/workspace/users/zhangtianle/others/pykdl_utils"
+ }
+ },
+ {
+ "name": "hrl_geom",
+ "version": "0.1.0",
+ "direct_url": {
+ "dir_info": {
+ "editable": true
+ },
+ "url": "file:///mnt/workspace/users/zhangtianle/others/hrl_geom"
+ }
+ },
+ {
+ "name": "lxml",
+ "version": "6.0.2",
+ "direct_url": null
+ },
+ {
+ "name": "urdf_parser_py",
+ "version": "0.0.4",
+ "direct_url": null
+ },
+ {
+ "name": "fla-core",
+ "version": "0.4.2",
+ "direct_url": null
+ },
+ {
+ "name": "flash-linear-attention",
+ "version": "0.4.2",
+ "direct_url": null
+ },
+ {
+ "name": "shellingham",
+ "version": "1.5.4",
+ "direct_url": null
+ },
+ {
+ "name": "annotated-doc",
+ "version": "0.0.4",
+ "direct_url": null
+ },
+ {
+ "name": "typer",
+ "version": "0.24.1",
+ "direct_url": null
+ },
+ {
+ "name": "typer-slim",
+ "version": "0.24.0",
+ "direct_url": null
+ },
+ {
+ "name": "openpi-client",
+ "version": "0.1.0",
+ "direct_url": {
+ "dir_info": {},
+ "url": "file:///mnt/workspace/users/lidongwei1/code/openpi-client"
+ }
+ },
+ {
+ "name": "pyzmq",
+ "version": "27.1.0",
+ "direct_url": null
+ },
+ {
+ "name": "xxhash",
+ "version": "3.6.0",
+ "direct_url": null
+ },
+ {
+ "name": "pyarrow",
+ "version": "23.0.1",
+ "direct_url": null
+ },
+ {
+ "name": "propcache",
+ "version": "0.4.1",
+ "direct_url": null
+ },
+ {
+ "name": "multidict",
+ "version": "6.7.1",
+ "direct_url": null
+ },
+ {
+ "name": "frozenlist",
+ "version": "1.8.0",
+ "direct_url": null
+ },
+ {
+ "name": "dill",
+ "version": "0.4.1",
+ "direct_url": null
+ },
+ {
+ "name": "async-timeout",
+ "version": "5.0.1",
+ "direct_url": null
+ },
+ {
+ "name": "aiohappyeyeballs",
+ "version": "2.6.1",
+ "direct_url": null
+ },
+ {
+ "name": "yarl",
+ "version": "1.23.0",
+ "direct_url": null
+ },
+ {
+ "name": "multiprocess",
+ "version": "0.70.19",
+ "direct_url": null
+ },
+ {
+ "name": "aiosignal",
+ "version": "1.4.0",
+ "direct_url": null
+ },
+ {
+ "name": "aiohttp",
+ "version": "3.13.5",
+ "direct_url": null
+ },
+ {
+ "name": "datasets",
+ "version": "4.8.4",
+ "direct_url": null
+ },
+ {
+ "name": "narwhals",
+ "version": "2.19.0",
+ "direct_url": null
+ },
+ {
+ "name": "plotly",
+ "version": "6.7.0",
+ "direct_url": null
+ },
+ {
+ "name": "hydra-core",
+ "version": "1.3.2",
+ "direct_url": null
+ },
+ {
+ "name": "peft",
+ "version": "0.19.1",
+ "direct_url": null
+ },
+ {
+ "name": "x-transformers",
+ "version": "2.19.0",
+ "direct_url": null
+ },
+ {
+ "name": "loguru",
+ "version": "0.7.3",
+ "direct_url": null
+ },
+ {
+ "name": "torch-einops-utils",
+ "version": "0.0.33",
+ "direct_url": null
+ },
+ {
+ "name": "einx",
+ "version": "0.4.3",
+ "direct_url": null
+ },
+ {
+ "name": "uvicorn",
+ "version": "0.46.0",
+ "direct_url": null
+ },
+ {
+ "name": "typing-inspection",
+ "version": "0.4.2",
+ "direct_url": null
+ },
+ {
+ "name": "starlette",
+ "version": "1.0.0",
+ "direct_url": null
+ },
+ {
+ "name": "fastapi",
+ "version": "0.136.1",
+ "direct_url": null
+ },
+ {
+ "name": "safetensors",
+ "version": "0.8.0rc0",
+ "direct_url": null
+ },
+ {
+ "name": "diffusers",
+ "version": "0.38.0",
+ "direct_url": null
+ },
+ {
+ "name": "easydict",
+ "version": "1.13",
+ "direct_url": null
+ },
+ {
+ "name": "ftfy",
+ "version": "6.3.1",
+ "direct_url": null
+ },
+ {
+ "name": "threadpoolctl",
+ "version": "3.6.0",
+ "direct_url": null
+ },
+ {
+ "name": "soxr",
+ "version": "1.1.0",
+ "direct_url": null
+ },
+ {
+ "name": "pycparser",
+ "version": "3.0",
+ "direct_url": null
+ },
+ {
+ "name": "llvmlite",
+ "version": "0.47.0",
+ "direct_url": null
+ },
+ {
+ "name": "joblib",
+ "version": "1.5.3",
+ "direct_url": null
+ },
+ {
+ "name": "audioread",
+ "version": "3.1.0",
+ "direct_url": null
+ },
+ {
+ "name": "scikit-learn",
+ "version": "1.7.2",
+ "direct_url": null
+ },
+ {
+ "name": "pooch",
+ "version": "1.9.0",
+ "direct_url": null
+ },
+ {
+ "name": "numba",
+ "version": "0.65.1",
+ "direct_url": null
+ },
+ {
+ "name": "cffi",
+ "version": "2.0.0",
+ "direct_url": null
+ },
+ {
+ "name": "soundfile",
+ "version": "0.13.1",
+ "direct_url": null
+ },
+ {
+ "name": "librosa",
+ "version": "0.11.0",
+ "direct_url": null
+ },
+ {
+ "name": "cryptography",
+ "version": "48.0.0",
+ "direct_url": null
+ },
+ {
+ "name": "dashscope",
+ "version": "1.25.18",
+ "direct_url": null
+ },
+ {
+ "name": "nltk",
+ "version": "3.9.4",
+ "direct_url": null
+ },
+ {
+ "name": "better-profanity",
+ "version": "0.7.0",
+ "direct_url": null
+ },
+ {
+ "name": "jmespath",
+ "version": "1.1.0",
+ "direct_url": null
+ },
+ {
+ "name": "botocore",
+ "version": "1.43.9",
+ "direct_url": null
+ },
+ {
+ "name": "s3transfer",
+ "version": "0.17.0",
+ "direct_url": null
+ },
+ {
+ "name": "boto3",
+ "version": "1.43.9",
+ "direct_url": null
+ },
+ {
+ "name": "megatron-core",
+ "version": "0.16.1",
+ "direct_url": null
+ },
+ {
+ "name": "braceexpand",
+ "version": "0.1.7",
+ "direct_url": null
+ },
+ {
+ "name": "webdataset",
+ "version": "1.0.2",
+ "direct_url": null
+ },
+ {
+ "name": "hf-xet",
+ "version": "1.5.0",
+ "direct_url": null
+ },
+ {
+ "name": "huggingface_hub",
+ "version": "1.15.0",
+ "direct_url": null
+ },
+ {
+ "name": "tokenizers",
+ "version": "0.22.2",
+ "direct_url": null
+ },
+ {
+ "name": "transformers",
+ "version": "5.8.1",
+ "direct_url": null
+ },
+ {
+ "name": "frozendict",
+ "version": "2.4.7",
+ "direct_url": null
+ },
+ {
+ "name": "hyper-connections",
+ "version": "0.4.11",
+ "direct_url": null
+ },
+ {
+ "name": "gymnasium",
+ "version": "0.29.1",
+ "direct_url": null
+ },
+ {
+ "name": "zstandard",
+ "version": "0.25.0",
+ "direct_url": null
+ },
+ {
+ "name": "ruamel.yaml",
+ "version": "0.19.1",
+ "direct_url": null
+ },
+ {
+ "name": "lz4",
+ "version": "4.4.5",
+ "direct_url": null
+ },
+ {
+ "name": "apsw",
+ "version": "3.53.1.0",
+ "direct_url": null
+ },
+ {
+ "name": "rosbags",
+ "version": "0.11.3",
+ "direct_url": null
+ },
+ {
+ "name": "sentencepiece",
+ "version": "0.2.1",
+ "direct_url": null
+ },
+ {
+ "name": "numpy",
+ "version": "2.2.6",
+ "direct_url": null
+ },
+ {
+ "name": "cmeel",
+ "version": "0.60.1",
+ "direct_url": null
+ },
+ {
+ "name": "cmeel-zlib",
+ "version": "1.3.2",
+ "direct_url": null
+ },
+ {
+ "name": "cmeel-tinyxml2",
+ "version": "11.0.0",
+ "direct_url": null
+ },
+ {
+ "name": "cmeel-qhull",
+ "version": "8.0.2.1",
+ "direct_url": null
+ },
+ {
+ "name": "cmeel-octomap",
+ "version": "1.10.0",
+ "direct_url": null
+ },
+ {
+ "name": "cmeel-console-bridge",
+ "version": "1.0.2.3",
+ "direct_url": null
+ },
+ {
+ "name": "cmeel-boost",
+ "version": "1.90.0",
+ "direct_url": null
+ },
+ {
+ "name": "eigenpy",
+ "version": "3.13.0",
+ "direct_url": null
+ },
+ {
+ "name": "cmeel-urdfdom",
+ "version": "6.0.0",
+ "direct_url": null
+ },
+ {
+ "name": "cmeel-assimp",
+ "version": "6.0.5",
+ "direct_url": null
+ },
+ {
+ "name": "libcoal",
+ "version": "3.0.3",
+ "direct_url": null
+ },
+ {
+ "name": "libpinocchio",
+ "version": "4.0.0",
+ "direct_url": null
+ },
+ {
+ "name": "coal",
+ "version": "3.0.3",
+ "direct_url": null
+ },
+ {
+ "name": "pin",
+ "version": "4.0.0",
+ "direct_url": null
+ },
+ {
+ "name": "gesim",
+ "version": "0.1.0",
+ "direct_url": {
+ "dir_info": {
+ "editable": true
+ },
+ "url": "file:///mnt/workspace/users/wangjunjie729/wjj/GE-Sim-V2-main"
+ }
+ },
+ {
+ "name": "liger_kernel",
+ "version": "0.8.0",
+ "direct_url": null
+ },
+ {
+ "name": "msgpack-numpy",
+ "version": "0.4.8",
+ "direct_url": {
+ "archive_info": {
+ "hash": "sha256=773c19d4dfbae1b3c7b791083e2caf66983bb19b40901646f61d8731554ae3da",
+ "hashes": {
+ "sha256": "773c19d4dfbae1b3c7b791083e2caf66983bb19b40901646f61d8731554ae3da"
+ }
+ },
+ "url": "file:///tmp/msgpack_numpy-0.4.8-py2.py3-none-any.whl"
+ }
+ },
+ {
+ "name": "pluggy",
+ "version": "1.6.0",
+ "direct_url": null
+ },
+ {
+ "name": "iniconfig",
+ "version": "2.3.0",
+ "direct_url": null
+ },
+ {
+ "name": "pytest",
+ "version": "8.4.2",
+ "direct_url": null
+ },
+ {
+ "name": "hrl_geom",
+ "version": "0.1.0",
+ "direct_url": null
+ },
+ {
+ "name": "pykdl_utils",
+ "version": "0.1.0",
+ "direct_url": null
+ }
+ ]
+}
diff --git a/examples/Behavior/README.md b/examples/Behavior/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..8e20f8fefed46d3ec1d56009d09a247f24b20c03
--- /dev/null
+++ b/examples/Behavior/README.md
@@ -0,0 +1,98 @@
+
+# 🚧Under construction
+This document provides instructions to run our framework with the [BEHAVIOR-1K Benchmark](https://github.com/StanfordVL/BEHAVIOR-1K). We follow the structure of [2025 BEHAVIOR Challenge](https://behavior.stanford.edu/challenge/index.html) so that you can train and evaluate on the 50 full-length household tasks.
+
+
+The evaluation process consists of two main parts:
+
+1. Setting up the `behavior` environment and dependencies.
+2. Running the evaluation by launching services in both `starVLA` and `behavior` environments.
+
+Note that to run evaluation on Behavior benchmark, you should **not** use GPUs without RT Cores (A100, H100). Otherwise you may encounter problems of Segmentation fault or low resolution. See [this](https://github.com/StanfordVL/BEHAVIOR-1K/issues/1872#issuecomment-3455002820) and [this](https://github.com/StanfordVL/BEHAVIOR-1K/issues/1875#issuecomment-3444246495) for discussion.
+
+
+## 📦 1. Environment Setup
+To set up the conda enviroment for `behavior` environment, use the following command:
+
+```
+git clone https://github.com/StanfordVL/BEHAVIOR-1K.git
+conda create -n behavior python=3.10 -y
+conda activate behavior
+cd BEHAVIOR-1K
+pip install "setuptools<=79"
+./setup.sh --omnigibson --bddl --joylo --dataset
+conda install -c conda-forge libglu
+pip install rich omegaconf hydra-core msgpack websockets av pandas google-auth
+```
+
+Also in starVLA env:
+```
+pip install websockets
+```
+
+## 🚀 2. Eval in Behavior
+
+Steps:
+1) Download the checkpoint:``
+2) Choose the script below according to your need
+
+(A) parallel evaluation script.
+
+```bash
+CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 bash examples/Behavior/start_parallel_eval.sh
+```
+
+Before running start_parallel_eval.sh, set the following three paths:
+- `star_vla_python`: Python interpreter for the StarVLA environment.
+- `sim_python`: Python interpreter for the Behavior environment.
+- `TASKS_JSONL_PATH`: This file contains the task description downloaded from the [training dataset](https://huggingface.co/datasets/behavior-1k/2025-challenge-demos), we have included it with path examples/Behavior/tasks.jsonl
+- `BEHAVIOR_ASSET_PATH`: Local path to the behavior asset path. The default path is in BEHAVIOR-1K/datasets after installing behavior with `./setup.sh --omnigibson --bddl --joylo --dataset`
+
+(B) For the ease of debugging, you may also start the client (evaluation environment) and server (policy) in two separate terminal:
+
+```bash
+bash examples/Behavior/start_server.sh
+bash examples/Behavior/start_client.sh
+```
+The above debugging files will conduct evaluation on train set
+
+(C) To prevent memory overflow, we implemented another file `start_parallel_eval_per_task.sh`:
+```bash
+CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 bash examples/Behavior/start_parallel_eval.sh
+```
+- The script will run evaluation for each task in `INSTANCE_NAMES` iteratively
+- For each tasks, allocate all instances from `TEST_EVAL_INSTANCE_IDS` across GPUs
+- Wait for the previous task to finish, then procede to the next task
+
+## 🔧 3. Notes
+
+### Wrapper
+1. RGBLowResWrapper: only use rgb as visual observation and camera resolutions of 224 * 224. Only using low-res RGB can help speed up the simulator and thus reduce evaluation time compared to the two other example wrappers. This wrapper is ok to use in standard track.
+2. DefaultWrapper: wrapper with the default observation config used during data collection (rgb + depth + segmentation, 720p for head camera and 480p for wrist camera). This wrapper is ok to use in standard track, but evaluation will be considerably slower compared to RGBLowResWrapper.
+3. RichObservationWrapper: this will load additional observation modalities, such as normal and flow, as well as privileged task information. This wrapper can only be used in privileged information track.
+
+
+### Action Dim
+BEHAVIOR has action dim = 23
+
+```
+"R1Pro": {
+ "base": np.s_[0:3], # Indices 0-2
+ "torso": np.s_[3:7], # Indices 3-6
+ "left_arm": np.s_[7:14], # Indices 7-13
+ "left_gripper": np.s_[14:15], # Index 14
+ "right_arm": np.s_[15:22], # Indices 15-21
+ "right_gripper": np.s_[22:23], # Index 22
+}
+```
+
+### Video Saving:
+The video will be saved in the format of {task_name}\_{idx}\_{epi}.mp4, where idx is the instance number, epi is the episode number
+
+### Common Bugs
+Segmentation fault (core dumped): a likely reason is vulkan is not successfully installed. Check this [link](https://maniskill.readthedocs.io/en/latest/user_guide/getting_started/installation.html#vulkan)
+
+ImportError: libGL.so.1: cannot open shared object file: No such file or directory:
+`apt-get install ffmpeg libsm6 libxext6 -y`
diff --git a/examples/Behavior/adaptive_ensemble.py b/examples/Behavior/adaptive_ensemble.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d7fe464d567ae745d53678bd62b92e33a0b1186
--- /dev/null
+++ b/examples/Behavior/adaptive_ensemble.py
@@ -0,0 +1,104 @@
+"""
+adaptive_ensemble.py
+
+"""
+
+from collections import deque
+import numpy as np
+
+
+class AdaptiveEnsembler:
+ def __init__(self, pred_action_horizon, adaptive_ensemble_alpha=0.0):
+ self.pred_action_horizon = pred_action_horizon
+ self.action_history = deque(maxlen=self.pred_action_horizon)
+ self.adaptive_ensemble_alpha = adaptive_ensemble_alpha
+
+ def reset(self):
+ self.action_history.clear()
+
+ def ensemble_action(self, cur_action):
+ self.action_history.append(cur_action)
+ num_actions = len(self.action_history)
+ if cur_action.ndim == 1:
+ curr_act_preds = np.stack(self.action_history)
+ else:
+ curr_act_preds = np.stack(
+ [pred_actions[i] for (i, pred_actions) in zip(range(num_actions - 1, -1, -1), self.action_history)]
+ )
+
+ # calculate cosine similarity between the current prediction and all previous predictions
+ ref = curr_act_preds[num_actions-1, :]
+ previous_pred = curr_act_preds
+ dot_product = np.sum(previous_pred * ref, axis=1)
+ norm_previous_pred = np.linalg.norm(previous_pred, axis=1)
+ norm_ref = np.linalg.norm(ref)
+ cos_similarity = dot_product / (norm_previous_pred * norm_ref + 1e-7)
+
+ # compute the weights for each prediction
+ weights = np.exp(self.adaptive_ensemble_alpha * cos_similarity)
+ weights = weights / weights.sum()
+
+ # compute the weighted average across all predictions for this timestep
+ cur_action = np.sum(weights[:, None] * curr_act_preds, axis=0)
+
+ return cur_action
+
+
+class ChunkedAdaptiveEnsembler:
+ def __init__(self, pred_action_horizon, update_interval, adaptive_ensemble_alpha=0.0):
+ self.pred_action_horizon = pred_action_horizon
+ self.update_interval = update_interval
+ self.adaptive_ensemble_alpha = adaptive_ensemble_alpha
+
+ self.action_history = []
+ self.current_step = 0
+
+ def reset(self):
+ self.action_history = []
+ self.current_step = 0
+
+ def ensemble_action(self, new_action_chunk):
+ self.action_history.append({
+ 'start_step': self.current_step,
+ 'actions': new_action_chunk
+ })
+
+ def step(self):
+ self.action_history = [
+ h for h in self.action_history
+ if h['start_step'] + len(h['actions']) > self.current_step
+ ]
+
+ relevant_preds = []
+
+ for history_item in self.action_history:
+ idx = self.current_step - history_item['start_step']
+
+ if 0 <= idx < len(history_item['actions']):
+ relevant_preds.append(history_item['actions'][idx])
+
+ if not relevant_preds:
+ raise ValueError(f"Step {self.current_step}: No actions available. Did you forget to initialize with an action chunk?")
+
+ curr_act_preds = np.stack(relevant_preds)
+ num_actions = curr_act_preds.shape[0]
+
+ if num_actions == 1:
+ final_action = curr_act_preds[0]
+ else:
+ ref = curr_act_preds[-1, :]
+ previous_pred = curr_act_preds
+
+ dot_product = np.sum(previous_pred * ref, axis=1)
+ norm_previous_pred = np.linalg.norm(previous_pred, axis=1)
+ norm_ref = np.linalg.norm(ref)
+ cos_similarity = dot_product / (norm_previous_pred * norm_ref + 1e-7)
+
+ weights = np.exp(self.adaptive_ensemble_alpha * cos_similarity)
+ weights = weights / weights.sum()
+
+ final_action = np.sum(weights[:, None] * curr_act_preds, axis=0)
+
+ self.current_step += 1
+
+ return final_action
diff --git a/examples/Behavior/custom_argparse.py b/examples/Behavior/custom_argparse.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c170bdf5c2a80e6f186afd23ef7f89eb4b09615
--- /dev/null
+++ b/examples/Behavior/custom_argparse.py
@@ -0,0 +1,43 @@
+# copy from SimplerEnv/simpler_env/evaluation/argparse.py
+
+import argparse
+
+import numpy as np
+
+
+def parse_range_tuple(t):
+ return np.linspace(t[0], t[1], int(t[2]))
+
+
+def get_args():
+ # parse command-line arguments
+ parser = argparse.ArgumentParser()
+ parser.add_argument(
+ "--policy-model",
+ type=str,
+ default="rt1",
+ help="Policy model type; e.g., 'rt1', 'octo-base', 'octo-small'",
+ )
+ parser.add_argument("--policy-setup", type=str, default="R1Pro", help="Policy setup")
+ parser.add_argument("--ckpt-path", type=str, default=None)
+
+ parser.add_argument("--eval-on-train-instances", type=lambda x: x.lower() == "true",default=True)
+ parser.add_argument("--logging-dir", type=str, default="./results")
+ parser.add_argument("--tf-memory-limit", type=int, default=3072, help="Tensorflow memory limit")
+ parser.add_argument("--async-freq", type=int, default=1)
+ parser.add_argument("--host", type=str, default="127.0.0.1", help="Octo init rng seed")
+ parser.add_argument("--port", type=int, default=10093)
+ parser.add_argument("--headless", type=bool, default=True, help="Whether to run in headless mode (no GUI)")
+ parser.add_argument("--write-video", type=bool, default=True, help="Whether to save videos of the evaluation")
+ parser.add_argument("--task-name", type=str, required=True, help="Task name")
+ parser.add_argument("--eval-instance-ids", type=str, default=None, help="Instance ids to evaluate on, if None, evaluate on all instances")
+ parser.add_argument("--behavior-tasks-jsonl-path", type=str, required=True, help="behavior tasks jsonl path")
+ parser.add_argument("--behavior-asset-path", type=str, required=True, help="parent path of 2025-challenge-task-instances data path (default to be BEHAVIOR-1k/datasets)")
+ parser.add_argument("--partial-scene-load", type=bool, default=False, help="Whether to only load task-relevant rooms for a specific task")
+ parser.add_argument("--wrappers", type=str, default="RGBLowResWrapper",choices=["RGBLowResWrapper", "DefaultWrapper", "RichObservationWrapper"], help="List of wrappers to apply to the environment")
+ parser.add_argument("--max-steps", type=int, default=None, help="Max steps per rollout episode, setting to null will use the default value (2 x average human demo completion steps)")
+ parser.add_argument("--use-state", default=False, type=lambda x: x.lower() == "true",help="Whether to use state as part of the observation")
+
+ args = parser.parse_args()
+
+ return args
\ No newline at end of file
diff --git a/examples/Behavior/model2behavior_interface.py b/examples/Behavior/model2behavior_interface.py
new file mode 100644
index 0000000000000000000000000000000000000000..b65d22f5249dd953dbd0247d760c58efc989f858
--- /dev/null
+++ b/examples/Behavior/model2behavior_interface.py
@@ -0,0 +1,384 @@
+from collections import deque
+from typing import Optional, Sequence, Dict, Any
+import os
+import cv2 as cv
+import matplotlib.pyplot as plt
+import numpy as np
+import torch
+from datetime import datetime
+
+from transforms3d.euler import euler2axangle
+from deployment.model_server.tools.websocket_policy_client import WebsocketClientPolicy
+
+from examples.Behavior.adaptive_ensemble import AdaptiveEnsembler, ChunkedAdaptiveEnsembler
+from pathlib import Path
+
+from starVLA.model.tools import read_mode_config
+
+# Import BEHAVIOR-specific utilities
+from omnigibson.learning.utils.eval_utils import ROBOT_CAMERA_NAMES, PROPRIOCEPTION_INDICES
+
+def start_debugpy_once():
+ """start debugpy once"""
+ import debugpy
+ if getattr(start_debugpy_once, "_started", False):
+ return
+ debugpy.listen(("0.0.0.0", 10092))
+ print("🔍 Waiting for VSCode attach on 0.0.0.0:10092 ...")
+ debugpy.wait_for_client()
+ start_debugpy_once._started = True
+
+class M1Inference:
+ def __init__(
+ self,
+ policy_ckpt_path,
+ policy_setup: str = "R1Pro",
+ horizon: int = 0,
+ action_ensemble_horizon: Optional[int] = None,
+ image_size: list[int] = [224, 224],
+ action_scale: float = 1.0,
+ cfg_scale: float = 1.5,
+ use_ddim: bool = True,
+ num_ddim_steps: int = 10,
+ action_ensemble: bool = False,
+ adaptive_ensemble_alpha: float = 0.1,
+ host: str = "0.0.0.0",
+ port: int = 10093,
+ task_description: str = None,
+ use_state: bool = False,
+ ) -> None:
+
+ # build client to connect server policy
+ self.client = WebsocketClientPolicy(host, port)
+
+ action_ensemble = True
+
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
+
+ # Robot type for BEHAVIOR
+ if policy_setup == "R1Pro":
+ unnorm_key = "R1Pro"
+ if action_ensemble_horizon is None:
+ action_ensemble_horizon = 5
+ self.sticky_gripper_num_repeat = 3
+ else:
+ raise NotImplementedError(
+ f"Policy setup {policy_setup} not supported for BEHAVIOR models."
+ )
+
+ self.policy_setup = policy_setup
+ self.unnorm_key = unnorm_key
+ self.action_ensemble = action_ensemble
+ self.adaptive_ensemble_alpha = adaptive_ensemble_alpha
+ self.action_ensemble_horizon = action_ensemble_horizon
+ self.policy_ckpt_path = policy_ckpt_path
+
+ print(f"*** policy_setup: {policy_setup}, unnorm_key: {unnorm_key} ***")
+ self.use_ddim = use_ddim
+ self.num_ddim_steps = num_ddim_steps
+ self.cfg_scale = cfg_scale
+ self.image_size = image_size
+ self.action_scale = action_scale
+ self.horizon = horizon
+
+ # Gripper control state
+ self.sticky_action_is_on = False
+ self.gripper_action_repeat = 0
+ self.sticky_gripper_action = 0.0
+ self.previous_gripper_action = None
+
+ # initial
+ self.action_chunk_size = 2
+ self.current_step = 0
+
+ # Task and image history
+ self.task_description = task_description
+ self.image_history = deque(maxlen=self.horizon)
+ if self.action_ensemble:
+ if self.action_chunk_size > 1:
+ self.action_ensembler = ChunkedAdaptiveEnsembler(self.action_ensemble_horizon, self.action_chunk_size, self.adaptive_ensemble_alpha)
+ else:
+ self.action_ensembler = AdaptiveEnsembler(self.action_ensemble_horizon, self.adaptive_ensemble_alpha)
+ else:
+ self.action_ensembler = None
+ self.num_image_history = 0
+
+ # Load action normalization stats
+ self.action_norm_stats = self.get_action_stats(self.unnorm_key, policy_ckpt_path=policy_ckpt_path)
+
+ self.use_state = use_state
+
+ # If want to debug, uncomment the following line
+ # if os.getenv("DEBUG", False):
+ # start_debugpy_once()
+
+ def reset(self, task_description: Optional[str] = None) -> None:
+ if task_description is not None:
+ self.task_description = task_description
+ if self.action_ensemble:
+ self.action_ensembler.reset()
+
+ self.sticky_action_is_on = False
+ self.gripper_action_repeat = 0
+ self.sticky_gripper_action = 0.0
+ self.previous_gripper_action = None
+ self.current_step = 0
+
+ def _generate_prop_state(self, proprio: np.ndarray) -> np.ndarray:
+ """Generate proprioceptive state for R1Pro robot."""
+ idx = PROPRIOCEPTION_INDICES[self.policy_setup]
+ qpos_list = [
+ proprio[idx["joint_qpos_sin"]][6:], # First 6 are base joints, which is NOT allowed in standard track
+ proprio[idx["joint_qpos_cos"]][6:], # First 6 are base joints, which is NOT allowed in standard track
+ ]
+ assert qpos_list[0].shape == (22,)
+ assert qpos_list[1].shape == (22,)
+ return np.concatenate(qpos_list, axis=0)
+
+ def _process_behavior_obs(self, obs: Dict[str, Any]) -> Dict[str, Any]:
+ """Process BEHAVIOR observations to extract images and proprioception."""
+ # Extract images from different camera views
+ try:
+ head_camera_key = ROBOT_CAMERA_NAMES[self.policy_setup]["head"] + "::rgb"
+ left_wrist_camera_key = ROBOT_CAMERA_NAMES[self.policy_setup]["left_wrist"] + "::rgb"
+ right_wrist_camera_key = ROBOT_CAMERA_NAMES[self.policy_setup]["right_wrist"] + "::rgb"
+
+ full_image = obs[head_camera_key][:, :, :3] # [224, 224, 3]
+ left_wrist_image = obs[left_wrist_camera_key][:, :, :3] # [224, 224, 3]
+ right_wrist_image = obs[right_wrist_camera_key][:, :, :3] # [224, 224, 3]
+ prop_state = self._generate_prop_state(obs["robot_r1::proprio"])
+
+ except KeyError as e:
+ print(f"Error extracting observations: {e}")
+ print(f"Available keys in obs: {list(obs.keys())}")
+ raise
+
+ # Resize images to policy input size
+ full_image = self._resize_image(full_image)
+ left_wrist_image = self._resize_image(left_wrist_image)
+ right_wrist_image = self._resize_image(right_wrist_image)
+
+
+ return {
+ "full_image": full_image,
+ "left_wrist_image": left_wrist_image,
+ "right_wrist_image": right_wrist_image,
+ "state": prop_state,
+ }
+
+ def forward(self, obs: Dict[str, Any]) -> torch.Tensor:
+ """
+ Forward pass for BEHAVIOR environment.
+
+ Args:
+ obs: Dictionary containing observations from BEHAVIOR environment
+
+ Returns:
+ torch.Tensor: Action tensor for the robot
+ """
+ # Process observations to extract images and proprioception
+ processed_obs = self._process_behavior_obs(obs)
+
+ # Use the head camera image as the primary input
+ primary_image = processed_obs["full_image"]
+ left_wrist_image = processed_obs["left_wrist_image"]
+ right_wrist_image = processed_obs["right_wrist_image"]
+ if "dual" in self.policy_ckpt_path.lower():
+ image_input = [primary_image]
+ wrist_image_input = [left_wrist_image, right_wrist_image]
+ else:
+ image_input = [primary_image, left_wrist_image, right_wrist_image]
+ wrist_image_input = None
+
+ # Get task description from environment if not already set
+ if self.task_description is None:
+ # Try to get task description from the environment
+ # This assumes the environment has a task attribute with show_instruction method
+ print(f"Warning: Could not get task description")
+ self.task_description = "Turn on the radio receiver that's on the table in the living room."
+
+ # Prepare proprioceptive state.
+ # GR00T action header expects state tensor to have shape (B, T_s, state_dim)
+ # so that after the MLP it becomes (B, T_s, hidden). If we pass a simple
+ # 1-D vector the downstream `torch.cat` fails because the ranks differ.
+ # Therefore, when state is enabled we reshape it to (1, 1, state_dim).
+
+ if self.use_state:
+ raw_state = processed_obs["state"] # shape (state_dim,)
+ state = raw_state[None, :] # → (1, state_dim)
+ example = {
+ "image": image_input,
+ "wrist_views": wrist_image_input,
+ "state": state,
+ "lang": self.task_description,
+ }
+ else:
+ example = {
+ "image": image_input,
+ "wrist_views": wrist_image_input,
+ "lang": self.task_description,
+ }
+
+ vla_input = {
+ "examples": [example],
+ }
+
+ # Get action from websocket server
+ action_chunk_size = self.action_chunk_size
+ if self.current_step % action_chunk_size == 0:
+ if self.current_step % 100 == 0:
+ print('Step:', self.current_step)
+ response = self.client.infer(vla_input)
+
+ # Check if the response indicates an error
+ if response.get("ok", True) == False or response.get("status") == "error":
+ error_info = response.get("error", {})
+ print(f"Websocket server returned an error:")
+ print(f"Status: {response.get('status')}")
+ print(f"Error details: {error_info}")
+ raise RuntimeError(f"Websocket server error: {error_info}")
+
+ # Extract and unnormalize actions
+ try:
+ normalized_actions = response["data"]["normalized_actions"] # B, chunk, D
+ except KeyError as e:
+ print(f"KeyError accessing response: {e}")
+ print(f"Available keys in response: {list(response.keys())}")
+ if "data" in response:
+ print(f"Keys in 'data': {list(response['data'].keys())}")
+ raise
+ # Take the first batch element (B dimension) → shape (T, D)
+ normalized_actions = normalized_actions[0]
+ # Un-normalize to get real-valued actions. Still shape (T, D)
+ self.raw_actions = self.unnormalize_actions(
+ normalized_actions=normalized_actions,
+ action_norm_stats=self.action_norm_stats
+ )
+
+ # Apply action ensembling if enabled
+ if self.action_ensemble and action_chunk_size > 1:
+ self.action_ensembler.ensemble_action(self.raw_actions)
+
+ if self.action_ensemble:
+ if action_chunk_size == 1:
+ raw_actions = self.action_ensembler.ensemble_action(self.raw_actions)[None]
+ else:
+ raw_actions = self.action_ensembler.step()[None]
+ else:
+ raw_actions = self.raw_actions[self.current_step % action_chunk_size][None]
+ self.current_step += 1
+
+ # Process raw actions for BEHAVIOR environment
+ raw_action = {
+ "base_pose": np.array(raw_actions[0,:3]),
+ "torso_pose": np.array(raw_actions[0,3:7]),
+ "left_arm_pose": np.array(raw_actions[0,7:14]),
+ "left_gripper_pose": np.array(raw_actions[0,14:15]),
+ "right_arm_pose": np.array(raw_actions[0,15:22]),
+ "right_gripper_pose": np.array(raw_actions[0,22:23]),
+ }
+
+ # Convert to BEHAVIOR action format
+ action = self._process_action_for_behavior(raw_action)
+
+ return torch.from_numpy(action).float()
+
+ def _process_action_for_behavior(self, raw_action: Dict[str, np.ndarray]) -> np.ndarray:
+ """Process raw action to BEHAVIOR environment format."""
+ # Process base, torso, left arm, right arm
+ base_pose = raw_action["base_pose"]
+ torso_pose = raw_action["torso_pose"]
+ left_arm_pose = raw_action["left_arm_pose"]
+ right_arm_pose = raw_action["right_arm_pose"]
+
+ # Process gripper action
+ left_gripper_pose = self._process_gripper_action(raw_action["left_gripper_pose"])
+ right_gripper_pose = self._process_gripper_action(raw_action["right_gripper_pose"])
+
+ # Combine all actions into a single array
+ # BEHAVIOR expects "ACTION_DIM": 23
+ # See the following files:
+ # - ACTION_QPOS_INDICES in omnigibson/learning/utils/eval_utils.py
+ # - action_keys in omnigibson/learning/configs/robot/r1pro.yaml
+ action = np.concatenate([
+ base_pose, # indices 0:3 (3 dims)
+ torso_pose, # indices 3:7 (4 dims)
+ left_arm_pose, # indices 7:14 (7 dims)
+ np.array([left_gripper_pose]), # index 14:15 (1 dim)
+ right_arm_pose, # indices 15:22 (7 dims)
+ np.array([right_gripper_pose]), # index 22:23 (1 dim)
+ ])
+
+ return action
+
+
+ def _process_gripper_action(self, open_gripper: np.ndarray) -> float:
+ """Process gripper action with sticky behavior for BEHAVIOR environment."""
+ # We currently don't apply any other sticky behavior for gripper action.
+ current_gripper_action = open_gripper[0]
+
+ return current_gripper_action
+
+ @staticmethod
+ def unnormalize_actions(normalized_actions: np.ndarray, action_norm_stats: Dict[str, np.ndarray]) -> np.ndarray:
+ """Unnormalize actions using the provided statistics."""
+ mask = action_norm_stats.get("mask", np.ones_like(action_norm_stats["min"], dtype=bool))
+ action_high, action_low = np.array(action_norm_stats["max"]), np.array(action_norm_stats["min"])
+ normalized_actions = np.clip(normalized_actions, -1, 1)
+
+ actions = np.where(
+ mask,
+ 0.5 * (normalized_actions + 1) * (action_high - action_low) + action_low,
+ normalized_actions,
+ )
+
+ return actions
+
+ @staticmethod
+ def get_action_stats(unnorm_key: str, policy_ckpt_path) -> dict:
+ """Load action normalization statistics from checkpoint."""
+ policy_ckpt_path = Path(policy_ckpt_path)
+ model_config, norm_stats = read_mode_config(policy_ckpt_path)
+
+ return norm_stats[unnorm_key]["action"]
+
+ def _resize_image(self, image: np.ndarray) -> np.ndarray:
+ """Resize image to policy input size."""
+
+ image = image.numpy()
+
+ image = cv.resize(image, tuple(self.image_size), interpolation=cv.INTER_AREA)
+ return image
+
+ def visualize_epoch(
+ self, predicted_raw_actions: Sequence[np.ndarray], images: Sequence[np.ndarray], save_path: str
+ ) -> None:
+ """Visualize predicted actions and images."""
+ images = [self._resize_image(image) for image in images]
+ ACTION_DIM_LABELS = ["x", "y", "z", "roll", "pitch", "yaw", "grasp"]
+
+ img_strip = np.concatenate(np.array(images[::3]), axis=1)
+
+ # set up plt figure
+ figure_layout = [["image"] * len(ACTION_DIM_LABELS), ACTION_DIM_LABELS]
+ plt.rcParams.update({"font.size": 12})
+ fig, axs = plt.subplot_mosaic(figure_layout)
+ fig.set_size_inches([45, 10])
+
+ # plot actions
+ pred_actions = np.array(
+ [
+ np.concatenate([a["world_vector"], a["rotation_delta"], a["open_gripper"]], axis=-1)
+ for a in predicted_raw_actions
+ ]
+ )
+ for action_dim, action_label in enumerate(ACTION_DIM_LABELS):
+ # actions have batch, horizon, dim, in this example we just take the first action for simplicity
+ axs[action_label].plot(pred_actions[:, action_dim], label="predicted action")
+ axs[action_label].set_title(action_label)
+ axs[action_label].set_xlabel("Time in one episode")
+
+ axs["image"].imshow(img_strip)
+ axs["image"].set_xlabel("Time in one episode (subsampled)")
+ plt.legend()
+ plt.savefig(save_path)
\ No newline at end of file
diff --git a/examples/Behavior/port_utils.sh b/examples/Behavior/port_utils.sh
new file mode 100644
index 0000000000000000000000000000000000000000..97e0f2ba1968aca12fe0235938c0ee597fba3eff
--- /dev/null
+++ b/examples/Behavior/port_utils.sh
@@ -0,0 +1,78 @@
+#!/bin/bash
+
+# Utility function to find an available port
+# Requires: used_ports array to be declared in the sourcing script before sourcing this file
+# Usage: port=$(find_available_port $base_port)
+find_available_port() {
+ local base_port=$1
+ local port=$base_port
+
+ # First check our internal tracking
+ while [[ " ${used_ports[@]} " =~ " ${port} " ]]; do
+ port=$((port + 1))
+ done
+
+ # Then check system ports if tools are available
+ if command -v netstat >/dev/null 2>&1; then
+ while netstat -tuln 2>/dev/null | grep -q ":$port "; do
+ port=$((port + 1))
+ done
+ elif command -v ss >/dev/null 2>&1; then
+ while ss -tuln 2>/dev/null | grep -q ":$port "; do
+ port=$((port + 1))
+ done
+ elif command -v lsof >/dev/null 2>&1; then
+ while lsof -i :$port >/dev/null 2>&1; do
+ port=$((port + 1))
+ done
+ else
+ # Fallback: just increment port and hope for the best
+ echo "⚠️ Warning: No port checking tools available, using port ${port}" >&2
+ fi
+
+ # Add to our tracking
+ used_ports+=($port)
+ echo $port
+}
+
+# Define a function to check if server is ready
+wait_for_server() {
+ local port=$1
+ local max_attempts=30
+ local attempt=0
+
+ echo "⏳ Waiting for server on port ${port} to be ready..." >&2
+ while [ $attempt -lt $max_attempts ]; do
+ # Try different methods to check if port is in use
+ local port_in_use=false
+
+ # Method 1: Try to connect to the port (most reliable)
+ if timeout 1 bash -c "echo >/dev/tcp/localhost/$port" 2>/dev/null; then
+ port_in_use=true
+ # Method 2: Use system tools if available
+ elif command -v netstat >/dev/null 2>&1; then
+ if netstat -tuln 2>/dev/null | grep -q ":$port "; then
+ port_in_use=true
+ fi
+ elif command -v ss >/dev/null 2>&1; then
+ if ss -tuln 2>/dev/null | grep -q ":$port "; then
+ port_in_use=true
+ fi
+ elif command -v lsof >/dev/null 2>&1; then
+ if lsof -i :$port >/dev/null 2>&1; then
+ port_in_use=true
+ fi
+ fi
+
+ if [ "$port_in_use" = true ]; then
+ echo "✅ Server on port ${port} is ready" >&2
+ return 0
+ fi
+
+ sleep 2
+ attempt=$((attempt + 1))
+ done
+
+ echo "❌ Server on port ${port} failed to start after $((max_attempts * 2)) seconds" >&2
+ return 1
+}
\ No newline at end of file
diff --git a/examples/Behavior/start_behavior_env.py b/examples/Behavior/start_behavior_env.py
new file mode 100644
index 0000000000000000000000000000000000000000..f96ef20f3af4913ade72d2f59ec45722c7d7ffe2
--- /dev/null
+++ b/examples/Behavior/start_behavior_env.py
@@ -0,0 +1,188 @@
+import os
+
+from examples.Behavior.custom_argparse import get_args
+from examples.Behavior.model2behavior_interface import M1Inference
+
+from omnigibson.learning.eval import Evaluator
+from omnigibson.macros import gm
+from omnigibson.learning.utils.eval_utils import TASK_NAMES_TO_INDICES
+from omnigibson.learning.utils.obs_utils import create_video_writer
+from omegaconf import DictConfig, OmegaConf
+import numpy as np
+import logging
+from pathlib import Path
+import json
+import csv
+
+
+def load_task_description(task_name: str, tasks_jsonl_path: Path = None) -> str:
+ """
+ Load task description from tasks.jsonl file based on task_name.
+ """
+ # Load tasks.jsonl and create mapping
+ task_name_to_description = {}
+ with open(tasks_jsonl_path, "r") as f:
+ for line in f:
+ task_data = json.loads(line)
+ task_name_to_description[task_data["task_name"]] = task_data["task"]
+
+ if task_name not in task_name_to_description:
+ raise KeyError(
+ f"Task name '{task_name}' not found in tasks.jsonl. "
+ f"Available tasks: {list(task_name_to_description.keys())}"
+ )
+
+ return task_name_to_description[task_name]
+
+# Module-specific constants
+NUM_EVAL_EPISODES = 1
+NUM_TRAIN_INSTANCES = 200 # 200 human-collected demonstrations
+NUM_EVAL_INSTANCES = 10 # 20 extra configuration instances
+
+# set global variables to boost performance
+gm.ENABLE_FLATCACHE = True
+gm.USE_GPU_DYNAMICS = False
+gm.ENABLE_TRANSITION_RULES = True
+
+# create module logger
+logger = logging.getLogger("evaluator")
+logger.setLevel(20) # info
+
+if __name__ == "__main__":
+ args = get_args()
+ args.eval_instance_ids = [int(x) for x in args.eval_instance_ids.split()]
+ # print("args.eval_instance_ids",args.eval_instance_ids)
+
+ os.environ["DISPLAY"] = ""
+ # prevent a single jax process from taking up all the GPU memory
+ os.environ["XLA_PYTHON_CLIENT_PREALLOCATE"] = "false"
+
+ # Load task description from tasks.jsonl using task_name
+ task_description = load_task_description(args.task_name,tasks_jsonl_path=args.behavior_tasks_jsonl_path)
+ logger.info(f"Loaded task description for '{args.task_name}': {task_description}")
+
+ model = M1Inference(
+ policy_ckpt_path=args.ckpt_path, # to get unnormalization stats
+ policy_setup=args.policy_setup,
+ port=args.port,
+ task_description=task_description,
+ )
+
+ # policy model creation; update this if you are using a new policy model
+ # run real-to-sim evaluation
+ # set headless mode
+ gm.HEADLESS = args.headless
+
+ # Set behavior data path, should be set to the path to the datasets folder under BEHAVIOR-1k
+ gm.DATA_PATH = args.behavior_asset_path
+ # set video path
+ if args.write_video:
+ video_path = Path(args.logging_dir).expanduser() / "videos"
+ video_path.mkdir(parents=True, exist_ok=True)
+ # get run instances
+ if args.eval_on_train_instances:
+ logger.info(
+ "You are evaluating on training instances, set eval_on_train_instances to False for test instances."
+ )
+ task_idx = TASK_NAMES_TO_INDICES[args.task_name]
+ with open(os.path.join(gm.DATA_PATH, "2025-challenge-task-instances", "metadata", "episodes.jsonl"), "r") as f:
+ episodes = [json.loads(line) for line in f]
+ instances_to_run = []
+ for episode in episodes:
+ if episode["episode_index"] // 1e4 == task_idx:
+ instances_to_run.append(str(int((episode["episode_index"] // 10) % 1e3)))
+ if args.eval_instance_ids:
+ assert set(args.eval_instance_ids).issubset(
+ set(range(NUM_TRAIN_INSTANCES))
+ ), f"eval instance ids must be in range({NUM_TRAIN_INSTANCES}), currently {args.eval_instance_ids}"
+ instances_to_run = [instances_to_run[i] for i in args.eval_instance_ids]
+ else:
+ instances_to_run = (
+ args.eval_instance_ids if args.eval_instance_ids is not None else set(range(NUM_EVAL_INSTANCES))
+ )
+ assert set(instances_to_run).issubset(
+ set(range(NUM_EVAL_INSTANCES))
+ ), f"eval instance ids must be in range({NUM_EVAL_INSTANCES})"
+ # load csv file
+ task_instance_csv_path = os.path.join(
+ gm.DATA_PATH, "2025-challenge-task-instances","metadata", "test_instances.csv"
+ )
+ with open(task_instance_csv_path, "r") as f:
+ lines = list(csv.reader(f))[1:]
+ assert (
+ lines[TASK_NAMES_TO_INDICES[args.task_name]][1] == args.task_name
+ ), f"Task name from config {args.task_name} does not match task name from csv {lines[TASK_NAMES_TO_INDICES[args.task_name]][1]}"
+ test_instances = lines[TASK_NAMES_TO_INDICES[args.task_name]][2].strip().split(",")
+ instances_to_run = [int(test_instances[i]) for i in instances_to_run]
+ # establish metrics
+ metrics = {}
+ metrics_path = Path(args.logging_dir).expanduser() / "metrics"
+ metrics_path.mkdir(parents=True, exist_ok=True)
+
+ config_dict = {
+ "env_wrapper": {"_target_": f"omnigibson.learning.wrappers.{args.wrappers}"},
+ "task": {"name": args.task_name},
+ "robot": {"type": "R1Pro", "controllers": None}, # TODO: add controllers
+ "partial_scene_load": args.partial_scene_load,
+ "max_steps": args.max_steps,
+ "write_video": args.write_video,
+ "model": {
+ "_target_": "examples.Behavior.model2behavior_interface.M1Inference",
+ "policy_ckpt_path": args.ckpt_path,
+ "policy_setup": args.policy_setup,
+ "port": args.port,
+ "task_description": task_description,
+ "use_state": args.use_state,
+ },
+ "policy_name": args.policy_model, # It's just a name
+ }
+
+ # Convert dictionary to OmegaConf DictConfig to support attribute access
+ config = OmegaConf.create(config_dict)
+
+ with Evaluator(cfg=config) as evaluator:
+ logger.info("Starting evaluation...")
+
+ for idx in instances_to_run:
+ evaluator.reset()
+ evaluator.load_task_instance(idx)
+ logger.info(f"Starting task instance {idx} for evaluation...")
+ for epi in range(NUM_EVAL_EPISODES):
+ evaluator.reset()
+ done = False
+ if config.write_video:
+ video_name = str(video_path) + f"/{config.task.name}_{idx}_{epi}.mp4"
+ evaluator.video_writer = create_video_writer(
+ fpath=video_name,
+ resolution=(448, 672),
+ )
+ # run metric start callbacks
+ for metric in evaluator.metrics:
+ metric.start_callback(evaluator.env)
+ while not done:
+ terminated, truncated = evaluator.step()
+
+ if terminated or truncated:
+ done = True
+ if config.write_video:
+ evaluator._write_video()
+ if evaluator.env._current_step % 1000 == 0:
+ logger.info(f"Current step: {evaluator.env._current_step}")
+ # run metric end callbacks
+ for metric in evaluator.metrics:
+ metric.end_callback(evaluator.env)
+ logger.info(f"Evaluation finished at step {evaluator.env._current_step}.")
+ logger.info(f"Evaluation exit state: {terminated}, {truncated}")
+ logger.info(f"Total trials: {evaluator.n_trials}")
+ logger.info(f"Total success trials: {evaluator.n_success_trials}")
+ # gather metric results and write to file
+ for metric in evaluator.metrics:
+ metrics.update(metric.gather_results())
+ with open(metrics_path / f"{config.task.name}_{idx}_{epi}.json", "w") as f:
+ json.dump(metrics, f)
+ # reset video writer
+ if config.write_video:
+ evaluator.video_writer = None
+ logger.info(f"Saved video to {video_name}")
+ else:
+ logger.warning("No observations were recorded.")
\ No newline at end of file
diff --git a/examples/Behavior/start_client.sh b/examples/Behavior/start_client.sh
new file mode 100644
index 0000000000000000000000000000000000000000..4e40ceba09572868fbc6de1b8f458d5246f895c9
--- /dev/null
+++ b/examples/Behavior/start_client.sh
@@ -0,0 +1,50 @@
+#!/bin/bash
+
+# Debug: print current python environment
+echo "Using Python: $(which python)"
+
+### MANUALLY SET THESE ###
+# set necessary environment variables
+export star_vla_python=
+export sim_python=
+export TASKS_JSONL_PATH=
+export BEHAVIOR_ASSET_PATH=
+export PYTHONPATH=$(pwd):${PYTHONPATH}
+
+# set model path and port
+MODEL_PATH="/workspace/llavavla0/playground/Checkpoints/BEHAVIOR-QwenDual-Pretrained-224/checkpoints/steps_300000_pytorch_model.pt"
+PORT=10197
+WRAPPERS="RGBLowResWrapper" # DefaultWrapper, RGBLowResWrapper or RichObservationWrapper
+USE_STATE=True
+
+# set task name
+TASK_NAME="turning_on_radio"
+EVAL_INSTANCE_IDS="0"
+### END OF MANUALLY SETUP ###
+
+
+# Force Vulkan to use only the NVIDIA ICD to avoid duplicate ICDs seen by the loader
+export VK_ICD_FILENAMES=/etc/vulkan/icd.d/nvidia_icd.json
+# Prefer NVIDIA GLX vendor when any GL deps are touched
+export __GLX_VENDOR_LIBRARY_NAME=nvidia
+
+# run single task
+export DEBUG=true
+echo "▶️ Running task '${TASK_NAME}'..."
+CUDA_VISIBLE_DEVICES=5 ${sim_python} examples/Behavior/start_behavior_env.py \
+ --ckpt-path ${MODEL_PATH} \
+ --eval-instance-ids \"${EVAL_INSTANCE_IDS}\" \
+ --eval-on-train-instances True \
+ --port ${PORT} \
+ --task-name ${TASK_NAME} \
+ --behavior-tasks-jsonl-path ${TASKS_JSONL_PATH} \
+ --behavior-asset-path ${BEHAVIOR_ASSET_PATH} \
+ --wrappers ${WRAPPERS} \
+ --use-state ${USE_STATE}
+
+
+# stop server
+echo "⏹️ Stopping server (PID: ${SERVER_PID})..."
+kill ${SERVER_PID}
+wait ${SERVER_PID} 2>/dev/null
+echo "✅ Server stopped"
\ No newline at end of file
diff --git a/examples/Behavior/start_parallel_eval.sh b/examples/Behavior/start_parallel_eval.sh
new file mode 100644
index 0000000000000000000000000000000000000000..9aa938cc8698d8cdac3a2026bee4325204c98327
--- /dev/null
+++ b/examples/Behavior/start_parallel_eval.sh
@@ -0,0 +1,141 @@
+#!/bin/bash
+
+### MANUALLY SET THESE ###
+# set the environment variables
+export star_vla_python=/root/miniconda3/envs/starVLA/bin/python
+export sim_python=/root/miniconda3/envs/behavior/bin/python
+export TASKS_JSONL_PATH=/workspace/llavavla0/examples/Behavior/tasks.jsonl
+export BEHAVIOR_ASSET_PATH=/workspace/llavavla0/BEHAVIOR-1K/datasets
+export PYTHONPATH=$(pwd):${PYTHONPATH}
+
+# set the eval parameters
+MODEL_PATH=/workspace/llavavla0/playground/Checkpoints/BEHAVIOR-QwenDual-Pretrained-224/checkpoints/steps_300000_pytorch_model.pt
+base_port=10197
+WRAPPERS="DefaultWrapper" # DefaultWrapper, RGBLowResWrapper or RichObservationWrapper
+USE_STATE=True # whether to use state as part of the observation
+TEST_NUM=1 # only evaluate one time as specified by the rule, note only one video will be saved
+
+
+# Configure which instances to evaluate
+# Space-separated list, e.g., "0" or "0 1 2", up to 9. The rule requires using the first 10 instances for evaluation results
+TEST_EVAL_INSTANCE_IDS="0 1 2 3 4 5 6 7"
+
+# Config which task to evaluate
+declare -a INSTANCE_NAMES=(
+ "turning_on_radio"
+)
+### END OF MANUALLY SETUP ###
+
+
+# Start Evaluating on train instances
+run_count=0
+
+# Track used ports to avoid conflicts
+declare -a used_ports=()
+
+# Source the port utility function
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+source "${SCRIPT_DIR}/port_utils.sh"
+
+if [ -z "$MODEL_PATH" ]; then
+ echo "❌ MODEL_PATH not provided as the first argument, using default value"
+ export MODEL_PATH="./results/Checkpoints/1007_qwenLargefm/checkpoints/steps_20000_pytorch_model.pt"
+fi
+
+ckpt_path=${MODEL_PATH}
+
+
+# Define a function to start the service
+start_service() {
+ local gpu_id=$1
+ local ckpt_path=$2
+ local base_port=$3
+ local port=$(find_available_port $base_port)
+ local server_log_dir="$(dirname "${ckpt_path}")/server_logs"
+ local svc_log="${server_log_dir}/$(basename "${ckpt_path%.*}")_policy_server_${port}.log"
+ mkdir -p "${server_log_dir}"
+
+ echo "▶️ Starting service on GPU ${gpu_id}, port ${port} (requested: ${base_port})" >&2
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${star_vla_python} deployment/model_server/server_policy.py \
+ --ckpt_path ${ckpt_path} \
+ --port ${port} \
+ --use_bf16 \
+ > "${svc_log}" 2>&1 &
+
+ local pid=$! # Capture the PID immediately
+
+ # Wait for server to be ready
+ if wait_for_server $port; then
+ echo "$pid:$port" # Return PID and port separated by colon
+ else
+ echo "❌ Failed to start server on port ${port}" >&2
+ return 1
+ fi
+}
+
+
+# Get the CUDA_VISIBLE_DEVICES list
+IFS=',' read -r -a CUDA_DEVICES <<< "$CUDA_VISIBLE_DEVICES" # Convert the comma-separated GPU list into an array
+NUM_GPUS=${#CUDA_DEVICES[@]} # Number of available GPUs
+
+# Handle case where CUDA_VISIBLE_DEVICES is not set
+if [ $NUM_GPUS -eq 0 ]; then
+ echo "⚠️ CUDA_VISIBLE_DEVICES not set, using default GPU 0"
+ CUDA_DEVICES=(0)
+ NUM_GPUS=1
+fi
+
+
+
+# Debug info
+echo "CUDA_VISIBLE_DEVICES: $CUDA_VISIBLE_DEVICES"
+echo "CUDA_DEVICES: ${CUDA_DEVICES[@]}"
+echo "NUM_GPUS: $NUM_GPUS"
+
+
+# Start Evaluating on test instances
+for task_name in "${INSTANCE_NAMES[@]}"; do
+ task_name=${task_name}
+ for ((run_idx=1; run_idx<=TEST_NUM; run_idx++)); do
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]}
+
+ ckpt_dir=$(dirname "${ckpt_path}")
+ ckpt_base=$(basename "${ckpt_path}")
+ ckpt_name="${ckpt_base%.*}" # strip .pt or .bin suffix
+
+ tag="run${run_idx}"
+ task_log="${ckpt_dir}/${ckpt_name}_infer_test_${task_name}.log.${tag}"
+
+ echo "▶️ Launching task [test_instances] run#${run_idx} on GPU $gpu_id, log → ${task_log}"
+
+ # Start the service and get the actual port used
+ requested_port=$((base_port + run_count))
+ actual_port=$(start_service ${gpu_id} ${ckpt_path} ${requested_port})
+
+ if [ $? -eq 0 ]; then
+ echo "✅ Server started successfully on port ${actual_port}"
+
+ # Build command with optional eval-instance-ids
+ cmd="CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/Behavior/start_behavior_env.py \
+ --ckpt-path ${ckpt_path} \
+ --eval-on-train-instances False \
+ --port ${actual_port} \
+ --task-name ${task_name} \
+ --behavior-tasks-jsonl-path ${TASKS_JSONL_PATH} \
+ --behavior-asset-path ${BEHAVIOR_ASSET_PATH} \
+ --wrappers ${WRAPPERS} \
+ --use-state ${USE_STATE} \
+ --eval-instance-ids \"${TEST_EVAL_INSTANCE_IDS}\""
+
+ eval "$cmd" > "${task_log}" 2>&1 &
+
+ else
+ echo "❌ Failed to start server for test instances run#${run_idx}, skipping..."
+ fi
+
+ run_count=$((run_count + 1))
+ done
+done
+
+wait
+echo "✅ All tests complete"
\ No newline at end of file
diff --git a/examples/Behavior/start_parallel_eval_per_task.sh b/examples/Behavior/start_parallel_eval_per_task.sh
new file mode 100644
index 0000000000000000000000000000000000000000..976e493f07a40178f3e3a746c7e505897a220952
--- /dev/null
+++ b/examples/Behavior/start_parallel_eval_per_task.sh
@@ -0,0 +1,302 @@
+#!/bin/bash
+
+### MANUALLY SET THESE ###
+# set the environment variables
+export star_vla_python=/root/miniconda3/envs/starVLA/bin/python
+export sim_python=/root/miniconda3/envs/behavior/bin/python
+export TASKS_JSONL_PATH=/workspace/llavavla0/examples/Behavior/tasks.jsonl
+export BEHAVIOR_ASSET_PATH=/workspace/llavavla0/BEHAVIOR-1K/datasets
+export PYTHONPATH=$(pwd):${PYTHONPATH}
+
+# set the eval parameters
+MODEL_PATH=/workspace/llavavla0/playground/Checkpoints/BEHAVIOR-QwenDual-Pretrained-224/checkpoints/steps_300000_pytorch_model.pt
+base_port=10197
+WRAPPERS="DefaultWrapper" # DefaultWrapper, RGBLowResWrapper or RichObservationWrapper
+USE_STATE=True # whether to use state as part of the observation
+TEST_NUM=1 # only evaluate one time as specified by the rule, note only one video will be saved
+
+
+# Configure which instances to evaluate
+# Space-separated list, e.g., "0" or "0 1 2", up to 9. The rule requires using the first 10 instances for evaluation results
+TEST_EVAL_INSTANCE_IDS="0 1 2 3 4 5 6 7"
+
+# Config which task to evaluate
+declare -a INSTANCE_NAMES=(
+ # B10
+ "turning_on_radio"
+ "picking_up_trash"
+ "putting_away_Halloween_decorations"
+ "cleaning_up_plates_and_food"
+ "can_meat"
+ "setting_mousetraps"
+ "hiding_Easter_eggs"
+ "picking_up_toys"
+ "rearranging_kitchen_furniture"
+ "putting_up_Christmas_decorations_inside"
+ # B20
+ "set_up_a_coffee_station_in_your_kitchen"
+ "putting_dishes_away_after_cleaning"
+ "preparing_lunch_box"
+ "loading_the_car"
+ "carrying_in_groceries"
+ "bringing_in_wood"
+ "moving_boxes_to_storage"
+ "bringing_water"
+ "tidying_bedroom"
+ "outfit_a_basic_toolbox"
+ # B30
+ "sorting_vegetables"
+ "collecting_childrens_toys"
+ "putting_shoes_on_rack"
+ "boxing_books_up_for_storage"
+ "storing_food"
+ "clearing_food_from_table_into_fridge"
+ "assembling_gift_baskets"
+ "sorting_household_items"
+ "getting_organized_for_work"
+ "clean_up_your_desk"
+ # B40
+ "setting_the_fire"
+ "clean_boxing_gloves"
+ "wash_a_baseball_cap"
+ "wash_dog_toys"
+ "hanging_pictures"
+ "attach_a_camera_to_a_tripod"
+ "clean_a_patio"
+ "clean_a_trumpet"
+ "spraying_for_bugs"
+ "spraying_fruit_trees"
+ # B50
+ "make_microwave_popcorn"
+ "cook_cabbage"
+ "chop_an_onion"
+ "slicing_vegetables"
+ "chopping_wood"
+ "cook_hot_dogs"
+ "cook_bacon"
+ "freeze_pies"
+ "canning_food"
+ "make_pizza"
+)
+### END OF MANUALLY SETUP ###
+
+# Start Evaluating on train instances
+run_count=0
+
+# Track used ports to avoid conflicts
+declare -a used_ports=()
+
+# Source the port utility function
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+source "${SCRIPT_DIR}/port_utils.sh"
+
+if [ -z "$MODEL_PATH" ]; then
+ echo "❌ MODEL_PATH not provided as the first argument, using default value"
+ export MODEL_PATH="./results/Checkpoints/1007_qwenLargefm/checkpoints/steps_20000_pytorch_model.pt"
+fi
+
+ckpt_path=${MODEL_PATH}
+
+
+# Define a function to start the service
+start_service() {
+ local gpu_id=$1
+ local ckpt_path=$2
+ local base_port=$3
+ local port=$(find_available_port $base_port)
+ local server_log_dir="$(dirname "${ckpt_path}")/server_logs"
+ local svc_log="${server_log_dir}/$(basename "${ckpt_path%.*}")_policy_server_${port}.log"
+ mkdir -p "${server_log_dir}"
+
+ echo "▶️ Starting service on GPU ${gpu_id}, port ${port} (requested: ${base_port})" >&2
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${star_vla_python} deployment/model_server/server_policy.py \
+ --ckpt_path ${ckpt_path} \
+ --port ${port} \
+ --use_bf16 \
+ > "${svc_log}" 2>&1 &
+
+ local pid=$! # Capture the PID immediately
+
+ # Wait for server to be ready
+ if wait_for_server $port; then
+ echo "$pid:$port" # Return PID and port separated by colon
+ else
+ echo "❌ Failed to start server on port ${port}" >&2
+ return 1
+ fi
+}
+
+# Define a function to stop the service
+stop_service() {
+ local pid=$1
+ if [ -n "$pid" ] && kill -0 $pid 2>/dev/null; then
+ echo "⏹️ Stopping service (PID: ${pid})..."
+ kill $pid
+ wait $pid 2>/dev/null
+ echo "✅ Service stopped"
+ fi
+}
+
+
+# Get the CUDA_VISIBLE_DEVICES list
+IFS=',' read -r -a CUDA_DEVICES <<< "$CUDA_VISIBLE_DEVICES" # Convert the comma-separated GPU list into an array
+NUM_GPUS=${#CUDA_DEVICES[@]} # Number of available GPUs
+
+# Handle case where CUDA_VISIBLE_DEVICES is not set
+if [ $NUM_GPUS -eq 0 ]; then
+ echo "⚠️ CUDA_VISIBLE_DEVICES not set, using default GPU 0"
+ CUDA_DEVICES=(0)
+ NUM_GPUS=1
+fi
+
+
+
+# Debug info
+echo "CUDA_VISIBLE_DEVICES: $CUDA_VISIBLE_DEVICES"
+echo "CUDA_DEVICES: ${CUDA_DEVICES[@]}"
+echo "NUM_GPUS: $NUM_GPUS"
+
+
+# Parse TEST_EVAL_INSTANCE_IDS into an array
+read -r -a INSTANCE_ID_ARRAY <<< "$TEST_EVAL_INSTANCE_IDS"
+NUM_INSTANCES=${#INSTANCE_ID_ARRAY[@]}
+
+echo "📊 Configuration:"
+echo " - Tasks to evaluate: ${#INSTANCE_NAMES[@]}"
+echo " - Instances per task: ${NUM_INSTANCES} (${TEST_EVAL_INSTANCE_IDS})"
+echo " - Available GPUs: ${NUM_GPUS} (${CUDA_DEVICES[@]})"
+echo " - Runs per task: ${TEST_NUM}"
+echo ""
+
+# Start Evaluating on test instances
+# For each task, run all instances in parallel across GPUs, then wait before next task
+for i in "${!INSTANCE_NAMES[@]}"; do
+ task_name="${INSTANCE_NAMES[i]}"
+ echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
+ echo "📋 Processing task $((i+1))/${#INSTANCE_NAMES[@]}: ${task_name}"
+ echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
+
+ # Arrays to track services and evaluations for this task
+ declare -a task_service_pids=()
+ declare -a task_service_ports=()
+ declare -a task_eval_pids=()
+ declare -a task_eval_logs=()
+
+ ckpt_dir=$(dirname "${ckpt_path}")
+ ckpt_base=$(basename "${ckpt_path}")
+ ckpt_name="${ckpt_base%.*}" # strip .pt or .bin suffix
+
+ # Launch all instances for this task in parallel
+ expected_launches=$((TEST_NUM * NUM_INSTANCES))
+ successful_launches=0
+
+ for ((run_idx=1; run_idx<=TEST_NUM; run_idx++)); do
+ for instance_idx in "${!INSTANCE_ID_ARRAY[@]}"; do
+ instance_id="${INSTANCE_ID_ARRAY[instance_idx]}"
+
+ # Distribute across GPUs
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]}
+
+ tag="run${run_idx}_instance${instance_id}"
+ task_log="${ckpt_dir}/${ckpt_name}_infer_test_${task_name}.log.${tag}"
+
+ echo "▶️ Launching instance ${instance_id} for task ${task_name} (run#${run_idx}) on GPU $gpu_id"
+
+ # Start the service and get the PID and port
+ requested_port=$((base_port + run_count))
+ service_info=$(start_service ${gpu_id} ${ckpt_path} ${requested_port})
+ service_exit_code=$?
+
+ if [ $service_exit_code -eq 0 ] && [ -n "$service_info" ]; then
+ # Extract PID and port from the returned string (format: "PID:PORT")
+ service_pid=$(echo $service_info | cut -d':' -f1)
+ actual_port=$(echo $service_info | cut -d':' -f2)
+
+ # Validate that we got both PID and port
+ if [ -z "$service_pid" ] || [ -z "$actual_port" ]; then
+ echo "❌ Invalid service info returned for instance ${instance_id}, skipping..."
+ run_count=$((run_count + 1))
+ continue
+ fi
+
+ task_service_pids+=($service_pid)
+ task_service_ports+=($actual_port)
+
+ echo "✅ Server started on port ${actual_port} (PID: ${service_pid}) for instance ${instance_id}"
+
+ # Build command with single instance ID
+ cmd="CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/Behavior/start_behavior_env.py \
+ --ckpt-path ${ckpt_path} \
+ --eval-on-train-instances False \
+ --port ${actual_port} \
+ --task-name ${task_name} \
+ --behavior-tasks-jsonl-path ${TASKS_JSONL_PATH} \
+ --behavior-asset-path ${BEHAVIOR_ASSET_PATH} \
+ --wrappers ${WRAPPERS} \
+ --use-state ${USE_STATE} \
+ --eval-instance-ids \"${instance_id}\""
+
+ # Run evaluation in background
+ echo "🔄 Starting evaluation for ${task_name} instance ${instance_id} (run#${run_idx})..."
+ eval "$cmd" > "${task_log}" 2>&1 &
+ eval_pid=$!
+
+ # Verify the background process started successfully
+ if ! kill -0 $eval_pid 2>/dev/null; then
+ echo "❌ Failed to start evaluation process for instance ${instance_id}"
+ stop_service ${service_pid}
+ run_count=$((run_count + 1))
+ continue
+ fi
+
+ task_eval_pids+=($eval_pid)
+ task_eval_logs+=("${task_log}")
+ successful_launches=$((successful_launches + 1))
+ else
+ echo "❌ Failed to start server for instance ${instance_id} (exit code: ${service_exit_code}), skipping..."
+ fi
+
+ run_count=$((run_count + 1))
+ done
+ done
+
+ echo ""
+ echo "📊 Launch summary: ${successful_launches}/${expected_launches} evaluations launched successfully"
+
+ # Wait for all evaluations for this task to complete
+ echo ""
+ echo "⏳ Waiting for all ${#task_eval_pids[@]} evaluations to complete for task: ${task_name}..."
+
+ failed_count=0
+ for eval_idx in "${!task_eval_pids[@]}"; do
+ eval_pid=${task_eval_pids[$eval_idx]}
+ eval_log=${task_eval_logs[$eval_idx]}
+
+ if wait $eval_pid; then
+ echo "✅ Evaluation completed successfully: ${eval_log}"
+ else
+ eval_exit_code=$?
+ echo "❌ Evaluation failed (exit code ${eval_exit_code}): ${eval_log}"
+ failed_count=$((failed_count + 1))
+ fi
+ done
+
+ # Stop all services for this task
+ echo ""
+ echo "⏹️ Stopping all services for task: ${task_name}..."
+ for service_pid in "${task_service_pids[@]}"; do
+ stop_service ${service_pid}
+ done
+
+ echo ""
+ if [ $failed_count -eq 0 ]; then
+ echo "✅ All evaluations completed successfully for task: ${task_name}"
+ else
+ echo "⚠️ Completed task: ${task_name} with ${failed_count} failed evaluation(s)"
+ fi
+ echo ""
+done
+
+echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
+echo "✅ All tests complete"
+echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
\ No newline at end of file
diff --git a/examples/Behavior/start_server.sh b/examples/Behavior/start_server.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b05438169d3f4bb418346ddda81ded6c0709f69c
--- /dev/null
+++ b/examples/Behavior/start_server.sh
@@ -0,0 +1,37 @@
+#!/bin/bash
+
+# Debug: 输出当前使用的 Python 环境
+echo "Using Python: $(which python)"
+
+### MANUALLY SET THESE ###
+
+# set necessary environment variables
+export star_vla_python=/opt/conda/envs/starVLA/bin/python
+export sim_python=/opt/conda/envs/behavior/bin/python
+export BEHAVIOR_ASSET_PATH=/workspace/llavavla0/BEHAVIOR-1K/datasets
+export PYTHONPATH=$(pwd):${PYTHONPATH}
+
+
+
+# set model path and port
+MODEL_PATH="/workspace/llavavla0/playground/Checkpoints/BEHAVIOR-QwenDual-Pretrained-224/checkpoints/steps_300000_pytorch_model.pt"
+PORT=10197
+WRAPPERS="DefaultWrapper"
+USE_STATE=True # whether to use state as part of the observation
+
+# 配置任务名称
+TASK_NAME="turning_on_radio"
+### END OF MANUALLY SETUP ###
+
+# Force Vulkan to use only the NVIDIA ICD to avoid duplicate ICDs seen by the loader
+export VK_ICD_FILENAMES=/etc/vulkan/icd.d/nvidia_icd.json
+# Prefer NVIDIA GLX vendor when any GL deps are touched
+export __GLX_VENDOR_LIBRARY_NAME=nvidia
+
+# 启动服务
+echo "▶️ Starting server on port ${PORT}..."
+CUDA_VISIBLE_DEVICES=5 ${star_vla_python} deployment/model_server/server_policy.py \
+ --ckpt_path ${MODEL_PATH} \
+ --port ${PORT} \
+ --is_debug \
+ --use_bf16
\ No newline at end of file
diff --git a/examples/Behavior/starvla_cotrain_behavior.yaml b/examples/Behavior/starvla_cotrain_behavior.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..0bf7942dc9f237f74e144dbb0f8a62c7f2130203
--- /dev/null
+++ b/examples/Behavior/starvla_cotrain_behavior.yaml
@@ -0,0 +1,112 @@
+run_id: qwenact
+run_root_dir: results/Checkpoints
+seed: 42
+trackers: [jsonl, wandb]
+wandb_entity: your_wandb_entity
+wandb_project: llavavla
+is_debug: false
+
+framework:
+ name: QwenGR00T
+ qwenvl:
+ base_vlm: ./playground/Pretrained_models/Qwen2.5-VL-3B-Instruct
+ attn_implementation: flash_attention_2
+ vl_hidden_dim: 2048
+ dino:
+ dino_backbone: dinov2_vits14
+
+ action_model:
+ action_model_type: DiT-B
+ action_hidden_dim: 1024 # 和 DiT 最后的 projection 对应,用于 ActionDecoder
+ hidden_size: 1024 # 和 DiT 最后的 projection 对应,用于 ActionDecoder
+ add_pos_embed: True
+ max_seq_len: 2048
+ action_dim: 23
+ state_dim: 44
+ future_action_window_size: 49
+ action_horizon: 50
+ past_action_window_size: 0
+ repeated_diffusion_steps: 8
+ noise_beta_alpha: 1.5
+ noise_beta_beta: 1.0
+ noise_s: 0.999
+ num_timestep_buckets: 1000
+ num_inference_timesteps: 4
+ num_target_vision_tokens: 32
+ diffusion_model_cfg: # DiT Transformers 的参数
+ cross_attention_dim: 2048 # VLM 的 dim
+ dropout: 0.2
+ final_dropout: true
+ interleave_self_attention: true
+ norm_type: "ada_norm"
+ num_layers: 16
+ output_dim: 1024
+ positional_embeddings: null
+
+
+
+datasets:
+ vlm_data:
+ dataset_py: vlm_datasets
+ dataformat: llava_json
+ dataset_use: asv2_conversation_en,asv2_detailed_description_en,asv2_region_captioning_en,coco_internvl_longcap_en,coco_karpathy_train_567_en,coco_negative_gpt4o_en,coco_poetry_zh,coco_rem_en_zh,cocorem_exist_yorn_en,cocotextv2_en,cocotextv2_gpt4o_en,okvqa_en,refcoco_grounding_aug_en,refcoco_grounding_en,tallyqa_coco_en,toloka_grounding_aug_en,vqav2_en,vsr_en
+ eval_dataset: aokvqa_cauldron_llava_format
+ data_flatten: false
+ base_interval: 2
+ max_pixels: 12845056
+ min_pixels: 3136
+ model_max_length: 2048
+ model_type: qwen2.5vl
+ per_device_batch_size: 4
+
+ vla_data:
+ dataset_py: lerobot_datasets
+ data_root_dir: playground/Datasets/behavior-1k
+ data_mix: BEHAVIOR_challenge
+ include_state: false
+ per_device_batch_size: 16
+ load_all_data_for_training: true
+ CoT_prompt: "Your task is {instruction}. To identify the key objects for your task. Locate their bounding boxes in [x1,y1,x2,y2] format."
+ CoT_answer: bbox
+ default_image_resolution: [3, 224, 224]
+
+
+trainer:
+ epochs: 100
+ max_train_steps: 100000
+ num_warmup_steps: 5000
+ save_interval: 5000
+ eval_interval: 100
+ learning_rate:
+ base: 2.5e-05
+ qwen_vl_interface: 1.0e-05
+ action_model: 1.0e-04
+ lr_scheduler_type: cosine_with_min_lr
+ scheduler_specific_kwargs:
+ min_lr: 1.0e-06
+ freeze_modules: ''
+ loss_scale:
+ vla: 1.0
+ vlm: 0.1
+ # pretrained_checkpoint: /gpfs/wangzixuan/Jinhui/llavavla0/playground/Checkpoints/1031_BEHAVIOR_challenge_qwengroot/checkpoints/steps_5000_pytorch_model.pt
+ # reload_modules: 'action_model,layer_qformer' # warning: this may cause model to not converge
+ repeated_diffusion_steps: 4
+ max_grad_norm: 1.0
+ warmup_ratio: 0.1
+ weight_decay: 0.0
+ logging_frequency: 10
+ gradient_clipping: 1.0
+ gradient_accumulation_steps: 1
+
+ optimizer:
+ name: AdamW
+ betas: [0.9, 0.95]
+ eps: 1.0e-08
+ weight_decay: 1.0e-08
+
+ # parameters to be determined
+ is_resume: false
+ resume_epoch: null
+ resume_step: null
+ enable_gradient_checkpointing: true
+ enable_mixed_precision_training: true
diff --git a/examples/CoTrainVLM/README.md b/examples/CoTrainVLM/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..8a4ea277ec7a3064cff5fabe747579cfa9e31196
--- /dev/null
+++ b/examples/CoTrainVLM/README.md
@@ -0,0 +1,120 @@
+
+## StarVLA Co-Training Guide: VLA with VLM Data 🚀
+
+This guide outlines the process for integrating VLM (Vision-Language Model) data to co-train the StarVLA (Vision-Language-Action) framework, enhancing its general visual and language understanding.
+
+---
+
+### 📦 1. Multi-Modal Data Preparation
+
+The VLM data must adhere to the [QwenVL Conversations JSON Data Structure](https://github.com/QwenLM/Qwen3-VL/tree/main/qwen-vl-finetune).
+
+
+#### Required Format:
+* Each data instance is a JSON object.
+* It links an **image file path** to a list of **human-GPT conversational turns**.
+
+```json
+{
+ "image": "path/to/images/001.jpg",
+ "conversations": [
+ {
+ "from": "human",
+ "value": "\nWhat's the main object in this picture?"
+ },
+ {
+ "from": "gpt",
+ "value": "A red apple on a wooden table"
+ }
+ ]
+}
+````
+
+#### Quick Start
+
+You can download our case dataset [LLaVA-OneVision-COCO](https://huggingface.co/datasets/StarVLA/LLaVA-OneVision-COCO).
+Unzip `sharegpt4v_coco.zip` and place it in `playground/Datasets/LLaVA-OneVision-COCO`.
+
+The resulting file structure will look like this:
+
+``` bash
+.../LLaVA-OneVision-COCO
+├── images
+│ └── sharegpt4v_coco
+└── llava_jsons
+ └── sharegpt4v_coco.json
+```
+
+-----
+
+### ⚙️ 2. VLM Dataset Configuration
+
+To add a custom VLM dataset, follow these steps:
+
+#### 2.1 Register Dataset (Python)
+
+Register your dataset by adding it to the `data_dict` in [qwen_data_config.py](./starVLA/dataloader/qwenvl_llavajson/qwen_data_config.py#L17).
+
+
+```python
+# Example Registration
+
+SHAREGPT4V_COCO = {
+ "annotation_path": f"{json_root}/sharegpt4v_coco.json",
+ "data_path": f"{image_root}/",
+}
+
+data_dict = {
+ "sharegpt4v_coco": SHAREGPT4V_COCO, # Use this name in the YAML config
+}
+```
+
+#### 2.2 Update Training YAML
+
+Include the VLM dataset configuration in your training YAML file (`your_train_config.yaml`).
+
+```yaml
+datasets:
+ vlm_data:
+ dataset_py: vlm_datasets
+ dataformat: llava_json
+ dataset_use: sharegpt4v_coco # Must match the name registered in 2.1
+```
+
+**Tip:** You can verify the VLM dataloader by running:
+
+```bash
+python starVLA/dataloader/vlm_datasets.py --config_yaml your_train_config.yaml
+```
+
+
+-----
+
+### 🚀 3. Training Execution
+
+Choose the appropriate script based on whether you want to train *only* on VLM data or *co-train* with VLA data.
+
+#### Option A: Train with VLM Data Only
+
+Use this for VLM-specific pre-training or fine-tuning.
+
+ * **Script:** `starVLA/training/train_starvla_vlm.py`
+
+
+
+```bash
+bash examples/CoTrainVLM/train_files/run_train_starvlm.sh
+```
+
+#### Option B: Co-Train VLA with VLM Data
+
+This simultaneously trains the model on both robotics (VLA) and multi-modal (VLM) data.
+
+ * **Script:** `starVLA/training/train_starvla_cotrain.py`
+
+
+
+```bash
+bash examples/CoTrainVLM/train_files/run_libero_cotrain.sh
+```
+
diff --git a/examples/CoTrainVLM/train_files/run_libero_cotrain.sh b/examples/CoTrainVLM/train_files/run_libero_cotrain.sh
new file mode 100644
index 0000000000000000000000000000000000000000..55fd4fe42011b19bcc1c12c77ecd4a135be04691
--- /dev/null
+++ b/examples/CoTrainVLM/train_files/run_libero_cotrain.sh
@@ -0,0 +1,76 @@
+
+
+export NCCL_SOCKET_IFNAME=bond0
+export NCCL_IB_HCA=mlx5_2,mlx5_3
+
+# used for check save when communication
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000 # timeout set to 1 hour (unit: seconds)
+
+###########################################################################################
+# === Please modify the following paths according to your environment ===
+Framework_name=QwenFast
+freeze_module_list=''
+base_vlm=playground/Pretrained_models/Qwen3-VL-4B-Instruct-Action
+config_yaml=./examples/LIBERO/train_files/starvla_cotrain_libero.yaml
+libero_data_root=playground/Datasets/LEROBOT_LIBERO_DATA
+data_mix=libero_all
+run_root_dir=./results/Checkpoints
+run_id=1207_libero4in1_qwen3fast_cotrain
+# === End of environment variable configuration ===
+###########################################################################################
+
+
+# export WANDB_MODE=disabled
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p ${output_dir}
+# mv this script to the output dir
+cp $0 ${output_dir}/
+
+
+accelerate launch \
+ --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \
+ --num_processes 8 \
+ starVLA/training/train_starvla_cotrain.py \
+ --config_yaml ${config_yaml} \
+ --framework.name ${Framework_name} \
+ --framework.qwenvl.base_vlm ${base_vlm} \
+ --datasets.vla_data.data_root_dir ${libero_data_root}\
+ --datasets.vla_data.data_mix ${data_mix} \
+ --datasets.vla_data.per_device_batch_size 2 \
+ --datasets.vlm_data.per_device_batch_size 2 \
+ --trainer.vla_data.video_backend torchvision_av \
+ --trainer.freeze_modules ${freeze_module_list} \
+ --trainer.max_train_steps 100000 \
+ --trainer.save_interval 10000 \
+ --trainer.logging_frequency 10 \
+ --trainer.eval_interval 1000 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project starVLA_Cotrain \
+ --wandb_entity jinhuiye \
+ # --is_debug True
+
+
+
+##### Multi-Server Multi-GPU training script #####
+ # accelerate launch \
+ # --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \
+ # --main_process_ip $MASTER_ADDR \
+ # --main_process_port $MASTER_PORT \
+ # --machine_rank $SLURM_PROCID \
+ # --num_machines $SLURM_NNODES \
+ # --num_processes=${TOTAL_GPUS} \
+ # starVLA/training/train_starvla.py \
+ # --config_yaml ${config_yaml} \
+ # --framework.name ${Framework_name} \
+ # --framework.qwenvl.base_vlm ${base_vlm} \
+ # --run_root_dir ${run_root_dir} \
+ # --run_id ${run_id} \
+ # --wandb_project your_project \
+ # --wandb_entity your_name
+##### Multi-Server Multi-GPU training script #####
+
+
diff --git a/examples/CoTrainVLM/train_files/run_train_starvlm.sh b/examples/CoTrainVLM/train_files/run_train_starvlm.sh
new file mode 100644
index 0000000000000000000000000000000000000000..6c45ed5012e0761be80de1511041ee719723fe81
--- /dev/null
+++ b/examples/CoTrainVLM/train_files/run_train_starvlm.sh
@@ -0,0 +1,71 @@
+
+
+export NCCL_SOCKET_IFNAME=bond0
+export NCCL_IB_HCA=mlx5_2,mlx5_3
+
+# used for check save when communication
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000 # timeout set to 1 hour (unit: seconds)
+
+###########################################################################################
+# === Please modify the following paths according to your environment ===
+Framework_name=QwenFast
+freeze_module_list=''
+base_vlm=playground/Pretrained_models/Qwen3-VL-4B-Instruct-Action
+config_yaml=./examples/LIBERO/train_files/starvla_cotrain_libero.yaml
+run_root_dir=./results/Checkpoints
+run_id=1207_libero4in1_starvlm
+vlm_data=sharegpt4v_coco
+# === End of environment variable configuration ===
+###########################################################################################
+
+
+# export WANDB_MODE=disabled
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p ${output_dir}
+# mv this script to the output dir
+cp $0 ${output_dir}/
+
+
+accelerate launch \
+ --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \
+ --num_processes 8 \
+ starVLA/training/train_starvlm.py \
+ --config_yaml ${config_yaml} \
+ --framework.name ${Framework_name} \
+ --framework.qwenvl.base_vlm ${base_vlm} \
+ --datasets.vlm_data.dataset_use ${vlm_data} \
+ --datasets.vlm_data.per_device_batch_size 2 \
+ --trainer.freeze_modules ${freeze_module_list} \
+ --trainer.max_train_steps 100000 \
+ --trainer.save_interval 10000 \
+ --trainer.logging_frequency 10 \
+ --trainer.eval_interval 1000 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project starVLA_Cotrain \
+ --wandb_entity jinhuiye \
+ # --is_debug True
+
+
+
+
+##### Multi-Server Multi-GPU training script #####
+ # accelerate launch \
+ # --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \
+ # --main_process_ip $MASTER_ADDR \
+ # --main_process_port $MASTER_PORT \
+ # --machine_rank $SLURM_PROCID \
+ # --num_machines $SLURM_NNODES \
+ # --num_processes=${TOTAL_GPUS} \
+ # starVLA/training/train_starvla.py \
+ # --config_yaml ${config_yaml} \
+ # --framework.name ${Framework_name} \
+ # --framework.qwenvl.base_vlm ${base_vlm} \
+ # --run_root_dir ${run_root_dir} \
+ # --run_id ${run_id} \
+ # --wandb_project your_project \
+ # --wandb_entity your_name
+##### Multi-Server Multi-GPU training script #####
diff --git a/examples/CoTrainVLM/train_files/starvla_cotrain_libero.yaml b/examples/CoTrainVLM/train_files/starvla_cotrain_libero.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..835c333cefdd556de4b878ab5851d6a909f9f90a
--- /dev/null
+++ b/examples/CoTrainVLM/train_files/starvla_cotrain_libero.yaml
@@ -0,0 +1,112 @@
+run_id: starvla
+run_root_dir: results/Checkpoints
+seed: 42
+trackers: [jsonl, wandb]
+wandb_entity: your_wandb_entity
+wandb_project: llavavla
+is_debug: false
+
+
+framework:
+ name: QwenGR00T
+ qwenvl:
+ base_vlm: ./playground/Pretrained_models/Qwen2.5-VL-3B-Instruct-Action
+ attn_implementation: flash_attention_2
+ vl_hidden_dim: 2048
+ dino:
+ dino_backbone: dinov2_vits14
+ action_model:
+ action_model_type: DiT-B
+ action_hidden_dim: 1024 # TODO merge with hidden_size, in config v2
+ hidden_size: 1024
+ add_pos_embed: True
+ max_seq_len: 1024
+ action_dim: 7
+ state_dim: 7
+ future_action_window_size: 7
+ action_horizon: 8 # need merge with future_action_window_size
+ past_action_window_size: 0
+ repeated_diffusion_steps: 8
+ noise_beta_alpha: 1.5
+ noise_beta_beta: 1.0
+ noise_s: 0.999
+ num_timestep_buckets: 1000
+ num_inference_timesteps: 4
+ num_target_vision_tokens: 32
+ diffusion_model_cfg: # DiT Transformers 的参数
+ cross_attention_dim: 2048 # VLM 的 dim
+ dropout: 0.2
+ final_dropout: true
+ interleave_self_attention: true
+ norm_type: "ada_norm"
+ num_layers: 16
+ output_dim: 1024
+ positional_embeddings: null
+
+ reduce_in_full_precision: true
+
+
+datasets:
+ vlm_data:
+ dataset_py: vlm_datasets
+ dataformat: llava_json
+ dataset_use: sharegpt4v_coco
+ eval_dataset: sharegpt4v_coco
+ data_flatten: false
+ base_interval: 2
+ max_pixels: 307200
+ min_pixels: 784
+ model_max_length: 2048
+ model_type: qwen2.5vl
+ per_device_batch_size: 4
+
+ vla_data:
+ dataset_py: lerobot_datasets
+ data_root_dir: playground/Datasets/LEROBOT_LIBERO_DATA
+ data_mix: libero_goal # libero_goal
+ action_type: delta_qpos
+ CoT_prompt: "Your task is {instruction}. To identify the key objects for your task. Locate their bounding boxes in [x1,y1,x2,y2] format."
+ CoT_answer: bbox
+ default_image_resolution: [3, 224, 224]
+ per_device_batch_size: 16
+ load_all_data_for_training: true
+ obs: ["image_0"]
+ video_backend: torchvision_av
+
+
+trainer:
+ epochs: 100
+ max_train_steps: 100000
+ num_warmup_steps: 5000
+ save_interval: 5000
+ eval_interval: 100
+ learning_rate:
+ base: 2.5e-05
+ qwen_vl_interface: 1.0e-05
+ action_model: 1.0e-04
+ lr_scheduler_type: cosine_with_min_lr
+ scheduler_specific_kwargs:
+ min_lr: 1.0e-06
+ freeze_modules: ''
+ loss_scale:
+ vla: 1.0
+ vlm: 0.1
+ max_grad_norm: 1.0
+ warmup_ratio: 0.1
+ weight_decay: 0.0
+ logging_frequency: 10
+ gradient_clipping: 1.0
+ gradient_accumulation_steps: 1
+
+ optimizer:
+ name: AdamW
+ betas: [0.9, 0.95]
+ eps: 1.0e-08
+ weight_decay: 1.0e-08
+
+ # parameters to be determined
+ is_resume: false
+ resume_epoch: null
+ resume_step: null
+ enable_gradient_checkpointing: true
+ enable_mixed_precision_training: true
diff --git a/examples/DreamZero/README.md b/examples/DreamZero/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..fd51be1418fcd3b3b5b1356bbd52b34175f91f13
--- /dev/null
+++ b/examples/DreamZero/README.md
@@ -0,0 +1,56 @@
+# DreamZero in starVLA
+
+`framework.name: DreamZero` now uses the official DreamZero backend from
+`https://github.com/dreamzero0/dreamzero`.
+
+It is not the local Cosmos-style latent action-frame proxy. The starVLA wrapper
+loads the official `GrootSimPolicy` / `VLA` stack and therefore uses the official
+`WANPolicyHead`, `CausalWanModel`, flow scheduler, causal video-action sampling,
+state/action tokens, and future-video prediction path.
+
+The official DreamZero Python code is vendored in this repo under
+`starVLA/external/dreamzero/groot`, so no external clone is required.
+
+Default mode: initialize DreamZero from a local Wan2.2 base model:
+
+```bash
+export DREAMZERO_INIT_MODE=wan22
+export DREAMZERO_WAN22_BASE=/mnt/workspace1/users/chidafeng/models/Wan2.2-TI2V-5B-Diffusers
+```
+
+Set `DREAMZERO_ROOT` only if you want to use another copy of the official code.
+If you already have an official DreamZero checkpoint, set
+`DREAMZERO_INIT_MODE=checkpoint` and `DREAMZERO_CKPT=/path/to/checkpoint`.
+
+Example config override:
+
+```yaml
+framework:
+ name: DreamZero
+ official:
+ init_mode: wan22
+ root: ./starVLA/external/dreamzero
+ checkpoint: null
+ wan22_base: /mnt/workspace1/users/chidafeng/models/Wan2.2-TI2V-5B-Diffusers
+ tokenizer_path: null
+ embodiment_tag: oxe_droid
+ image_height: 160
+ image_width: 320
+ frames_per_chunk: 4
+ num_video_frames: 5
+ train_architecture: lora
+ action_model:
+ action_dim: 32
+ state_dim: 64
+ future_action_window_size: 15
+ action_horizon: 16
+ past_action_window_size: 0
+ policy:
+ decode_future_images: true
+```
+
+For RoboCasa training:
+
+```bash
+bash examples/Robocasa_tabletop/train_files/run_yzh_dreamzero_policy_fm.sh 8
+```
diff --git a/examples/LIBERO/README.md b/examples/LIBERO/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..dbd1b5df97fd45a069df481832af20133da1512f
--- /dev/null
+++ b/examples/LIBERO/README.md
@@ -0,0 +1,123 @@
+# 🚀 LIBERO Evaluation
+
+This document provides instructions for reproducing our **experimental results** with LIBERO.
+The evaluation process consists of two main parts:
+
+1. Setting up the `LIBERO` environment and dependencies.
+2. Running the evaluation by launching services in both `starVLA` and `LIBERO` environments.
+
+We have verified that this workflow runs successfully on both **NVIDIA A100** and **RTX 4090** GPUs.
+
+---
+
+
+## ⬇️ 0. Download Checkpoints
+
+
+We provide a collection of pretrained checkpoints on Hugging Face to make community evaluation easier: [🤗 StarVLA/bench-libero](https://huggingface.co/collections/StarVLA/bench-libero). Their corresponding results on LIBERO are summarized in the table below.
+
+### 📊 Experimental Results
+
+| Model | Steps | Epochs | Spatial | Object | Goal | Long | Avg |
+|---------------------|-------|--------|---------|--------|------|-------|-------|
+| $\pi_0$+FAST | - | - | 96.4 | 96.8 | 88.6 | 60.2 | 85.5 |
+| OpenVLA-OFT | 175K | 223 | 97.6 | 98.4 | 97.9 | 94.5 | 97.1 |
+| $\pi_0$ | - | - | 96.8 | 98.8 | 95.8 | 85.2 | 94.1 |
+| GR00T-N1.5 | 20K | 203 | 92.0 | 92.0 | 86.0 | 76.0 | 86.5 |
+| **Qwen2.5-VL-FAST** | 30K | 9.54 | 97.3 | 97.2 | 96.1 | 90.2 | 95.2 |
+| **Qwen2.5-VL-OFT** | 30K | 9.54 | 97.4 | 98.0 | 96.8 | 92.0 | 96.1 |
+| **Qwen2.5-VL-GR00T**| 30K | 9.54 | 97.8 | 98.2 | 94.6 | 90.8 | 95.4 |
+| **Qwen3-VL-FAST** | 30K | 9.54 | 97.3 | 97.4 | 96.3 | 90.6 | 95.4 |
+| **Qwen3-VL-OFT** | 30K | 9.54 | 97.8 | 98.6 | 96.2 | 93.8 | 96.6 |
+| **Qwen3-VL-GR00T** | 30K | 9.54 | 97.8 | 98.8 | 97.4 | 92.0 | 96.5 |
+
+We train one policy for all 4 suites. All
+scores are averaged over 500 trials for each task suite (10 tasks × 50 episodes).
+
+---
+
+
+## 📦 1. Environment Setup
+
+To set up the environment, please first follow the official [LIBERO repository](https://github.com/Lifelong-Robot-Learning/LIBERO) to install the base `LIBERO` environment.
+
+⚠️ **Common issue:** LIBERO defaults to Python 3.8, but the syntax updates between 3.8 and 3.10 are substantial. **We verified that using Python 3.10 avoids many issues**.
+
+
+Afterwards, inside the `LIBERO` environment, install the following dependencies:
+
+```bash
+pip install tyro matplotlib mediapy websockets msgpack
+pip install numpy==1.24.4
+```
+
+---
+
+## 🚀 2. Evaluation Workflow
+
+The evaluation should be run **from the repository root** using **two separate terminals**, one for each environment:
+
+- **starVLA environment**: runs the inference server.
+- **LIBERO environment**: runs the simulation.
+
+### Step 1. Start the server (starVLA environment)
+
+In the first terminal, activate the `starVLA` conda environment and run:
+
+```bash
+bash examples/LIBERO/eval_files/run_policy_server.sh
+```
+
+⚠️ **Note:** Please ensure that you specify the correct checkpoint path in `examples/LIBERO/eval_files/run_policy_server.sh`
+
+
+---
+
+### Step 2. Start the simulation (LIBERO environment)
+
+In the second terminal, activate the `LIBERO` conda environment and run:
+
+```bash
+bash examples/LIBERO/eval_files/eval_libero.sh
+```
+⚠️ **Note:** Please ensure that you specify the correct checkpoint path in `eval_libero.sh` to load action unnormalization stats.
+
+Also ensure the environment variables at the top of `eval_libero.sh` are correctly set.
+
+Finally, each result will also save a video for visualization, as shown below:
+
+
+
+---
+
+
+# 🚀 LIBERO Training
+
+## 📦 Step 0: Download the training dataset
+Download the datasets to the playground/Datasets/LEROBOT_LIBERO_DATA directory:
+- [LIBERO-spatial](https://huggingface.co/datasets/IPEC-COMMUNITY/libero_spatial_no_noops_1.0.0_lerobot)
+- [LIBERO-object](https://huggingface.co/datasets/IPEC-COMMUNITY/libero_object_no_noops_1.0.0_lerobot)
+- [LIBERO-goal](https://huggingface.co/datasets/IPEC-COMMUNITY/libero_goal_no_noops_1.0.0_lerobot)
+- [LIBERO-10](https://huggingface.co/datasets/IPEC-COMMUNITY/libero_10_no_noops_1.0.0_lerobot)
+
+And move `modality.json` to each `$LEROBOT_LIBERO_DATA/subset/meta/modality.json`.
+
+You could quickly prepare these by running:
+```bash
+# Set DEST to the directory where you want to store the data
+export DEST=/path/to/your/data/directory
+bash examples/LIBERO/data_preparation.sh
+```
+
+
+## 🚀 Step1: Start Training
+
+Most of the required training files have been organized in [train_files](train_files).
+
+Please run the following command to start training:
+
+```bash
+bash examples/LIBERO/train_files/run_libero_train.sh
+```
+⚠️ **Note:** Please ensure that you specify the correct path in `examples/LIBERO/train_files/run_libero_train.sh`
+
diff --git a/examples/LIBERO/data_preparation.sh b/examples/LIBERO/data_preparation.sh
new file mode 100644
index 0000000000000000000000000000000000000000..076a1f9a217feb08a84d49ee0c411b99c5cb8be6
--- /dev/null
+++ b/examples/LIBERO/data_preparation.sh
@@ -0,0 +1,42 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+# Usage:
+# export DEST=/path/to/dir && bash examples/LIBERO/data_preparation.sh
+# or
+# bash examples/LIBERO/data_preparation.sh /path/to/dir
+
+DEST="${DEST:-${1:-}}"
+if [[ -z "${DEST}" ]]; then
+ echo "ERROR: DEST is not set."
+ echo " export DEST=/path/to/dir && bash examples/LIBERO/data_preparation.sh"
+ echo " or: bash examples/LIBERO/data_preparation.sh /path/to/dir"
+ exit 1
+fi
+
+CUR="$(pwd)"
+mkdir -p "$DEST"
+
+python -m pip install -U "huggingface-hub==0.35.3"
+
+for repo in \
+ IPEC-COMMUNITY/libero_spatial_no_noops_1.0.0_lerobot \
+ IPEC-COMMUNITY/libero_object_no_noops_1.0.0_lerobot \
+ IPEC-COMMUNITY/libero_goal_no_noops_1.0.0_lerobot \
+ IPEC-COMMUNITY/libero_10_no_noops_1.0.0_lerobot
+do
+ hf download "$repo" --repo-type dataset --local-dir "$DEST/libero/${repo##*/}"
+done
+
+hf download "StarVLA/LLaVA-OneVision-COCO" --repo-type dataset --local-dir "$DEST/LLaVA-OneVision-COCO"
+unzip -- "$DEST/LLaVA-OneVision-COCO/sharegpt4v_coco.zip" -d "$DEST/LLaVA-OneVision-COCO/"
+
+mkdir -p "$CUR/playground/Datasets"
+ln -s "$DEST/libero" "$CUR/playground/Datasets/LEROBOT_LIBERO_DATA"
+ln -s "$DEST/LLaVA-OneVision-COCO" "$CUR/playground/Datasets/LLaVA-OneVision-COCO"
+
+## move modality
+cp "$CUR/examples/LIBERO/train_files/modality.json" "$CUR/playground/Datasets/LEROBOT_LIBERO_DATA/libero_10_no_noops_1.0.0_lerobot/meta"
+cp "$CUR/examples/LIBERO/train_files/modality.json" "$CUR/playground/Datasets/LEROBOT_LIBERO_DATA/libero_goal_no_noops_1.0.0_lerobot/meta"
+cp "$CUR/examples/LIBERO/train_files/modality.json" "$CUR/playground/Datasets/LEROBOT_LIBERO_DATA/libero_object_no_noops_1.0.0_lerobot/meta"
+cp "$CUR/examples/LIBERO/train_files/modality.json" "$CUR/playground/Datasets/LEROBOT_LIBERO_DATA/libero_spatial_no_noops_1.0.0_lerobot/meta"
diff --git a/examples/LIBERO/eval_files/auto_eval_scripts/REAMDE.md b/examples/LIBERO/eval_files/auto_eval_scripts/REAMDE.md
new file mode 100644
index 0000000000000000000000000000000000000000..48b1952d12275106e509442490c2a4a67168a12a
--- /dev/null
+++ b/examples/LIBERO/eval_files/auto_eval_scripts/REAMDE.md
@@ -0,0 +1,7 @@
+# Auto Evaluation Scripts
+
+This folder contains the scripts we use internally to run quick evaluations across every task.
+A fully automated run depends on our in-house platform setup, so the scripts may not work unchanged on your own infrastructure.
+Please treat them as references and consult `run_policy_server.sh` and `start_simpler_env.sh` for the underlying workflow.
+
+
diff --git a/examples/LIBERO/eval_files/auto_eval_scripts/auto_eval_libero.sh b/examples/LIBERO/eval_files/auto_eval_scripts/auto_eval_libero.sh
new file mode 100644
index 0000000000000000000000000000000000000000..accd4567abce5054baa7aab2c351ab8c28504809
--- /dev/null
+++ b/examples/LIBERO/eval_files/auto_eval_scripts/auto_eval_libero.sh
@@ -0,0 +1,32 @@
+#!/bin/bash
+
+cd /mnt/petrelfs/yejinhui/Projects/starVLA
+SCRIPT_PATH="./examples/LIBERO/eval_files/auto_eval_scripts/eval_libero_parall.sh"
+your_ckpt=/mnt/petrelfs/yejinhui/Projects/starVLA/results/Checkpoints/1226_libero4in1_qwen3oft/checkpoints/steps_50000_pytorch_model.pt
+run_index_base=346
+
+#####################################################
+task_suite_name=libero_10 # align with your model
+run_index=$((run_index_base + 0))
+bash $SCRIPT_PATH $your_ckpt $task_suite_name $run_index &
+#####################################################
+
+sleep 15
+#####################################################
+task_suite_name=libero_goal # align with your model
+run_index=$((run_index_base + 1))
+bash $SCRIPT_PATH $your_ckpt $task_suite_name $run_index &
+#####################################################
+sleep 15
+#####################################################
+task_suite_name=libero_object # align with your model
+run_index=$((run_index_base + 2))
+bash $SCRIPT_PATH $your_ckpt $task_suite_name $run_index &
+#####################################################
+sleep 15
+####################################################
+task_suite_name=libero_spatial # align with your model
+run_index=$((run_index_base + 3))
+bash $SCRIPT_PATH $your_ckpt $task_suite_name $run_index &
+#####################################################
+
diff --git a/examples/LIBERO/eval_files/auto_eval_scripts/eval_libero_parall.sh b/examples/LIBERO/eval_files/auto_eval_scripts/eval_libero_parall.sh
new file mode 100644
index 0000000000000000000000000000000000000000..d9d9c444832ea5d23c6dc8f4110db9799caf883a
--- /dev/null
+++ b/examples/LIBERO/eval_files/auto_eval_scripts/eval_libero_parall.sh
@@ -0,0 +1,72 @@
+###########################################################################################
+# === Please modify the following paths according to your environment ===
+export LIBERO_HOME=/mnt/petrelfs/share/yejinhui/Projects/LIBERO # Root directory of the LIBERO project
+export LIBERO_python=/mnt/petrelfs/share/yejinhui/Envs/miniconda3/envs/lerobot/bin/python # Path to the Python environment
+export starVLA_python=/mnt/petrelfs/share/yejinhui/Envs/miniconda3/envs/starVLA/bin/python # Path to the Python environment
+
+# === End of environment variable configuration ===
+export LIBERO_CONFIG_PATH=${LIBERO_HOME}/libero # Path to LIBERO configuration files
+export PYTHONPATH=$PYTHONPATH:${LIBERO_HOME} # let eval_libero find the LIBERO tools
+export PYTHONPATH=$(pwd):${PYTHONPATH} # let LIBERO find the websocket tools from starVLA repo
+###########################################################################################
+
+
+
+##### === variables for which evaluation to setup ===
+your_ckpt=$1 # results/Checkpoints/1025_libero_all_qwengroot/checkpoints/steps_20000_pytorch_model.pt
+task_suite_name=$2 # align with your model | libero_goal
+run_index=$3
+# your_ckpt=results/Checkpoints/1025_libero_10_qwengroot/checkpoints/steps_10000_pytorch_model.pt
+# task_suite_name=libero_10
+# run_index=8
+##### === variables for which evaluation to setup ===
+
+num_gpus=8
+gpu_id=$((run_index % num_gpus))
+
+num_trials_per_task=50
+host="127.0.0.1"
+base_port=$((6450 + run_index))
+unnorm_key="franka"
+
+CUDA_VISIBLE_DEVICES=$gpu_id ${starVLA_python} deployment/model_server/server_policy.py \
+ --ckpt_path ${your_ckpt} \
+ --port ${base_port} \
+ --use_bf16 &
+
+
+# 获取服务的 PID
+server_pid=$!
+
+
+# Extract model_root from your_ckpt
+model_root=$(echo "$your_ckpt" | awk -F'/checkpoints/' '{print $1}')
+folder_name=$(echo "$your_ckpt" | awk -F'/' '{print $(NF-2)"_"$(NF-1)"_"$NF}')
+
+video_out_path="${model_root}/videos/${task_suite_name}/${folder_name}"
+log_path="${model_root}/logs/${task_suite_name}"
+mkdir -p "$video_out_path"
+mkdir -p "$log_path"
+
+
+
+${LIBERO_python} ./examples/LIBERO/eval_files/eval_libero.py \
+ --args.pretrained-path ${your_ckpt} \
+ --args.host "$host" \
+ --args.port $base_port \
+ --args.task-suite-name "$task_suite_name" \
+ --args.num-trials-per-task "$num_trials_per_task" \
+ --args.video-out-path "$video_out_path" \
+ 2>&1 | tee ${log_path}/${folder_name}.log
+
+echo "Evaluation completed. Videos saved to ${video_out_path}, logs saved to ${log_path}/${folder_name}.log"
+
+
+
+
+if [ -n "$server_pid" ]; then
+ echo "Killing server process with PID: $server_pid"
+ kill $server_pid
+else
+ echo "No server process found to kill."
+fi
\ No newline at end of file
diff --git a/examples/LIBERO/eval_files/auto_eval_scripts/readme.md b/examples/LIBERO/eval_files/auto_eval_scripts/readme.md
new file mode 100644
index 0000000000000000000000000000000000000000..caf2bf073181891fa353cfb6bde0ee0477b46ee4
--- /dev/null
+++ b/examples/LIBERO/eval_files/auto_eval_scripts/readme.md
@@ -0,0 +1,5 @@
+
+# 这里包含了我们自己内部使用的 全部标本, 它们用于先快速的评测 全部task。
+# 全自动评测 会和使用的平台有些绑定,使用我们无法确定是否在用户自己的平台依然有效,
+# 我们发出来只是提供更多的参考, 具体原理还是参考 `examples/LIBERO/README.md`
+
diff --git a/examples/LIBERO/eval_files/auto_eval_scripts/see_sr_auto.sh b/examples/LIBERO/eval_files/auto_eval_scripts/see_sr_auto.sh
new file mode 100644
index 0000000000000000000000000000000000000000..4d760f177312304ef524f3a59bbb1d7914efd76e
--- /dev/null
+++ b/examples/LIBERO/eval_files/auto_eval_scripts/see_sr_auto.sh
@@ -0,0 +1,19 @@
+#!/bin/bash
+
+# 指定日志文件的根目录
+log_dir="results/Checkpoints/1226_libero4in1_qwen3oft"
+
+# 遍历指定目录下的所有日志文件
+last_Folder=""
+find "$log_dir" -type f -name "*.log" | while read -r log_file; do
+ # 提取日志文件中最后一个 "Total success rate" 的值
+ success_rate=$(grep "INFO | >> Total success rate:" "$log_file" | tail -n 1)
+
+ # 如果找到匹配的内容,则输出日志文件路径和对应的成功率
+ if [ -n "$success_rate" ]; then
+ echo "Folder: $(basename "$(dirname "$log_file")")"
+ echo "File: $(basename "$log_file")"
+ echo "$success_rate"
+ echo
+ fi
+done
\ No newline at end of file
diff --git a/examples/LIBERO/eval_files/eval_libero.py b/examples/LIBERO/eval_files/eval_libero.py
new file mode 100644
index 0000000000000000000000000000000000000000..23d6c29bffba5b11a612d5b3a3f4424988226ee4
--- /dev/null
+++ b/examples/LIBERO/eval_files/eval_libero.py
@@ -0,0 +1,299 @@
+import dataclasses
+import datetime as dt
+import json
+import logging
+import math
+import os
+import pathlib
+from pathlib import Path
+import requests
+import time
+
+import imageio
+import numpy as np
+import tqdm
+import tyro
+from libero.libero import benchmark, get_libero_path
+from libero.libero.envs import OffScreenRenderEnv
+os.environ["TOKENIZERS_PARALLELISM"] = "false"
+from examples.LIBERO.eval_files.model2libero_interface import ModelClient
+
+
+LIBERO_DUMMY_ACTION = [0.0] * 6 + [-1.0]
+LIBERO_ENV_RESOLUTION = 256 # resolution used to render training data
+def _binarize_gripper_open(open_val: np.ndarray | float) -> np.ndarray:
+ arr = np.asarray(open_val, dtype=np.float32).reshape(-1)
+ v = float(arr[0])
+ bin_val = 1.0 - 2.0 * (v > 0.5)
+ return np.asarray([bin_val], dtype=np.float32)
+
+
+@dataclasses.dataclass
+class Args:
+ host: str = "127.0.0.1"
+ port: int = 10093
+ resize_size = [224,224]
+
+ #################################################################################################################
+ # LIBERO environment-specific parameters
+ #################################################################################################################
+ task_suite_name: str = "libero_goal" # Task suite. Options: libero_spatial, libero_object, libero_goal, libero_10, libero_90
+ num_steps_wait: int = 10 # Number of steps to wait for objects to stabilize i n sim
+ num_trials_per_task: int = 50 # Number of rollouts per task
+
+ #################################################################################################################
+ # Utils
+ #################################################################################################################
+ video_out_path: str = "experiments/libero/logs" # Path to save videos
+
+ seed: int = 7 # Random Seed (for reproducibility)
+
+ pretrained_path: str = ""
+
+ post_process_action: bool = True
+
+ job_name: str = "test"
+
+
+def eval_libero(args: Args) -> None:
+ logging.info(f"Arguments: {json.dumps(dataclasses.asdict(args), indent=4)}")
+
+ # Set random seed
+ np.random.seed(args.seed)
+
+ # Initialize LIBERO task suite
+ benchmark_dict = benchmark.get_benchmark_dict()
+ task_suite = benchmark_dict[args.task_suite_name]()
+ num_tasks_in_suite = task_suite.n_tasks
+ logging.info(f"Task suite: {args.task_suite_name}")
+
+ # args.video_out_path = f"{date_base}+{args.job_name}"
+
+ pathlib.Path(args.video_out_path).mkdir(parents=True, exist_ok=True)
+
+ if args.task_suite_name == "libero_spatial":
+ max_steps = 220 # longest training demo has 193 steps
+ elif args.task_suite_name == "libero_object":
+ max_steps = 280 # longest training demo has 254 steps
+ elif args.task_suite_name == "libero_goal":
+ max_steps = 300 # longest training demo has 270 steps
+ elif args.task_suite_name == "libero_10":
+ max_steps = 520 # longest training demo has 505 steps
+ elif args.task_suite_name == "libero_90":
+ max_steps = 400 # longest training demo has 373 steps
+ else:
+ raise ValueError(f"Unknown task suite: {args.task_suite_name}")
+
+ client_model = ModelClient(
+ policy_ckpt_path=args.pretrained_path, # to get unnormalization stats
+ host=args.host,
+ port=args.port,
+ image_size=args.resize_size,
+ )
+
+
+ # Start evaluation
+ total_episodes, total_successes = 0, 0
+ for task_id in tqdm.tqdm(range(num_tasks_in_suite)):
+ # Get task
+ task = task_suite.get_task(task_id)
+
+ # Get default LIBERO initial states
+ initial_states = task_suite.get_task_init_states(task_id)
+
+ # Initialize LIBERO environment and task description
+ env, task_description = _get_libero_env(task, LIBERO_ENV_RESOLUTION, args.seed)
+
+ # Start episodes
+ task_episodes, task_successes = 0, 0
+ for episode_idx in tqdm.tqdm(range(args.num_trials_per_task)):
+ logging.info(f"\nTask: {task_description}")
+
+ # Reset environment
+ client_model.reset(task_description=task_description) # Reset the client connection
+ env.reset()
+
+ # Set initial states
+ obs = env.set_init_state(initial_states[episode_idx])
+
+ # Setup
+ t = 0
+ replay_images = []
+ full_actions = []
+
+ logging.info(f"Starting episode {task_episodes + 1}...")
+ step = 0
+
+ # full_actions = np.load("./debug/action.npy")
+
+ while t < max_steps + args.num_steps_wait:
+ # try:
+ # IMPORTANT: Do nothing for the first few timesteps because the simulator drops objects
+ # and we need to wait for them to fall
+ if t < args.num_steps_wait:
+ obs, reward, done, info = env.step(LIBERO_DUMMY_ACTION)
+ t += 1
+ continue
+
+ # IMPORTANT: rotate 180 degrees to match train preprocessing
+ img = np.ascontiguousarray(obs["agentview_image"][::-1, ::-1])
+ wrist_img = np.ascontiguousarray(
+ obs["robot0_eye_in_hand_image"][::-1, ::-1]
+ )
+
+ # Save preprocessed image for replay video
+ replay_images.append(img)
+
+ state = np.concatenate(
+ (
+ obs["robot0_eef_pos"],
+ _quat2axisangle(obs["robot0_eef_quat"]),
+ obs["robot0_gripper_qpos"],
+ )
+ )
+
+ observation = { #
+ "observation.primary": np.expand_dims(
+ img, axis=0
+ ), # (H, W, C), dtype=unit8, range(0-255)
+ "observation.wrist_image": np.expand_dims(
+ wrist_img, axis=0
+ ), # (H, W, C)
+ "observation.state": np.expand_dims(state, axis=0),
+ "instruction": [str(task_description)],
+ }
+
+ # align key with model API --> 这里给了两个图像 --> check training
+ example_dict = {
+ "image": [observation["observation.primary"][0], observation["observation.wrist_image"][0]],
+ "lang": observation["instruction"][0],
+ }
+
+
+ start_time = time.time()
+
+ response = client_model.step(example=example_dict, step=step)
+
+ end_time = time.time()
+ # print(f"time: {end_time - start_time}")
+
+ # #
+ raw_action = response["raw_action"]
+
+ world_vector_delta = np.asarray(raw_action.get("world_vector"), dtype=np.float32).reshape(-1)
+ rotation_delta = np.asarray(raw_action.get("rotation_delta"), dtype=np.float32).reshape(-1)
+ open_gripper = np.asarray(raw_action.get("open_gripper"), dtype=np.float32).reshape(-1)
+ gripper = _binarize_gripper_open(open_gripper)
+
+ if not (world_vector_delta.size == 3 and rotation_delta.size == 3 and open_gripper.size == 1):
+ logging.warning(f"Unexpected action sizes: "
+ f"wv={world_vector_delta.shape}, rot={rotation_delta.shape}, grip={gripper.shape}. "
+ f"Falling back to LIBERO_DUMMY_ACTION.")
+ raise ValueError(
+ f"Invalid action sizes: world_vector={world_vector_delta.shape}, "
+ f"rotation_delta={rotation_delta.shape}, gripper={gripper.shape}"
+ )
+ else:
+ delta_action = np.concatenate([world_vector_delta, rotation_delta, gripper], axis=0)
+
+ full_actions.append(delta_action)
+
+ # __import__("ipdb").set_trace()
+ # see ../robosuite/controllers/controller_factory.py
+ obs, reward, done, info = env.step(delta_action.tolist())
+ if done:
+ task_successes += 1
+ total_successes += 1
+ break
+ t += 1
+ step += 1
+
+ task_episodes += 1
+ total_episodes += 1
+
+ # Save a replay video of the episode
+ suffix = "success" if done else "failure"
+ task_segment = task_description.replace(" ", "_")
+ imageio.mimwrite(
+ pathlib.Path(args.video_out_path)
+ / f"rollout_{task_segment}_episode{episode_idx}_{suffix}.mp4",
+ [np.asarray(x) for x in replay_images],
+ fps=10,
+ )
+
+ full_actions = np.stack(full_actions)
+ # np.save(pathlib.Path(args.video_out_path) / f"rollout_{task_segment}_episode{episode_idx}_{suffix}.npy", full_actions)
+
+ # print(pathlib.Path(args.video_out_path) / f"rollout_{task_segment}_episode{episode_idx}_{suffix}.mp4")
+ # Log current results
+ logging.info(f"Success: {done}")
+ logging.info(f"# episodes completed so far: {total_episodes}")
+ logging.info(
+ f"# successes: {total_successes} ({total_successes / total_episodes * 100:.1f}%)"
+ )
+
+ # Log final results
+ logging.info(
+ f"Current task success rate: {float(task_successes) / float(task_episodes)}"
+ )
+ logging.info(
+ f"Current total success rate: {float(total_successes) / float(total_episodes)}"
+ )
+
+ logging.info(
+ f"Total success rate: {float(total_successes) / float(total_episodes)}"
+ )
+ logging.info(f"Total episodes: {total_episodes}")
+
+
+def _get_libero_env(task, resolution, seed):
+ """Initializes and returns the LIBERO environment, along with the task description."""
+ task_description = task.language
+ task_bddl_file = (
+ pathlib.Path(get_libero_path("bddl_files"))
+ / task.problem_folder
+ / task.bddl_file
+ )
+ env_args = {
+ "bddl_file_name": task_bddl_file,
+ "camera_heights": resolution,
+ "camera_widths": resolution,
+ }
+ env = OffScreenRenderEnv(**env_args)
+ env.seed(
+ seed
+ ) # IMPORTANT: seed seems to affect object positions even when using fixed initial state
+ return env, task_description
+
+
+def _quat2axisangle(quat):
+ """
+ Copied from robosuite: https://github.com/ARISE-Initiative/robosuite/blob/eafb81f54ffc104f905ee48a16bb15f059176ad3/robosuite/utils/transform_utils.py#L490C1-L512C55
+ """
+ # clip quaternion
+ if quat[3] > 1.0:
+ quat[3] = 1.0
+ elif quat[3] < -1.0:
+ quat[3] = -1.0
+
+ den = np.sqrt(1.0 - quat[3] * quat[3])
+ if math.isclose(den, 0.0):
+ # This is (close to) a zero degree rotation, immediately return
+ return np.zeros(3)
+
+ return (quat[:3] * 2.0 * math.acos(quat[3])) / den
+
+
+def start_debugpy_once():
+ import debugpy
+ if getattr(start_debugpy_once, "_started", False):
+ return
+ debugpy.listen(("0.0.0.0", 10092))
+ print("🔍 Waiting for VSCode attach on 0.0.0.0:10092 ...")
+ debugpy.wait_for_client()
+ start_debugpy_once._started = True
+
+if __name__ == "__main__":
+ if os.getenv("DEBUG", False):
+ start_debugpy_once()
+ tyro.cli(eval_libero)
\ No newline at end of file
diff --git a/examples/LIBERO/eval_files/eval_libero.sh b/examples/LIBERO/eval_files/eval_libero.sh
new file mode 100644
index 0000000000000000000000000000000000000000..5cda5113fac708a1888456bc1548734940c1adc6
--- /dev/null
+++ b/examples/LIBERO/eval_files/eval_libero.sh
@@ -0,0 +1,41 @@
+#!/bin/bash
+
+cd /mnt/petrelfs/yejinhui/Projects/starVLA
+conda activate starVLA
+
+###########################################################################################
+# === Please modify the following paths according to your environment ===
+export LIBERO_HOME=/mnt/petrelfs/share/yejinhui/Projects/LIBERO
+export LIBERO_CONFIG_PATH=${LIBERO_HOME}/libero
+export LIBERO_Python=/mnt/petrelfs/share/yejinhui/Envs/miniconda3/envs/lerobot/bin/python
+
+export PYTHONPATH=$PYTHONPATH:${LIBERO_HOME} # let eval_libero find the LIBERO tools
+export PYTHONPATH=$(pwd):${PYTHONPATH} # let LIBERO find the websocket tools from main repo
+
+
+host="127.0.0.1"
+base_port=5694
+unnorm_key="franka"
+your_ckpt=./results/Checkpoints/1208_libero_all_QwenPI_qwen3/checkpoints/steps_50000_pytorch_model.pt
+export DEBUG=true
+
+folder_name=$(echo "$your_ckpt" | awk -F'/' '{print $(NF-2)"_"$(NF-1)"_"$NF}')
+# === End of environment variable configuration ===
+###########################################################################################
+
+LOG_DIR="logs/$(date +"%Y%m%d_%H%M%S")"
+mkdir -p ${LOG_DIR}
+
+
+task_suite_name=libero_goal
+num_trials_per_task=50
+video_out_path="results/${task_suite_name}/${folder_name}"
+
+
+${LIBERO_Python} ./examples/LIBERO/eval_files/eval_libero.py \
+ --args.pretrained-path ${your_ckpt} \
+ --args.host "$host" \
+ --args.port $base_port \
+ --args.task-suite-name "$task_suite_name" \
+ --args.num-trials-per-task "$num_trials_per_task" \
+ --args.video-out-path "$video_out_path"
diff --git a/examples/LIBERO/eval_files/model2libero_interface.py b/examples/LIBERO/eval_files/model2libero_interface.py
new file mode 100644
index 0000000000000000000000000000000000000000..14c6b13b7ca39fb2c6810d8e28b6a5684236e604
--- /dev/null
+++ b/examples/LIBERO/eval_files/model2libero_interface.py
@@ -0,0 +1,221 @@
+from collections import deque
+from typing import Optional, Sequence
+import os
+import cv2 as cv
+import matplotlib.pyplot as plt
+import numpy as np
+
+from deployment.model_server.tools.websocket_policy_client import WebsocketClientPolicy
+
+from examples.SimplerEnv.eval_files.adaptive_ensemble import AdaptiveEnsembler
+from typing import Dict
+import numpy as np
+from pathlib import Path
+from PIL import Image
+
+from starVLA.model.tools import read_mode_config
+
+
+class ModelClient:
+ def __init__(
+ self,
+ policy_ckpt_path,
+ unnorm_key: Optional[str] = None,
+ policy_setup: str = "franka",
+ horizon: int = 0,
+ action_ensemble = True,
+ action_ensemble_horizon: Optional[int] = 3, # different cross sim
+ image_size: list[int] = [224, 224],
+ use_ddim: bool = True,
+ num_ddim_steps: int = 10,
+ adaptive_ensemble_alpha = 0.1,
+ host="0.0.0.0",
+ port=10095,
+ ) -> None:
+
+ # build client to connect server policy
+ self.client = WebsocketClientPolicy(host, port)
+ self.policy_setup = policy_setup
+ self.unnorm_key = unnorm_key
+
+ print(f"*** policy_setup: {policy_setup}, unnorm_key: {unnorm_key} ***")
+ self.use_ddim = use_ddim
+ self.num_ddim_steps = num_ddim_steps
+ self.image_size = image_size
+ self.horizon = horizon #0
+ self.action_ensemble = action_ensemble
+ self.adaptive_ensemble_alpha = adaptive_ensemble_alpha
+ self.action_ensemble_horizon = action_ensemble_horizon
+ self.sticky_action_is_on = False
+ self.gripper_action_repeat = 0
+ self.sticky_gripper_action = 0.0
+ self.previous_gripper_action = None
+
+ self.task_description = None
+ self.image_history = deque(maxlen=self.horizon)
+ if self.action_ensemble:
+ self.action_ensembler = AdaptiveEnsembler(self.action_ensemble_horizon, self.adaptive_ensemble_alpha)
+ else:
+ self.action_ensembler = None
+ self.num_image_history = 0
+
+ self.action_norm_stats = self.get_action_stats(self.unnorm_key, policy_ckpt_path=policy_ckpt_path)
+ self.action_chunk_size = self.get_action_chunk_size(policy_ckpt_path=policy_ckpt_path)
+
+
+ def _add_image_to_history(self, image: np.ndarray) -> None:
+ self.image_history.append(image)
+ self.num_image_history = min(self.num_image_history + 1, self.horizon)
+
+ def reset(self, task_description: str) -> None:
+ self.task_description = task_description
+ self.image_history.clear()
+ if self.action_ensemble:
+ self.action_ensembler.reset()
+ self.num_image_history = 0
+
+ self.sticky_action_is_on = False
+ self.gripper_action_repeat = 0
+ self.sticky_gripper_action = 0.0
+ self.previous_gripper_action = None
+
+
+ def step(
+ self,
+ example: dict,
+ step: int = 0,
+ **kwargs
+ ) -> tuple[dict[str, np.ndarray], dict[str, np.ndarray]]:
+ """
+ Perform one step of inference
+ :param image: Input image in the format (H, W, 3), type uint8
+ :param task_description: Task description text
+ :return: (raw action, processed action)
+ """
+
+ task_description = example.get("lang", None)
+ images = example["image"] # list of images for history
+
+ if example is not None:
+ if task_description != self.task_description:
+ self.reset(task_description)
+
+ images = [self._resize_image(image) for image in images]
+ example["image"] = images
+ vla_input = {
+ "examples": [example],
+ "do_sample": False,
+ "use_ddim": self.use_ddim,
+ "num_ddim_steps": self.num_ddim_steps,
+ }
+
+
+ action_chunk_size = self.action_chunk_size
+ if step % action_chunk_size == 0:
+ response = self.client.predict_action(vla_input)
+ try:
+ normalized_actions = response["data"]["normalized_actions"] # B, chunk, D
+ except KeyError:
+ print(f"Response data: {response}")
+ raise KeyError(f"Key 'normalized_actions' not found in response data: {response['data'].keys()}")
+
+ normalized_actions = normalized_actions[0]
+ self.raw_actions = self.unnormalize_actions(normalized_actions=normalized_actions, action_norm_stats=self.action_norm_stats)
+
+ raw_actions = self.raw_actions[step % action_chunk_size][None]
+
+ raw_action = {
+ "world_vector": np.array(raw_actions[0, :3]),
+ "rotation_delta": np.array(raw_actions[0, 3:6]),
+ "open_gripper": np.array(raw_actions[0, 6:7]), # range [0, 1]; 1 = open; 0 = close
+ }
+
+ return {"raw_action": raw_action}
+
+ @staticmethod
+ def unnormalize_actions(normalized_actions: np.ndarray, action_norm_stats: Dict[str, np.ndarray]) -> np.ndarray:
+ mask = action_norm_stats.get("mask", np.ones_like(action_norm_stats["min"], dtype=bool))
+ action_high, action_low = np.array(action_norm_stats["max"]), np.array(action_norm_stats["min"])
+ normalized_actions = np.clip(normalized_actions, -1, 1)
+ normalized_actions[:, 6] = np.where(normalized_actions[:, 6] < 0.5, 0, 1)
+ actions = np.where(
+ mask,
+ 0.5 * (normalized_actions + 1) * (action_high - action_low) + action_low,
+ normalized_actions,
+ )
+
+ return actions
+
+ @staticmethod
+ def get_action_stats(unnorm_key: str, policy_ckpt_path) -> dict:
+ """
+ Duplicate stats accessor (retained for backward compatibility).
+ """
+ policy_ckpt_path = Path(policy_ckpt_path)
+ model_config, norm_stats = read_mode_config(policy_ckpt_path) # read config and norm_stats
+
+ unnorm_key = ModelClient._check_unnorm_key(norm_stats, unnorm_key)
+ return norm_stats[unnorm_key]["action"]
+
+ @staticmethod
+ def get_action_chunk_size(policy_ckpt_path):
+ model_config, _ = read_mode_config(policy_ckpt_path) # read config and norm_stats
+ # import ipdb; ipdb.set_trace()
+ return model_config['framework']['action_model']['future_action_window_size'] + 1
+
+
+ def _resize_image(self, image: np.ndarray) -> np.ndarray:
+ image = cv.resize(image, tuple(self.image_size), interpolation=cv.INTER_AREA)
+ return image
+
+ def visualize_epoch(
+ self, predicted_raw_actions: Sequence[np.ndarray], images: Sequence[np.ndarray], save_path: str
+ ) -> None:
+ images = [self._resize_image(image) for image in images]
+ ACTION_DIM_LABELS = ["x", "y", "z", "roll", "pitch", "yaw", "grasp"]
+
+ img_strip = np.concatenate(np.array(images[::3]), axis=1)
+
+ # set up plt figure
+ figure_layout = [["image"] * len(ACTION_DIM_LABELS), ACTION_DIM_LABELS]
+ plt.rcParams.update({"font.size": 12})
+ fig, axs = plt.subplot_mosaic(figure_layout)
+ fig.set_size_inches([45, 10])
+
+ # plot actions
+ pred_actions = np.array(
+ [
+ np.concatenate([a["world_vector"], a["rotation_delta"], a["open_gripper"]], axis=-1)
+ for a in predicted_raw_actions
+ ]
+ )
+ for action_dim, action_label in enumerate(ACTION_DIM_LABELS):
+ # actions have batch, horizon, dim, in this example we just take the first action for simplicity
+ axs[action_label].plot(pred_actions[:, action_dim], label="predicted action")
+ axs[action_label].set_title(action_label)
+ axs[action_label].set_xlabel("Time in one episode")
+
+ axs["image"].imshow(img_strip)
+ axs["image"].set_xlabel("Time in one episode (subsampled)")
+ plt.legend()
+ plt.savefig(save_path)
+
+ @staticmethod
+ def _check_unnorm_key(norm_stats, unnorm_key):
+ """
+ Duplicate helper (retained for backward compatibility).
+ See primary _check_unnorm_key above.
+ """
+ if unnorm_key is None:
+ assert len(norm_stats) == 1, (
+ f"Your model was trained on more than one dataset, "
+ f"please pass a `unnorm_key` from the following options to choose the statistics "
+ f"used for un-normalizing actions: {norm_stats.keys()}"
+ )
+ unnorm_key = next(iter(norm_stats.keys()))
+
+ assert unnorm_key in norm_stats, (
+ f"The `unnorm_key` you chose is not in the set of available dataset statistics, "
+ f"please choose from: {norm_stats.keys()}"
+ )
+ return unnorm_key
diff --git a/examples/LIBERO/eval_files/run_policy_server.sh b/examples/LIBERO/eval_files/run_policy_server.sh
new file mode 100644
index 0000000000000000000000000000000000000000..27f766531929608cf20dfacc0e8ce577a666a4ab
--- /dev/null
+++ b/examples/LIBERO/eval_files/run_policy_server.sh
@@ -0,0 +1,15 @@
+#!/bin/bash
+export PYTHONPATH=$(pwd):${PYTHONPATH} # let LIBERO find the websocket tools from main repo
+export star_vla_python=/mnt/petrelfs/share/yejinhui/Envs/miniconda3/envs/starVLA/bin/python
+your_ckpt=results/Checkpoints/1208_libero_all_QwenPI_qwen3/checkpoints/steps_50000_pytorch_model.pt
+gpu_id=7
+port=5694
+################# star Policy Server ######################
+
+# export DEBUG=true
+CUDA_VISIBLE_DEVICES=$gpu_id ${star_vla_python} deployment/model_server/server_policy.py \
+ --ckpt_path ${your_ckpt} \
+ --port ${port} \
+ --use_bf16
+
+# #################################
diff --git a/examples/LIBERO/train_files/modality.json b/examples/LIBERO/train_files/modality.json
new file mode 100644
index 0000000000000000000000000000000000000000..085f340d34a647fc47c069c49c453ac70bd4f083
--- /dev/null
+++ b/examples/LIBERO/train_files/modality.json
@@ -0,0 +1,77 @@
+{
+ "state": {
+ "x": {
+ "start": 0,
+ "end": 1
+ },
+ "y": {
+ "start": 1,
+ "end": 2
+ },
+ "z": {
+ "start": 2,
+ "end": 3
+ },
+ "roll": {
+ "start": 3,
+ "end": 4
+ },
+ "pitch": {
+ "start": 4,
+ "end": 5
+ },
+ "yaw": {
+ "start": 5,
+ "end": 6
+ },
+ "pad": {
+ "start": 6,
+ "end": 7
+ },
+ "gripper": {
+ "start": 7,
+ "end": 8
+ }
+ },
+ "action": {
+ "x": {
+ "start": 0,
+ "end": 1
+ },
+ "y": {
+ "start": 1,
+ "end": 2
+ },
+ "z": {
+ "start": 2,
+ "end": 3
+ },
+ "roll": {
+ "start": 3,
+ "end": 4
+ },
+ "pitch": {
+ "start": 4,
+ "end": 5
+ },
+ "yaw": {
+ "start": 5,
+ "end": 6
+ },
+ "gripper": {
+ "start": 6,
+ "end": 7
+ }
+ },
+ "video": {
+ "primary_image": {
+ "original_key": "observation.images.image"
+ },
+ "wrist_image": {
+ "original_key": "observation.images.wrist_image"
+ }
+ },
+ "annotation": {
+ "human.action.task_description": {"original_key": "task_index"}
+ }
+}
\ No newline at end of file
diff --git a/examples/LIBERO/train_files/run_libero_train.sh b/examples/LIBERO/train_files/run_libero_train.sh
new file mode 100644
index 0000000000000000000000000000000000000000..fe448f8a3b98a9f482f516022b5b6416a7d5a491
--- /dev/null
+++ b/examples/LIBERO/train_files/run_libero_train.sh
@@ -0,0 +1,76 @@
+
+
+export NCCL_SOCKET_IFNAME=bond0
+export NCCL_IB_HCA=mlx5_2,mlx5_3
+
+# used for check save when communication
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=10000 # timeout set to 1 hour (unit: seconds)
+export NCCL_SOCKET_TIMEOUT_MS=360000
+###########################################################################################
+# === Please modify the following paths according to your environment ===
+Framework_name=CosmoPredict2OFT
+freeze_module_list=''
+base_wm=playground/Pretrained_models/nvidia/Cosmos-Predict2-2B-Video2World
+base_vlm=${base_wm}
+config_yaml=./examples/LIBERO/train_files/starvla_cotrain_libero.yaml
+libero_data_root=playground/Datasets/LEROBOT_LIBERO_DATA
+data_mix=libero_all
+run_root_dir=./results/Checkpoints
+run_id=1229_libero4in1_qwen3oft
+# === End of environment variable configuration ===
+###########################################################################################
+
+
+# export WANDB_MODE=disabled
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p ${output_dir}
+# mv this script to the output dir
+cp $0 ${output_dir}/
+
+
+accelerate launch \
+ --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \
+ --num_processes 8 \
+ starVLA/training/train_starvla.py \
+ --config_yaml ${config_yaml} \
+ --framework.name ${Framework_name} \
+ --framework.qwenvl.base_vlm ${base_vlm} \
+ --framework.world_model.base_wm ${base_wm} \
+ --framework.world_model.extract_layers "[-1]" \
+ --datasets.vla_data.data_root_dir ${libero_data_root}\
+ --datasets.vla_data.data_mix ${data_mix} \
+ --datasets.vla_data.per_device_batch_size 16 \
+ --trainer.vla_data.video_backend torchvision_av \
+ --trainer.freeze_modules ${freeze_module_list} \
+ --trainer.max_train_steps 80000 \
+ --trainer.save_interval 10000 \
+ --trainer.logging_frequency 100 \
+ --trainer.eval_interval 100 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project starVLA_Libero \
+ --wandb_entity jinhuiye \
+ # --is_debug True
+
+
+
+##### Multi-Server Multi-GPU training script #####
+ # accelerate launch \
+ # --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \
+ # --main_process_ip $MASTER_ADDR \
+ # --main_process_port $MASTER_PORT \
+ # --machine_rank $SLURM_PROCID \
+ # --num_machines $SLURM_NNODES \
+ # --num_processes=${TOTAL_GPUS} \
+ # starVLA/training/train_starvla.py \
+ # --config_yaml ${config_yaml} \
+ # --framework.name ${Framework_name} \
+ # --framework.qwenvl.base_vlm ${base_vlm} \
+ # --run_root_dir ${run_root_dir} \
+ # --run_id ${run_id} \
+ # --wandb_project your_project \
+ # --wandb_entity your_name
+##### Multi-Server Multi-GPU training script #####
diff --git a/examples/LIBERO/train_files/starvla_cotrain_libero.yaml b/examples/LIBERO/train_files/starvla_cotrain_libero.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..224b6cecedf5d1b4b3ff7ac7ec9a5990cf84670f
--- /dev/null
+++ b/examples/LIBERO/train_files/starvla_cotrain_libero.yaml
@@ -0,0 +1,115 @@
+run_id: starvla
+run_root_dir: results/Checkpoints
+seed: 42
+trackers: [jsonl, wandb]
+wandb_entity: your_wandb_entity
+wandb_project: llavavla
+is_debug: false
+
+
+framework:
+ name: QwenGR00T
+ qwenvl:
+ base_vlm: ./playground/Pretrained_models/Qwen2.5-VL-3B-Instruct-Action
+ attn_implementation: flash_attention_2
+ vl_hidden_dim: 2048
+ world_model:
+ base_wm: ./playground/Pretrained_models/nvidia/Cosmos-Predict2-2B-Video2World
+ extract_layers: [-1]
+ dino:
+ dino_backbone: dinov2_vits14
+ action_model:
+ action_model_type: DiT-B
+ action_hidden_dim: 1024 # TODO merge with hidden_size, in config v2
+ hidden_size: 1024
+ add_pos_embed: True
+ max_seq_len: 1024
+ action_dim: 7
+ state_dim: 7
+ future_action_window_size: 7
+ action_horizon: 8 # need merge with future_action_window_size
+ past_action_window_size: 0
+ repeated_diffusion_steps: 8
+ noise_beta_alpha: 1.5
+ noise_beta_beta: 1.0
+ noise_s: 0.999
+ num_timestep_buckets: 1000
+ num_inference_timesteps: 4
+ num_target_vision_tokens: 32
+ diffusion_model_cfg: # DiT Transformers 的参数
+ cross_attention_dim: 2048 # VLM 的 dim
+ dropout: 0.2
+ final_dropout: true
+ interleave_self_attention: true
+ norm_type: "ada_norm"
+ num_layers: 16
+ output_dim: 1024
+ positional_embeddings: null
+
+ reduce_in_full_precision: true
+
+
+datasets:
+ vlm_data:
+ dataset_py: vlm_datasets
+ dataformat: llava_json
+ dataset_use: sharegpt4v_coco
+ eval_dataset: sharegpt4v_coco
+ data_flatten: false
+ base_interval: 2
+ max_pixels: 307200
+ min_pixels: 784
+ model_max_length: 2048
+ model_type: qwen2.5vl
+ per_device_batch_size: 4
+
+ vla_data:
+ dataset_py: lerobot_datasets
+ data_root_dir: playground/Datasets/LEROBOT_LIBERO_DATA
+ data_mix: libero_all # libero_goal
+ action_type: delta_qpos
+ CoT_prompt: "Your task is {instruction}. To identify the key objects for your task. Locate their bounding boxes in [x1,y1,x2,y2] format."
+ CoT_answer: bbox
+ default_image_resolution: [3, 224, 224]
+ per_device_batch_size: 16
+ load_all_data_for_training: true
+ obs: ["image_0"]
+ video_backend: torchvision_av
+
+
+trainer:
+ epochs: 100
+ max_train_steps: 100000
+ num_warmup_steps: 5000
+ save_interval: 5000
+ eval_interval: 100
+ learning_rate:
+ base: 2.5e-05
+ qwen_vl_interface: 1.0e-05
+ action_model: 1.0e-04
+ lr_scheduler_type: cosine_with_min_lr
+ scheduler_specific_kwargs:
+ min_lr: 1.0e-06
+ freeze_modules: ''
+ loss_scale:
+ vla: 1.0
+ vlm: 0.1
+ max_grad_norm: 1.0
+ warmup_ratio: 0.1
+ weight_decay: 0.0
+ logging_frequency: 10
+ gradient_clipping: 1.0
+ gradient_accumulation_steps: 1
+
+ optimizer:
+ name: AdamW
+ betas: [0.9, 0.95]
+ eps: 1.0e-08
+ weight_decay: 1.0e-08
+
+ # parameters to be determined
+ is_resume: false
+ resume_epoch: null
+ resume_step: null
+ enable_gradient_checkpointing: true
+ enable_mixed_precision_training: true
diff --git a/examples/Pretrain/run_pretrain_cosmos_policy.sh b/examples/Pretrain/run_pretrain_cosmos_policy.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e2ed26610287c401b0819cad9c143aa878c7a964
--- /dev/null
+++ b/examples/Pretrain/run_pretrain_cosmos_policy.sh
@@ -0,0 +1,104 @@
+#!/usr/bin/env zsh
+set -euo pipefail
+
+# Cosmos2 EDM Policy training script:
+# action/future-image latent frames are trained with a sigma-space denoising objective.
+
+if [ -d /sys/class/infiniband ]; then
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
+else
+ RDMA_DEVICES=""
+fi
+
+if [ -n "${RDMA_DEVICES}" ]; then
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
+ export NCCL_IB_HCA
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
+ export NCCL_IB_DISABLE=0
+ export NCCL_NET_GDR_LEVEL=2
+else
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
+ export NCCL_IB_DISABLE=1
+fi
+
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS || true
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+
+if [ -f /mnt/workspace/envs/conda3/bin/activate ]; then
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+fi
+
+NUM_GPUS_PER_NODE=8
+
+Framework_name=CosmoPredict2PolicyEDM
+base_wm=/mnt/workspace1/users/chidafeng/models/Cosmos-Predict2-2B-Video2World
+# base_wm=/mnt/workspace/users/yuanzhihao/code/starVLA/playground/Pretrained_models/Cosmos-Predict2.5-2B-Post-Trained
+base_vlm=${base_wm}
+freeze_module_list=backbone.vae,backbone.text_encoder
+data_root_dir=/mnt/workspace/datasets/
+data_mix=agi-beta_robotwin_robocasa
+
+action_dim=32
+state_dim=64
+
+run_root_dir=./outputs/cosmos2_policy
+run_id=pretrain_agi-beta_robotwin_robocasa
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p "${output_dir}"
+export WANDB_MODE=offline
+export WANDB_DIR="${output_dir}/wandb"
+mkdir -p "${WANDB_DIR}"
+cp "$0" "${output_dir}/"
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
+ starVLA/training/train_starvla.py \
+ --config_yaml ./examples/Pretrain/starvla_cotrain_robocasa_gr1.yaml \
+ --framework.name ${Framework_name} \
+ --framework.world_model.base_wm "${base_wm}" \
+ --framework.world_model.height 224 \
+ --framework.world_model.width 224 \
+ --framework.world_model.text_max_length 128 \
+ --framework.qwenvl.base_vlm "${base_vlm}" \
+ --framework.action_model.action_dim ${action_dim} \
+ --framework.action_model.state_dim ${state_dim} \
+ --framework.policy.sigma_data 1.0 \
+ --framework.policy.sigma_min 0.0002 \
+ --framework.policy.sigma_max 80.0 \
+ --framework.policy.sigma_p_mean -1.2 \
+ --framework.policy.sigma_p_std 1.2 \
+ --framework.policy.hybrid_sigma_distribution true \
+ --framework.policy.hybrid_sigma_lognormal_prob 0.7 \
+ --framework.policy.uniform_lower 1.0 \
+ --framework.policy.uniform_upper 85.0 \
+ --framework.policy.rho 7.0 \
+ --framework.policy.loss_weighting edm \
+ --framework.policy.max_loss_weight 100.0 \
+ --framework.policy.num_inference_steps 5 \
+ --framework.policy.sampler 2ab \
+ --framework.policy.preconditioning true \
+ --framework.policy.future_image_loss_weight 1.0 \
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
+ --datasets.vla_data.data_mix "${data_mix}" \
+ --datasets.vla_data.per_device_batch_size 16 \
+ --trainer.freeze_modules "${freeze_module_list}" \
+ --trainer.max_train_steps 300000 \
+ --trainer.save_interval 50000 \
+ --trainer.logging_frequency 200 \
+ --trainer.eval_interval 200 \
+ --trainer.learning_rate.base 1e-5 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project joyRA_robocasa \
+ --wandb_entity curryyuan \
+ 2>&1 | tee -a "${output_dir}/train.log"
diff --git a/examples/Pretrain/run_pretrain_debug.sh b/examples/Pretrain/run_pretrain_debug.sh
new file mode 100644
index 0000000000000000000000000000000000000000..d94f914668d8d04029dffe2f7831d73ef1a5242d
--- /dev/null
+++ b/examples/Pretrain/run_pretrain_debug.sh
@@ -0,0 +1,104 @@
+RDMA_DEVICES=$(ls /sys/class/infiniband)
+if [ -z "$RDMA_DEVICES" ]; then
+ log "ERROR: No active RDMA devices found. Exiting script." >&2
+ exit 1
+fi
+
+# 设置RDMA设备列表 (逗号分隔)
+NCCL_IB_HCA=$(echo "$RDMA_DEVICES" | tr '\n' ',' | sed 's/,$//')
+export NCCL_IB_HCA
+echo "Detected RDMA devices: $NCCL_IB_HCA"
+
+# 获取GID_INDEX
+NCCL_IB_GID_INDEX=""
+output=$(show_gids | grep v2)
+# 遍历每一行
+while IFS= read -r line; do
+ ipv4=$(echo "$line" | awk '{print $5}')
+ # 检查IPv4地址是否有值(不是空字符串且不是全0地址)
+ if [[ -n "$ipv4" && "$ipv4" != "0000:0000:0000:0000:0000:ffff:0000:0000" && "$ipv4" =~ [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+ ]]; then
+ NCCL_IB_GID_INDEX=$(echo "$line" | awk '{print $3}')
+ # 找到第一个匹配项后立即退出循环
+ break
+ fi
+done <<<"$output"
+
+export NCCL_SOCKET_IFNAME="eth0"
+
+# 处理分布式训练需要使用到的相关环境变量
+export NCCL_IB_HCA=${NCCL_IB_HCA}
+export NCCL_IB_GID_INDEX=${NCCL_IB_GID_INDEX}
+export NCCL_NET_GDR_LEVEL=2
+# export NCCL_DEBUG_SUBSYS=ALL
+# 加速
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS
+export NCCL_IB_DISABLE=0
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME}
+
+# used for check save when communication
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000 # timeout set to 1 hour (unit: seconds)
+
+# ==== 多节点配置 ====
+# 总节点数(根据实际情况修改)
+NUM_NODES=${PET_NNODES}
+# 当前节点索引(0-based,每个节点启动时需指定不同值)
+NODE_RANK=${PET_NODE_RANK}
+# 主节点IP地址(确保所有节点可访问)
+MASTER_ADDR=${PET_MASTER_ADDR} # 替换为实际主节点IP
+# 主节点端口(保持与代码中一致)
+MASTER_PORT=${PET_MASTER_PORT}
+NUM_GPUS_PER_NODE=2
+
+source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+
+Framework_name=QwenPerceiver
+base_vlm=./playground/Pretrained_models/Qwen3-VL-4B-Instruct
+freeze_module_list='' # just for fast debug, sota is under fully FT, i.g., freeze_module_list=""
+DIT_TYPE="DiT-B"
+data_root_dir=/mnt/workspace/datasets/
+data_mix=sq_egodex-f_nvwa-f_robotwin_robocasa
+
+
+run_root_dir=./outputs
+run_id=pretrain_sq_egodex-f_nvwa-f_robotwin_robocasa
+
+export WANDB_MODE=offline
+export WANDB_DIR=../../
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p ${output_dir}
+# mv this script to the output dir
+cp $0 ${output_dir}/
+
+LOGFILE=${output_dir}/train_$(date +%Y%m%d_%H%M%S).log
+
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-26500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE:-8} \
+ starVLA/training/train_starvla.py \
+ --config_yaml examples/Suqian_agibot/train_files/starvla_cotrain_robocasa_gr1.yaml \
+ --framework.name ${Framework_name} \
+ --framework.qwenvl.base_vlm ${base_vlm} \
+ --framework.action_model.action_model_type ${DIT_TYPE} \
+ --datasets.vla_data.data_root_dir ${data_root_dir} \
+ --datasets.vla_data.data_mix ${data_mix} \
+ --datasets.vla_data.per_device_batch_size 32 \
+ --trainer.freeze_modules ${freeze_module_list} \
+ --trainer.max_train_steps 300000 \
+ --trainer.save_interval 10000 \
+ --trainer.logging_frequency 100 \
+ --trainer.eval_interval 100 \
+ --trainer.learning_rate.base 3e-5 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project starVLA_robocasa \
+ --wandb_entity curryyuan \
+ 2>&1 | tee -a "${output_dir}/train.log"
+ # --is_debug True
\ No newline at end of file
diff --git a/examples/Pretrain/starvla_cotrain_robocasa_gr1.yaml b/examples/Pretrain/starvla_cotrain_robocasa_gr1.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..0f26f182d4813cdaf3fe6ceafcb56aca27d06930
--- /dev/null
+++ b/examples/Pretrain/starvla_cotrain_robocasa_gr1.yaml
@@ -0,0 +1,116 @@
+run_id: qwenact
+run_root_dir: results/Checkpoints
+seed: 42
+trackers: [jsonl, wandb]
+wandb_entity: your_wandb_entity
+wandb_project: starvla
+is_debug: false
+
+framework:
+ name: QwenGR00T
+ qwenvl:
+ base_vlm: ./playground/Pretrained_models/Qwen3-VL-4B-Instruct-Action
+ attn_implementation: flash_attention_2
+ vl_hidden_dim: 2048
+ dino:
+ dino_backbone: dinov2_vits14
+
+ action_model:
+ action_model_type: DiT-B
+ hidden_size: 2560 # 和 DiT 最后的 projection 对应,用于 ActionDecoder
+ add_pos_embed: True
+ max_seq_len: 1024
+ action_dim: 32
+ state_dim: 64
+ future_action_window_size: 29
+ action_horizon: 30
+ past_action_window_size: 0
+ repeated_diffusion_steps: 8
+ noise_beta_alpha: 1.5
+ noise_beta_beta: 1.0
+ noise_s: 0.999
+ num_timestep_buckets: 1000
+ num_inference_timesteps: 4
+ num_target_vision_tokens: 32
+ diffusion_model_cfg: # DiT Transformers 的参数
+ cross_attention_dim: 2048 # VLM 的 dim
+ dropout: 0.2
+ final_dropout: true
+ interleave_self_attention: true
+ norm_type: "ada_norm"
+ num_layers: 16
+ output_dim: 2560
+ positional_embeddings: null
+
+
+
+datasets:
+ vlm_data:
+ dataset_py: vlm_datasets
+ dataformat: llava_json
+ # dataset_use: cambrain_300k_vlapt,refspatial_2d_100k_vlapt,refspatial_3d_150k_vlapt,refspatial_3d_visual_50k_vlapt,robovqa_300k_vlapt,gal_subtask_110k
+ dataset_use: agibot_subtask,sq_subtask,cambrain_300k_vlapt,refspatial_2d_100k_vlapt,refspatial_3d_150k_vlapt,refspatial_3d_visual_50k_vlapt # gal_subtask_110k
+ eval_dataset: sq_subtask
+ data_flatten: false
+ base_interval: 2
+ max_pixels: 50176
+ min_pixels: 784
+ model_max_length: 4096
+ model_type: qwen2.5vl
+ per_device_batch_size: 4
+
+ vla_data:
+ dataset_py: lerobot_datasets
+ data_root_dir: /mnt/workspace/datasets/suqian_agibot_lerobot_data/
+ data_mix: suqian_test # bridge_rt_1
+ action_type: delta_ee
+ CoT_prompt: "{instruction}"
+ CoT_answer: bbox
+ default_image_resolution: [3, 224, 224]
+ per_device_batch_size: 16
+ load_all_data_for_training: true
+ obs: ["image_0"]
+ image_size: [224,224]
+ delete_pause_frame: false
+ include_state: false
+ video_backend: torchvision_av
+
+trainer:
+ epochs: 100
+ max_train_steps: 100000
+ num_warmup_steps: 5000
+ save_interval: 5000
+ eval_interval: 100
+ learning_rate:
+ base: 1e-05
+ qwen_vl_interface: 1.0e-05
+ action_model: 1.0e-04
+ lr_scheduler_type: cosine_with_min_lr
+ scheduler_specific_kwargs:
+ min_lr: 5.0e-07
+ freeze_modules: ''
+ loss_scale:
+ vla: 1.0
+ vlm: 0.05
+ # pretrained_checkpoint: outputs/StarVLA_Qwen3_VL_GR00T_Robocasa_gr1/checkpoints/steps_90000_pytorch_model.pt
+ # reload_modules: 'action_model,layer_qformer' # warning: this may cause model to not converge
+ repeated_diffusion_steps: 4
+ max_grad_norm: 1.0
+ warmup_ratio: 0.1
+ weight_decay: 0.0
+ logging_frequency: 10
+ gradient_clipping: 1.0
+ gradient_accumulation_steps: 1
+
+ optimizer:
+ name: AdamW
+ betas: [0.9, 0.95]
+ eps: 1.0e-08
+ weight_decay: 1.0e-08
+
+ # parameters to be determined
+ is_resume: false
+ resume_epoch: null
+ resume_step: null
+ enable_gradient_checkpointing: true
+ enable_mixed_precision_training: true
diff --git a/examples/Robocasa_tabletop/README.md b/examples/Robocasa_tabletop/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..0009d95610b97e5f090a1af3fe1cf5f37f6b8a0b
--- /dev/null
+++ b/examples/Robocasa_tabletop/README.md
@@ -0,0 +1,136 @@
+# 🚀 Robocasa-GR1-Tabletop-Tasks Evaluation
+
+This document provides instructions for reproducing our **experimental results** with [robocasa-gr1-tabletop-tasks](https://github.com/robocasa/robocasa-gr1-tabletop-tasks).
+The evaluation process consists of two main parts:
+
+1. Setting up the `robocasa` environment and dependencies.
+2. Running the evaluation by launching services in both `starVLA` and `robocasa` environments.
+
+We have verified that this workflow runs successfully on **NVIDIA A100** GPUs.
+
+
+# Evaluation
+
+
+
+
+## ⬇️ 0. Download Checkpoints
+First, download the checkpoints from
+- [Qwen3VL-GR00T](https://huggingface.co/StarVLA/Qwen3-VL-GR00T-Robocasa-gr1)
+- [Qwen3VL-OFT](https://huggingface.co/StarVLA/Qwen3-VL-OFT-Robocasa)
+
+## 📦 1. Environment Setup
+
+To set up the environment, please first follow the [official RoboCasa installation guide](https://github.com/robocasa/robocasa-gr1-tabletop-tasks?tab=readme-ov-file#getting-started) to install the base `robocasa-gr1-tabletop-tasks` environment.
+
+than pip soceket support
+
+'''bash
+pip install tyro
+'''
+
+---
+
+## 🚀 2. Evaluation Workflow
+
+### Step 1. Start the server (starVLA environment)
+
+In the first terminal, activate the `starVLA` conda environment and run:
+
+```bash
+python deployment/model_server/server_policy.py \
+ --ckpt_path ${your_ckpt} \
+ --port 5678 \
+ --use_bf16
+```
+
+---
+
+### Step 2. Start the simulation (robocasa environment)
+
+In the second terminal, activate the `robocasa` conda environment and run:
+
+```bash
+export PYTHONPATH=$(pwd):${PYTHONPATH}
+your_ckpt=StarVLA/Qwen3-VL-OFT-Robocasa/checkpoints/steps_90000_pytorch_model.pt
+
+python examples/Robocasa_tabletop/eval_files/simulation_env.py\
+ --args.env_name ${env_name} \
+ --args.port 5678 \
+ --args.n_episodes 50 \
+ --args.n_envs 1 \
+ --args.max_episode_steps 720 \
+ --args.n_action_steps 12 \
+ --args.video_out_path ${video_out_path} \
+ --args.pretrained_path ${your_ckpt}
+```
+
+
+### Optional: Batch Evaluation
+
+If you have more GPU, you can use the batch evaluation script:
+```bash
+bash examples/Robocasa_tabletop/batch_eval_args.sh
+```
+⚠️ **Note:** Please ensure that you specify the correct checkpoint path in `batch_eval_args.sh`
+
+---
+## 📊 Experimental Results
+
+# RoboCasa GR1 Tabletop Tasks Evaluation Results
+
+| Task | GR00T-N1.6 | Qwen3GR00T | Qwen3PI | Qwen3OFT | Qwen3FAST |
+|------|------------|------------|---------|----------|-----------|
+| **PnP Bottle To Cabinet Close** | 51.5 | 46.0 | 26.0 | **30.0** | 38.0 |
+| **PnP Can To Drawer Close** | 13.0 | 80.0 | 62.0 | **76.0** | 44.0 |
+| **PnP Cup To Drawer Close** | 8.5 | 54.0 | 42.0 | **44.0** | 56.0 |
+| **PnP Milk To Microwave Close** | 14.0 | 48.0 | 50.0 | **44.0** | 44.0 |
+| **PnP Potato To Microwave Close** | 41.5 | 28.0 | 42.0 | **32.0** | 14.0 |
+| **PnP Wine To Cabinet Close** | 16.5 | 46.0 | 32.0 | **36.0** | 14.0 |
+| | | | | | |
+| **PnP Novel From Cuttingboard To Basket** | 58.0 | 48.0 | 40.0 | **50.0** | 54.0 |
+| **PnP Novel From Cuttingboard To Cardboardbox** | 46.5 | 40.0 | 46.0 | **40.0** | 42.0 |
+| **PnP Novel From Cuttingboard To Pan** | 68.5 | 68.0 | 60.0 | **70.0** | 58.0 |
+| **PnP Novel From Cuttingboard To Pot** | 65.0 | 52.0 | 40.0 | **54.0** | 58.0 |
+| **PnP Novel From Cuttingboard To Tieredbasket** | 46.5 | 56.0 | 44.0 | **38.0** | 40.0 |
+| | | | | | |
+| **PnP Novel From Placemat To Basket** | 58.5 | 42.0 | 44.0 | **32.0** | 36.0 |
+| **PnP Novel From Placemat To Bowl** | 57.5 | 44.0 | 52.0 | **58.0** | 38.0 |
+| **PnP Novel From Placemat To Plate** | 63.0 | 48.0 | 50.0 | **52.0** | 42.0 |
+| **PnP Novel From Placemat To Tieredshelf** | 28.5 | 18.0 | 28.0 | **24.0** | 18.0 |
+| | | | | | |
+| **PnP Novel From Plate To Bowl** | 57.0 | 60.0 | 52.0 | **60.0** | 52.0 |
+| **PnP Novel From Plate To Cardboardbox** | 43.5 | 50.0 | 40.0 | **50.0** | 30.0 |
+| **PnP Novel From Plate To Pan** | 51.0 | 54.0 | 36.0 | **66.0** | 48.0 |
+| **PnP Novel From Plate To Plate** | 78.7 | 70.0 | 48.0 | **68.0** | 50.0 |
+| | | | | | |
+| **PnP Novel From Tray To Cardboardbox** | 51.5 | 38.0 | 34.0 | **44.0** | 28.0 |
+| **PnP Novel From Tray To Plate** | 71.0 | 56.0 | 64.0 | **56.0** | 34.0 |
+| **PnP Novel From Tray To Pot** | 64.5 | 50.0 | 44.0 | **62.0** | 46.0 |
+| **PnP Novel From Tray To Tieredbasket** | 57.0 | 36.0 | 50.0 | **54.0** | 36.0 |
+| **PnP Novel From Tray To Tieredshelf** | 31.5 | 16.0 | 28.0 | **30.0** | 16.0 |
+| | | | | | |
+| **Average** | **47.6** | **47.8** | **43.9** | **48.8** | **39.0** |
+
+*Note: All values are success rates in percentage (%). A single model was trained for all 24 tasks. Results are reported over 50 rollouts per task.*
+
+---
+
+
+# 🚀 Reproduce Training Results
+## 📦 Step0: Download the training dataset
+Download the PhysicalAI-Robotics-GR00T-X-Embodiment-Sim directory datasets from [HuggingFace](https://huggingface.co/datasets/nvidia/PhysicalAI-Robotics-GR00T-X-Embodiment-Sim) to the playground/Datasets/nvidia/PhysicalAI-Robotics-GR00T-X-Embodiment-Sim directory
+
+To download only the relevant finetuning folders, you can refer [GR00T-N1.5](https://github.com/NVIDIA/Isaac-GR00T/tree/4af2b622892f7dcb5aae5a3fb70bcb02dc217b96/examples/RoboCasa#-1-dataset-preparation) repo's instruction.
+Or using the script download the *_1000 folders.
+
+```bash
+python examples/Robocasa_tabletop/download_gr00t_ft_data.py
+```
+
+## 🚀 Step1: Start Training
+Different datasets can be selected by modifying the parameter `data_mix`, and the following script can be used to fine-tune the `*_1000` datasets:
+```bash
+bash examples/Robocasa_tabletop/train_files/run_robocasa.sh
+```
+
diff --git a/examples/Robocasa_tabletop/eval_files/.ipynb_checkpoints/batch_eval_args_wm_vjepa_180000-checkpoint.sh b/examples/Robocasa_tabletop/eval_files/.ipynb_checkpoints/batch_eval_args_wm_vjepa_180000-checkpoint.sh
new file mode 100644
index 0000000000000000000000000000000000000000..5b62da69722f3e85ea6a7c82dcc971a7221bc5f4
--- /dev/null
+++ b/examples/Robocasa_tabletop/eval_files/.ipynb_checkpoints/batch_eval_args_wm_vjepa_180000-checkpoint.sh
@@ -0,0 +1,244 @@
+#!/bin/bash
+
+# ============================================================
+# WM Evaluation Script for wam_vjepa_100000 model
+# Based on batch_eval_args_wm.sh, adapted for maxiangkai's WM4A project
+# ============================================================
+
+export OMP_NUM_THREADS=1
+export MKL_NUM_THREADS=1
+export OPENBLAS_NUM_THREADS=1
+
+# NVIDIA H200 EGL Rendering Path
+export LD_LIBRARY_PATH=/mnt/workspace/lib/nvidia_egl:\$LD_LIBRARY_PATH
+export PYOPENGL_PLATFORM=egl
+export __GLX_VENDOR_LIBRARY_NAME=nvidia
+export MUJOCO_GL=egl
+export STARVLA_WM_DEBUG=${STARVLA_WM_DEBUG:-0}
+export STARVLA_WM_DEBUG_MAX=${STARVLA_WM_DEBUG_MAX:-6}
+export STARVLA_ACTION_DEBUG=${STARVLA_ACTION_DEBUG:-0}
+export STARVLA_ACTION_DEBUG_MAX=${STARVLA_ACTION_DEBUG_MAX:-20}
+
+cd /mnt/workspace/users/maxiangkai/projects/WM4A
+starVLA_PYTHON=/mnt/workspace/envs/conda3/envs/starVLA_1/bin/python
+ROBOCASA_PYTHON=/mnt/workspace/envs/conda3/envs/robocasa/bin/python
+export PYTHONPATH=$(pwd):${PYTHONPATH}
+
+CKPT_DEFAULT="/mnt/workspace/users/maxiangkai/projects/WM4A/outputs/cosmopredict25_vjepa_ImageLatent/robocasa_06-26-16-51/checkpoints/steps_180000_pytorch_model.pt"
+SIMULATION_SCRIPT="examples/Robocasa_tabletop/eval_files/simulation_env_wm.py"
+
+N_ENVS_DEFAULT=1
+MAX_EPISODE_STEPS_DEFAULT=720
+N_ACTION_STEPS_DEFAULT=12
+NUM_INFERENCE_STEPS_DEFAULT=5
+SHIFT_DEFAULT=5.0
+
+BASE_PORT=29999
+NUM_GPUS=8 # mytest
+
+CKPT_PATH=${1:-$CKPT_DEFAULT}
+N_ENVS=${2:-$N_ENVS_DEFAULT}
+MAX_EPISODE_STEPS=${3:-$MAX_EPISODE_STEPS_DEFAULT}
+N_ACTION_STEPS=${4:-$N_ACTION_STEPS_DEFAULT}
+NUM_INFERENCE_STEPS=${5:-$NUM_INFERENCE_STEPS_DEFAULT}
+SHIFT=${6:-$SHIFT_DEFAULT}
+
+echo "=== WM Evaluation Configuration ==="
+echo "Checkpoint Path : ${CKPT_PATH}"
+echo "Number of Envs : ${N_ENVS}"
+echo "Max Episode Steps : ${MAX_EPISODE_STEPS}"
+echo "Action Chunk Length : ${N_ACTION_STEPS}"
+echo "Inference Steps : ${NUM_INFERENCE_STEPS}"
+echo "RF Shift : ${SHIFT}"
+echo "Simulation Script : ${SIMULATION_SCRIPT}"
+echo "==================================="
+
+SERVER_PIDS=()
+EVAL_PIDS=()
+CLEANED_UP=0
+
+kill_process_tree() {
+ local PID=$1
+ local SIGNAL=${2:-TERM}
+
+ if [[ -z "${PID}" ]] || ! kill -0 "${PID}" 2>/dev/null; then
+ return
+ fi
+
+ local CHILD_PIDS
+ CHILD_PIDS=$(pgrep -P "${PID}" 2>/dev/null || true)
+ for CHILD_PID in ${CHILD_PIDS}; do
+ kill_process_tree "${CHILD_PID}" "${SIGNAL}"
+ done
+
+ kill -"${SIGNAL}" "${PID}" 2>/dev/null || true
+}
+
+cleanup() {
+ local EXIT_CODE=$?
+ if [[ "${CLEANED_UP}" -eq 1 ]]; then
+ exit "${EXIT_CODE}"
+ fi
+ CLEANED_UP=1
+
+ trap - INT TERM EXIT
+
+ echo ""
+ echo "Cleaning up WM evaluation processes..."
+
+ for PID in "${EVAL_PIDS[@]}" "${SERVER_PIDS[@]}"; do
+ kill_process_tree "${PID}" TERM
+ done
+
+ sleep 2
+
+ for PID in "${EVAL_PIDS[@]}" "${SERVER_PIDS[@]}"; do
+ kill_process_tree "${PID}" KILL
+ done
+
+ wait 2>/dev/null || true
+ echo "Cleanup finished."
+ exit "${EXIT_CODE}"
+}
+
+trap cleanup INT TERM EXIT
+
+EvalEnv() {
+ local GPU_ID=$1
+ local PORT=$2
+ local ENV_NAME=$3
+ local CKPT_PATH=$4
+ local LOG_DIR=$5
+ local ROBOCASA_PYTHON=$6
+ local N_ENVS=$7
+ local MAX_EPISODE_STEPS=$8
+ local N_ACTION_STEPS=$9
+ local NUM_INFERENCE_STEPS=${10}
+ local SHIFT=${11}
+
+ local SAVE_ROOT=$(dirname "$(dirname "$CKPT_PATH")")
+ local ckpt_name=$(basename "$CKPT_PATH" .pt)
+ local VIDEO_OUT_PATH="${SAVE_ROOT}/videos/${ckpt_name}/$(basename "${LOG_DIR}")/${ENV_NAME}"
+ mkdir -p "${VIDEO_OUT_PATH}"
+
+ echo "Launching WM evaluation | GPU ${GPU_ID} | Port ${PORT} | Env ${ENV_NAME}"
+
+ CUDA_VISIBLE_DEVICES=${GPU_ID} \
+ MUJOCO_GL=egl \
+ PYOPENGL_PLATFORM=egl \
+ MUJOCO_EGL_DEVICE_ID=${GPU_ID} \
+ ${ROBOCASA_PYTHON} "${SIMULATION_SCRIPT}" \
+ --args.env_name "${ENV_NAME}" \
+ --args.port "${PORT}" \
+ --args.n_episodes 50 \
+ --args.n_envs "${N_ENVS}" \
+ --args.max_episode_steps "${MAX_EPISODE_STEPS}" \
+ --args.n_action_steps "${N_ACTION_STEPS}" \
+ --args.num_inference_steps "${NUM_INFERENCE_STEPS}" \
+ --args.shift "${SHIFT}" \
+ --args.video_out_path "${VIDEO_OUT_PATH}" \
+ --args.pretrained_path "${CKPT_PATH}" \
+ > "${LOG_DIR}/eval_env_${ENV_NAME//\//_}_gpu${GPU_ID}.log" 2>&1
+}
+
+ENV_NAMES=(
+ gr1_unified/PnPCupToDrawerClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPPotatoToMicrowaveClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPMilkToMicrowaveClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPBottleToCabinetClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPWineToCabinetClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPCanToDrawerClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToBasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToPanSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToPotSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToTieredbasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToBasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToBowlSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToPlateSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToTieredshelfSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToBowlSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToPanSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToPlateSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToPlateSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToPotSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToTieredbasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToTieredshelfSplitA_GR1ArmsAndWaistFourierHands_Env
+)
+
+LOG_DIR="${CKPT_PATH}.log/wm_eval_$(date +%Y%m%d_%H%M%S)"
+mkdir -p "${LOG_DIR}"
+
+echo "=== Launching WM Multi-GPU Evaluation ==="
+echo "GPUs : ${NUM_GPUS}"
+echo "Num Environments : ${#ENV_NAMES[@]}"
+echo "Log Directory : ${LOG_DIR}"
+
+# Kill any existing processes on target ports
+echo "Cleaning up stale processes on target ports..."
+for GPU_ID in $(seq 0 $((NUM_GPUS - 1))); do
+ PORT=$((BASE_PORT + GPU_ID))
+ PID=$(lsof -ti:${PORT} 2>/dev/null || true)
+ if [ -n "${PID}" ]; then
+ echo "Killing process ${PID} on port ${PORT}"
+ kill -9 ${PID} 2>/dev/null || true
+ fi
+done
+sleep 2
+
+for GPU_ID in $(seq 0 $((NUM_GPUS - 1))); do
+ PORT=$((BASE_PORT + GPU_ID))
+ echo "Starting policy server | GPU ${GPU_ID} | Port ${PORT}"
+
+ CUDA_VISIBLE_DEVICES=${GPU_ID} \
+ ${starVLA_PYTHON} deployment/model_server/server_policy.py \
+ --ckpt_path "${CKPT_PATH}" \
+ --port "${PORT}" \
+ --use_bf16 \
+ > "${LOG_DIR}/server_gpu${GPU_ID}_port${PORT}.log" 2>&1 &
+
+ SERVER_PIDS[$GPU_ID]=$!
+ sleep 10
+done
+
+sleep 30
+
+COUNT=0
+for ENV_NAME in "${ENV_NAMES[@]}"; do
+ GPU_ID=$((COUNT % NUM_GPUS))
+ PORT=$((BASE_PORT + GPU_ID))
+
+ if (( (COUNT + 1) % NUM_GPUS == 0 )); then
+ EvalEnv "${GPU_ID}" "${PORT}" "${ENV_NAME}" "${CKPT_PATH}" "${LOG_DIR}" \
+ "${ROBOCASA_PYTHON}" "${N_ENVS}" "${MAX_EPISODE_STEPS}" "${N_ACTION_STEPS}" "${NUM_INFERENCE_STEPS}" "${SHIFT}" &
+ EVAL_PIDS+=($!)
+ wait "${EVAL_PIDS[@]}"
+ EVAL_PIDS=()
+ else
+ EvalEnv "${GPU_ID}" "${PORT}" "${ENV_NAME}" "${CKPT_PATH}" "${LOG_DIR}" \
+ "${ROBOCASA_PYTHON}" "${N_ENVS}" "${MAX_EPISODE_STEPS}" "${N_ACTION_STEPS}" "${NUM_INFERENCE_STEPS}" "${SHIFT}" &
+ EVAL_PIDS+=($!)
+ fi
+
+ COUNT=$((COUNT + 1))
+ sleep 2
+done
+
+while pgrep -f "${SIMULATION_SCRIPT}" > /dev/null; do
+ echo "Waiting for all WM evaluation environments to finish..."
+ sleep 30
+done
+
+echo ""
+echo "Shutting down policy servers..."
+
+for PID in "${SERVER_PIDS[@]}"; do
+ kill_process_tree "${PID}" TERM
+ echo "Killed server PID ${PID}"
+done
+
+echo "=== WM Evaluation Finished ==="
+
+python summarize_eval_logs.py "${LOG_DIR}"
\ No newline at end of file
diff --git a/examples/Robocasa_tabletop/eval_files/.ipynb_checkpoints/batch_eval_args_wm_vjepa_280000-checkpoint.sh b/examples/Robocasa_tabletop/eval_files/.ipynb_checkpoints/batch_eval_args_wm_vjepa_280000-checkpoint.sh
new file mode 100644
index 0000000000000000000000000000000000000000..7a71b50e8cec64a4cb8775fb76891d0d2337665c
--- /dev/null
+++ b/examples/Robocasa_tabletop/eval_files/.ipynb_checkpoints/batch_eval_args_wm_vjepa_280000-checkpoint.sh
@@ -0,0 +1,244 @@
+#!/bin/bash
+
+# ============================================================
+# WM Evaluation Script for wam_vjepa_100000 model
+# Based on batch_eval_args_wm.sh, adapted for maxiangkai's WM4A project
+# ============================================================
+
+export OMP_NUM_THREADS=1
+export MKL_NUM_THREADS=1
+export OPENBLAS_NUM_THREADS=1
+
+# NVIDIA H200 EGL Rendering Path
+export LD_LIBRARY_PATH=/mnt/workspace/lib/nvidia_egl:\$LD_LIBRARY_PATH
+export PYOPENGL_PLATFORM=egl
+export __GLX_VENDOR_LIBRARY_NAME=nvidia
+export MUJOCO_GL=egl
+export STARVLA_WM_DEBUG=${STARVLA_WM_DEBUG:-0}
+export STARVLA_WM_DEBUG_MAX=${STARVLA_WM_DEBUG_MAX:-6}
+export STARVLA_ACTION_DEBUG=${STARVLA_ACTION_DEBUG:-0}
+export STARVLA_ACTION_DEBUG_MAX=${STARVLA_ACTION_DEBUG_MAX:-20}
+
+cd /mnt/workspace/users/maxiangkai/projects/WM4A
+starVLA_PYTHON=/mnt/workspace/envs/conda3/envs/starVLA_1/bin/python
+ROBOCASA_PYTHON=/mnt/workspace/envs/conda3/envs/robocasa/bin/python
+export PYTHONPATH=$(pwd):${PYTHONPATH}
+
+CKPT_DEFAULT="/mnt/workspace/users/maxiangkai/projects/WM4A/outputs/cosmopredict25_vjepa_ImageLatent/robocasa_06-28-13-10/checkpoints/steps_280000_pytorch_model.pt"
+SIMULATION_SCRIPT="examples/Robocasa_tabletop/eval_files/simulation_env_wm.py"
+
+N_ENVS_DEFAULT=1
+MAX_EPISODE_STEPS_DEFAULT=720
+N_ACTION_STEPS_DEFAULT=12
+NUM_INFERENCE_STEPS_DEFAULT=5
+SHIFT_DEFAULT=5.0
+
+BASE_PORT=19999
+NUM_GPUS=8 # mytest
+
+CKPT_PATH=${1:-$CKPT_DEFAULT}
+N_ENVS=${2:-$N_ENVS_DEFAULT}
+MAX_EPISODE_STEPS=${3:-$MAX_EPISODE_STEPS_DEFAULT}
+N_ACTION_STEPS=${4:-$N_ACTION_STEPS_DEFAULT}
+NUM_INFERENCE_STEPS=${5:-$NUM_INFERENCE_STEPS_DEFAULT}
+SHIFT=${6:-$SHIFT_DEFAULT}
+
+echo "=== WM Evaluation Configuration ==="
+echo "Checkpoint Path : ${CKPT_PATH}"
+echo "Number of Envs : ${N_ENVS}"
+echo "Max Episode Steps : ${MAX_EPISODE_STEPS}"
+echo "Action Chunk Length : ${N_ACTION_STEPS}"
+echo "Inference Steps : ${NUM_INFERENCE_STEPS}"
+echo "RF Shift : ${SHIFT}"
+echo "Simulation Script : ${SIMULATION_SCRIPT}"
+echo "==================================="
+
+SERVER_PIDS=()
+EVAL_PIDS=()
+CLEANED_UP=0
+
+kill_process_tree() {
+ local PID=$1
+ local SIGNAL=${2:-TERM}
+
+ if [[ -z "${PID}" ]] || ! kill -0 "${PID}" 2>/dev/null; then
+ return
+ fi
+
+ local CHILD_PIDS
+ CHILD_PIDS=$(pgrep -P "${PID}" 2>/dev/null || true)
+ for CHILD_PID in ${CHILD_PIDS}; do
+ kill_process_tree "${CHILD_PID}" "${SIGNAL}"
+ done
+
+ kill -"${SIGNAL}" "${PID}" 2>/dev/null || true
+}
+
+cleanup() {
+ local EXIT_CODE=$?
+ if [[ "${CLEANED_UP}" -eq 1 ]]; then
+ exit "${EXIT_CODE}"
+ fi
+ CLEANED_UP=1
+
+ trap - INT TERM EXIT
+
+ echo ""
+ echo "Cleaning up WM evaluation processes..."
+
+ for PID in "${EVAL_PIDS[@]}" "${SERVER_PIDS[@]}"; do
+ kill_process_tree "${PID}" TERM
+ done
+
+ sleep 2
+
+ for PID in "${EVAL_PIDS[@]}" "${SERVER_PIDS[@]}"; do
+ kill_process_tree "${PID}" KILL
+ done
+
+ wait 2>/dev/null || true
+ echo "Cleanup finished."
+ exit "${EXIT_CODE}"
+}
+
+trap cleanup INT TERM EXIT
+
+EvalEnv() {
+ local GPU_ID=$1
+ local PORT=$2
+ local ENV_NAME=$3
+ local CKPT_PATH=$4
+ local LOG_DIR=$5
+ local ROBOCASA_PYTHON=$6
+ local N_ENVS=$7
+ local MAX_EPISODE_STEPS=$8
+ local N_ACTION_STEPS=$9
+ local NUM_INFERENCE_STEPS=${10}
+ local SHIFT=${11}
+
+ local SAVE_ROOT=$(dirname "$(dirname "$CKPT_PATH")")
+ local ckpt_name=$(basename "$CKPT_PATH" .pt)
+ local VIDEO_OUT_PATH="${SAVE_ROOT}/videos/${ckpt_name}/$(basename "${LOG_DIR}")/${ENV_NAME}"
+ mkdir -p "${VIDEO_OUT_PATH}"
+
+ echo "Launching WM evaluation | GPU ${GPU_ID} | Port ${PORT} | Env ${ENV_NAME}"
+
+ CUDA_VISIBLE_DEVICES=${GPU_ID} \
+ MUJOCO_GL=egl \
+ PYOPENGL_PLATFORM=egl \
+ MUJOCO_EGL_DEVICE_ID=${GPU_ID} \
+ ${ROBOCASA_PYTHON} "${SIMULATION_SCRIPT}" \
+ --args.env_name "${ENV_NAME}" \
+ --args.port "${PORT}" \
+ --args.n_episodes 50 \
+ --args.n_envs "${N_ENVS}" \
+ --args.max_episode_steps "${MAX_EPISODE_STEPS}" \
+ --args.n_action_steps "${N_ACTION_STEPS}" \
+ --args.num_inference_steps "${NUM_INFERENCE_STEPS}" \
+ --args.shift "${SHIFT}" \
+ --args.video_out_path "${VIDEO_OUT_PATH}" \
+ --args.pretrained_path "${CKPT_PATH}" \
+ > "${LOG_DIR}/eval_env_${ENV_NAME//\//_}_gpu${GPU_ID}.log" 2>&1
+}
+
+ENV_NAMES=(
+ gr1_unified/PnPCupToDrawerClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPPotatoToMicrowaveClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPMilkToMicrowaveClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPBottleToCabinetClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPWineToCabinetClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPCanToDrawerClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToBasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToPanSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToPotSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToTieredbasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToBasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToBowlSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToPlateSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToTieredshelfSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToBowlSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToPanSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToPlateSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToPlateSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToPotSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToTieredbasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToTieredshelfSplitA_GR1ArmsAndWaistFourierHands_Env
+)
+
+LOG_DIR="${CKPT_PATH}.log/wm_eval_$(date +%Y%m%d_%H%M%S)"
+mkdir -p "${LOG_DIR}"
+
+echo "=== Launching WM Multi-GPU Evaluation ==="
+echo "GPUs : ${NUM_GPUS}"
+echo "Num Environments : ${#ENV_NAMES[@]}"
+echo "Log Directory : ${LOG_DIR}"
+
+# Kill any existing processes on target ports
+echo "Cleaning up stale processes on target ports..."
+for GPU_ID in $(seq 0 $((NUM_GPUS - 1))); do
+ PORT=$((BASE_PORT + GPU_ID))
+ PID=$(lsof -ti:${PORT} 2>/dev/null || true)
+ if [ -n "${PID}" ]; then
+ echo "Killing process ${PID} on port ${PORT}"
+ kill -9 ${PID} 2>/dev/null || true
+ fi
+done
+sleep 2
+
+for GPU_ID in $(seq 0 $((NUM_GPUS - 1))); do
+ PORT=$((BASE_PORT + GPU_ID))
+ echo "Starting policy server | GPU ${GPU_ID} | Port ${PORT}"
+
+ CUDA_VISIBLE_DEVICES=${GPU_ID} \
+ ${starVLA_PYTHON} deployment/model_server/server_policy.py \
+ --ckpt_path "${CKPT_PATH}" \
+ --port "${PORT}" \
+ --use_bf16 \
+ > "${LOG_DIR}/server_gpu${GPU_ID}_port${PORT}.log" 2>&1 &
+
+ SERVER_PIDS[$GPU_ID]=$!
+ sleep 10
+done
+
+sleep 30
+
+COUNT=0
+for ENV_NAME in "${ENV_NAMES[@]}"; do
+ GPU_ID=$((COUNT % NUM_GPUS))
+ PORT=$((BASE_PORT + GPU_ID))
+
+ if (( (COUNT + 1) % NUM_GPUS == 0 )); then
+ EvalEnv "${GPU_ID}" "${PORT}" "${ENV_NAME}" "${CKPT_PATH}" "${LOG_DIR}" \
+ "${ROBOCASA_PYTHON}" "${N_ENVS}" "${MAX_EPISODE_STEPS}" "${N_ACTION_STEPS}" "${NUM_INFERENCE_STEPS}" "${SHIFT}" &
+ EVAL_PIDS+=($!)
+ wait "${EVAL_PIDS[@]}"
+ EVAL_PIDS=()
+ else
+ EvalEnv "${GPU_ID}" "${PORT}" "${ENV_NAME}" "${CKPT_PATH}" "${LOG_DIR}" \
+ "${ROBOCASA_PYTHON}" "${N_ENVS}" "${MAX_EPISODE_STEPS}" "${N_ACTION_STEPS}" "${NUM_INFERENCE_STEPS}" "${SHIFT}" &
+ EVAL_PIDS+=($!)
+ fi
+
+ COUNT=$((COUNT + 1))
+ sleep 2
+done
+
+while pgrep -f "${SIMULATION_SCRIPT}" > /dev/null; do
+ echo "Waiting for all WM evaluation environments to finish..."
+ sleep 30
+done
+
+echo ""
+echo "Shutting down policy servers..."
+
+for PID in "${SERVER_PIDS[@]}"; do
+ kill_process_tree "${PID}" TERM
+ echo "Killed server PID ${PID}"
+done
+
+echo "=== WM Evaluation Finished ==="
+
+python summarize_eval_logs.py "${LOG_DIR}"
\ No newline at end of file
diff --git a/examples/Robocasa_tabletop/eval_files/.ipynb_checkpoints/batch_eval_args_wm_vjepa_back-checkpoint.sh b/examples/Robocasa_tabletop/eval_files/.ipynb_checkpoints/batch_eval_args_wm_vjepa_back-checkpoint.sh
new file mode 100644
index 0000000000000000000000000000000000000000..9e0b76ab3ea97eb44b2bf1d36e7e6bb568f18089
--- /dev/null
+++ b/examples/Robocasa_tabletop/eval_files/.ipynb_checkpoints/batch_eval_args_wm_vjepa_back-checkpoint.sh
@@ -0,0 +1,39 @@
+#!/bin/bash
+# Background wrapper for batch_eval_args_wm_vjepa_70000.sh
+
+EVAL_SCRIPT="$(cd "$(dirname "$0")" && pwd)/batch_eval_args_wm_vjepa_280000.sh"
+LOG_FILE="/mnt/workspace/users/maxiangkai/projects/WM4A/examples/Robocasa_tabletop/eval_files/eval_back_$(date +%Y%m%d_%H%M%S).log"
+mkdir -p "$(dirname "${LOG_FILE}")"
+
+if [ ! -f "${EVAL_SCRIPT}" ]; then
+ echo "ERROR: cannot find ${EVAL_SCRIPT}" >&2; exit 1
+fi
+
+nohup setsid bash "${EVAL_SCRIPT}" "$@" >"${LOG_FILE}" 2>&1 &
+EVAL_PID=$!
+disown "${EVAL_PID}" 2>/dev/null || true
+sleep 1
+
+ABS_LOG_FILE="$(cd "$(dirname "${LOG_FILE}")" && pwd)/$(basename "${LOG_FILE}")"
+
+cat </dev/null; echo ""; echo "Detached from log. Eval PID=${EVAL_PID} still running."; echo " Re-attach: tail -F ${ABS_LOG_FILE}"; exit 0' INT
+wait "${TAIL_PID}"
\ No newline at end of file
diff --git a/examples/Robocasa_tabletop/eval_files/adaptive_ensemble.py b/examples/Robocasa_tabletop/eval_files/adaptive_ensemble.py
new file mode 100644
index 0000000000000000000000000000000000000000..520f85cc53c72aff24208476cc96a6042f4fb6c7
--- /dev/null
+++ b/examples/Robocasa_tabletop/eval_files/adaptive_ensemble.py
@@ -0,0 +1,44 @@
+"""
+adaptive_ensemble.py
+
+"""
+
+from collections import deque
+import numpy as np
+
+
+class AdaptiveEnsembler:
+ def __init__(self, pred_action_horizon, adaptive_ensemble_alpha=0.0):
+ self.pred_action_horizon = pred_action_horizon
+ self.action_history = deque(maxlen=self.pred_action_horizon)
+ self.adaptive_ensemble_alpha = adaptive_ensemble_alpha
+
+ def reset(self):
+ self.action_history.clear()
+
+ def ensemble_action(self, cur_action):
+ self.action_history.append(cur_action)
+ num_actions = len(self.action_history)
+ if cur_action.ndim == 1:
+ curr_act_preds = np.stack(self.action_history)
+ else:
+ curr_act_preds = np.stack(
+ [pred_actions[i] for (i, pred_actions) in zip(range(num_actions - 1, -1, -1), self.action_history)]
+ )
+
+ # calculate cosine similarity between the current prediction and all previous predictions
+ ref = curr_act_preds[num_actions-1, :]
+ previous_pred = curr_act_preds
+ dot_product = np.sum(previous_pred * ref, axis=1)
+ norm_previous_pred = np.linalg.norm(previous_pred, axis=1)
+ norm_ref = np.linalg.norm(ref)
+ cos_similarity = dot_product / (norm_previous_pred * norm_ref + 1e-7)
+
+ # compute the weights for each prediction
+ weights = np.exp(self.adaptive_ensemble_alpha * cos_similarity)
+ weights = weights / weights.sum()
+
+ # compute the weighted average across all predictions for this timestep
+ cur_action = np.sum(weights[:, None] * curr_act_preds, axis=0)
+
+ return cur_action
\ No newline at end of file
diff --git a/examples/Robocasa_tabletop/eval_files/base_config.py b/examples/Robocasa_tabletop/eval_files/base_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..020e071824a297cd11933583ae1967224dc17a0a
--- /dev/null
+++ b/examples/Robocasa_tabletop/eval_files/base_config.py
@@ -0,0 +1,33 @@
+from pydantic import BaseModel
+from abc import ABC, abstractmethod
+from typing import Dict, Any
+
+class ModalityConfig(BaseModel):
+ """Configuration for a modality."""
+
+ delta_indices: list[int]
+ """Delta indices to sample relative to the current index. The returned data will correspond to the original data at a sampled base index + delta indices."""
+ modality_keys: list[str]
+ """The keys to load for the modality in the dataset."""
+
+
+class BasePolicy(ABC):
+ @abstractmethod
+ def get_action(self, observations: Dict[str, Any]) -> Dict[str, Any]:
+ """
+ Abstract method to get the action for a given state.
+
+ Args:
+ observations: The observations from the environment.
+
+ Returns:
+ The action to take in the environment in dictionary format.
+ """
+ raise NotImplementedError
+
+ @abstractmethod
+ def get_modality_config(self) -> Dict[str, ModalityConfig]:
+ """
+ Return the modality config of the policy.
+ """
+ raise NotImplementedError
diff --git a/examples/Robocasa_tabletop/eval_files/batch_eval_args.sh b/examples/Robocasa_tabletop/eval_files/batch_eval_args.sh
new file mode 100644
index 0000000000000000000000000000000000000000..7aa1408ca758f223630527b8d6f91fb6f5796c3f
--- /dev/null
+++ b/examples/Robocasa_tabletop/eval_files/batch_eval_args.sh
@@ -0,0 +1,257 @@
+#!/bin/bash
+
+# ============================================================
+# Argument Parsing
+# ============================================================
+###########################################################################################
+# === Please modify the paths to Python executables in conda environments ===
+
+export OMP_NUM_THREADS=1
+export MKL_NUM_THREADS=1
+export OPENBLAS_NUM_THREADS=1
+
+
+# export LD_LIBRARY_PATH=/tmp/nvidia-gl-extract/usr/lib/x86_64-linux-gnu:$LD_LIBRARY_PATH
+# export VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/nvidia_icd.json
+
+# NVIDIA H200 EGL Rendering Path
+export LD_LIBRARY_PATH=/mnt/workspace/lib/nvidia_egl:\$LD_LIBRARY_PATH
+export PYOPENGL_PLATFORM=egl
+export __GLX_VENDOR_LIBRARY_NAME=nvidia
+export MUJOCO_GL=egl
+
+cd /mnt/workspace/users/yuanzhihao/code/starVLA
+starVLA_PYTHON=/mnt/workspace/envs/conda3/envs/starVLA_1/bin/python
+ROBOCASA_PYTHON=/mnt/workspace/envs/conda3/envs/robocasa/bin/python
+export PYTHONPATH=$(pwd):${PYTHONPATH}
+CKPT_DEFAULT="/mnt/workspace/users/yuanzhihao/code/starVLA/outputs/cosmopredict25_perceiver_robocasa_teleop_ee/checkpoints/steps_300000_pytorch_model.pt"
+# CKPT_DEFAULT="/mnt/workspace/users/yuanzhihao/code/starVLA/outputs/StarVLA_Qwen3_VL_GR00T_Robocasa_gr1/checkpoints/steps_90000_pytorch_model.pt"
+
+# === End of environment variable configuration ===
+###########################################################################################
+
+N_ENVS_DEFAULT=1
+MAX_EPISODE_STEPS_DEFAULT=720
+N_ACTION_STEPS_DEFAULT=12
+
+BASE_PORT=9999
+NUM_GPUS=2
+
+# Parse command-line arguments
+CKPT_PATH=${1:-$CKPT_DEFAULT}
+N_ENVS=${2:-$N_ENVS_DEFAULT}
+MAX_EPISODE_STEPS=${3:-$MAX_EPISODE_STEPS_DEFAULT}
+N_ACTION_STEPS=${4:-$N_ACTION_STEPS_DEFAULT}
+
+
+echo "=== Evaluation Configuration ==="
+echo "Checkpoint Path : ${CKPT_PATH}"
+echo "Number of Envs : ${N_ENVS}"
+echo "Max Episode Steps : ${MAX_EPISODE_STEPS}"
+echo "Action Chunk Length : ${N_ACTION_STEPS}"
+echo "================================"
+
+SERVER_PIDS=()
+EVAL_PIDS=()
+CLEANED_UP=0
+
+kill_process_tree() {
+ local PID=$1
+ local SIGNAL=${2:-TERM}
+
+ if [[ -z "${PID}" ]] || ! kill -0 "${PID}" 2>/dev/null; then
+ return
+ fi
+
+ local CHILD_PIDS
+ CHILD_PIDS=$(pgrep -P "${PID}" 2>/dev/null || true)
+ for CHILD_PID in ${CHILD_PIDS}; do
+ kill_process_tree "${CHILD_PID}" "${SIGNAL}"
+ done
+
+ kill -"${SIGNAL}" "${PID}" 2>/dev/null || true
+}
+
+cleanup() {
+ local EXIT_CODE=$?
+ if [[ "${CLEANED_UP}" -eq 1 ]]; then
+ exit "${EXIT_CODE}"
+ fi
+ CLEANED_UP=1
+
+ trap - INT TERM EXIT
+
+ echo ""
+ echo "Cleaning up evaluation processes..."
+
+ for PID in "${EVAL_PIDS[@]}" "${SERVER_PIDS[@]}"; do
+ kill_process_tree "${PID}" TERM
+ done
+
+ sleep 2
+
+ for PID in "${EVAL_PIDS[@]}" "${SERVER_PIDS[@]}"; do
+ kill_process_tree "${PID}" KILL
+ done
+
+ wait 2>/dev/null || true
+ echo "Cleanup finished."
+ exit "${EXIT_CODE}"
+}
+
+trap cleanup INT TERM EXIT
+
+# ============================================================
+# Evaluation Function
+# ============================================================
+
+EvalEnv() {
+ local GPU_ID=$1
+ local PORT=$2
+ local ENV_NAME=$3
+ local CKPT_PATH=$4
+ local LOG_DIR=$5
+ local ROBOCASA_PYTHON=$6
+ local N_ENVS=$7
+ local MAX_EPISODE_STEPS=$8
+ local N_ACTION_STEPS=$9
+ local SIMULATION_SCRIPT="${SIMULATION_SCRIPT:-examples/Robocasa_tabletop/eval_files/simulation_env.py}"
+ # save root CKPT_PATH 的 parent 文件夹
+ local SAVE_ROOT=$(dirname "$(dirname "$CKPT_PATH")")
+ local ckpt_name=$(basename "$CKPT_PATH" .pt)
+ local VIDEO_OUT_PATH="${SAVE_ROOT}/videos/${ckpt_name}/n_action_steps_${N_ACTION_STEPS}_max_episode_steps_${MAX_EPISODE_STEPS}_n_envs_${N_ENVS}_${ENV_NAME}"
+ mkdir -p "${VIDEO_OUT_PATH}"
+
+ echo "Launching evaluation | GPU ${GPU_ID} | Port ${PORT} | Env ${ENV_NAME}"
+
+ CUDA_VISIBLE_DEVICES=${GPU_ID} \
+ MUJOCO_GL=egl \
+ PYOPENGL_PLATFORM=egl \
+ EGL_VISIBLE_DEVICES=0 \
+ MUJOCO_EGL_DEVICE_ID=0 \
+ ${ROBOCASA_PYTHON} "${SIMULATION_SCRIPT}" \
+ --args.env_name "${ENV_NAME}" \
+ --args.port "${PORT}" \
+ --args.n_episodes 50 \
+ --args.n_envs "${N_ENVS}" \
+ --args.max_episode_steps "${MAX_EPISODE_STEPS}" \
+ --args.n_action_steps "${N_ACTION_STEPS}" \
+ --args.video_out_path "${VIDEO_OUT_PATH}" \
+ --args.pretrained_path "${CKPT_PATH}" \
+ > "${LOG_DIR}/eval_env_${ENV_NAME//\//_}_gpu${GPU_ID}.log" 2>&1
+}
+
+# ============================================================
+# Environment List
+# ============================================================
+
+ENV_NAMES=(
+ gr1_unified/PnPCupToDrawerClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPPotatoToMicrowaveClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPMilkToMicrowaveClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPBottleToCabinetClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPWineToCabinetClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPCanToDrawerClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToBasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToPanSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToPotSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToTieredbasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToBasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToBowlSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToPlateSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToTieredshelfSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToBowlSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToPanSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToPlateSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToPlateSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToPotSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToTieredbasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToTieredshelfSplitA_GR1ArmsAndWaistFourierHands_Env
+)
+
+# ============================================================
+# Runtime Configuration
+# ============================================================
+
+
+
+LOG_DIR="${CKPT_PATH}.log/eval_$(date +%Y%m%d_%H%M%S)"
+mkdir -p "${LOG_DIR}"
+
+echo "=== Launching Multi-GPU Evaluation ==="
+echo "GPUs : ${NUM_GPUS}"
+echo "Num Environments: ${#ENV_NAMES[@]}"
+echo "Log Directory : ${LOG_DIR}"
+
+# ============================================================
+# Step 1: Launch Policy Servers
+# ============================================================
+
+for GPU_ID in $(seq 0 $((NUM_GPUS - 1))); do
+ PORT=$((BASE_PORT + GPU_ID))
+ echo "Starting policy server | GPU ${GPU_ID} | Port ${PORT}"
+
+ CUDA_VISIBLE_DEVICES=${GPU_ID} \
+ ${starVLA_PYTHON} deployment/model_server/server_policy.py \
+ --ckpt_path "${CKPT_PATH}" \
+ --port "${PORT}" \
+ --use_bf16 \
+ > "${LOG_DIR}/server_gpu${GPU_ID}_port${PORT}.log" 2>&1 &
+
+ SERVER_PIDS[$GPU_ID]=$!
+
+ sleep 10
+done
+
+sleep 30
+
+# ============================================================
+# Step 2: Dispatch Environments to GPUs
+# ============================================================
+
+COUNT=0
+for ENV_NAME in "${ENV_NAMES[@]}"; do
+ GPU_ID=$((COUNT % NUM_GPUS))
+ PORT=$((BASE_PORT + GPU_ID))
+
+ if (( (COUNT + 1) % NUM_GPUS == 0 )); then
+ EvalEnv "${GPU_ID}" "${PORT}" "${ENV_NAME}" "${CKPT_PATH}" "${LOG_DIR}" \
+ "${ROBOCASA_PYTHON}" "${N_ENVS}" "${MAX_EPISODE_STEPS}" "${N_ACTION_STEPS}" &
+ EVAL_PIDS+=($!)
+ wait "${EVAL_PIDS[@]}"
+ EVAL_PIDS=()
+ else
+ EvalEnv "${GPU_ID}" "${PORT}" "${ENV_NAME}" "${CKPT_PATH}" "${LOG_DIR}" \
+ "${ROBOCASA_PYTHON}" "${N_ENVS}" "${MAX_EPISODE_STEPS}" "${N_ACTION_STEPS}" &
+ EVAL_PIDS+=($!)
+ fi
+
+ COUNT=$((COUNT + 1))
+
+ sleep 2
+done
+
+# ============================================================
+# Step 3: Cleanup
+# ============================================================
+
+# 判断是否还有 examples/Robocasa_tabletop/eval_files/simulation_env.py
+while pgrep -f "examples/Robocasa_tabletop/eval_files/simulation_env.py" > /dev/null; do
+ echo "Waiting for all evaluation environments to finish..."
+ sleep 30
+done
+
+echo ""
+echo "Shutting down policy servers..."
+
+for PID in "${SERVER_PIDS[@]}"; do
+ kill_process_tree "${PID}" TERM
+ echo "Killed server PID ${PID}"
+done
+
+echo "=== Evaluation Finished ==="
+
+python summarize_eval_logs.py ${LOG_DIR}
diff --git a/examples/Robocasa_tabletop/eval_files/batch_eval_args_wm.sh b/examples/Robocasa_tabletop/eval_files/batch_eval_args_wm.sh
new file mode 100644
index 0000000000000000000000000000000000000000..374a3c7d00760232c577c4a6af2c0f54d0ff214a
--- /dev/null
+++ b/examples/Robocasa_tabletop/eval_files/batch_eval_args_wm.sh
@@ -0,0 +1,232 @@
+#!/bin/bash
+
+# ============================================================
+# WM Evaluation Script
+# ============================================================
+
+export OMP_NUM_THREADS=1
+export MKL_NUM_THREADS=1
+export OPENBLAS_NUM_THREADS=1
+
+# NVIDIA H200 EGL Rendering Path
+export LD_LIBRARY_PATH=/mnt/workspace/lib/nvidia_egl:\$LD_LIBRARY_PATH
+export PYOPENGL_PLATFORM=egl
+export __GLX_VENDOR_LIBRARY_NAME=nvidia
+export MUJOCO_GL=egl
+export STARVLA_WM_DEBUG=${STARVLA_WM_DEBUG:-0}
+export STARVLA_WM_DEBUG_MAX=${STARVLA_WM_DEBUG_MAX:-6}
+export STARVLA_ACTION_DEBUG=${STARVLA_ACTION_DEBUG:-0}
+export STARVLA_ACTION_DEBUG_MAX=${STARVLA_ACTION_DEBUG_MAX:-20}
+
+cd /mnt/workspace/users/yuanzhihao/code/starVLA
+starVLA_PYTHON=/mnt/workspace/envs/conda3/envs/starVLA_1/bin/python
+ROBOCASA_PYTHON=/mnt/workspace/envs/conda3/envs/robocasa/bin/python
+export PYTHONPATH=$(pwd):${PYTHONPATH}
+
+CKPT_DEFAULT="/mnt/workspace/users/yuanzhihao/code/starVLA/outputs1/cosmopredict25_perceiver_dit4dit/robocasa_teleop_ee_new_head_goal_image/checkpoints/steps_250000_pytorch_model.pt"
+SIMULATION_SCRIPT="examples/Robocasa_tabletop/eval_files/simulation_env_wm.py"
+
+N_ENVS_DEFAULT=1
+MAX_EPISODE_STEPS_DEFAULT=720
+N_ACTION_STEPS_DEFAULT=12
+NUM_INFERENCE_STEPS_DEFAULT=5
+SHIFT_DEFAULT=5.0
+
+BASE_PORT=9999
+NUM_GPUS=8
+
+CKPT_PATH=${1:-$CKPT_DEFAULT}
+N_ENVS=${2:-$N_ENVS_DEFAULT}
+MAX_EPISODE_STEPS=${3:-$MAX_EPISODE_STEPS_DEFAULT}
+N_ACTION_STEPS=${4:-$N_ACTION_STEPS_DEFAULT}
+NUM_INFERENCE_STEPS=${5:-$NUM_INFERENCE_STEPS_DEFAULT}
+SHIFT=${6:-$SHIFT_DEFAULT}
+
+echo "=== WM Evaluation Configuration ==="
+echo "Checkpoint Path : ${CKPT_PATH}"
+echo "Number of Envs : ${N_ENVS}"
+echo "Max Episode Steps : ${MAX_EPISODE_STEPS}"
+echo "Action Chunk Length : ${N_ACTION_STEPS}"
+echo "Inference Steps : ${NUM_INFERENCE_STEPS}"
+echo "RF Shift : ${SHIFT}"
+echo "Simulation Script : ${SIMULATION_SCRIPT}"
+echo "==================================="
+
+SERVER_PIDS=()
+EVAL_PIDS=()
+CLEANED_UP=0
+
+kill_process_tree() {
+ local PID=$1
+ local SIGNAL=${2:-TERM}
+
+ if [[ -z "${PID}" ]] || ! kill -0 "${PID}" 2>/dev/null; then
+ return
+ fi
+
+ local CHILD_PIDS
+ CHILD_PIDS=$(pgrep -P "${PID}" 2>/dev/null || true)
+ for CHILD_PID in ${CHILD_PIDS}; do
+ kill_process_tree "${CHILD_PID}" "${SIGNAL}"
+ done
+
+ kill -"${SIGNAL}" "${PID}" 2>/dev/null || true
+}
+
+cleanup() {
+ local EXIT_CODE=$?
+ if [[ "${CLEANED_UP}" -eq 1 ]]; then
+ exit "${EXIT_CODE}"
+ fi
+ CLEANED_UP=1
+
+ trap - INT TERM EXIT
+
+ echo ""
+ echo "Cleaning up WM evaluation processes..."
+
+ for PID in "${EVAL_PIDS[@]}" "${SERVER_PIDS[@]}"; do
+ kill_process_tree "${PID}" TERM
+ done
+
+ sleep 2
+
+ for PID in "${EVAL_PIDS[@]}" "${SERVER_PIDS[@]}"; do
+ kill_process_tree "${PID}" KILL
+ done
+
+ wait 2>/dev/null || true
+ echo "Cleanup finished."
+ exit "${EXIT_CODE}"
+}
+
+trap cleanup INT TERM EXIT
+
+EvalEnv() {
+ local GPU_ID=$1
+ local PORT=$2
+ local ENV_NAME=$3
+ local CKPT_PATH=$4
+ local LOG_DIR=$5
+ local ROBOCASA_PYTHON=$6
+ local N_ENVS=$7
+ local MAX_EPISODE_STEPS=$8
+ local N_ACTION_STEPS=$9
+ local NUM_INFERENCE_STEPS=${10}
+ local SHIFT=${11}
+
+ local SAVE_ROOT=$(dirname "$(dirname "$CKPT_PATH")")
+ local ckpt_name=$(basename "$CKPT_PATH" .pt)
+ local VIDEO_OUT_PATH="${SAVE_ROOT}/videos/${ckpt_name}/$(basename "${LOG_DIR}")/${ENV_NAME}"
+ mkdir -p "${VIDEO_OUT_PATH}"
+
+ echo "Launching WM evaluation | GPU ${GPU_ID} | Port ${PORT} | Env ${ENV_NAME}"
+
+ CUDA_VISIBLE_DEVICES=${GPU_ID} \
+ MUJOCO_GL=egl \
+ PYOPENGL_PLATFORM=egl \
+ EGL_VISIBLE_DEVICES=0 \
+ MUJOCO_EGL_DEVICE_ID=0 \
+ ${ROBOCASA_PYTHON} "${SIMULATION_SCRIPT}" \
+ --args.env_name "${ENV_NAME}" \
+ --args.port "${PORT}" \
+ --args.n_episodes 50 \
+ --args.n_envs "${N_ENVS}" \
+ --args.max_episode_steps "${MAX_EPISODE_STEPS}" \
+ --args.n_action_steps "${N_ACTION_STEPS}" \
+ --args.num_inference_steps "${NUM_INFERENCE_STEPS}" \
+ --args.shift "${SHIFT}" \
+ --args.video_out_path "${VIDEO_OUT_PATH}" \
+ --args.pretrained_path "${CKPT_PATH}" \
+ > "${LOG_DIR}/eval_env_${ENV_NAME//\//_}_gpu${GPU_ID}.log" 2>&1
+}
+
+ENV_NAMES=(
+ gr1_unified/PnPCupToDrawerClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPPotatoToMicrowaveClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPMilkToMicrowaveClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPBottleToCabinetClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPWineToCabinetClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPCanToDrawerClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToBasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToPanSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToPotSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToTieredbasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToBasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToBowlSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToPlateSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToTieredshelfSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToBowlSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToPanSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToPlateSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToPlateSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToPotSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToTieredbasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToTieredshelfSplitA_GR1ArmsAndWaistFourierHands_Env
+)
+
+LOG_DIR="${CKPT_PATH}.log/wm_eval_$(date +%Y%m%d_%H%M%S)"
+mkdir -p "${LOG_DIR}"
+
+echo "=== Launching WM Multi-GPU Evaluation ==="
+echo "GPUs : ${NUM_GPUS}"
+echo "Num Environments : ${#ENV_NAMES[@]}"
+echo "Log Directory : ${LOG_DIR}"
+
+for GPU_ID in $(seq 0 $((NUM_GPUS - 1))); do
+ PORT=$((BASE_PORT + GPU_ID))
+ echo "Starting policy server | GPU ${GPU_ID} | Port ${PORT}"
+
+ CUDA_VISIBLE_DEVICES=${GPU_ID} \
+ ${starVLA_PYTHON} deployment/model_server/server_policy.py \
+ --ckpt_path "${CKPT_PATH}" \
+ --port "${PORT}" \
+ --use_bf16 \
+ > "${LOG_DIR}/server_gpu${GPU_ID}_port${PORT}.log" 2>&1 &
+
+ SERVER_PIDS[$GPU_ID]=$!
+ sleep 10
+done
+
+sleep 30
+
+COUNT=0
+for ENV_NAME in "${ENV_NAMES[@]}"; do
+ GPU_ID=$((COUNT % NUM_GPUS))
+ PORT=$((BASE_PORT + GPU_ID))
+
+ if (( (COUNT + 1) % NUM_GPUS == 0 )); then
+ EvalEnv "${GPU_ID}" "${PORT}" "${ENV_NAME}" "${CKPT_PATH}" "${LOG_DIR}" \
+ "${ROBOCASA_PYTHON}" "${N_ENVS}" "${MAX_EPISODE_STEPS}" "${N_ACTION_STEPS}" "${NUM_INFERENCE_STEPS}" "${SHIFT}" &
+ EVAL_PIDS+=($!)
+ wait "${EVAL_PIDS[@]}"
+ EVAL_PIDS=()
+ else
+ EvalEnv "${GPU_ID}" "${PORT}" "${ENV_NAME}" "${CKPT_PATH}" "${LOG_DIR}" \
+ "${ROBOCASA_PYTHON}" "${N_ENVS}" "${MAX_EPISODE_STEPS}" "${N_ACTION_STEPS}" "${NUM_INFERENCE_STEPS}" "${SHIFT}" &
+ EVAL_PIDS+=($!)
+ fi
+
+ COUNT=$((COUNT + 1))
+ sleep 2
+done
+
+while pgrep -f "${SIMULATION_SCRIPT}" > /dev/null; do
+ echo "Waiting for all WM evaluation environments to finish..."
+ sleep 30
+done
+
+echo ""
+echo "Shutting down policy servers..."
+
+for PID in "${SERVER_PIDS[@]}"; do
+ kill_process_tree "${PID}" TERM
+ echo "Killed server PID ${PID}"
+done
+
+echo "=== WM Evaluation Finished ==="
+
+python summarize_eval_logs.py "${LOG_DIR}"
diff --git a/examples/Robocasa_tabletop/eval_files/batch_eval_args_wm_dino_100000.sh b/examples/Robocasa_tabletop/eval_files/batch_eval_args_wm_dino_100000.sh
new file mode 100644
index 0000000000000000000000000000000000000000..135af6846cf082173ae9b268bdf149d325bc3042
--- /dev/null
+++ b/examples/Robocasa_tabletop/eval_files/batch_eval_args_wm_dino_100000.sh
@@ -0,0 +1,245 @@
+#!/bin/bash
+
+# ============================================================
+# WM Evaluation Script for wam_dino_100000 model
+# Based on batch_eval_args_wm.sh, adapted for maxiangkai's WM4A project
+# ============================================================
+
+export OMP_NUM_THREADS=1
+export MKL_NUM_THREADS=1
+export OPENBLAS_NUM_THREADS=1
+
+# NVIDIA H200 EGL Rendering Path
+export LD_LIBRARY_PATH=/mnt/workspace/lib/nvidia_egl:\$LD_LIBRARY_PATH
+export PYOPENGL_PLATFORM=egl
+export __GLX_VENDOR_LIBRARY_NAME=nvidia
+export MUJOCO_GL=egl
+export STARVLA_WM_DEBUG=${STARVLA_WM_DEBUG:-0}
+export STARVLA_WM_DEBUG_MAX=${STARVLA_WM_DEBUG_MAX:-6}
+export STARVLA_ACTION_DEBUG=${STARVLA_ACTION_DEBUG:-0}
+export STARVLA_ACTION_DEBUG_MAX=${STARVLA_ACTION_DEBUG_MAX:-20}
+
+cd /mnt/workspace/users/maxiangkai/projects/WM4A
+starVLA_PYTHON=/mnt/workspace/envs/conda3/envs/starVLA_1/bin/python
+ROBOCASA_PYTHON=/mnt/workspace/envs/conda3/envs/robocasa/bin/python
+export PYTHONPATH=$(pwd):${PYTHONPATH}
+export PYTHONPATH="${PYTHONPATH}:/mnt/workspace/users/maxiangkai/projects/WM4A:/mnt/workspace/users/maxiangkai/projects/WM4A/starVLA/facebookresearch_vjepa2_main"
+
+CKPT_DEFAULT="/mnt/workspace/users/maxiangkai/projects/WM4A/outputs/cosmopredict25_dino/robocasa_dino_06-13-19-42/checkpoints/steps_100000_pytorch_model.pt"
+SIMULATION_SCRIPT="examples/Robocasa_tabletop/eval_files/simulation_env_wm.py"
+
+N_ENVS_DEFAULT=1
+MAX_EPISODE_STEPS_DEFAULT=720
+N_ACTION_STEPS_DEFAULT=12
+NUM_INFERENCE_STEPS_DEFAULT=5
+SHIFT_DEFAULT=5.0
+
+BASE_PORT=29999
+NUM_GPUS=2 # mytest
+
+CKPT_PATH=${1:-$CKPT_DEFAULT}
+N_ENVS=${2:-$N_ENVS_DEFAULT}
+MAX_EPISODE_STEPS=${3:-$MAX_EPISODE_STEPS_DEFAULT}
+N_ACTION_STEPS=${4:-$N_ACTION_STEPS_DEFAULT}
+NUM_INFERENCE_STEPS=${5:-$NUM_INFERENCE_STEPS_DEFAULT}
+SHIFT=${6:-$SHIFT_DEFAULT}
+
+echo "=== WM Evaluation Configuration ==="
+echo "Checkpoint Path : ${CKPT_PATH}"
+echo "Number of Envs : ${N_ENVS}"
+echo "Max Episode Steps : ${MAX_EPISODE_STEPS}"
+echo "Action Chunk Length : ${N_ACTION_STEPS}"
+echo "Inference Steps : ${NUM_INFERENCE_STEPS}"
+echo "RF Shift : ${SHIFT}"
+echo "Simulation Script : ${SIMULATION_SCRIPT}"
+echo "==================================="
+
+SERVER_PIDS=()
+EVAL_PIDS=()
+CLEANED_UP=0
+
+kill_process_tree() {
+ local PID=$1
+ local SIGNAL=${2:-TERM}
+
+ if [[ -z "${PID}" ]] || ! kill -0 "${PID}" 2>/dev/null; then
+ return
+ fi
+
+ local CHILD_PIDS
+ CHILD_PIDS=$(pgrep -P "${PID}" 2>/dev/null || true)
+ for CHILD_PID in ${CHILD_PIDS}; do
+ kill_process_tree "${CHILD_PID}" "${SIGNAL}"
+ done
+
+ kill -"${SIGNAL}" "${PID}" 2>/dev/null || true
+}
+
+cleanup() {
+ local EXIT_CODE=$?
+ if [[ "${CLEANED_UP}" -eq 1 ]]; then
+ exit "${EXIT_CODE}"
+ fi
+ CLEANED_UP=1
+
+ trap - INT TERM EXIT
+
+ echo ""
+ echo "Cleaning up WM evaluation processes..."
+
+ for PID in "${EVAL_PIDS[@]}" "${SERVER_PIDS[@]}"; do
+ kill_process_tree "${PID}" TERM
+ done
+
+ sleep 2
+
+ for PID in "${EVAL_PIDS[@]}" "${SERVER_PIDS[@]}"; do
+ kill_process_tree "${PID}" KILL
+ done
+
+ wait 2>/dev/null || true
+ echo "Cleanup finished."
+ exit "${EXIT_CODE}"
+}
+
+trap cleanup INT TERM EXIT
+
+EvalEnv() {
+ local GPU_ID=$1
+ local PORT=$2
+ local ENV_NAME=$3
+ local CKPT_PATH=$4
+ local LOG_DIR=$5
+ local ROBOCASA_PYTHON=$6
+ local N_ENVS=$7
+ local MAX_EPISODE_STEPS=$8
+ local N_ACTION_STEPS=$9
+ local NUM_INFERENCE_STEPS=${10}
+ local SHIFT=${11}
+
+ local SAVE_ROOT=$(dirname "$(dirname "$CKPT_PATH")")
+ local ckpt_name=$(basename "$CKPT_PATH" .pt)
+ local VIDEO_OUT_PATH="${SAVE_ROOT}/videos/${ckpt_name}/$(basename "${LOG_DIR}")/${ENV_NAME}"
+ mkdir -p "${VIDEO_OUT_PATH}"
+
+ echo "Launching WM evaluation | GPU ${GPU_ID} | Port ${PORT} | Env ${ENV_NAME}"
+
+ CUDA_VISIBLE_DEVICES=${GPU_ID} \
+ MUJOCO_GL=egl \
+ PYOPENGL_PLATFORM=egl \
+ MUJOCO_EGL_DEVICE_ID=${GPU_ID} \
+ ${ROBOCASA_PYTHON} "${SIMULATION_SCRIPT}" \
+ --args.env_name "${ENV_NAME}" \
+ --args.port "${PORT}" \
+ --args.n_episodes 50 \
+ --args.n_envs "${N_ENVS}" \
+ --args.max_episode_steps "${MAX_EPISODE_STEPS}" \
+ --args.n_action_steps "${N_ACTION_STEPS}" \
+ --args.num_inference_steps "${NUM_INFERENCE_STEPS}" \
+ --args.shift "${SHIFT}" \
+ --args.video_out_path "${VIDEO_OUT_PATH}" \
+ --args.pretrained_path "${CKPT_PATH}" \
+ > "${LOG_DIR}/eval_env_${ENV_NAME//\//_}_gpu${GPU_ID}.log" 2>&1
+}
+
+ENV_NAMES=(
+ gr1_unified/PnPCupToDrawerClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPPotatoToMicrowaveClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPMilkToMicrowaveClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPBottleToCabinetClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPWineToCabinetClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPCanToDrawerClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToBasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToPanSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToPotSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToTieredbasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToBasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToBowlSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToPlateSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToTieredshelfSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToBowlSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToPanSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToPlateSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToPlateSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToPotSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToTieredbasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToTieredshelfSplitA_GR1ArmsAndWaistFourierHands_Env
+)
+
+LOG_DIR="${CKPT_PATH}.log/wm_eval_$(date +%Y%m%d_%H%M%S)"
+mkdir -p "${LOG_DIR}"
+
+echo "=== Launching WM Multi-GPU Evaluation ==="
+echo "GPUs : ${NUM_GPUS}"
+echo "Num Environments : ${#ENV_NAMES[@]}"
+echo "Log Directory : ${LOG_DIR}"
+
+# Kill any existing processes on target ports
+echo "Cleaning up stale processes on target ports..."
+for GPU_ID in $(seq 0 $((NUM_GPUS - 1))); do
+ PORT=$((BASE_PORT + GPU_ID))
+ PID=$(lsof -ti:${PORT} 2>/dev/null || true)
+ if [ -n "${PID}" ]; then
+ echo "Killing process ${PID} on port ${PORT}"
+ kill -9 ${PID} 2>/dev/null || true
+ fi
+done
+sleep 2
+
+for GPU_ID in $(seq 0 $((NUM_GPUS - 1))); do
+ PORT=$((BASE_PORT + GPU_ID))
+ echo "Starting policy server | GPU ${GPU_ID} | Port ${PORT}"
+
+ CUDA_VISIBLE_DEVICES=${GPU_ID} \
+ ${starVLA_PYTHON} deployment/model_server/server_policy.py \
+ --ckpt_path "${CKPT_PATH}" \
+ --port "${PORT}" \
+ --use_bf16 \
+ > "${LOG_DIR}/server_gpu${GPU_ID}_port${PORT}.log" 2>&1 &
+
+ SERVER_PIDS[$GPU_ID]=$!
+ sleep 10
+done
+
+sleep 30
+
+COUNT=0
+for ENV_NAME in "${ENV_NAMES[@]}"; do
+ GPU_ID=$((COUNT % NUM_GPUS))
+ PORT=$((BASE_PORT + GPU_ID))
+
+ if (( (COUNT + 1) % NUM_GPUS == 0 )); then
+ EvalEnv "${GPU_ID}" "${PORT}" "${ENV_NAME}" "${CKPT_PATH}" "${LOG_DIR}" \
+ "${ROBOCASA_PYTHON}" "${N_ENVS}" "${MAX_EPISODE_STEPS}" "${N_ACTION_STEPS}" "${NUM_INFERENCE_STEPS}" "${SHIFT}" &
+ EVAL_PIDS+=($!)
+ wait "${EVAL_PIDS[@]}"
+ EVAL_PIDS=()
+ else
+ EvalEnv "${GPU_ID}" "${PORT}" "${ENV_NAME}" "${CKPT_PATH}" "${LOG_DIR}" \
+ "${ROBOCASA_PYTHON}" "${N_ENVS}" "${MAX_EPISODE_STEPS}" "${N_ACTION_STEPS}" "${NUM_INFERENCE_STEPS}" "${SHIFT}" &
+ EVAL_PIDS+=($!)
+ fi
+
+ COUNT=$((COUNT + 1))
+ sleep 2
+done
+
+while pgrep -f "${SIMULATION_SCRIPT}" > /dev/null; do
+ echo "Waiting for all WM evaluation environments to finish..."
+ sleep 30
+done
+
+echo ""
+echo "Shutting down policy servers..."
+
+for PID in "${SERVER_PIDS[@]}"; do
+ kill_process_tree "${PID}" TERM
+ echo "Killed server PID ${PID}"
+done
+
+echo "=== WM Evaluation Finished ==="
+
+python summarize_eval_logs.py "${LOG_DIR}"
\ No newline at end of file
diff --git a/examples/Robocasa_tabletop/eval_files/batch_eval_args_wm_dino_back.sh b/examples/Robocasa_tabletop/eval_files/batch_eval_args_wm_dino_back.sh
new file mode 100644
index 0000000000000000000000000000000000000000..044cdc595d61c9c69464ced2679ed7f2dcd717bc
--- /dev/null
+++ b/examples/Robocasa_tabletop/eval_files/batch_eval_args_wm_dino_back.sh
@@ -0,0 +1,39 @@
+#!/bin/bash
+# Background wrapper for batch_eval_args_wm_dino_100000.sh
+
+EVAL_SCRIPT="$(cd "$(dirname "$0")" && pwd)/batch_eval_args_wm_dino_100000.sh"
+LOG_FILE="/mnt/workspace/users/maxiangkai/projects/WM4A/outputs/cosmopredict25_dino/robocasa_dino_06-13-19-42/eval_back_$(date +%Y%m%d_%H%M%S).log"
+mkdir -p "$(dirname "${LOG_FILE}")"
+
+if [ ! -f "${EVAL_SCRIPT}" ]; then
+ echo "ERROR: cannot find ${EVAL_SCRIPT}" >&2; exit 1
+fi
+
+nohup setsid bash "${EVAL_SCRIPT}" "$@" >"${LOG_FILE}" 2>&1 &
+EVAL_PID=$!
+disown "${EVAL_PID}" 2>/dev/null || true
+sleep 1
+
+ABS_LOG_FILE="$(cd "$(dirname "${LOG_FILE}")" && pwd)/$(basename "${LOG_FILE}")"
+
+cat </dev/null; echo ""; echo "Detached from log. Eval PID=${EVAL_PID} still running."; echo " Re-attach: tail -F ${ABS_LOG_FILE}"; exit 0' INT
+wait "${TAIL_PID}"
\ No newline at end of file
diff --git a/examples/Robocasa_tabletop/eval_files/batch_eval_args_wm_joyra05.sh b/examples/Robocasa_tabletop/eval_files/batch_eval_args_wm_joyra05.sh
new file mode 100644
index 0000000000000000000000000000000000000000..a6bc3be9967cbc19e697fdb6981c714f0cd364f4
--- /dev/null
+++ b/examples/Robocasa_tabletop/eval_files/batch_eval_args_wm_joyra05.sh
@@ -0,0 +1,246 @@
+#!/bin/bash
+
+# ============================================================
+# WM Evaluation Script for wam_vjepa_70000 model
+# Based on batch_eval_args_wm.sh, adapted for maxiangkai's WM4A project
+# ============================================================
+
+export OMP_NUM_THREADS=1
+export MKL_NUM_THREADS=1
+export OPENBLAS_NUM_THREADS=1
+
+# NVIDIA H200 EGL Rendering Path
+export LD_LIBRARY_PATH=/mnt/workspace/lib/nvidia_egl:\$LD_LIBRARY_PATH
+export PYOPENGL_PLATFORM=egl
+export __GLX_VENDOR_LIBRARY_NAME=nvidia
+export MUJOCO_GL=egl
+export STARVLA_WM_DEBUG=${STARVLA_WM_DEBUG:-0}
+export STARVLA_WM_DEBUG_MAX=${STARVLA_WM_DEBUG_MAX:-6}
+export STARVLA_ACTION_DEBUG=${STARVLA_ACTION_DEBUG:-0}
+export STARVLA_ACTION_DEBUG_MAX=${STARVLA_ACTION_DEBUG_MAX:-20}
+
+cd /mnt/workspace/users/maxiangkai/projects/WM4A
+starVLA_PYTHON=/mnt/workspace/envs/conda3/envs/starVLA_1/bin/python
+ROBOCASA_PYTHON=/mnt/workspace/envs/conda3/envs/robocasa/bin/python
+export PYTHONPATH=$(pwd):${PYTHONPATH}
+
+CKPT_DEFAULT="/mnt/workspace/users/maxiangkai/projects/MaskWAM/outputs/joyra05mask_new_wm4a/robocasa_pretrainwan/checkpoints/steps_250000_pytorch_model.pt"
+# CKPT_DEFAULT="/mnt/workspace/users/maxiangkai/projects/MaskWAM/outputs/joyra05mask_new_wm4a/robocasa_scratchwan/checkpoints/steps_150000_pytorch_model.pt"
+SIMULATION_SCRIPT="examples/Robocasa_tabletop/eval_files/simulation_env_wm.py"
+
+N_ENVS_DEFAULT=1
+MAX_EPISODE_STEPS_DEFAULT=720
+N_ACTION_STEPS_DEFAULT=12
+NUM_INFERENCE_STEPS_DEFAULT=5
+SHIFT_DEFAULT=5.0
+
+BASE_PORT=29999
+# BASE_PORT=39999
+NUM_GPUS=2 # mytest
+
+CKPT_PATH=${1:-$CKPT_DEFAULT}
+N_ENVS=${2:-$N_ENVS_DEFAULT}
+MAX_EPISODE_STEPS=${3:-$MAX_EPISODE_STEPS_DEFAULT}
+N_ACTION_STEPS=${4:-$N_ACTION_STEPS_DEFAULT}
+NUM_INFERENCE_STEPS=${5:-$NUM_INFERENCE_STEPS_DEFAULT}
+SHIFT=${6:-$SHIFT_DEFAULT}
+
+echo "=== WM Evaluation Configuration ==="
+echo "Checkpoint Path : ${CKPT_PATH}"
+echo "Number of Envs : ${N_ENVS}"
+echo "Max Episode Steps : ${MAX_EPISODE_STEPS}"
+echo "Action Chunk Length : ${N_ACTION_STEPS}"
+echo "Inference Steps : ${NUM_INFERENCE_STEPS}"
+echo "RF Shift : ${SHIFT}"
+echo "Simulation Script : ${SIMULATION_SCRIPT}"
+echo "==================================="
+
+SERVER_PIDS=()
+EVAL_PIDS=()
+CLEANED_UP=0
+
+kill_process_tree() {
+ local PID=$1
+ local SIGNAL=${2:-TERM}
+
+ if [[ -z "${PID}" ]] || ! kill -0 "${PID}" 2>/dev/null; then
+ return
+ fi
+
+ local CHILD_PIDS
+ CHILD_PIDS=$(pgrep -P "${PID}" 2>/dev/null || true)
+ for CHILD_PID in ${CHILD_PIDS}; do
+ kill_process_tree "${CHILD_PID}" "${SIGNAL}"
+ done
+
+ kill -"${SIGNAL}" "${PID}" 2>/dev/null || true
+}
+
+cleanup() {
+ local EXIT_CODE=$?
+ if [[ "${CLEANED_UP}" -eq 1 ]]; then
+ exit "${EXIT_CODE}"
+ fi
+ CLEANED_UP=1
+
+ trap - INT TERM EXIT
+
+ echo ""
+ echo "Cleaning up WM evaluation processes..."
+
+ for PID in "${EVAL_PIDS[@]}" "${SERVER_PIDS[@]}"; do
+ kill_process_tree "${PID}" TERM
+ done
+
+ sleep 2
+
+ for PID in "${EVAL_PIDS[@]}" "${SERVER_PIDS[@]}"; do
+ kill_process_tree "${PID}" KILL
+ done
+
+ wait 2>/dev/null || true
+ echo "Cleanup finished."
+ exit "${EXIT_CODE}"
+}
+
+trap cleanup INT TERM EXIT
+
+EvalEnv() {
+ local GPU_ID=$1
+ local PORT=$2
+ local ENV_NAME=$3
+ local CKPT_PATH=$4
+ local LOG_DIR=$5
+ local ROBOCASA_PYTHON=$6
+ local N_ENVS=$7
+ local MAX_EPISODE_STEPS=$8
+ local N_ACTION_STEPS=$9
+ local NUM_INFERENCE_STEPS=${10}
+ local SHIFT=${11}
+
+ local SAVE_ROOT=$(dirname "$(dirname "$CKPT_PATH")")
+ local ckpt_name=$(basename "$CKPT_PATH" .pt)
+ local VIDEO_OUT_PATH="${SAVE_ROOT}/videos/${ckpt_name}/$(basename "${LOG_DIR}")/${ENV_NAME}"
+ mkdir -p "${VIDEO_OUT_PATH}"
+
+ echo "Launching WM evaluation | GPU ${GPU_ID} | Port ${PORT} | Env ${ENV_NAME}"
+
+ CUDA_VISIBLE_DEVICES=${GPU_ID} \
+ MUJOCO_GL=egl \
+ PYOPENGL_PLATFORM=egl \
+ MUJOCO_EGL_DEVICE_ID=${GPU_ID} \
+ ${ROBOCASA_PYTHON} "${SIMULATION_SCRIPT}" \
+ --args.env_name "${ENV_NAME}" \
+ --args.port "${PORT}" \
+ --args.n_episodes 50 \
+ --args.n_envs "${N_ENVS}" \
+ --args.max_episode_steps "${MAX_EPISODE_STEPS}" \
+ --args.n_action_steps "${N_ACTION_STEPS}" \
+ --args.num_inference_steps "${NUM_INFERENCE_STEPS}" \
+ --args.shift "${SHIFT}" \
+ --args.video_out_path "${VIDEO_OUT_PATH}" \
+ --args.pretrained_path "${CKPT_PATH}" \
+ > "${LOG_DIR}/eval_env_${ENV_NAME//\//_}_gpu${GPU_ID}.log" 2>&1
+}
+
+ENV_NAMES=(
+ gr1_unified/PnPCupToDrawerClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPPotatoToMicrowaveClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPMilkToMicrowaveClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPBottleToCabinetClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPWineToCabinetClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPCanToDrawerClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToBasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToPanSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToPotSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToTieredbasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToBasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToBowlSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToPlateSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToTieredshelfSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToBowlSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToPanSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToPlateSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToPlateSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToPotSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToTieredbasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToTieredshelfSplitA_GR1ArmsAndWaistFourierHands_Env
+)
+
+LOG_DIR="${CKPT_PATH}.log/wm_eval_$(date +%Y%m%d_%H%M%S)"
+mkdir -p "${LOG_DIR}"
+
+echo "=== Launching WM Multi-GPU Evaluation ==="
+echo "GPUs : ${NUM_GPUS}"
+echo "Num Environments : ${#ENV_NAMES[@]}"
+echo "Log Directory : ${LOG_DIR}"
+
+# Kill any existing processes on target ports
+echo "Cleaning up stale processes on target ports..."
+for GPU_ID in $(seq 0 $((NUM_GPUS - 1))); do
+ PORT=$((BASE_PORT + GPU_ID))
+ PID=$(lsof -ti:${PORT} 2>/dev/null || true)
+ if [ -n "${PID}" ]; then
+ echo "Killing process ${PID} on port ${PORT}"
+ kill -9 ${PID} 2>/dev/null || true
+ fi
+done
+sleep 2
+
+for GPU_ID in $(seq 0 $((NUM_GPUS - 1))); do
+ PORT=$((BASE_PORT + GPU_ID))
+ echo "Starting policy server | GPU ${GPU_ID} | Port ${PORT}"
+
+ CUDA_VISIBLE_DEVICES=${GPU_ID} \
+ ${starVLA_PYTHON} deployment/model_server/server_policy.py \
+ --ckpt_path "${CKPT_PATH}" \
+ --port "${PORT}" \
+ --use_bf16 \
+ > "${LOG_DIR}/server_gpu${GPU_ID}_port${PORT}.log" 2>&1 &
+
+ SERVER_PIDS[$GPU_ID]=$!
+ sleep 10
+done
+
+sleep 30
+
+COUNT=0
+for ENV_NAME in "${ENV_NAMES[@]}"; do
+ GPU_ID=$((COUNT % NUM_GPUS))
+ PORT=$((BASE_PORT + GPU_ID))
+
+ if (( (COUNT + 1) % NUM_GPUS == 0 )); then
+ EvalEnv "${GPU_ID}" "${PORT}" "${ENV_NAME}" "${CKPT_PATH}" "${LOG_DIR}" \
+ "${ROBOCASA_PYTHON}" "${N_ENVS}" "${MAX_EPISODE_STEPS}" "${N_ACTION_STEPS}" "${NUM_INFERENCE_STEPS}" "${SHIFT}" &
+ EVAL_PIDS+=($!)
+ wait "${EVAL_PIDS[@]}"
+ EVAL_PIDS=()
+ else
+ EvalEnv "${GPU_ID}" "${PORT}" "${ENV_NAME}" "${CKPT_PATH}" "${LOG_DIR}" \
+ "${ROBOCASA_PYTHON}" "${N_ENVS}" "${MAX_EPISODE_STEPS}" "${N_ACTION_STEPS}" "${NUM_INFERENCE_STEPS}" "${SHIFT}" &
+ EVAL_PIDS+=($!)
+ fi
+
+ COUNT=$((COUNT + 1))
+ sleep 2
+done
+
+while pgrep -f "${SIMULATION_SCRIPT}" > /dev/null; do
+ echo "Waiting for all WM evaluation environments to finish..."
+ sleep 30
+done
+
+echo ""
+echo "Shutting down policy servers..."
+
+for PID in "${SERVER_PIDS[@]}"; do
+ kill_process_tree "${PID}" TERM
+ echo "Killed server PID ${PID}"
+done
+
+echo "=== WM Evaluation Finished ==="
+
+python summarize_eval_logs.py "${LOG_DIR}"
\ No newline at end of file
diff --git a/examples/Robocasa_tabletop/eval_files/batch_eval_args_wm_joyra05_back.sh b/examples/Robocasa_tabletop/eval_files/batch_eval_args_wm_joyra05_back.sh
new file mode 100644
index 0000000000000000000000000000000000000000..76974b02d147220ebfcc142a9167d53a7bf69b74
--- /dev/null
+++ b/examples/Robocasa_tabletop/eval_files/batch_eval_args_wm_joyra05_back.sh
@@ -0,0 +1,39 @@
+#!/bin/bash
+# Background wrapper for batch_eval_args_wm_joyra05.sh
+
+EVAL_SCRIPT="$(cd "$(dirname "$0")" && pwd)/batch_eval_args_wm_joyra05.sh"
+LOG_FILE="/mnt/workspace/users/maxiangkai/projects/JoyRA_robocasa/eval_back_$(date +%Y%m%d_%H%M%S).log"
+mkdir -p "$(dirname "${LOG_FILE}")"
+
+if [ ! -f "${EVAL_SCRIPT}" ]; then
+ echo "ERROR: cannot find ${EVAL_SCRIPT}" >&2; exit 1
+fi
+
+nohup setsid bash "${EVAL_SCRIPT}" "$@" >"${LOG_FILE}" 2>&1 &
+EVAL_PID=$!
+disown "${EVAL_PID}" 2>/dev/null || true
+sleep 1
+
+ABS_LOG_FILE="$(cd "$(dirname "${LOG_FILE}")" && pwd)/$(basename "${LOG_FILE}")"
+
+cat </dev/null; echo ""; echo "Detached from log. Eval PID=${EVAL_PID} still running."; echo " Re-attach: tail -F ${ABS_LOG_FILE}"; exit 0' INT
+wait "${TAIL_PID}"
\ No newline at end of file
diff --git a/examples/Robocasa_tabletop/eval_files/batch_eval_args_wm_vjepa_180000.sh b/examples/Robocasa_tabletop/eval_files/batch_eval_args_wm_vjepa_180000.sh
new file mode 100644
index 0000000000000000000000000000000000000000..5b62da69722f3e85ea6a7c82dcc971a7221bc5f4
--- /dev/null
+++ b/examples/Robocasa_tabletop/eval_files/batch_eval_args_wm_vjepa_180000.sh
@@ -0,0 +1,244 @@
+#!/bin/bash
+
+# ============================================================
+# WM Evaluation Script for wam_vjepa_100000 model
+# Based on batch_eval_args_wm.sh, adapted for maxiangkai's WM4A project
+# ============================================================
+
+export OMP_NUM_THREADS=1
+export MKL_NUM_THREADS=1
+export OPENBLAS_NUM_THREADS=1
+
+# NVIDIA H200 EGL Rendering Path
+export LD_LIBRARY_PATH=/mnt/workspace/lib/nvidia_egl:\$LD_LIBRARY_PATH
+export PYOPENGL_PLATFORM=egl
+export __GLX_VENDOR_LIBRARY_NAME=nvidia
+export MUJOCO_GL=egl
+export STARVLA_WM_DEBUG=${STARVLA_WM_DEBUG:-0}
+export STARVLA_WM_DEBUG_MAX=${STARVLA_WM_DEBUG_MAX:-6}
+export STARVLA_ACTION_DEBUG=${STARVLA_ACTION_DEBUG:-0}
+export STARVLA_ACTION_DEBUG_MAX=${STARVLA_ACTION_DEBUG_MAX:-20}
+
+cd /mnt/workspace/users/maxiangkai/projects/WM4A
+starVLA_PYTHON=/mnt/workspace/envs/conda3/envs/starVLA_1/bin/python
+ROBOCASA_PYTHON=/mnt/workspace/envs/conda3/envs/robocasa/bin/python
+export PYTHONPATH=$(pwd):${PYTHONPATH}
+
+CKPT_DEFAULT="/mnt/workspace/users/maxiangkai/projects/WM4A/outputs/cosmopredict25_vjepa_ImageLatent/robocasa_06-26-16-51/checkpoints/steps_180000_pytorch_model.pt"
+SIMULATION_SCRIPT="examples/Robocasa_tabletop/eval_files/simulation_env_wm.py"
+
+N_ENVS_DEFAULT=1
+MAX_EPISODE_STEPS_DEFAULT=720
+N_ACTION_STEPS_DEFAULT=12
+NUM_INFERENCE_STEPS_DEFAULT=5
+SHIFT_DEFAULT=5.0
+
+BASE_PORT=29999
+NUM_GPUS=8 # mytest
+
+CKPT_PATH=${1:-$CKPT_DEFAULT}
+N_ENVS=${2:-$N_ENVS_DEFAULT}
+MAX_EPISODE_STEPS=${3:-$MAX_EPISODE_STEPS_DEFAULT}
+N_ACTION_STEPS=${4:-$N_ACTION_STEPS_DEFAULT}
+NUM_INFERENCE_STEPS=${5:-$NUM_INFERENCE_STEPS_DEFAULT}
+SHIFT=${6:-$SHIFT_DEFAULT}
+
+echo "=== WM Evaluation Configuration ==="
+echo "Checkpoint Path : ${CKPT_PATH}"
+echo "Number of Envs : ${N_ENVS}"
+echo "Max Episode Steps : ${MAX_EPISODE_STEPS}"
+echo "Action Chunk Length : ${N_ACTION_STEPS}"
+echo "Inference Steps : ${NUM_INFERENCE_STEPS}"
+echo "RF Shift : ${SHIFT}"
+echo "Simulation Script : ${SIMULATION_SCRIPT}"
+echo "==================================="
+
+SERVER_PIDS=()
+EVAL_PIDS=()
+CLEANED_UP=0
+
+kill_process_tree() {
+ local PID=$1
+ local SIGNAL=${2:-TERM}
+
+ if [[ -z "${PID}" ]] || ! kill -0 "${PID}" 2>/dev/null; then
+ return
+ fi
+
+ local CHILD_PIDS
+ CHILD_PIDS=$(pgrep -P "${PID}" 2>/dev/null || true)
+ for CHILD_PID in ${CHILD_PIDS}; do
+ kill_process_tree "${CHILD_PID}" "${SIGNAL}"
+ done
+
+ kill -"${SIGNAL}" "${PID}" 2>/dev/null || true
+}
+
+cleanup() {
+ local EXIT_CODE=$?
+ if [[ "${CLEANED_UP}" -eq 1 ]]; then
+ exit "${EXIT_CODE}"
+ fi
+ CLEANED_UP=1
+
+ trap - INT TERM EXIT
+
+ echo ""
+ echo "Cleaning up WM evaluation processes..."
+
+ for PID in "${EVAL_PIDS[@]}" "${SERVER_PIDS[@]}"; do
+ kill_process_tree "${PID}" TERM
+ done
+
+ sleep 2
+
+ for PID in "${EVAL_PIDS[@]}" "${SERVER_PIDS[@]}"; do
+ kill_process_tree "${PID}" KILL
+ done
+
+ wait 2>/dev/null || true
+ echo "Cleanup finished."
+ exit "${EXIT_CODE}"
+}
+
+trap cleanup INT TERM EXIT
+
+EvalEnv() {
+ local GPU_ID=$1
+ local PORT=$2
+ local ENV_NAME=$3
+ local CKPT_PATH=$4
+ local LOG_DIR=$5
+ local ROBOCASA_PYTHON=$6
+ local N_ENVS=$7
+ local MAX_EPISODE_STEPS=$8
+ local N_ACTION_STEPS=$9
+ local NUM_INFERENCE_STEPS=${10}
+ local SHIFT=${11}
+
+ local SAVE_ROOT=$(dirname "$(dirname "$CKPT_PATH")")
+ local ckpt_name=$(basename "$CKPT_PATH" .pt)
+ local VIDEO_OUT_PATH="${SAVE_ROOT}/videos/${ckpt_name}/$(basename "${LOG_DIR}")/${ENV_NAME}"
+ mkdir -p "${VIDEO_OUT_PATH}"
+
+ echo "Launching WM evaluation | GPU ${GPU_ID} | Port ${PORT} | Env ${ENV_NAME}"
+
+ CUDA_VISIBLE_DEVICES=${GPU_ID} \
+ MUJOCO_GL=egl \
+ PYOPENGL_PLATFORM=egl \
+ MUJOCO_EGL_DEVICE_ID=${GPU_ID} \
+ ${ROBOCASA_PYTHON} "${SIMULATION_SCRIPT}" \
+ --args.env_name "${ENV_NAME}" \
+ --args.port "${PORT}" \
+ --args.n_episodes 50 \
+ --args.n_envs "${N_ENVS}" \
+ --args.max_episode_steps "${MAX_EPISODE_STEPS}" \
+ --args.n_action_steps "${N_ACTION_STEPS}" \
+ --args.num_inference_steps "${NUM_INFERENCE_STEPS}" \
+ --args.shift "${SHIFT}" \
+ --args.video_out_path "${VIDEO_OUT_PATH}" \
+ --args.pretrained_path "${CKPT_PATH}" \
+ > "${LOG_DIR}/eval_env_${ENV_NAME//\//_}_gpu${GPU_ID}.log" 2>&1
+}
+
+ENV_NAMES=(
+ gr1_unified/PnPCupToDrawerClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPPotatoToMicrowaveClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPMilkToMicrowaveClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPBottleToCabinetClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPWineToCabinetClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPCanToDrawerClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToBasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToPanSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToPotSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToTieredbasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToBasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToBowlSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToPlateSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToTieredshelfSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToBowlSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToPanSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToPlateSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToPlateSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToPotSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToTieredbasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToTieredshelfSplitA_GR1ArmsAndWaistFourierHands_Env
+)
+
+LOG_DIR="${CKPT_PATH}.log/wm_eval_$(date +%Y%m%d_%H%M%S)"
+mkdir -p "${LOG_DIR}"
+
+echo "=== Launching WM Multi-GPU Evaluation ==="
+echo "GPUs : ${NUM_GPUS}"
+echo "Num Environments : ${#ENV_NAMES[@]}"
+echo "Log Directory : ${LOG_DIR}"
+
+# Kill any existing processes on target ports
+echo "Cleaning up stale processes on target ports..."
+for GPU_ID in $(seq 0 $((NUM_GPUS - 1))); do
+ PORT=$((BASE_PORT + GPU_ID))
+ PID=$(lsof -ti:${PORT} 2>/dev/null || true)
+ if [ -n "${PID}" ]; then
+ echo "Killing process ${PID} on port ${PORT}"
+ kill -9 ${PID} 2>/dev/null || true
+ fi
+done
+sleep 2
+
+for GPU_ID in $(seq 0 $((NUM_GPUS - 1))); do
+ PORT=$((BASE_PORT + GPU_ID))
+ echo "Starting policy server | GPU ${GPU_ID} | Port ${PORT}"
+
+ CUDA_VISIBLE_DEVICES=${GPU_ID} \
+ ${starVLA_PYTHON} deployment/model_server/server_policy.py \
+ --ckpt_path "${CKPT_PATH}" \
+ --port "${PORT}" \
+ --use_bf16 \
+ > "${LOG_DIR}/server_gpu${GPU_ID}_port${PORT}.log" 2>&1 &
+
+ SERVER_PIDS[$GPU_ID]=$!
+ sleep 10
+done
+
+sleep 30
+
+COUNT=0
+for ENV_NAME in "${ENV_NAMES[@]}"; do
+ GPU_ID=$((COUNT % NUM_GPUS))
+ PORT=$((BASE_PORT + GPU_ID))
+
+ if (( (COUNT + 1) % NUM_GPUS == 0 )); then
+ EvalEnv "${GPU_ID}" "${PORT}" "${ENV_NAME}" "${CKPT_PATH}" "${LOG_DIR}" \
+ "${ROBOCASA_PYTHON}" "${N_ENVS}" "${MAX_EPISODE_STEPS}" "${N_ACTION_STEPS}" "${NUM_INFERENCE_STEPS}" "${SHIFT}" &
+ EVAL_PIDS+=($!)
+ wait "${EVAL_PIDS[@]}"
+ EVAL_PIDS=()
+ else
+ EvalEnv "${GPU_ID}" "${PORT}" "${ENV_NAME}" "${CKPT_PATH}" "${LOG_DIR}" \
+ "${ROBOCASA_PYTHON}" "${N_ENVS}" "${MAX_EPISODE_STEPS}" "${N_ACTION_STEPS}" "${NUM_INFERENCE_STEPS}" "${SHIFT}" &
+ EVAL_PIDS+=($!)
+ fi
+
+ COUNT=$((COUNT + 1))
+ sleep 2
+done
+
+while pgrep -f "${SIMULATION_SCRIPT}" > /dev/null; do
+ echo "Waiting for all WM evaluation environments to finish..."
+ sleep 30
+done
+
+echo ""
+echo "Shutting down policy servers..."
+
+for PID in "${SERVER_PIDS[@]}"; do
+ kill_process_tree "${PID}" TERM
+ echo "Killed server PID ${PID}"
+done
+
+echo "=== WM Evaluation Finished ==="
+
+python summarize_eval_logs.py "${LOG_DIR}"
\ No newline at end of file
diff --git a/examples/Robocasa_tabletop/eval_files/batch_eval_args_wm_vjepa_280000.sh b/examples/Robocasa_tabletop/eval_files/batch_eval_args_wm_vjepa_280000.sh
new file mode 100644
index 0000000000000000000000000000000000000000..7a71b50e8cec64a4cb8775fb76891d0d2337665c
--- /dev/null
+++ b/examples/Robocasa_tabletop/eval_files/batch_eval_args_wm_vjepa_280000.sh
@@ -0,0 +1,244 @@
+#!/bin/bash
+
+# ============================================================
+# WM Evaluation Script for wam_vjepa_100000 model
+# Based on batch_eval_args_wm.sh, adapted for maxiangkai's WM4A project
+# ============================================================
+
+export OMP_NUM_THREADS=1
+export MKL_NUM_THREADS=1
+export OPENBLAS_NUM_THREADS=1
+
+# NVIDIA H200 EGL Rendering Path
+export LD_LIBRARY_PATH=/mnt/workspace/lib/nvidia_egl:\$LD_LIBRARY_PATH
+export PYOPENGL_PLATFORM=egl
+export __GLX_VENDOR_LIBRARY_NAME=nvidia
+export MUJOCO_GL=egl
+export STARVLA_WM_DEBUG=${STARVLA_WM_DEBUG:-0}
+export STARVLA_WM_DEBUG_MAX=${STARVLA_WM_DEBUG_MAX:-6}
+export STARVLA_ACTION_DEBUG=${STARVLA_ACTION_DEBUG:-0}
+export STARVLA_ACTION_DEBUG_MAX=${STARVLA_ACTION_DEBUG_MAX:-20}
+
+cd /mnt/workspace/users/maxiangkai/projects/WM4A
+starVLA_PYTHON=/mnt/workspace/envs/conda3/envs/starVLA_1/bin/python
+ROBOCASA_PYTHON=/mnt/workspace/envs/conda3/envs/robocasa/bin/python
+export PYTHONPATH=$(pwd):${PYTHONPATH}
+
+CKPT_DEFAULT="/mnt/workspace/users/maxiangkai/projects/WM4A/outputs/cosmopredict25_vjepa_ImageLatent/robocasa_06-28-13-10/checkpoints/steps_280000_pytorch_model.pt"
+SIMULATION_SCRIPT="examples/Robocasa_tabletop/eval_files/simulation_env_wm.py"
+
+N_ENVS_DEFAULT=1
+MAX_EPISODE_STEPS_DEFAULT=720
+N_ACTION_STEPS_DEFAULT=12
+NUM_INFERENCE_STEPS_DEFAULT=5
+SHIFT_DEFAULT=5.0
+
+BASE_PORT=19999
+NUM_GPUS=8 # mytest
+
+CKPT_PATH=${1:-$CKPT_DEFAULT}
+N_ENVS=${2:-$N_ENVS_DEFAULT}
+MAX_EPISODE_STEPS=${3:-$MAX_EPISODE_STEPS_DEFAULT}
+N_ACTION_STEPS=${4:-$N_ACTION_STEPS_DEFAULT}
+NUM_INFERENCE_STEPS=${5:-$NUM_INFERENCE_STEPS_DEFAULT}
+SHIFT=${6:-$SHIFT_DEFAULT}
+
+echo "=== WM Evaluation Configuration ==="
+echo "Checkpoint Path : ${CKPT_PATH}"
+echo "Number of Envs : ${N_ENVS}"
+echo "Max Episode Steps : ${MAX_EPISODE_STEPS}"
+echo "Action Chunk Length : ${N_ACTION_STEPS}"
+echo "Inference Steps : ${NUM_INFERENCE_STEPS}"
+echo "RF Shift : ${SHIFT}"
+echo "Simulation Script : ${SIMULATION_SCRIPT}"
+echo "==================================="
+
+SERVER_PIDS=()
+EVAL_PIDS=()
+CLEANED_UP=0
+
+kill_process_tree() {
+ local PID=$1
+ local SIGNAL=${2:-TERM}
+
+ if [[ -z "${PID}" ]] || ! kill -0 "${PID}" 2>/dev/null; then
+ return
+ fi
+
+ local CHILD_PIDS
+ CHILD_PIDS=$(pgrep -P "${PID}" 2>/dev/null || true)
+ for CHILD_PID in ${CHILD_PIDS}; do
+ kill_process_tree "${CHILD_PID}" "${SIGNAL}"
+ done
+
+ kill -"${SIGNAL}" "${PID}" 2>/dev/null || true
+}
+
+cleanup() {
+ local EXIT_CODE=$?
+ if [[ "${CLEANED_UP}" -eq 1 ]]; then
+ exit "${EXIT_CODE}"
+ fi
+ CLEANED_UP=1
+
+ trap - INT TERM EXIT
+
+ echo ""
+ echo "Cleaning up WM evaluation processes..."
+
+ for PID in "${EVAL_PIDS[@]}" "${SERVER_PIDS[@]}"; do
+ kill_process_tree "${PID}" TERM
+ done
+
+ sleep 2
+
+ for PID in "${EVAL_PIDS[@]}" "${SERVER_PIDS[@]}"; do
+ kill_process_tree "${PID}" KILL
+ done
+
+ wait 2>/dev/null || true
+ echo "Cleanup finished."
+ exit "${EXIT_CODE}"
+}
+
+trap cleanup INT TERM EXIT
+
+EvalEnv() {
+ local GPU_ID=$1
+ local PORT=$2
+ local ENV_NAME=$3
+ local CKPT_PATH=$4
+ local LOG_DIR=$5
+ local ROBOCASA_PYTHON=$6
+ local N_ENVS=$7
+ local MAX_EPISODE_STEPS=$8
+ local N_ACTION_STEPS=$9
+ local NUM_INFERENCE_STEPS=${10}
+ local SHIFT=${11}
+
+ local SAVE_ROOT=$(dirname "$(dirname "$CKPT_PATH")")
+ local ckpt_name=$(basename "$CKPT_PATH" .pt)
+ local VIDEO_OUT_PATH="${SAVE_ROOT}/videos/${ckpt_name}/$(basename "${LOG_DIR}")/${ENV_NAME}"
+ mkdir -p "${VIDEO_OUT_PATH}"
+
+ echo "Launching WM evaluation | GPU ${GPU_ID} | Port ${PORT} | Env ${ENV_NAME}"
+
+ CUDA_VISIBLE_DEVICES=${GPU_ID} \
+ MUJOCO_GL=egl \
+ PYOPENGL_PLATFORM=egl \
+ MUJOCO_EGL_DEVICE_ID=${GPU_ID} \
+ ${ROBOCASA_PYTHON} "${SIMULATION_SCRIPT}" \
+ --args.env_name "${ENV_NAME}" \
+ --args.port "${PORT}" \
+ --args.n_episodes 50 \
+ --args.n_envs "${N_ENVS}" \
+ --args.max_episode_steps "${MAX_EPISODE_STEPS}" \
+ --args.n_action_steps "${N_ACTION_STEPS}" \
+ --args.num_inference_steps "${NUM_INFERENCE_STEPS}" \
+ --args.shift "${SHIFT}" \
+ --args.video_out_path "${VIDEO_OUT_PATH}" \
+ --args.pretrained_path "${CKPT_PATH}" \
+ > "${LOG_DIR}/eval_env_${ENV_NAME//\//_}_gpu${GPU_ID}.log" 2>&1
+}
+
+ENV_NAMES=(
+ gr1_unified/PnPCupToDrawerClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPPotatoToMicrowaveClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPMilkToMicrowaveClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPBottleToCabinetClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPWineToCabinetClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPCanToDrawerClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToBasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToPanSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToPotSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToTieredbasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToBasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToBowlSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToPlateSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToTieredshelfSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToBowlSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToPanSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToPlateSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToPlateSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToPotSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToTieredbasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToTieredshelfSplitA_GR1ArmsAndWaistFourierHands_Env
+)
+
+LOG_DIR="${CKPT_PATH}.log/wm_eval_$(date +%Y%m%d_%H%M%S)"
+mkdir -p "${LOG_DIR}"
+
+echo "=== Launching WM Multi-GPU Evaluation ==="
+echo "GPUs : ${NUM_GPUS}"
+echo "Num Environments : ${#ENV_NAMES[@]}"
+echo "Log Directory : ${LOG_DIR}"
+
+# Kill any existing processes on target ports
+echo "Cleaning up stale processes on target ports..."
+for GPU_ID in $(seq 0 $((NUM_GPUS - 1))); do
+ PORT=$((BASE_PORT + GPU_ID))
+ PID=$(lsof -ti:${PORT} 2>/dev/null || true)
+ if [ -n "${PID}" ]; then
+ echo "Killing process ${PID} on port ${PORT}"
+ kill -9 ${PID} 2>/dev/null || true
+ fi
+done
+sleep 2
+
+for GPU_ID in $(seq 0 $((NUM_GPUS - 1))); do
+ PORT=$((BASE_PORT + GPU_ID))
+ echo "Starting policy server | GPU ${GPU_ID} | Port ${PORT}"
+
+ CUDA_VISIBLE_DEVICES=${GPU_ID} \
+ ${starVLA_PYTHON} deployment/model_server/server_policy.py \
+ --ckpt_path "${CKPT_PATH}" \
+ --port "${PORT}" \
+ --use_bf16 \
+ > "${LOG_DIR}/server_gpu${GPU_ID}_port${PORT}.log" 2>&1 &
+
+ SERVER_PIDS[$GPU_ID]=$!
+ sleep 10
+done
+
+sleep 30
+
+COUNT=0
+for ENV_NAME in "${ENV_NAMES[@]}"; do
+ GPU_ID=$((COUNT % NUM_GPUS))
+ PORT=$((BASE_PORT + GPU_ID))
+
+ if (( (COUNT + 1) % NUM_GPUS == 0 )); then
+ EvalEnv "${GPU_ID}" "${PORT}" "${ENV_NAME}" "${CKPT_PATH}" "${LOG_DIR}" \
+ "${ROBOCASA_PYTHON}" "${N_ENVS}" "${MAX_EPISODE_STEPS}" "${N_ACTION_STEPS}" "${NUM_INFERENCE_STEPS}" "${SHIFT}" &
+ EVAL_PIDS+=($!)
+ wait "${EVAL_PIDS[@]}"
+ EVAL_PIDS=()
+ else
+ EvalEnv "${GPU_ID}" "${PORT}" "${ENV_NAME}" "${CKPT_PATH}" "${LOG_DIR}" \
+ "${ROBOCASA_PYTHON}" "${N_ENVS}" "${MAX_EPISODE_STEPS}" "${N_ACTION_STEPS}" "${NUM_INFERENCE_STEPS}" "${SHIFT}" &
+ EVAL_PIDS+=($!)
+ fi
+
+ COUNT=$((COUNT + 1))
+ sleep 2
+done
+
+while pgrep -f "${SIMULATION_SCRIPT}" > /dev/null; do
+ echo "Waiting for all WM evaluation environments to finish..."
+ sleep 30
+done
+
+echo ""
+echo "Shutting down policy servers..."
+
+for PID in "${SERVER_PIDS[@]}"; do
+ kill_process_tree "${PID}" TERM
+ echo "Killed server PID ${PID}"
+done
+
+echo "=== WM Evaluation Finished ==="
+
+python summarize_eval_logs.py "${LOG_DIR}"
\ No newline at end of file
diff --git a/examples/Robocasa_tabletop/eval_files/batch_eval_args_wm_vjepa_back.sh b/examples/Robocasa_tabletop/eval_files/batch_eval_args_wm_vjepa_back.sh
new file mode 100644
index 0000000000000000000000000000000000000000..9e0b76ab3ea97eb44b2bf1d36e7e6bb568f18089
--- /dev/null
+++ b/examples/Robocasa_tabletop/eval_files/batch_eval_args_wm_vjepa_back.sh
@@ -0,0 +1,39 @@
+#!/bin/bash
+# Background wrapper for batch_eval_args_wm_vjepa_70000.sh
+
+EVAL_SCRIPT="$(cd "$(dirname "$0")" && pwd)/batch_eval_args_wm_vjepa_280000.sh"
+LOG_FILE="/mnt/workspace/users/maxiangkai/projects/WM4A/examples/Robocasa_tabletop/eval_files/eval_back_$(date +%Y%m%d_%H%M%S).log"
+mkdir -p "$(dirname "${LOG_FILE}")"
+
+if [ ! -f "${EVAL_SCRIPT}" ]; then
+ echo "ERROR: cannot find ${EVAL_SCRIPT}" >&2; exit 1
+fi
+
+nohup setsid bash "${EVAL_SCRIPT}" "$@" >"${LOG_FILE}" 2>&1 &
+EVAL_PID=$!
+disown "${EVAL_PID}" 2>/dev/null || true
+sleep 1
+
+ABS_LOG_FILE="$(cd "$(dirname "${LOG_FILE}")" && pwd)/$(basename "${LOG_FILE}")"
+
+cat </dev/null; echo ""; echo "Detached from log. Eval PID=${EVAL_PID} still running."; echo " Re-attach: tail -F ${ABS_LOG_FILE}"; exit 0' INT
+wait "${TAIL_PID}"
\ No newline at end of file
diff --git a/examples/Robocasa_tabletop/eval_files/gr1_pos_transform.py b/examples/Robocasa_tabletop/eval_files/gr1_pos_transform.py
new file mode 100644
index 0000000000000000000000000000000000000000..a0b6c783f842ebab17bc4d9e59195eba726c1ea7
--- /dev/null
+++ b/examples/Robocasa_tabletop/eval_files/gr1_pos_transform.py
@@ -0,0 +1,1019 @@
+import argparse
+import cv2
+import numpy as np
+import pandas as pd
+from pathlib import Path
+from typing import Dict, Iterable, List, Tuple, Optional
+from dataclasses import dataclass, field
+from urdf_parser_py.urdf import URDF
+from pykdl_utils.kdl_parser import kdl_tree_from_urdf_model
+from pykdl_utils.kdl_kinematics import KDLKinematics
+from scipy.spatial.transform import Rotation as R
+from tqdm import tqdm
+import PyKDL as kdl
+# import tensorflow as tf
+# --- 辅助函数 (保持不变) ---
+@dataclass
+class GR1RetargetConfig:
+ """Main configuration for GR1 retarget."""
+ urdf_path: str = str(
+ (Path(__file__).resolve().parents[3] / "runtime_assets/GR1T2/GR1T2_fourier_hand_6dof.urdf")
+ )
+ camera_intrinsics: dict = field(
+ default_factory=lambda: {"fx": 502.8689, "fy": 502.8689, "cx": 640.0, "cy": 400.0}
+ )
+ACTION_LAYOUT: Dict[str, tuple[int, int]] = {
+ "left_arm": (0, 7), "left_hand": (7, 13), "left_leg": (13, 19),
+ "neck": (19, 22), "right_arm": (22, 29), "right_hand": (29, 35),
+ "right_leg": (35, 41), "waist": (41, 44),
+}
+def slice_action_vector(action: np.ndarray) -> Dict[str, np.ndarray]:
+ return {
+ group: np.asarray(action[start:end], dtype=np.float64)
+ for group, (start, end) in ACTION_LAYOUT.items()
+ }
+def classify_joint(joint_name: str) -> str:
+ name = joint_name.lower()
+ if "waist" in name or "torso" in name or "pelvis" in name: return "waist"
+ if "neck" in name or "head" in name: return "neck"
+ if "left" in name:
+ if "hand" in name or "finger" in name or "thumb" in name: return "left_hand"
+ if "leg" in name or "hip" in name or "knee" in name or "ankle" in name: return "left_leg"
+ return "left_arm"
+ if "right" in name:
+ if "hand" in name or "finger" in name or "thumb" in name: return "right_hand"
+ if "leg" in name or "hip" in name or "knee" in name or "ankle" in name: return "right_leg"
+ return "right_arm"
+ raise KeyError(f"无法为关节 '{joint_name}' 推断分组。")
+def build_joint_array(kin: KDLKinematics, action_slices: Dict[str, np.ndarray], allowed_groups: Iterable[str]) -> List[float]:
+ allowed, counters = set(allowed_groups), {g: 0 for g in allowed_groups}
+ joint_names = kin.get_joint_names()
+ arr = [0.0] * len(joint_names)
+ for idx, joint_name in enumerate(joint_names):
+ group = classify_joint(joint_name)
+ if group not in allowed: raise KeyError(f"关节 '{joint_name}' 的分组 '{group}' 不在允许范围 {allowed} 内。")
+ values, offset = action_slices.get(group, []), counters.get(group, 0)
+ if offset >= len(values): raise IndexError(f"分组 '{group}' 的动作长度不足。")
+ arr[idx], counters[group] = values[offset], offset + 1
+ return arr
+# --- 核心重构类 (严格按照 v0.py 逻辑重写) ---
+class BodyRetargeter:
+ def __init__(self, urdf_path: Path, camera_intrinsics: Dict[str, float]):
+ print("正在初始化 BodyRetargeter (v0 逻辑)...")
+ self.camera_intrinsics = camera_intrinsics
+
+ robot_urdf = URDF.from_xml_file(str(urdf_path))
+ tree = kdl_tree_from_urdf_model(robot_urdf)
+ base_link = "torso_link"
+
+ # 创建 v0.py 中使用的所有长运动学链
+ self.kin_head = KDLKinematics(robot_urdf, base_link, "head_pitch_link", tree)
+ self.kin_left_arm = KDLKinematics(robot_urdf, base_link, "left_hand_pitch_link", tree)
+ self.kin_right_arm = KDLKinematics(robot_urdf, base_link, "right_hand_pitch_link", tree)
+
+ # 直接保存 PyKDL chain 以便 IK 求解使用
+ self.chain_head = tree.getChain(base_link, "head_pitch_link")
+ self.chain_left_arm = tree.getChain(base_link, "left_hand_pitch_link")
+ self.chain_right_arm = tree.getChain(base_link, "right_hand_pitch_link")
+
+ # 定义相机在头部坐标系中的固定变换 (外参)
+ t_cam_in_head = [2.650 - 2.65017178 + 0.23, -1.944 + 2.174 - 0.23, 1.538 - 1.4475]
+ #q_cam_in_head = [-0.206, 0.677, -0.607, 0.206] # w, x, y, z
+ #q_cam_in_head = [-0.676, 0.676, 0.205, -0.205]
+ q_cam_in_head = [-0.205, 0.676, -0.676, 0.205]
+ T_cam_in_head = self._create_transform(t_cam_in_head, q_cam_in_head)
+ self.T_head_to_cam = np.linalg.inv(T_cam_in_head)
+ self.hand_orientation_axes = [
+ ("+x", np.array([1.0, 0.0, 0.0], dtype=np.float64), (0, 0, 255)),
+ ("+y", np.array([0.0, 1.0, 0.0], dtype=np.float64), (0, 255, 0)),
+ ("+z", np.array([0.0, 0.0, -1.0], dtype=np.float64), (255, 0, 0)),
+ ]
+ self.hand_orientation_length = 0.12
+
+ self._chain_max_reach = {
+ "head": self._compute_chain_max_reach(self.chain_head),
+ "left_arm": self._compute_chain_max_reach(self.chain_left_arm),
+ "right_arm": self._compute_chain_max_reach(self.chain_right_arm),
+ }
+ self._ik_last_solution = {name: None for name in self._chain_max_reach}
+ self._workspace_margin = 0.05
+ self._ik_local_margin = np.deg2rad(90.0)
+
+ print("初始化完成。")
+ def _create_transform(self, t: List[float], q: List[float]) -> np.ndarray:
+ T = np.eye(4)
+ # q 是 (w, x, y, z), scipy 需要 (x, y, z, w)
+ T[:3, :3] = R.from_quat([q[1], q[2], q[3], q[0]]).as_matrix()
+ T[:3, 3] = t
+ return T
+ def _compute_chain_max_reach(self, chain: kdl.Chain) -> float:
+ reach = 0.0
+ for idx in range(chain.getNrOfSegments()):
+ segment = chain.getSegment(idx)
+ frame = segment.getFrameToTip()
+ reach += frame.p.Norm()
+ return float(reach)
+ def _is_target_within_workspace(self, chain_name: str, target_pose: np.ndarray) -> bool:
+ max_reach = self._chain_max_reach.get(chain_name)
+ if max_reach is None:
+ return True
+ distance = float(np.linalg.norm(target_pose[:3, 3]))
+ return distance <= max_reach + self._workspace_margin
+ def _prepare_fallback_solution(
+ self,
+ chain_name: str,
+ q_init: List[float],
+ num_joints: int,
+ q_min: kdl.JntArray,
+ q_max: kdl.JntArray,
+ ) -> Tuple[List[float], str]:
+ candidate = [q_init[i] if i < len(q_init) else 0.0 for i in range(num_joints)]
+ reason = "使用初始关节作为兜底"
+ fallback: List[float] = []
+ for i in range(num_joints):
+ val = candidate[i] if i < len(candidate) else 0.0
+ lower = q_min[i]
+ upper = q_max[i]
+ fallback.append(float(max(min(val, upper), lower)))
+ return fallback, reason
+ def process_kinematics_dataloader(self, action_vectors: np.ndarray) -> Tuple[Tuple[np.ndarray, np.ndarray], Tuple[np.ndarray, np.ndarray]]:
+ """
+ 批量处理运动学数据,返回轴角表示。
+
+ 参数:
+ action_vectors: shape (batch_size, 44) 或 (44,) 的动作向量
+
+ 返回:
+ ((left_hand_pos, left_hand_axisangle), (right_hand_pos, right_hand_axisangle))
+ - left_hand_pos: shape (batch_size, 3) 或 (3,)
+ - left_hand_axisangle: shape (batch_size, 3) 或 (3,)
+ - right_hand_pos: shape (batch_size, 3) 或 (3,)
+ - right_hand_axisangle: shape (batch_size, 3) 或 (3,)
+ """
+ # 确保输入是 numpy array(tf.py_function 会自动转换,但这里做个保险)
+ action_vectors = np.asarray(action_vectors)
+
+ # 处理单个向量的情况
+ if action_vectors.ndim == 1:
+ action_vectors = action_vectors[np.newaxis, :] # shape (1, 44)
+ squeeze_output = True
+ else:
+ squeeze_output = False
+
+ batch_size = action_vectors.shape[0]
+
+ # 初始化输出数组
+ left_hand_positions = np.zeros((batch_size, 3), dtype=np.float64)
+ right_hand_positions = np.zeros((batch_size, 3), dtype=np.float64)
+ left_hand_axisangles = np.zeros((batch_size, 3), dtype=np.float64)
+ right_hand_axisangles = np.zeros((batch_size, 3), dtype=np.float64)
+
+ # 批量处理每个动作向量
+ for i in range(batch_size):
+ action_vector = action_vectors[i]
+ action_slices = slice_action_vector(action_vector)
+
+ # 构建 v0.py 使用的包含 waist 和 neck 的关节数组
+ q_head = build_joint_array(self.kin_head, action_slices, ("waist", "neck"))
+ q_left_arm = build_joint_array(self.kin_left_arm, action_slices, ("waist", "left_arm"))
+ q_right_arm = build_joint_array(self.kin_right_arm, action_slices, ("waist", "right_arm"))
+
+ # 正向运动学
+ T_torso_to_head = self.kin_head.forward(q_head)
+ T_torso_to_left_hand = self.kin_left_arm.forward(q_left_arm)
+ T_torso_to_right_hand = self.kin_right_arm.forward(q_right_arm)
+
+ # 坐标系转换
+ T_inv_torso_to_head = np.linalg.inv(T_torso_to_head)
+ T_head_to_left_hand = T_inv_torso_to_head @ T_torso_to_left_hand
+ T_head_to_right_hand = T_inv_torso_to_head @ T_torso_to_right_hand
+
+ # 最终转换到相机坐标系
+ T_cam_to_left_hand = self.T_head_to_cam @ T_head_to_left_hand
+ T_cam_to_right_hand = self.T_head_to_cam @ T_head_to_right_hand
+
+ # 提取位置(展平为一维数组)
+ left_hand_positions[i] = T_cam_to_left_hand[:3, 3].flatten()
+ right_hand_positions[i] = T_cam_to_right_hand[:3, 3].flatten()
+
+ # 提取旋转矩阵并转换为轴角表示
+ left_hand_rot_mat = T_cam_to_left_hand[:3, :3]
+ right_hand_rot_mat = T_cam_to_right_hand[:3, :3]
+
+ # 使用 scipy 将旋转矩阵转换为轴角(rotvec)
+ left_hand_axisangles[i] = R.from_matrix(left_hand_rot_mat).as_rotvec()
+ right_hand_axisangles[i] = R.from_matrix(right_hand_rot_mat).as_rotvec()
+
+ # 如果输入是单个向量,则压缩批次维度
+ if squeeze_output:
+ left_hand_positions = left_hand_positions[0]
+ right_hand_positions = right_hand_positions[0]
+ left_hand_axisangles = left_hand_axisangles[0]
+ right_hand_axisangles = right_hand_axisangles[0]
+
+ return (left_hand_positions, left_hand_axisangles), (right_hand_positions, right_hand_axisangles)
+
+ # FK:
+ def process_frame_kinematics(self, action_vector: np.ndarray) -> Tuple[Tuple[np.ndarray, np.ndarray], Tuple[np.ndarray, np.ndarray]]:
+ action_slices = slice_action_vector(action_vector)
+
+ # 构建 v0.py 使用的包含 waist 和 neck 的关节数组
+ q_head = build_joint_array(self.kin_head, action_slices, ("waist", "neck"))
+ q_left_arm = build_joint_array(self.kin_left_arm, action_slices, ("waist", "left_arm"))
+ q_right_arm = build_joint_array(self.kin_right_arm, action_slices, ("waist", "right_arm"))
+
+ # 正向运动学
+ T_torso_to_head = self.kin_head.forward(q_head)
+ T_torso_to_left_hand = self.kin_left_arm.forward(q_left_arm)
+ T_torso_to_right_hand = self.kin_right_arm.forward(q_right_arm)
+
+ # 坐标系转换
+ T_inv_torso_to_head = np.linalg.inv(T_torso_to_head)
+ T_head_to_left_hand = T_inv_torso_to_head @ T_torso_to_left_hand
+ T_head_to_right_hand = T_inv_torso_to_head @ T_torso_to_right_hand
+
+ # 最终转换到相机坐标系
+ T_cam_to_left_hand = self.T_head_to_cam @ T_head_to_left_hand
+ T_cam_to_right_hand = self.T_head_to_cam @ T_head_to_right_hand
+
+ left_hand_pos = np.asarray(T_cam_to_left_hand[:3, 3]).flatten()
+ right_hand_pos = np.asarray(T_cam_to_right_hand[:3, 3]).flatten()
+ #import pdb; pdb.set_trace()
+ left_hand_rot = np.asarray(T_cam_to_left_hand[:3, :3], dtype=np.float64)
+ right_hand_rot = np.asarray(T_cam_to_right_hand[:3, :3], dtype=np.float64)
+
+ return (left_hand_pos, left_hand_rot), (right_hand_pos, right_hand_rot)
+ # FK + 转轴角表示
+ def process_frame_kinematics_axisangle(self, action_vector: np.ndarray) -> Tuple[Tuple[np.ndarray, np.ndarray], Tuple[np.ndarray, np.ndarray]]:
+ """
+ 处理运动学数据并返回轴角表示。支持单个向量或批量处理。
+
+ 参数:
+ action_vector: shape (batch_size, 44) 或 (44,) 的动作向量
+
+ 返回:
+ ((left_hand_pos, left_hand_axisangle), (right_hand_pos, right_hand_axisangle))
+ - left_hand_pos: shape (batch_size, 3) 或 (3,)
+ - left_hand_axisangle: shape (batch_size, 3) 或 (3,)
+ - right_hand_pos: shape (batch_size, 3) 或 (3,)
+ - right_hand_axisangle: shape (batch_size, 3) 或 (3,)
+ """
+ # 确保输入是 numpy array
+ action_vector = np.asarray(action_vector)
+
+ # 处理单个向量的情况
+ if action_vector.ndim == 1:
+ action_vector = action_vector[np.newaxis, :] # shape (1, 44)
+ squeeze_output = True
+ else:
+ squeeze_output = False
+
+ batch_size = action_vector.shape[0]
+
+ # 初始化输出数组
+ left_hand_positions = np.zeros((batch_size, 3), dtype=np.float64)
+ right_hand_positions = np.zeros((batch_size, 3), dtype=np.float64)
+ left_hand_axisangles = np.zeros((batch_size, 3), dtype=np.float64)
+ right_hand_axisangles = np.zeros((batch_size, 3), dtype=np.float64)
+ left_qpos_states = np.zeros((batch_size, 7), dtype=np.float64)
+ right_qpos_states = np.zeros((batch_size, 7), dtype=np.float64)
+
+ # 批量处理每个动作向量
+ for i in range(batch_size):
+ action_slices = slice_action_vector(action_vector[i])
+ # 新增:从切片中提取并保存左右臂的关节状态
+ left_qpos_states[i] = action_slices["left_arm"]
+ right_qpos_states[i] = action_slices["right_arm"]
+
+ # 构建 v0.py 使用的包含 waist 和 neck 的关节数组
+ q_head = build_joint_array(self.kin_head, action_slices, ("waist", "neck"))
+ q_left_arm = build_joint_array(self.kin_left_arm, action_slices, ("waist", "left_arm"))
+ q_right_arm = build_joint_array(self.kin_right_arm, action_slices, ("waist", "right_arm"))
+
+ # 正向运动学
+ T_torso_to_head = self.kin_head.forward(q_head)
+ T_torso_to_left_hand = self.kin_left_arm.forward(q_left_arm)
+ T_torso_to_right_hand = self.kin_right_arm.forward(q_right_arm)
+
+ # 坐标系转换
+ T_inv_torso_to_head = np.linalg.inv(T_torso_to_head)
+ T_head_to_left_hand = T_inv_torso_to_head @ T_torso_to_left_hand
+ T_head_to_right_hand = T_inv_torso_to_head @ T_torso_to_right_hand
+
+ # 最终转换到相机坐标系
+ T_cam_to_left_hand = self.T_head_to_cam @ T_head_to_left_hand
+ T_cam_to_right_hand = self.T_head_to_cam @ T_head_to_right_hand
+
+ # 提取位置(展平为一维数组)
+ left_hand_positions[i] = T_cam_to_left_hand[:3, 3].flatten()
+ right_hand_positions[i] = T_cam_to_right_hand[:3, 3].flatten()
+
+ # 提取旋转矩阵并转换为轴角表示
+ left_hand_rot = np.asarray(T_cam_to_left_hand[:3, :3], dtype=np.float64)
+ right_hand_rot = np.asarray(T_cam_to_right_hand[:3, :3], dtype=np.float64)
+
+ # 将旋转矩阵转换为轴角(rotation vector)
+ left_hand_axisangles[i] = R.from_matrix(left_hand_rot).as_rotvec()
+ right_hand_axisangles[i] = R.from_matrix(right_hand_rot).as_rotvec()
+
+ # 如果输入是单个向量,则压缩批次维度
+ if squeeze_output:
+ left_hand_positions = left_hand_positions[0]
+ right_hand_positions = right_hand_positions[0]
+ left_hand_axisangles = left_hand_axisangles[0]
+ right_hand_axisangles = right_hand_axisangles[0]
+ left_qpos_states = left_qpos_states[0]
+ right_qpos_states = right_qpos_states[0]
+ return (left_hand_positions, left_hand_axisangles), (right_hand_positions, right_hand_axisangles), (left_qpos_states, right_qpos_states)
+
+ # IK 解算 + 轴角表示:
+ def inverse_kinematics_from_camera_axisangle(self,
+ left_hand_pos: np.ndarray,
+ left_hand_axisangle: np.ndarray,
+ right_hand_pos: np.ndarray,
+ right_hand_axisangle: np.ndarray,
+ current_action_vector: Optional[np.ndarray] = None,
+ q_init_left: Optional[np.ndarray] = None,
+ q_init_right: Optional[np.ndarray] = None) -> Tuple[Optional[np.ndarray], Optional[np.ndarray]]:
+ """
+ 从相机坐标系下的手部位姿反向求解关节角度。支持单个样本或批量处理。
+
+ 参数:
+ left_hand_pos: 左手位置,shape (batch_size, 3) 或 (3,) - 相机坐标系
+ left_hand_axisangle: 左手轴角表示,shape (batch_size, 3) 或 (3,) - 相机坐标系
+ right_hand_pos: 右手位置,shape (batch_size, 3) 或 (3,) - 相机坐标系
+ right_hand_axisangle: 右手轴角表示,shape (batch_size, 3) 或 (3,) - 相机坐标系
+ current_action_vector: 当前完整动作向量,shape (batch_size, 44) 或 (44,)
+ 用于获取 waist 和 neck 的角度
+ 如果为 None,则使用零角度作为初始猜测
+ q_init_left: 左臂的初始关节角度猜测,使用当前step的state,shape (batch_size, num_joints) 或 (num_joints,)
+ q_init_right: 右臂的初始关节角度猜测,使用当前step的state,shape (batch_size, num_joints) 或 (num_joints,)
+
+ 返回:
+ (q_left_arm, q_right_arm): 左臂和右臂的关节角度
+ - shape (batch_size, num_joints) 或 (num_joints,),取决于输入
+ - 如果 IK 求解失败,对应的返回值为 None
+ """
+ # 确保输入是 numpy array
+ left_hand_pos = np.asarray(left_hand_pos, dtype=np.float64)
+ left_hand_axisangle = np.asarray(left_hand_axisangle, dtype=np.float64)
+ right_hand_pos = np.asarray(right_hand_pos, dtype=np.float64)
+ right_hand_axisangle = np.asarray(right_hand_axisangle, dtype=np.float64)
+
+ # 处理单个样本的情况
+ if left_hand_pos.ndim == 1:
+ left_hand_pos = left_hand_pos[np.newaxis, :] # shape (1, 3)
+ left_hand_axisangle = left_hand_axisangle[np.newaxis, :] # shape (1, 3)
+ right_hand_pos = right_hand_pos[np.newaxis, :] # shape (1, 3)
+ right_hand_axisangle = right_hand_axisangle[np.newaxis, :] # shape (1, 3)
+ squeeze_output = True
+ else:
+ squeeze_output = False
+
+ batch_size = left_hand_pos.shape[0]
+
+ # 处理 current_action_vector
+ if current_action_vector is not None:
+ current_action_vector = np.asarray(current_action_vector, dtype=np.float64)
+ if current_action_vector.ndim == 1:
+ current_action_vector = current_action_vector[np.newaxis, :] # shape (1, 44)
+
+ # 处理初始猜测
+ if q_init_left is not None:
+ q_init_left = np.asarray(q_init_left, dtype=np.float64)
+ if q_init_left.ndim == 1:
+ q_init_left = q_init_left[np.newaxis, :]
+
+ if q_init_right is not None:
+ q_init_right = np.asarray(q_init_right, dtype=np.float64)
+ if q_init_right.ndim == 1:
+ q_init_right = q_init_right[np.newaxis, :]
+
+ # 获取关节数量
+ num_left_joints = len(self.kin_left_arm.get_joint_names())
+ num_right_joints = len(self.kin_right_arm.get_joint_names())
+
+ # 初始化输出数组(使用 None 填充,因为 IK 可能失败)
+ q_left_arm_batch = []
+ q_right_arm_batch = []
+
+ # 批量处理每个样本
+ for i in range(batch_size):
+ # 提取当前样本的数据
+ curr_left_pos = left_hand_pos[i]
+ curr_left_axisangle = left_hand_axisangle[i]
+ curr_right_pos = right_hand_pos[i]
+ curr_right_axisangle = right_hand_axisangle[i]
+
+ # === 步骤1: 将轴角表示转换为旋转矩阵,构建 4x4 变换矩阵 ===
+ left_hand_rot = R.from_rotvec(curr_left_axisangle).as_matrix()
+ right_hand_rot = R.from_rotvec(curr_right_axisangle).as_matrix()
+
+ # 构建相机坐标系下的手部变换矩阵
+ T_cam_to_left_hand = np.eye(4)
+ T_cam_to_left_hand[:3, :3] = left_hand_rot
+ T_cam_to_left_hand[:3, 3] = curr_left_pos
+
+ T_cam_to_right_hand = np.eye(4)
+ T_cam_to_right_hand[:3, :3] = right_hand_rot
+ T_cam_to_right_hand[:3, 3] = curr_right_pos
+
+ # === 步骤2: 获取 waist 和 neck 的当前角度,计算 T_torso_to_head ===
+ if current_action_vector is not None:
+ # 从完整动作向量中提取 waist 和 neck
+ action_slices = slice_action_vector(current_action_vector[i])
+ q_head = build_joint_array(self.kin_head, action_slices, ("waist", "neck"))
+
+ # 如果没有提供初始猜测,从 action_vector 中提取
+ if q_init_left is None:
+ curr_q_init_left = build_joint_array(self.kin_left_arm, action_slices, ("waist", "left_arm"))
+ else:
+ curr_q_init_left = q_init_left[i].tolist()
+
+ if q_init_right is None:
+ curr_q_init_right = build_joint_array(self.kin_right_arm, action_slices, ("waist", "right_arm"))
+ else:
+ curr_q_init_right = q_init_right[i].tolist()
+ else:
+ # 使用零角度作为默认值
+ num_head_joints = len(self.kin_head.get_joint_names())
+ q_head = [0.0] * num_head_joints
+
+ if q_init_left is None:
+ curr_q_init_left = [0.0] * num_left_joints
+ else:
+ curr_q_init_left = q_init_left[i].tolist()
+
+ if q_init_right is None:
+ curr_q_init_right = [0.0] * num_right_joints
+ else:
+ curr_q_init_right = q_init_right[i].tolist()
+
+ # 计算 torso 到 head 的变换
+ T_torso_to_head = self.kin_head.forward(q_head)
+
+ # === 步骤3: 坐标系转换(相机 -> head -> torso)===
+ T_cam_to_head = np.linalg.inv(self.T_head_to_cam)
+
+ # 相机坐标系 -> 头部坐标系
+ T_head_to_left_hand = T_cam_to_head @ T_cam_to_left_hand
+ T_head_to_right_hand = T_cam_to_head @ T_cam_to_right_hand
+
+ # 头部坐标系 -> torso 坐标系
+ T_torso_to_left_hand = T_torso_to_head @ T_head_to_left_hand
+ T_torso_to_right_hand = T_torso_to_head @ T_head_to_right_hand
+
+ # === 步骤4: 使用 IK 求解器求解关节角度 ===
+ q_left_arm = self._solve_ik(self.chain_left_arm, T_torso_to_left_hand, curr_q_init_left, chain_name="left_arm")
+ q_right_arm = self._solve_ik(self.chain_right_arm, T_torso_to_right_hand, curr_q_init_right, chain_name="right_arm")
+
+ # 将结果添加到批次列表
+ if q_left_arm is not None:
+ q_left_arm_batch.append(np.array(q_left_arm))
+ else:
+ q_left_arm_batch.append(None)
+
+ if q_right_arm is not None:
+ q_right_arm_batch.append(np.array(q_right_arm))
+ else:
+ q_right_arm_batch.append(None)
+
+ # === 步骤5: 整理输出 ===
+ # 检查是否所有样本都成功求解
+ all_left_success = all(q is not None for q in q_left_arm_batch)
+ all_right_success = all(q is not None for q in q_right_arm_batch)
+
+ # 转换为 numpy 数组(如果所有样本都成功)
+ if all_left_success:
+ q_left_arm_result = np.array(q_left_arm_batch)
+ else:
+ # 有失败的情况,返回列表
+ q_left_arm_result = q_left_arm_batch if not squeeze_output else (q_left_arm_batch[0] if q_left_arm_batch else None)
+ if not all_left_success and squeeze_output:
+ return q_left_arm_result, None
+
+ if all_right_success:
+ q_right_arm_result = np.array(q_right_arm_batch)
+ else:
+ # 有失败的情况,返回列表
+ q_right_arm_result = q_right_arm_batch if not squeeze_output else (q_right_arm_batch[0] if q_right_arm_batch else None)
+ if not all_right_success and squeeze_output:
+ return None, q_right_arm_result
+
+ # 如果输入是单个样本,则压缩批次维度
+ if squeeze_output:
+ q_left_arm_result = q_left_arm_result[0] if all_left_success else q_left_arm_batch[0]
+ q_right_arm_result = q_right_arm_result[0] if all_right_success else q_right_arm_batch[0]
+
+ return q_left_arm_result, q_right_arm_result
+
+ def inverse_kinematics_from_camera(self,
+ T_cam_to_hand: np.ndarray,
+ initial_q: np.ndarray,
+ kin: KDLKinematics) -> Optional[np.ndarray]:
+ """
+ 从相机坐标系下的手部位姿反向求解关节角度。
+
+ 参数:
+ T_cam_to_hand: 相机坐标系到手部的变换矩阵 (4x4)
+ initial_q: 初始关节角度(用于IK求解的初始猜测)
+ kin: 使用的运动学链(left_arm 或 right_arm)
+
+ 返回:
+ 求解的关节角度,如果求解失败则返回 None
+ """
+ # 步骤1: 将相机坐标系的位姿转换回 torso 坐标系
+ # T_cam_to_hand -> T_head_to_hand -> T_torso_to_hand
+
+ # 相机到头部的变换(T_head_to_cam 的逆)
+ T_cam_to_head = np.linalg.inv(self.T_head_to_cam)
+
+ # 相机 -> 头部 -> 手部
+ T_head_to_hand = T_cam_to_head @ T_cam_to_hand
+
+ # 需要知道 T_torso_to_head,但这需要当前的 neck 和 waist 关节角度
+ # 这里我们使用初始关节角度来计算(应该传入当前的 q_head)
+ # 暂时简化处理:假设已知完整的 torso 到 head 的变换
+
+ # 实际上需要完整的关节配置来计算 T_torso_to_head
+ # 这里返回 None,需要完整实现
+ return None
+ def verify_ik_solution(self,
+ action_vector: np.ndarray,
+ verbose: bool = True) -> Dict[str, any]:
+ """
+ 验证 FK -> IK -> FK 的完整流程。
+
+ 参数:
+ action_vector: 原始动作向量
+ verbose: 是否打印详细信息
+
+ 返回:
+ 包含验证结果的字典
+ """
+ action_slices = slice_action_vector(action_vector)
+
+ # === 步骤1: 原始 FK ===
+ q_head = build_joint_array(self.kin_head, action_slices, ("waist", "neck"))
+ q_left_arm_original = build_joint_array(self.kin_left_arm, action_slices, ("waist", "left_arm"))
+ q_right_arm_original = build_joint_array(self.kin_right_arm, action_slices, ("waist", "right_arm"))
+
+ # 正向运动学
+ T_torso_to_head = self.kin_head.forward(q_head)
+ T_torso_to_left_hand = self.kin_left_arm.forward(q_left_arm_original)
+ T_torso_to_right_hand = self.kin_right_arm.forward(q_right_arm_original)
+
+ # 转换到相机坐标系
+ T_inv_torso_to_head = np.linalg.inv(T_torso_to_head)
+ T_head_to_left_hand = T_inv_torso_to_head @ T_torso_to_left_hand
+ T_head_to_right_hand = T_inv_torso_to_head @ T_torso_to_right_hand
+
+ T_cam_to_left_hand = self.T_head_to_cam @ T_head_to_left_hand
+ T_cam_to_right_hand = self.T_head_to_cam @ T_head_to_right_hand
+
+ # === 步骤2: 反向变换(相机 -> torso)===
+ T_cam_to_head = np.linalg.inv(self.T_head_to_cam)
+
+ # 相机系下的手部位姿 -> 头部系下的手部位姿
+ T_head_to_left_hand_recovered = T_cam_to_head @ T_cam_to_left_hand
+ T_head_to_right_hand_recovered = T_cam_to_head @ T_cam_to_right_hand
+
+ # 头部系 -> torso 系
+ T_torso_to_left_hand_recovered = T_torso_to_head @ T_head_to_left_hand_recovered
+ T_torso_to_right_hand_recovered = T_torso_to_head @ T_head_to_right_hand_recovered
+
+ # === 步骤3: IK 求解 ===
+ # 使用 PyKDL 的 IK 求解器
+ q_left_arm_ik = self._solve_ik(self.chain_left_arm, T_torso_to_left_hand_recovered, q_left_arm_original, chain_name="left_arm")
+ q_right_arm_ik = self._solve_ik(self.chain_right_arm, T_torso_to_right_hand_recovered, q_right_arm_original, chain_name="right_arm")
+
+ # === 步骤4: 验证 FK ===
+ if q_left_arm_ik is not None:
+ T_torso_to_left_hand_verified = self.kin_left_arm.forward(q_left_arm_ik)
+ else:
+ T_torso_to_left_hand_verified = None
+
+ if q_right_arm_ik is not None:
+ T_torso_to_right_hand_verified = self.kin_right_arm.forward(q_right_arm_ik)
+ else:
+ T_torso_to_right_hand_verified = None
+
+ # === 步骤5: 计算误差 ===
+ results = {
+ 'left_arm': self._compute_errors(
+ q_left_arm_original, q_left_arm_ik,
+ T_torso_to_left_hand, T_torso_to_left_hand_verified
+ ),
+ 'right_arm': self._compute_errors(
+ q_right_arm_original, q_right_arm_ik,
+ T_torso_to_right_hand, T_torso_to_right_hand_verified
+ ),
+ }
+ print("original q_left_arm_original: ", q_left_arm_original)
+ print("original q_right_arm_original: ", q_right_arm_original)
+ print("ik q_left_arm_ik: ", q_left_arm_ik)
+ print("ik q_right_arm_ik: ", q_right_arm_ik)
+ print("T_torso_to_left_hand_verified: ", T_torso_to_left_hand_verified)
+ print("T_torso_to_left_hand: ", T_torso_to_left_hand)
+ print("T_torso_to_right_hand_verified: ", T_torso_to_right_hand_verified)
+ print("T_torso_to_right_hand: ", T_torso_to_right_hand)
+
+ if verbose:
+ print("\n=== IK 验证结果 ===")
+ for arm_name, result in results.items():
+ print(f"\n{arm_name}:")
+ if result['ik_success']:
+ print(f" 关节角度误差 (度): {result['joint_error_deg']:.4f}")
+ print(f" 位置误差 (m): {result['position_error']:.6f}")
+ print(f" 姿态误差 (度): {result['orientation_error_deg']:.4f}")
+ else:
+ print(f" IK 求解失败")
+
+ return results
+ def _solve_ik(
+ self,
+ chain: kdl.Chain,
+ target_pose: np.ndarray,
+ q_init: List[float],
+ chain_name: str = "unnamed",
+ ) -> Optional[List[float]]:
+ """
+ 使用 KDL IK 求解器求解逆向运动学。
+
+ 参数:
+ chain: 运动学链(PyKDL Chain)
+ target_pose: 目标位姿 (4x4 矩阵)
+ q_init: 初始关节角度
+ chain_name: 用于日志与缓存的链名称
+
+ 返回:
+ 求解的关节角度;若常规 IK 失败,将返回兜底解(上一帧成功解或初始关节)
+ """
+ chain_label = chain_name or "unnamed"
+ try:
+ if chain_label not in self._ik_last_solution:
+ self._ik_last_solution[chain_label] = None
+ if chain_label not in self._chain_max_reach:
+ self._chain_max_reach[chain_label] = self._compute_chain_max_reach(chain)
+ # 将 numpy 矩阵转换为 PyKDL Frame
+ target_frame = self._numpy_to_kdl_frame(target_pose)
+
+ num_joints = chain.getNrOfJoints()
+
+ # 设置全局关节限制
+ global_q_min = kdl.JntArray(num_joints)
+ global_q_max = kdl.JntArray(num_joints)
+ for i in range(num_joints):
+ global_q_min[i] = -2.0 * np.pi # 较宽的限制
+ global_q_max[i] = 2.0 * np.pi
+ q_init_full = [q_init[i] if i < len(q_init) else 0.0 for i in range(num_joints)]
+
+ if not self._is_target_within_workspace(chain_label, target_pose):
+ fallback_solution, reason = self._prepare_fallback_solution(
+ chain_label, q_init, num_joints, global_q_min, global_q_max
+ )
+ print(f" 目标超出 {chain_label} 工作空间,{reason}。")
+ self._ik_last_solution[chain_label] = fallback_solution
+ return fallback_solution
+
+ # 创建求解器所需组件
+ fk_solver = kdl.ChainFkSolverPos_recursive(chain)
+ ik_vel_solver = kdl.ChainIkSolverVel_pinv(chain)
+ # 多次尝试以提高成功率
+ max_attempts = 5
+ base_maxiter = 200
+ eps_schedule = [1e-6, 5e-6, 1e-5, 5e-5, 1e-4]
+ seed_noise = 0.25 # 单位: 弧度
+ for attempt in range(max_attempts):
+ eps = eps_schedule[min(attempt, len(eps_schedule) - 1)]
+ maxiter = base_maxiter * (attempt + 1)
+ local_margin = self._ik_local_margin * (attempt + 1)
+ local_q_min = kdl.JntArray(num_joints)
+ local_q_max = kdl.JntArray(num_joints)
+ for i in range(num_joints):
+ center = q_init_full[i]
+ lower = max(center - local_margin, global_q_min[i])
+ upper = min(center + local_margin, global_q_max[i])
+ if lower >= upper:
+ lower = global_q_min[i]
+ upper = global_q_max[i]
+ local_q_min[i] = lower
+ local_q_max[i] = upper
+ ik_solver = kdl.ChainIkSolverPos_NR_JL(
+ chain, local_q_min, local_q_max, fk_solver, ik_vel_solver,
+ maxiter=maxiter, eps=eps
+ )
+ q_init_kdl = kdl.JntArray(num_joints)
+ noise_scale = seed_noise * attempt
+ for i in range(num_joints):
+ init_val = q_init_full[i]
+ if attempt > 0:
+ init_val += float(np.random.uniform(-noise_scale, noise_scale))
+ # 限制在局部关节范围内
+ init_val = max(min(init_val, local_q_max[i]), local_q_min[i])
+ q_init_kdl[i] = init_val
+ q_out = kdl.JntArray(num_joints)
+ ret = ik_solver.CartToJnt(q_init_kdl, target_frame, q_out)
+ if ret >= 0:
+ solution = [q_out[i] for i in range(num_joints)]
+ self._ik_last_solution[chain_label] = solution
+ return solution
+ print(
+ f" IK 求解失败({chain_label}),第 {attempt + 1}/{max_attempts} 次尝试,"
+ f"返回码: {ret},maxiter={maxiter},eps={eps}"
+ )
+ # 使用 LMA 求解器兜底
+ try:
+ lma_solver = kdl.ChainIkSolverPos_LMA(chain, eps=1e-4, maxiter=2000)
+ q_init_kdl = kdl.JntArray(num_joints)
+ for i in range(num_joints):
+ init_val = q_init_full[i]
+ q_init_kdl[i] = max(min(init_val, global_q_max[i]), global_q_min[i])
+ q_out = kdl.JntArray(num_joints)
+ ret = lma_solver.CartToJnt(q_init_kdl, target_frame, q_out)
+ if ret >= 0:
+ solution = [q_out[i] for i in range(num_joints)]
+ self._ik_last_solution[chain_label] = solution
+ print(f" LMA 求解器成功为 {chain_label} 找到解。")
+ return solution
+ print(f" LMA 求解器仍失败({chain_label}),返回码: {ret}")
+ except Exception as lma_err:
+ print(f" LMA 求解器调用异常({chain_label}): {lma_err}")
+ # 最终兜底策略
+ fallback_solution, reason = self._prepare_fallback_solution(
+ chain_label, q_init, num_joints, global_q_min, global_q_max
+ )
+ print(f" IK 多次尝试仍失败({chain_label}),{reason}。")
+ self._ik_last_solution[chain_label] = fallback_solution
+ return fallback_solution
+
+ except Exception as e:
+ print(f"IK 求解异常({chain_label}): {e}")
+ import traceback
+ traceback.print_exc()
+ num_joints = chain.getNrOfJoints()
+ limit = 2.0 * np.pi
+ fallback = [
+ float(np.clip(q_init[i] if i < len(q_init) else 0.0, -limit, limit))
+ for i in range(num_joints)
+ ]
+ self._ik_last_solution[chain_label] = fallback
+ return fallback
+ def _numpy_to_kdl_frame(self, T: np.ndarray) -> kdl.Frame:
+ """将 numpy 4x4 变换矩阵转换为 PyKDL Frame"""
+ rotation = kdl.Rotation(
+ T[0, 0], T[0, 1], T[0, 2],
+ T[1, 0], T[1, 1], T[1, 2],
+ T[2, 0], T[2, 1], T[2, 2]
+ )
+ position = kdl.Vector(T[0, 3], T[1, 3], T[2, 3])
+ return kdl.Frame(rotation, position)
+ def _compute_errors(self,
+ q_original: List[float],
+ q_ik: Optional[List[float]],
+ T_original: np.ndarray,
+ T_ik: Optional[np.ndarray]) -> Dict[str, any]:
+ """计算原始值和 IK 求解值之间的误差"""
+ if q_ik is None or T_ik is None:
+ return {
+ 'ik_success': False,
+ 'joint_error_deg': None,
+ 'position_error': None,
+ 'orientation_error_deg': None
+ }
+
+ # 关节角度误差(转换为度)
+ q_original_arr = np.array(q_original)
+ q_ik_arr = np.array(q_ik)
+ joint_error = np.linalg.norm(q_original_arr - q_ik_arr)
+ joint_error_deg = np.rad2deg(joint_error)
+
+ # 位置误差
+ pos_original = T_original[:3, 3]
+ pos_ik = T_ik[:3, 3]
+ position_error = np.linalg.norm(pos_original - pos_ik)
+
+ # 姿态误差(使用旋转矩阵的差异)
+ R_original = T_original[:3, :3]
+ R_ik = T_ik[:3, :3]
+ R_error = R_original.T @ R_ik
+ # 计算旋转角度
+ trace = np.trace(R_error)
+ angle_error = np.arccos(np.clip((trace - 1) / 2, -1, 1))
+ orientation_error_deg = np.rad2deg(angle_error)
+
+ return {
+ 'ik_success': True,
+ 'joint_error_deg': joint_error_deg,
+ 'position_error': position_error,
+ 'orientation_error_deg': orientation_error_deg,
+ 'q_original': q_original,
+ 'q_ik': q_ik
+ }
+
+ def process_episode(self, video_path: Path, parquet_path: Path, output_path: Path, verify_ik: bool = True):
+ print(f"开始处理 episode: {video_path.parent.name}")
+ df = pd.read_parquet(parquet_path)
+ #actions = df["action"].tolist()
+ #import pdb; pdb.set_trace()
+ actions = df["observation.state"].tolist()
+ cap = cv2.VideoCapture(str(video_path))
+ if not cap.isOpened(): raise FileNotFoundError(f"无法打开视频: {video_path}")
+
+ fps = int(cap.get(cv2.CAP_PROP_FPS))
+ # 修改:输出视频的分辨率应为处理后的 256x256
+ output_resolution = (256, 256)
+ #output_resolution = (1280, 800)
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
+ out = cv2.VideoWriter(str(output_path), fourcc, fps, output_resolution)
+
+ num_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
+ print(f"视频总帧数: {num_frames}, 动作数据总数: {len(actions)}")
+
+ # === IK 验证(在第一帧上执行)===
+ if verify_ik and len(actions) > 0:
+ print("\n执行 IK 验证(使用第一帧数据)...")
+ ik_results = self.verify_ik_solution(np.array(actions[0]), verbose=True)
+
+ for i in tqdm(range(min(num_frames, len(actions))), desc="处理视频帧"):
+ ok, frame = cap.read()
+ if not ok: break
+
+ # 修改:将原始帧处理为 256x256
+ final_frame = process_img_cotrain(frame)
+
+ (left_pos, left_rot), (right_pos, right_rot) = self.process_frame_kinematics(np.array(actions[i]))
+ #import pdb; pdb.set_trace()
+
+ # 修改:在处理后的 256x256 图像上绘制点
+ self._draw_projection(i, final_frame, left_pos, left_rot, color=(0, 0, 255)) # 左手红色
+ self._draw_projection(i, final_frame, right_pos, right_rot, color=(255, 0, 0)) # 右手蓝色
+
+ out.write(final_frame)
+
+ cap.release()
+ out.release()
+ print(f"\n处理完成!新视频已保存到: {output_path}")
+ def _draw_projection(self, index, frame: np.ndarray, pos_3d: Optional[np.ndarray], orientation: Optional[np.ndarray], color: Tuple[int, int, int]):
+ # 修改:此方法现在包含完整的投影和坐标变换逻辑
+ if pos_3d is None: return
+ X, Y, Z = pos_3d
+
+ u_final, v_final = -1, -1
+ if Z > 0:
+ # 1. 投影到虚拟的 1280x800 图像上
+ u_orig = self.camera_intrinsics['fx'] * (X / Z) + self.camera_intrinsics['cx']
+ v_orig = self.camera_intrinsics['fy'] * (Y / Z) + self.camera_intrinsics['cy']
+
+ # 2. 将 2D 坐标点变换到 256x256 空间
+ u_final, v_final = transform_point_cotrain(u_orig, v_orig)
+ #u_final, v_final = int(u_orig), int(v_orig)
+
+
+
+ h, w, _ = frame.shape
+ #import pdb; pdb.set_trace()
+ if 0 <= u_final < w and 0 <= v_final < h:
+ cv2.circle(frame, (u_final, v_final), radius=5, color=color, thickness=-1)
+ if orientation is not None:
+ orientation_arr = np.asarray(orientation, dtype=np.float64)
+ orientation_mat = None
+ if orientation_arr.shape == (3, 3):
+ orientation_mat = orientation_arr
+ else:
+ flat = orientation_arr.reshape(-1)
+ if flat.size == 9:
+ orientation_mat = flat.reshape(3, 3)
+ axes_to_draw: List[Tuple[np.ndarray, Tuple[int, int, int]]] = []
+ if orientation_mat is not None:
+ for _, axis_vec, axis_color in self.hand_orientation_axes:
+ axis_cam = orientation_mat @ axis_vec
+ axes_to_draw.append((axis_cam, axis_color))
+ else:
+ flat = orientation_arr.reshape(-1)
+ if flat.size == 3:
+ axes_to_draw.append((flat, color))
+ for axis_cam, axis_color in axes_to_draw:
+ axis_cam = np.asarray(axis_cam, dtype=np.float64).reshape(-1)
+ if axis_cam.size != 3:
+ continue
+ axis_norm = np.linalg.norm(axis_cam)
+ if axis_norm <= 1e-6:
+ continue
+ axis_dir = axis_cam / axis_norm
+ base_pos = np.asarray(pos_3d, dtype=np.float64)
+ length = self.hand_orientation_length
+ for _ in range(5):
+ tip_pos = base_pos + length * axis_dir
+ if tip_pos[2] <= 1e-5:
+ length *= 0.5
+ continue
+ u_tip = self.camera_intrinsics['fx'] * (tip_pos[0] / tip_pos[2]) + self.camera_intrinsics['cx']
+ v_tip = self.camera_intrinsics['fy'] * (tip_pos[1] / tip_pos[2]) + self.camera_intrinsics['cy']
+ u_tip_final, v_tip_final = transform_point_cotrain(u_tip, v_tip)
+ if 0 <= u_tip_final < w and 0 <= v_tip_final < h:
+ cv2.arrowedLine(
+ frame,
+ (u_final, v_final),
+ (u_tip_final, v_tip_final),
+ axis_color,
+ thickness=2,
+ tipLength=0.2,
+ )
+ break
+ length *= 0.7
+def process_img_cotrain(img: np.ndarray) -> np.ndarray:
+ """
+ 将原始图像(1280x800)处理为最终输入模型的图像(256x256)。
+ 这个函数与 robocasa 中的 gymnasium_groot.py 里的实现完全一致。
+ """
+ # 确认输入是 1280x800 的原始图像
+ if not (img.shape[0] == 800 and img.shape[1] == 1280):
+ # 如果视频本身就是 256x256,直接返回
+ if img.shape[0] == 256 and img.shape[1] == 256:
+ #import pdb; pdb.set_trace()
+ # h_src, w_src = img.shape[:2]
+ # target_w, target_h = 1280, 800
+
+ # # 计算填充量(居中填充)
+ # pad_w_left = (target_w - w_src) // 2
+ # pad_w_right = target_w - w_src - pad_w_left
+ # pad_h_top = (target_h - h_src) // 2
+ # pad_h_bottom = target_h - h_src - pad_h_top
+
+ # # 填充到目标尺寸
+ # img = np.pad(
+ # img,
+ # ((pad_h_top, pad_h_bottom), (pad_w_left, pad_w_right), (0, 0)),
+ # mode="constant",
+ # constant_values=0,
+ # )
+ return img
+ raise ValueError(f"输入图像尺寸 {img.shape} 不符合预期的 1280x800")
+ oh, ow = 256, 256
+ # 定义一个裁剪区域 (top, bottom, left, right)
+ crop = (310, 770, 110, 1130)
+ # 步骤 1: 裁剪原始图像
+ img = img[crop[0] : crop[1], crop[2] : crop[3]]
+ # 步骤 2: 第一次缩放,将裁剪后的图像缩放到 720x480
+ img_resized = cv2.resize(img, (720, 480), cv2.INTER_AREA)
+
+ # 计算填充量,使其变为正方形
+ width_pad = (img_resized.shape[1] - img_resized.shape[0]) // 2
+ # 步骤 3: 填充黑边,使其变为 720x720 的正方形
+ img_pad = np.pad(
+ img_resized,
+ ((width_pad, width_pad), (0, 0), (0, 0)),
+ mode="constant",
+ constant_values=0,
+ )
+ # 步骤 4: 第二次缩放,将 720x720 的图像缩放到最终的 256x256
+ img_resized = cv2.resize(img_pad, (oh, ow), cv2.INTER_AREA)
+ return img_resized
+def transform_point_cotrain(u: float, v: float) -> tuple[int, int]:
+ """
+ 对投影到 1280x800 图像上的 2D 点应用与 process_img_cotrain 相同的几何变换。
+ """
+ # 步骤 1: 裁剪坐标
+ crop_bounds = (310, 770, 110, 1130) # top, bottom, left, right
+ u_cropped = u - crop_bounds[2]
+ v_cropped = v - crop_bounds[0]
+ # 步骤 2: 第一次缩放
+ original_cropped_size = (1020, 460) # width, height
+ resized1_size = (720, 480)
+ scale_u1 = resized1_size[0] / original_cropped_size[0]
+ scale_v1 = resized1_size[1] / original_cropped_size[1]
+ u_resized1 = u_cropped * scale_u1
+ v_resized1 = v_cropped * scale_v1
+ # 步骤 3: 填充坐标
+ pad_amount = (resized1_size[0] - resized1_size[1]) // 2 # 120
+ u_padded = u_resized1
+ v_padded = v_resized1 + pad_amount
+ # 步骤 4: 第二次缩放
+ padded_size = (720, 720)
+ final_size = (256, 256)
+ scale_u2 = final_size[0] / padded_size[0]
+ scale_v2 = final_size[1] / padded_size[1]
+ u_final = u_padded * scale_u2
+ v_final = v_padded * scale_v2
+ return int(u_final), int(v_final)
+def main():
+ parser = argparse.ArgumentParser(description="批量处理机器人视频,投影手部关节点 (v0 逻辑)。")
+ parser.add_argument("--dataset-root", type=Path, default=Path("/vla/users/lijiayi/robocasa_datasets_fewshots/gr1_unified.PosttrainPnPNovelFromCuttingboardToPanSplitA_GR1ArmsAndWaistFourierHands_100"))
+ parser.add_argument("--urdf-path", type=Path, default=Path("/vla/users/lijiayi/code/robot_retarget/retarget/body_retarget/GR1T2/urdf/GR1T2_fourier_hand_6dof.urdf"))
+ parser.add_argument("--output-dir", type=Path, default=Path("/vla/users/lijiayi/code/robot_retarget/retarget/body_retarget/output_videos"))
+ parser.add_argument("--verify-ik", action="store_true", default=True, help="是否执行 IK 验证")
+ parser.add_argument("--no-verify-ik", dest="verify_ik", action="store_false", help="禁用 IK 验证")
+ args = parser.parse_args()
+
+ args.output_dir.mkdir(parents=True, exist_ok=True)
+ camera_intrinsics = {'fx': 502.8689, 'fy': 502.8689, 'cx': 640.0, 'cy': 400.0}
+
+ retargeter = BodyRetargeter(urdf_path=args.urdf_path, camera_intrinsics=camera_intrinsics)
+
+ parquet_path = args.dataset_root / "data/chunk-000/episode_000098.parquet"
+ video_path = args.dataset_root / "videos/chunk-000/observation.images.ego_view/episode_000098.mp4"
+ output_path = args.output_dir / "episode_000093_projected_v8_logic.mp4"
+ retargeter.process_episode(video_path, parquet_path, output_path, verify_ik=args.verify_ik)
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/examples/Robocasa_tabletop/eval_files/gr1_pos_transform_new.py b/examples/Robocasa_tabletop/eval_files/gr1_pos_transform_new.py
new file mode 100644
index 0000000000000000000000000000000000000000..face25fde7d91a938129e26cdf782b67fc5c4fdc
--- /dev/null
+++ b/examples/Robocasa_tabletop/eval_files/gr1_pos_transform_new.py
@@ -0,0 +1,1275 @@
+import argparse
+import cv2
+import numpy as np
+import pandas as pd
+from pathlib import Path
+from typing import Dict, Iterable, List, Tuple, Optional
+from dataclasses import dataclass, field
+from urdf_parser_py.urdf import URDF
+from pykdl_utils.kdl_parser import kdl_tree_from_urdf_model
+from pykdl_utils.kdl_kinematics import KDLKinematics
+from scipy.spatial.transform import Rotation as R
+from tqdm import tqdm
+import PyKDL as kdl
+# import tensorflow as tf
+
+# --- 辅助函数 (保持不变) ---
+
+
+@dataclass
+class GR1RetargetConfig:
+ """Main configuration for GR1 retarget."""
+
+ urdf_path: str = str(
+ # (Path(__file__).resolve().parents[3] / "runtime_assets/GR1T2/GR1T2_fourier_hand_6dof.urdf")
+ (Path(__file__).resolve().parents[3] / "runtime_assets/GR1T2/GR1T2_fourier_hand_6dof.urdf"))
+ camera_intrinsics: dict = field(default_factory=lambda: {"fx": 502.8689, "fy": 502.8689, "cx": 640.0, "cy": 400.0})
+
+
+ACTION_LAYOUT: Dict[str, tuple[int, int]] = {
+ "left_arm": (0, 7),
+ "left_hand": (7, 13),
+ "left_leg": (13, 19),
+ "neck": (19, 22),
+ "right_arm": (22, 29),
+ "right_hand": (29, 35),
+ "right_leg": (35, 41),
+ "waist": (41, 44),
+}
+
+
+def slice_action_vector(action: np.ndarray) -> Dict[str, np.ndarray]:
+ return {group: np.asarray(action[start:end], dtype=np.float64) for group, (start, end) in ACTION_LAYOUT.items()}
+
+
+def classify_joint(joint_name: str) -> str:
+ name = joint_name.lower()
+ if "waist" in name or "torso" in name or "pelvis" in name:
+ return "waist"
+ if "neck" in name or "head" in name:
+ return "neck"
+ if "left" in name:
+ if "hand" in name or "finger" in name or "thumb" in name:
+ return "left_hand"
+ if "leg" in name or "hip" in name or "knee" in name or "ankle" in name:
+ return "left_leg"
+ return "left_arm"
+ if "right" in name:
+ if "hand" in name or "finger" in name or "thumb" in name:
+ return "right_hand"
+ if "leg" in name or "hip" in name or "knee" in name or "ankle" in name:
+ return "right_leg"
+ return "right_arm"
+ raise KeyError(f"无法为关节 '{joint_name}' 推断分组。")
+
+
+def build_joint_array(kin: KDLKinematics, action_slices: Dict[str, np.ndarray], allowed_groups: Iterable[str]) -> List[float]:
+ allowed, counters = set(allowed_groups), {g: 0 for g in allowed_groups}
+ joint_names = kin.get_joint_names()
+ arr = [0.0] * len(joint_names)
+ for idx, joint_name in enumerate(joint_names):
+ group = classify_joint(joint_name)
+ if group not in allowed:
+ raise KeyError(f"关节 '{joint_name}' 的分组 '{group}' 不在允许范围 {allowed} 内。")
+ values, offset = action_slices.get(group, []), counters.get(group, 0)
+ if offset >= len(values):
+ raise IndexError(f"分组 '{group}' 的动作长度不足。")
+ arr[idx], counters[group] = values[offset], offset + 1
+ return arr
+
+
+# --- 核心重构类 (严格按照 v0.py 逻辑重写) ---
+class BodyRetargeter:
+
+ def __init__(self, urdf_path: Path, camera_intrinsics: Dict[str, float]):
+ print("正在初始化 BodyRetargeter (v0 逻辑)...")
+ self.camera_intrinsics = camera_intrinsics
+
+ robot_urdf = URDF.from_xml_file(str(urdf_path))
+ tree = kdl_tree_from_urdf_model(robot_urdf)
+ base_link = "torso_link"
+
+ # 创建 v0.py 中使用的所有长运动学链
+ # 修改:使用 hand_base_link 作为末端,与 FK (body_retarget_robocasa_eepose_keypoints_v5.py) 保持一致
+ self.kin_head = KDLKinematics(robot_urdf, base_link, "head_pitch_link", tree)
+ self.kin_left_arm = KDLKinematics(robot_urdf, base_link, "left_hand_pitch_link", tree)
+ self.kin_right_arm = KDLKinematics(robot_urdf, base_link, "right_hand_pitch_link", tree)
+
+ # 直接保存 PyKDL chain 以便 IK 求解使用
+ self.chain_head = tree.getChain(base_link, "head_pitch_link")
+ self.chain_left_arm = tree.getChain(base_link, "left_hand_pitch_link")
+ self.chain_right_arm = tree.getChain(base_link, "right_hand_pitch_link")
+
+ # 定义相机在头部坐标系中的固定变换 (外参)
+ t_cam_in_head = [2.650 - 2.65017178 + 0.23, -1.944 + 2.174 - 0.23, 1.538 - 1.4475]
+ #q_cam_in_head = [-0.206, 0.677, -0.607, 0.206] # w, x, y, z
+ #q_cam_in_head = [-0.676, 0.676, 0.205, -0.205]
+ q_cam_in_head = [-0.205, 0.676, -0.676, 0.205]
+ T_cam_in_head = self._create_transform(t_cam_in_head, q_cam_in_head)
+ self.T_head_to_cam = np.linalg.inv(T_cam_in_head)
+ self.hand_orientation_axes = [
+ ("+x", np.array([1.0, 0.0, 0.0], dtype=np.float64), (0, 0, 255)),
+ ("+y", np.array([0.0, 1.0, 0.0], dtype=np.float64), (0, 255, 0)),
+ ("+z", np.array([0.0, 0.0, -1.0], dtype=np.float64), (255, 0, 0)),
+ ]
+ self.hand_orientation_length = 0.12
+
+ self._chain_max_reach = {
+ "head": self._compute_chain_max_reach(self.chain_head),
+ "left_arm": self._compute_chain_max_reach(self.chain_left_arm),
+ "right_arm": self._compute_chain_max_reach(self.chain_right_arm),
+ }
+ # self._ik_last_solution = {name: None for name in self._chain_max_reach}
+ self._workspace_margin = 0.05
+ self._ik_local_margin_max = np.deg2rad(90.0) # 最大局部搜索范围 120度
+ self._ik_local_margin = np.deg2rad(60.0)
+ self._ik_last_solution = {}
+ self._ik_damping = 1e-3 # IK 阻尼因子
+
+ # === 是否使用 URDF 关节限制(设为 False 则使用宽松的 ±π 限制)===
+ self._use_urdf_joint_limits = True
+
+ # === 从 URDF 提取真实关节限制 ===
+ self._joint_limits = self._extract_joint_limits_from_urdf(robot_urdf)
+ self._chain_joint_limits = {
+ "left_arm": self._get_chain_joint_limits(self.kin_left_arm),
+ "right_arm": self._get_chain_joint_limits(self.kin_right_arm),
+ "head": self._get_chain_joint_limits(self.kin_head),
+ }
+
+ # 打印关节限制信息(调试用)
+ print("\n=== URDF 关节限制 ===")
+ for chain_name in ["left_arm", "right_arm"]:
+ if chain_name == "left_arm":
+ joint_names = self.kin_left_arm.get_joint_names()
+ else:
+ joint_names = self.kin_right_arm.get_joint_names()
+ q_min, q_max = self._chain_joint_limits[chain_name]
+ print(f"\n{chain_name}:")
+ for i, name in enumerate(joint_names):
+ print(f" {name}: [{np.rad2deg(q_min[i]):.1f}°, {np.rad2deg(q_max[i]):.1f}°]")
+ print("=" * 30)
+
+ print("初始化完成。")
+
+ # 添加功能,为每个并行的n_episodes保存最后一个IK解算结果,防止因为其他一个IK求解成功后将其他解覆盖掉
+ # === [FIX] helper:确保每个 env_idx 有独立 bucket,避免 batch 覆盖 ===
+ def _ensure_env_bucket(self, env_idx: int):
+ env_idx = int(env_idx)
+ if env_idx not in self._ik_last_solution:
+ # 初始化该 env 的所有链 last_solution
+ self._ik_last_solution[env_idx] = {name: None for name in self._chain_max_reach}
+
+ def _get_last_solution(self, env_idx: int, chain_label: str):
+ self._ensure_env_bucket(env_idx)
+ return self._ik_last_solution[int(env_idx)].get(chain_label, None)
+
+ def _set_last_solution(self, env_idx: int, chain_label: str, sol):
+ self._ensure_env_bucket(env_idx)
+ self._ik_last_solution[int(env_idx)][chain_label] = sol
+
+ # === [FIX] 添加 reset_ik_cache 方法,用于清空 IK 历史缓存(last_solution) ===
+ def reset_ik_cache(self, env_idx: Optional[int] = None):
+ """
+ 清空 IK 历史缓存(last_solution)。
+ - env_idx=None: 清空所有并行 env 的缓存
+ - env_idx=int : 只清空指定 env slot 的缓存
+ """
+ if env_idx is None:
+ self._ik_last_solution.clear()
+ return
+ self._ik_last_solution.pop(int(env_idx), None)
+
+ def _extract_joint_limits_from_urdf(self, robot_urdf: URDF) -> Dict[str, Tuple[float, float]]:
+ """从 URDF 中提取所有关节的限制。"""
+ joint_limits = {}
+ for joint in robot_urdf.joints:
+ if joint.type in ['revolute', 'prismatic'] and joint.limit is not None:
+ lower = joint.limit.lower if joint.limit.lower is not None else -np.pi
+ upper = joint.limit.upper if joint.limit.upper is not None else np.pi
+ joint_limits[joint.name] = (float(lower), float(upper))
+ elif joint.type == 'continuous':
+ joint_limits[joint.name] = (-2.0 * np.pi, 2.0 * np.pi)
+ return joint_limits
+
+ def _get_chain_joint_limits(self, kin: KDLKinematics) -> Tuple[np.ndarray, np.ndarray]:
+ """获取运动学链中所有关节的限制。"""
+ joint_names = kin.get_joint_names()
+ num_joints = len(joint_names)
+ q_min = np.zeros(num_joints)
+ q_max = np.zeros(num_joints)
+
+ for i, joint_name in enumerate(joint_names):
+ if joint_name in self._joint_limits:
+ q_min[i], q_max[i] = self._joint_limits[joint_name]
+ else:
+ q_min[i], q_max[i] = -np.pi, np.pi
+ print(f"警告:未找到关节 '{joint_name}' 的限制,使用默认值 [-π, π]")
+
+ return q_min, q_max
+
+ def _create_transform(self, t: List[float], q: List[float]) -> np.ndarray:
+ T = np.eye(4)
+ # q 是 (w, x, y, z), scipy 需要 (x, y, z, w)
+ T[:3, :3] = R.from_quat([q[1], q[2], q[3], q[0]]).as_matrix()
+ T[:3, 3] = t
+ return T
+
+ def _compute_chain_max_reach(self, chain: kdl.Chain) -> float:
+ reach = 0.0
+ for idx in range(chain.getNrOfSegments()):
+ segment = chain.getSegment(idx)
+ frame = segment.getFrameToTip()
+ reach += frame.p.Norm()
+ return float(reach)
+
+ def _is_target_within_workspace(self, chain_name: str, target_pose: np.ndarray) -> bool:
+ max_reach = self._chain_max_reach.get(chain_name)
+ if max_reach is None:
+ return True
+ distance = float(np.linalg.norm(target_pose[:3, 3]))
+ return distance <= max_reach + self._workspace_margin
+
+ def _prepare_fallback_solution(
+ self,
+ chain_name: str,
+ q_init: List[float],
+ num_joints: int,
+ q_min: kdl.JntArray,
+ q_max: kdl.JntArray,
+ ) -> Tuple[List[float], str]:
+ candidate = [q_init[i] if i < len(q_init) else 0.0 for i in range(num_joints)]
+ reason = "使用初始关节作为兜底"
+
+ fallback: List[float] = []
+ for i in range(num_joints):
+ val = candidate[i] if i < len(candidate) else 0.0
+ lower = q_min[i]
+ upper = q_max[i]
+ fallback.append(float(max(min(val, upper), lower)))
+ return fallback, reason
+
+ # 组成44DOF向量的辅助函数
+ def _build_full_44dof_vector(obs_dict):
+ """
+ 从包含批处理数据的观测字典中构建一个 (batch_size, 44) 的完整状态向量。
+
+ Args:
+ obs_dict (Dict[str, np.ndarray]): 观测字典,其中 state 的形状为 (B, T, D)。
+ B 是批次大小 (环境数量), T 是时间步, D 是特征维度。
+
+ Returns:
+ np.ndarray: 形状为 (B, 44) 的状态向量。
+ """
+ # 定义44-DoF向量中每个部分的起始和结束索引
+ layout_44dof = {
+ "left_arm": (0, 7),
+ "left_hand": (7, 13),
+ "left_leg": (13, 19),
+ "neck": (19, 22),
+ "right_arm": (22, 29),
+ "right_hand": (29, 35),
+ "right_leg": (35, 41),
+ "waist": (41, 44),
+ }
+
+ # 从任意一个存在的状态键确定批次大小
+ batch_size = 0
+ for key in obs_dict:
+ if key.startswith("state."):
+ batch_size = obs_dict[key].shape[0]
+ break
+
+ if batch_size == 0:
+ # 如果没有找到任何 state key,无法确定批次大小,返回空数组或抛出错误
+ # 这里我们假设至少会有一个 state key
+ # 如果可能完全没有state,则需要根据具体情况处理
+ # 例如,可以尝试从 "video" key 获取 batch_size
+ if "video.ego_view" in obs_dict:
+ batch_size = obs_dict["video.ego_view"].shape[0]
+ else: # 默认返回一个 (1, 44) 的零向量
+ return np.zeros((1, 44), dtype=np.float64)
+
+ # 初始化一个 (batch_size, 44) 的零矩阵
+ full_vector = np.zeros((batch_size, 44), dtype=np.float64)
+
+ # 遍历布局,填充 full_vector
+ for part_name, (start, end) in layout_44dof.items():
+ obs_key = f"state.{part_name}"
+
+ if obs_key in obs_dict:
+ # 提取数据,形状为 (B, T, D)
+ data = np.asarray(obs_dict[obs_key])
+
+ # 我们只关心最后一个时间步的数据,其形状为 (B, D)
+ last_time_step_data = data[:, -1, :]
+
+ # 将数据填充到 full_vector 的正确位置
+ full_vector[:, start:end] = last_time_step_data
+ # 如果 obs_key 不在字典中,则该部分将保持为零,符合要求
+
+ return full_vector
+
+ def process_kinematics_dataloader(self,
+ action_vectors: np.ndarray) -> Tuple[Tuple[np.ndarray, np.ndarray], Tuple[np.ndarray, np.ndarray]]:
+ """
+ 批量处理运动学数据,返回轴角表示。
+
+ 参数:
+ action_vectors: shape (batch_size, 44) 或 (44,) 的动作向量
+
+ 返回:
+ ((left_hand_pos, left_hand_axisangle), (right_hand_pos, right_hand_axisangle))
+ - left_hand_pos: shape (batch_size, 3) 或 (3,)
+ - left_hand_axisangle: shape (batch_size, 3) 或 (3,)
+ - right_hand_pos: shape (batch_size, 3) 或 (3,)
+ - right_hand_axisangle: shape (batch_size, 3) 或 (3,)
+ """
+ # 确保输入是 numpy array(tf.py_function 会自动转换,但这里做个保险)
+ action_vectors = np.asarray(action_vectors)
+
+ # 处理单个向量的情况
+ if action_vectors.ndim == 1:
+ action_vectors = action_vectors[np.newaxis, :] # shape (1, 44)
+ squeeze_output = True
+ else:
+ squeeze_output = False
+
+ batch_size = action_vectors.shape[0]
+
+ # 初始化输出数组
+ left_hand_positions = np.zeros((batch_size, 3), dtype=np.float64)
+ right_hand_positions = np.zeros((batch_size, 3), dtype=np.float64)
+ left_hand_axisangles = np.zeros((batch_size, 3), dtype=np.float64)
+ right_hand_axisangles = np.zeros((batch_size, 3), dtype=np.float64)
+
+ # 批量处理每个动作向量
+ for i in range(batch_size):
+ action_vector = action_vectors[i]
+ action_slices = slice_action_vector(action_vector)
+
+ # 构建 v0.py 使用的包含 waist 和 neck 的关节数组
+ q_head = build_joint_array(self.kin_head, action_slices, ("waist", "neck"))
+ q_left_arm = build_joint_array(self.kin_left_arm, action_slices, ("waist", "left_arm"))
+ q_right_arm = build_joint_array(self.kin_right_arm, action_slices, ("waist", "right_arm"))
+
+ # 正向运动学
+ T_torso_to_head = self.kin_head.forward(q_head)
+ T_torso_to_left_hand = self.kin_left_arm.forward(q_left_arm)
+ T_torso_to_right_hand = self.kin_right_arm.forward(q_right_arm)
+
+ # 坐标系转换
+ T_inv_torso_to_head = np.linalg.inv(T_torso_to_head)
+ T_head_to_left_hand = T_inv_torso_to_head @ T_torso_to_left_hand
+ T_head_to_right_hand = T_inv_torso_to_head @ T_torso_to_right_hand
+
+ # 最终转换到相机坐标系
+ T_cam_to_left_hand = self.T_head_to_cam @ T_head_to_left_hand
+ T_cam_to_right_hand = self.T_head_to_cam @ T_head_to_right_hand
+
+ # 提取位置(展平为一维数组)
+ left_hand_positions[i] = T_cam_to_left_hand[:3, 3].flatten()
+ right_hand_positions[i] = T_cam_to_right_hand[:3, 3].flatten()
+
+ # 提取旋转矩阵并转换为轴角表示
+ left_hand_rot_mat = T_cam_to_left_hand[:3, :3]
+ right_hand_rot_mat = T_cam_to_right_hand[:3, :3]
+
+ # 使用 scipy 将旋转矩阵转换为轴角(rotvec)
+ left_hand_axisangles[i] = R.from_matrix(left_hand_rot_mat).as_rotvec()
+ right_hand_axisangles[i] = R.from_matrix(right_hand_rot_mat).as_rotvec()
+
+ # 如果输入是单个向量,则压缩批次维度
+ if squeeze_output:
+ left_hand_positions = left_hand_positions[0]
+ right_hand_positions = right_hand_positions[0]
+ left_hand_axisangles = left_hand_axisangles[0]
+ right_hand_axisangles = right_hand_axisangles[0]
+
+ return (left_hand_positions, left_hand_axisangles), (right_hand_positions, right_hand_axisangles)
+
+ # FK:
+ def process_frame_kinematics(self, action_vector: np.ndarray) -> Tuple[Tuple[np.ndarray, np.ndarray], Tuple[np.ndarray, np.ndarray]]:
+ action_slices = slice_action_vector(action_vector)
+
+ # 构建 v0.py 使用的包含 waist 和 neck 的关节数组
+ q_head = build_joint_array(self.kin_head, action_slices, ("waist", "neck"))
+ q_left_arm = build_joint_array(self.kin_left_arm, action_slices, ("waist", "left_arm"))
+ q_right_arm = build_joint_array(self.kin_right_arm, action_slices, ("waist", "right_arm"))
+
+ # 正向运动学
+ T_torso_to_head = self.kin_head.forward(q_head)
+ T_torso_to_left_hand = self.kin_left_arm.forward(q_left_arm)
+ T_torso_to_right_hand = self.kin_right_arm.forward(q_right_arm)
+
+ # 坐标系转换
+ T_inv_torso_to_head = np.linalg.inv(T_torso_to_head)
+ T_head_to_left_hand = T_inv_torso_to_head @ T_torso_to_left_hand
+ T_head_to_right_hand = T_inv_torso_to_head @ T_torso_to_right_hand
+
+ # 最终转换到相机坐标系
+ T_cam_to_left_hand = self.T_head_to_cam @ T_head_to_left_hand
+ T_cam_to_right_hand = self.T_head_to_cam @ T_head_to_right_hand
+
+ left_hand_pos = np.asarray(T_cam_to_left_hand[:3, 3]).flatten()
+ right_hand_pos = np.asarray(T_cam_to_right_hand[:3, 3]).flatten()
+
+ #import pdb; pdb.set_trace()
+ left_hand_rot = np.asarray(T_cam_to_left_hand[:3, :3], dtype=np.float64)
+ right_hand_rot = np.asarray(T_cam_to_right_hand[:3, :3], dtype=np.float64)
+
+ return (left_hand_pos, left_hand_rot), (right_hand_pos, right_hand_rot)
+
+ # FK + 转轴角表示
+ def process_frame_kinematics_axisangle(
+ self, action_vector: np.ndarray) -> Tuple[Tuple[np.ndarray, np.ndarray], Tuple[np.ndarray, np.ndarray]]:
+ """
+ 处理运动学数据并返回轴角表示。支持单个向量或批量处理。
+
+ 参数:
+ action_vector: shape (batch_size, 44) 或 (44,) 的动作向量
+
+ 返回:
+ ((left_hand_pos, left_hand_axisangle), (right_hand_pos, right_hand_axisangle))
+ - left_hand_pos: shape (batch_size, 3) 或 (3,)
+ - left_hand_axisangle: shape (batch_size, 3) 或 (3,)
+ - right_hand_pos: shape (batch_size, 3) 或 (3,)
+ - right_hand_axisangle: shape (batch_size, 3) 或 (3,)
+ """
+ # 确保输入是 numpy array
+ action_vector = np.asarray(action_vector)
+
+ # 处理单个向量的情况
+ if action_vector.ndim == 1:
+ action_vector = action_vector[np.newaxis, :] # shape (1, 44)
+ squeeze_output = True
+ else:
+ squeeze_output = False
+
+ batch_size = action_vector.shape[0]
+
+ # 初始化输出数组
+ left_hand_positions = np.zeros((batch_size, 3), dtype=np.float64)
+ right_hand_positions = np.zeros((batch_size, 3), dtype=np.float64)
+ left_hand_axisangles = np.zeros((batch_size, 3), dtype=np.float64)
+ right_hand_axisangles = np.zeros((batch_size, 3), dtype=np.float64)
+ left_qpos_states = np.zeros((batch_size, 7), dtype=np.float64)
+ right_qpos_states = np.zeros((batch_size, 7), dtype=np.float64)
+
+ # 批量处理每个动作向量
+ for i in range(batch_size):
+ action_slices = slice_action_vector(action_vector[i])
+
+ # 新增:从切片中提取并保存左右臂的关节状态
+ left_qpos_states[i] = action_slices["left_arm"]
+ right_qpos_states[i] = action_slices["right_arm"]
+
+ # 构建 v0.py 使用的包含 waist 和 neck 的关节数组
+ q_head = build_joint_array(self.kin_head, action_slices, ("waist", "neck"))
+ q_left_arm = build_joint_array(self.kin_left_arm, action_slices, ("waist", "left_arm"))
+ q_right_arm = build_joint_array(self.kin_right_arm, action_slices, ("waist", "right_arm"))
+
+ # 正向运动学
+ T_torso_to_head = self.kin_head.forward(q_head)
+ T_torso_to_left_hand = self.kin_left_arm.forward(q_left_arm)
+ T_torso_to_right_hand = self.kin_right_arm.forward(q_right_arm)
+
+ # 坐标系转换
+ T_inv_torso_to_head = np.linalg.inv(T_torso_to_head)
+ T_head_to_left_hand = T_inv_torso_to_head @ T_torso_to_left_hand
+ T_head_to_right_hand = T_inv_torso_to_head @ T_torso_to_right_hand
+
+ # 最终转换到相机坐标系
+ T_cam_to_left_hand = self.T_head_to_cam @ T_head_to_left_hand
+ T_cam_to_right_hand = self.T_head_to_cam @ T_head_to_right_hand
+
+ # 提取位置(展平为一维数组)
+ left_hand_positions[i] = T_cam_to_left_hand[:3, 3].flatten()
+ right_hand_positions[i] = T_cam_to_right_hand[:3, 3].flatten()
+
+ # 提取旋转矩阵并转换为轴角表示
+ left_hand_rot = np.asarray(T_cam_to_left_hand[:3, :3], dtype=np.float64)
+ right_hand_rot = np.asarray(T_cam_to_right_hand[:3, :3], dtype=np.float64)
+
+ # 将旋转矩阵转换为轴角(rotation vector)
+ left_hand_axisangles[i] = R.from_matrix(left_hand_rot).as_rotvec()
+ right_hand_axisangles[i] = R.from_matrix(right_hand_rot).as_rotvec()
+
+ # 如果输入是单个向量,则压缩批次维度
+ if squeeze_output:
+ left_hand_positions = left_hand_positions[0]
+ right_hand_positions = right_hand_positions[0]
+ left_hand_axisangles = left_hand_axisangles[0]
+ right_hand_axisangles = right_hand_axisangles[0]
+ left_qpos_states = left_qpos_states[0]
+ right_qpos_states = right_qpos_states[0]
+ return (left_hand_positions, left_hand_axisangles), (right_hand_positions, right_hand_axisangles), (left_qpos_states,
+ right_qpos_states)
+
+ # IK 解算 + 轴角表示:
+ def inverse_kinematics_from_camera_axisangle(
+ self,
+ left_hand_pos: np.ndarray,
+ left_hand_axisangle: np.ndarray,
+ right_hand_pos: np.ndarray,
+ right_hand_axisangle: np.ndarray,
+ current_action_vector: Optional[np.ndarray] = None,
+ q_init_left: Optional[np.ndarray] = None,
+ q_init_right: Optional[np.ndarray] = None) -> Tuple[Optional[np.ndarray], Optional[np.ndarray]]:
+ """
+ 从相机坐标系下的手部位姿反向求解关节角度。支持单个样本或批量处理。
+
+ 参数:
+ left_hand_pos: 左手位置,shape (batch_size, 3) 或 (3,) - 相机坐标系
+ left_hand_axisangle: 左手轴角表示,shape (batch_size, 3) 或 (3,) - 相机坐标系
+ right_hand_pos: 右手位置,shape (batch_size, 3) 或 (3,) - 相机坐标系
+ right_hand_axisangle: 右手轴角表示,shape (batch_size, 3) 或 (3,) - 相机坐标系
+ current_action_vector: 当前完整动作向量,shape (batch_size, 44) 或 (44,)
+ 用于获取 waist 和 neck 的角度
+ 如果为 None,则使用零角度作为初始猜测
+ q_init_left: 左臂的初始关节角度猜测,使用当前step的state,shape (batch_size, num_joints) 或 (num_joints,)
+ q_init_right: 右臂的初始关节角度猜测,使用当前step的state,shape (batch_size, num_joints) 或 (num_joints,)
+
+ 返回:
+ (q_left_arm, q_right_arm): 左臂和右臂的关节角度
+ - shape (batch_size, num_joints) 或 (num_joints,),取决于输入
+ - 如果 IK 求解失败,对应的返回值为 None
+ """
+ # 确保输入是 numpy array
+ left_hand_pos = np.asarray(left_hand_pos, dtype=np.float64)
+ left_hand_axisangle = np.asarray(left_hand_axisangle, dtype=np.float64)
+ right_hand_pos = np.asarray(right_hand_pos, dtype=np.float64)
+ right_hand_axisangle = np.asarray(right_hand_axisangle, dtype=np.float64)
+
+ # 处理单个样本的情况
+ if left_hand_pos.ndim == 1:
+ left_hand_pos = left_hand_pos[np.newaxis, :] # shape (1, 3)
+ left_hand_axisangle = left_hand_axisangle[np.newaxis, :] # shape (1, 3)
+ right_hand_pos = right_hand_pos[np.newaxis, :] # shape (1, 3)
+ right_hand_axisangle = right_hand_axisangle[np.newaxis, :] # shape (1, 3)
+ squeeze_output = True
+ else:
+ squeeze_output = False
+
+ batch_size = left_hand_pos.shape[0]
+
+ # 处理 current_action_vector
+ if current_action_vector is not None:
+ current_action_vector = np.asarray(current_action_vector, dtype=np.float64)
+ if current_action_vector.ndim == 1:
+ current_action_vector = current_action_vector[np.newaxis, :] # shape (1, 44)
+
+ # 处理初始猜测
+ if q_init_left is not None:
+ q_init_left = np.asarray(q_init_left, dtype=np.float64)
+ if q_init_left.ndim == 1:
+ q_init_left = q_init_left[np.newaxis, :]
+
+ if q_init_right is not None:
+ q_init_right = np.asarray(q_init_right, dtype=np.float64)
+ if q_init_right.ndim == 1:
+ q_init_right = q_init_right[np.newaxis, :]
+
+ # 获取关节数量
+ num_left_joints = len(self.kin_left_arm.get_joint_names())
+ num_right_joints = len(self.kin_right_arm.get_joint_names())
+
+ # 初始化输出数组(使用 None 填充,因为 IK 可能失败)
+ q_left_arm_batch = []
+ q_right_arm_batch = []
+
+ # 批量处理每个样本
+ for i in range(batch_size):
+ # 提取当前样本的数据
+ curr_left_pos = left_hand_pos[i]
+ curr_left_axisangle = left_hand_axisangle[i]
+ curr_right_pos = right_hand_pos[i]
+ curr_right_axisangle = right_hand_axisangle[i]
+
+ # === 步骤1: 将轴角表示转换为旋转矩阵,构建 4x4 变换矩阵 ===
+ left_hand_rot = R.from_rotvec(curr_left_axisangle).as_matrix()
+ right_hand_rot = R.from_rotvec(curr_right_axisangle).as_matrix()
+
+ # 构建相机坐标系下的手部变换矩阵
+ T_cam_to_left_hand = np.eye(4)
+ T_cam_to_left_hand[:3, :3] = left_hand_rot
+ T_cam_to_left_hand[:3, 3] = curr_left_pos
+
+ T_cam_to_right_hand = np.eye(4)
+ T_cam_to_right_hand[:3, :3] = right_hand_rot
+ T_cam_to_right_hand[:3, 3] = curr_right_pos
+
+ # === 步骤2: 获取 waist 和 neck 的当前角度,计算 T_torso_to_head ===
+ if current_action_vector is not None:
+ # 从完整动作向量中提取 waist 和 neck
+ action_slices = slice_action_vector(current_action_vector[i])
+ q_head = build_joint_array(self.kin_head, action_slices, ("waist", "neck"))
+
+ # 如果没有提供初始猜测,从 action_vector 中提取
+ if q_init_left is None:
+ curr_q_init_left = build_joint_array(self.kin_left_arm, action_slices, ("waist", "left_arm"))
+ else:
+ curr_q_init_left = q_init_left[i].tolist()
+
+ if q_init_right is None:
+ curr_q_init_right = build_joint_array(self.kin_right_arm, action_slices, ("waist", "right_arm"))
+ else:
+ curr_q_init_right = q_init_right[i].tolist()
+ else:
+ # 使用零角度作为默认值
+ num_head_joints = len(self.kin_head.get_joint_names())
+ q_head = [0.0] * num_head_joints
+
+ if q_init_left is None:
+ curr_q_init_left = [0.0] * num_left_joints
+ else:
+ curr_q_init_left = q_init_left[i].tolist()
+
+ if q_init_right is None:
+ curr_q_init_right = [0.0] * num_right_joints
+ else:
+ curr_q_init_right = q_init_right[i].tolist()
+
+ # 计算 torso 到 head 的变换
+ T_torso_to_head = self.kin_head.forward(q_head)
+
+ # === 步骤3: 坐标系转换(相机 -> head -> torso)===
+ T_cam_to_head = np.linalg.inv(self.T_head_to_cam)
+
+ # 相机坐标系 -> 头部坐标系
+ T_head_to_left_hand = T_cam_to_head @ T_cam_to_left_hand
+ T_head_to_right_hand = T_cam_to_head @ T_cam_to_right_hand
+
+ # 头部坐标系 -> torso 坐标系
+ T_torso_to_left_hand = T_torso_to_head @ T_head_to_left_hand
+ T_torso_to_right_hand = T_torso_to_head @ T_head_to_right_hand
+
+ # === 步骤4: 使用 IK 求解器求解关节角度 ===
+ # q_left_arm = self._solve_ik(self.chain_left_arm, T_torso_to_left_hand, curr_q_init_left, chain_name="left_arm")
+ # q_right_arm = self._solve_ik(self.chain_right_arm, T_torso_to_right_hand, curr_q_init_right, chain_name="right_arm")
+ q_left_arm = self._solve_ik(self.chain_left_arm, T_torso_to_left_hand, curr_q_init_left, chain_name="left_arm", env_idx=i)
+ q_right_arm = self._solve_ik(self.chain_right_arm, T_torso_to_right_hand, curr_q_init_right, chain_name="right_arm", env_idx=i)
+ # 将结果添加到批次列表
+ if q_left_arm is not None:
+ q_left_arm_batch.append(np.array(q_left_arm))
+ else:
+ q_left_arm_batch.append(None)
+
+ if q_right_arm is not None:
+ q_right_arm_batch.append(np.array(q_right_arm))
+ else:
+ q_right_arm_batch.append(None)
+
+ # === 步骤5: 整理输出 ===
+ # 检查是否所有样本都成功求解
+ all_left_success = all(q is not None for q in q_left_arm_batch)
+ all_right_success = all(q is not None for q in q_right_arm_batch)
+
+ # 转换为 numpy 数组(如果所有样本都成功)
+ if all_left_success:
+ q_left_arm_result = np.array(q_left_arm_batch)
+ else:
+ # 有失败的情况,返回列表
+ q_left_arm_result = q_left_arm_batch if not squeeze_output else (q_left_arm_batch[0] if q_left_arm_batch else None)
+ if not all_left_success and squeeze_output:
+ return q_left_arm_result, None
+
+ if all_right_success:
+ q_right_arm_result = np.array(q_right_arm_batch)
+ else:
+ # 有失败的情况,返回列表
+ q_right_arm_result = q_right_arm_batch if not squeeze_output else (q_right_arm_batch[0] if q_right_arm_batch else None)
+ if not all_right_success and squeeze_output:
+ return None, q_right_arm_result
+
+ # 如果输入是单个样本,则压缩批次维度
+ if squeeze_output:
+ q_left_arm_result = q_left_arm_result[0] if all_left_success else q_left_arm_batch[0]
+ q_right_arm_result = q_right_arm_result[0] if all_right_success else q_right_arm_batch[0]
+
+ return q_left_arm_result, q_right_arm_result
+
+ def inverse_kinematics_from_camera(self, T_cam_to_hand: np.ndarray, initial_q: np.ndarray, kin: KDLKinematics) -> Optional[np.ndarray]:
+ """
+ 从相机坐标系下的手部位姿反向求解关节角度。
+
+ 参数:
+ T_cam_to_hand: 相机坐标系到手部的变换矩阵 (4x4)
+ initial_q: 初始关节角度(用于IK求解的初始猜测)
+ kin: 使用的运动学链(left_arm 或 right_arm)
+
+ 返回:
+ 求解的关节角度,如果求解失败则返回 None
+ """
+ # 步骤1: 将相机坐标系的位姿转换回 torso 坐标系
+ # T_cam_to_hand -> T_head_to_hand -> T_torso_to_hand
+
+ # 相机到头部的变换(T_head_to_cam 的逆)
+ T_cam_to_head = np.linalg.inv(self.T_head_to_cam)
+
+ # 相机 -> 头部 -> 手部
+ T_head_to_hand = T_cam_to_head @ T_cam_to_hand
+
+ # 需要知道 T_torso_to_head,但这需要当前的 neck 和 waist 关节角度
+ # 这里我们使用初始关节角度来计算(应该传入当前的 q_head)
+ # 暂时简化处理:假设已知完整的 torso 到 head 的变换
+
+ # 实际上需要完整的关节配置来计算 T_torso_to_head
+ # 这里返回 None,需要完整实现
+ return None
+
+ def verify_ik_solution(self, action_vector: np.ndarray, verbose: bool = True) -> Dict[str, any]:
+ """
+ 验证 FK -> IK -> FK 的完整流程。
+
+ 参数:
+ action_vector: 原始动作向量
+ verbose: 是否打印详细信息
+
+ 返回:
+ 包含验证结果的字典
+ """
+ action_slices = slice_action_vector(action_vector)
+
+ # === 步骤1: 原始 FK ===
+ q_head = build_joint_array(self.kin_head, action_slices, ("waist", "neck"))
+ q_left_arm_original = build_joint_array(self.kin_left_arm, action_slices, ("waist", "left_arm"))
+ q_right_arm_original = build_joint_array(self.kin_right_arm, action_slices, ("waist", "right_arm"))
+
+ # 正向运动学
+ T_torso_to_head = self.kin_head.forward(q_head)
+ T_torso_to_left_hand = self.kin_left_arm.forward(q_left_arm_original)
+ T_torso_to_right_hand = self.kin_right_arm.forward(q_right_arm_original)
+
+ # 转换到相机坐标系
+ T_inv_torso_to_head = np.linalg.inv(T_torso_to_head)
+ T_head_to_left_hand = T_inv_torso_to_head @ T_torso_to_left_hand
+ T_head_to_right_hand = T_inv_torso_to_head @ T_torso_to_right_hand
+
+ T_cam_to_left_hand = self.T_head_to_cam @ T_head_to_left_hand
+ T_cam_to_right_hand = self.T_head_to_cam @ T_head_to_right_hand
+
+ # === 步骤2: 反向变换(相机 -> torso)===
+ T_cam_to_head = np.linalg.inv(self.T_head_to_cam)
+
+ # 相机系下的手部位姿 -> 头部系下的手部位姿
+ T_head_to_left_hand_recovered = T_cam_to_head @ T_cam_to_left_hand
+ T_head_to_right_hand_recovered = T_cam_to_head @ T_cam_to_right_hand
+
+ # 头部系 -> torso 系
+ T_torso_to_left_hand_recovered = T_torso_to_head @ T_head_to_left_hand_recovered
+ T_torso_to_right_hand_recovered = T_torso_to_head @ T_head_to_right_hand_recovered
+
+ # === 步骤3: IK 求解 ===
+ # 使用 PyKDL 的 IK 求解器
+ q_left_arm_ik = self._solve_ik(self.chain_left_arm, T_torso_to_left_hand_recovered, q_left_arm_original, chain_name="left_arm")
+ q_right_arm_ik = self._solve_ik(self.chain_right_arm, T_torso_to_right_hand_recovered, q_right_arm_original, chain_name="right_arm")
+
+ # === 步骤4: 验证 FK ===
+ if q_left_arm_ik is not None:
+ T_torso_to_left_hand_verified = self.kin_left_arm.forward(q_left_arm_ik)
+ else:
+ T_torso_to_left_hand_verified = None
+
+ if q_right_arm_ik is not None:
+ T_torso_to_right_hand_verified = self.kin_right_arm.forward(q_right_arm_ik)
+ else:
+ T_torso_to_right_hand_verified = None
+
+ # === 步骤5: 计算误差 ===
+ results = {
+ 'left_arm': self._compute_errors(q_left_arm_original, q_left_arm_ik, T_torso_to_left_hand, T_torso_to_left_hand_verified),
+ 'right_arm': self._compute_errors(q_right_arm_original, q_right_arm_ik, T_torso_to_right_hand, T_torso_to_right_hand_verified),
+ }
+
+ # print("original q_left_arm_original: ", q_left_arm_original)
+ # print("original q_right_arm_original: ", q_right_arm_original)
+ # print("ik q_left_arm_ik: ", q_left_arm_ik)
+ # print("ik q_right_arm_ik: ", q_right_arm_ik)
+
+ # print("T_torso_to_left_hand_verified: ", T_torso_to_left_hand_verified)
+ # print("T_torso_to_left_hand: ", T_torso_to_left_hand)
+ # print("T_torso_to_right_hand_verified: ", T_torso_to_right_hand_verified)
+ # print("T_torso_to_right_hand: ", T_torso_to_right_hand)
+
+ if verbose:
+ print("\n=== IK 验证结果 ===")
+ for arm_name, result in results.items():
+ print(f"\n{arm_name}:")
+ if result['ik_success']:
+ print(f" 关节角度误差 (度): {result['joint_error_deg']:.4f}")
+ print(f" 位置误差 (m): {result['position_error']:.6f}")
+ print(f" 姿态误差 (度): {result['orientation_error_deg']:.4f}")
+ else:
+ print(f" IK 求解失败")
+
+ return results
+
+ def _solve_ik(
+ self,
+ chain: kdl.Chain,
+ target_pose: np.ndarray,
+ q_init: List[float],
+ chain_name: str = "unnamed",
+ env_idx: int = 0,
+ ) -> Optional[List[float]]:
+ """
+ 使用 KDL IK 求解器求解逆向运动学。
+
+ 参数:
+ chain: 运动学链(PyKDL Chain)
+ target_pose: 目标位姿 (4x4 矩阵)
+ q_init: 初始关节角度
+ chain_name: 用于日志与缓存的链名称
+
+ 返回:
+ 求解的关节角度;若常规 IK 失败,将返回兜底解(上一帧成功解或初始关节)
+
+ 关键改动:
+ - last_solution 按 env_idx 分桶保存:self._ik_last_solution[env_idx][chain_label]
+ """
+
+ chain_label = chain_name or "unnamed"
+ env_idx = int(env_idx)
+ try:
+ # === [FIX] 确保该 env 的 bucket 存在 ===
+ self._ensure_env_bucket(env_idx)
+
+ if chain_label not in self._chain_max_reach:
+ self._chain_max_reach[chain_label] = self._compute_chain_max_reach(chain)
+
+ # 将 numpy 矩阵转换为 PyKDL Frame
+ target_frame = self._numpy_to_kdl_frame(target_pose)
+
+ num_joints = chain.getNrOfJoints()
+
+ # 设置全局关节限制
+ global_q_min = kdl.JntArray(num_joints)
+ global_q_max = kdl.JntArray(num_joints)
+
+ if self._use_urdf_joint_limits and chain_label in self._chain_joint_limits:
+ # 使用 URDF 中的真实限制
+ urdf_q_min, urdf_q_max = self._chain_joint_limits[chain_label]
+ for i in range(num_joints):
+ global_q_min[i] = urdf_q_min[i] if i < len(urdf_q_min) else -np.pi
+ global_q_max[i] = urdf_q_max[i] if i < len(urdf_q_max) else np.pi
+ else:
+ # 使用宽松的默认限制
+ for i in range(num_joints):
+ global_q_min[i] = -2.0 * np.pi
+ global_q_max[i] = 2.0 * np.pi
+
+ q_init_full = [q_init[i] if i < len(q_init) else 0.0 for i in range(num_joints)]
+
+ # 先取“该 env 的 last_solution”作为最终兜底候选
+ last_sol = self._get_last_solution(env_idx, chain_label)
+
+ if not self._is_target_within_workspace(chain_label, target_pose):
+ # 优先用 last_solution;否则用当前 q_init 做兜底
+ fallback_solution = last_sol
+ if fallback_solution is None:
+ fallback_solution, reason = self._prepare_fallback_solution(chain_label, q_init, num_joints, global_q_min, global_q_max)
+ else:
+ reason = "使用该 env 的上一帧 IK 解作为兜底"
+ print(f" 目标超出 {chain_label} 工作空间,{reason}。")
+
+ self._set_last_solution(env_idx, chain_label, fallback_solution)
+
+ return fallback_solution
+
+ # 创建求解器所需组件
+ fk_solver = kdl.ChainFkSolverPos_recursive(chain)
+ # ik_vel_solver = kdl.ChainIkSolverVel_pinv(chain)
+ ik_vel_solver = kdl.ChainIkSolverVel_wdls(chain) # 使用 PyKDL 内置的 WDLS(Weighted Damped Least Squares)求解器,支持阻尼
+ ik_vel_solver.setLambda(self._ik_damping) # 设置阻尼因子,避免奇异点
+
+ # 多次尝试以提高成功率
+ max_attempts = 5
+ base_maxiter = 200
+ eps_schedule = [1e-6, 5e-6, 1e-5, 5e-5, 1e-4]
+ seed_noise = 0.25 # 单位: 弧度
+
+ for attempt in range(max_attempts):
+ eps = eps_schedule[min(attempt, len(eps_schedule) - 1)]
+ maxiter = base_maxiter * (attempt + 1)
+ # local_margin = self._ik_local_margin * (attempt + 1)
+ local_margin = min(self._ik_local_margin * (attempt + 1), self._ik_local_margin_max)
+
+ local_q_min = kdl.JntArray(num_joints)
+ local_q_max = kdl.JntArray(num_joints)
+ for i in range(num_joints):
+ center = q_init_full[i]
+ lower = max(center - local_margin, global_q_min[i])
+ upper = min(center + local_margin, global_q_max[i])
+ if lower >= upper:
+ lower = global_q_min[i]
+ upper = global_q_max[i]
+ local_q_min[i] = lower
+ local_q_max[i] = upper
+
+ ik_solver = kdl.ChainIkSolverPos_NR_JL(chain, local_q_min, local_q_max, fk_solver, ik_vel_solver, maxiter=maxiter, eps=eps)
+
+ q_init_kdl = kdl.JntArray(num_joints)
+ noise_scale = seed_noise * attempt
+ for i in range(num_joints):
+ init_val = q_init_full[i]
+ if attempt > 0:
+ init_val += float(np.random.uniform(-noise_scale, noise_scale))
+ # 限制在局部关节范围内
+ init_val = max(min(init_val, local_q_max[i]), local_q_min[i])
+ q_init_kdl[i] = init_val
+
+ q_out = kdl.JntArray(num_joints)
+ ret = ik_solver.CartToJnt(q_init_kdl, target_frame, q_out)
+
+ if ret >= 0:
+ solution = [q_out[i] for i in range(num_joints)]
+ # self._ik_last_solution[chain_label] = solution
+
+ # === 添加角度连续性处理,防止正pai负pai跳变 ===
+ prev_solution = self._get_last_solution(env_idx, chain_label)
+ if prev_solution is not None:
+ unwrapped_solution = []
+ for i, (curr, prev) in enumerate(zip(solution, prev_solution)):
+ # 计算角度差并归一化到 [-π, π]
+ diff = curr - prev
+ # 将差值归一化到 [-π, π] 范围
+ diff = ((diff + np.pi) % (2 * np.pi)) - np.pi
+ # 使用修正后的差值
+ unwrapped_solution.append(prev + diff)
+ solution = unwrapped_solution
+
+ self._set_last_solution(env_idx, chain_label, solution)
+ return solution
+
+ # print(
+ # f" IK 求解失败({chain_label}),第 {attempt + 1}/{max_attempts} 次尝试,"
+ # f"返回码: {ret},maxiter={maxiter},eps={eps}"
+ # )
+
+ # 最终兜底策略
+ # fallback_solution, reason = self._prepare_fallback_solution(
+ # chain_label, q_init, num_joints, global_q_min, global_q_max
+ # )
+ # self._ik_last_solution[chain_label] = fallback_solution
+ # 最终兜底:优先 last_solution,否则用 q_init clip
+ fallback_solution = last_sol
+ if fallback_solution is None:
+ fallback_solution, _ = self._prepare_fallback_solution(chain_label, q_init, num_joints, global_q_min, global_q_max)
+
+ self._set_last_solution(env_idx, chain_label, fallback_solution)
+ # print(f" IK 多次尝试仍失败({chain_label}),{reason}。")
+
+ return fallback_solution
+
+ except Exception as e:
+ print(f"IK 求解异常({chain_label}, env={env_idx}): {e}")
+ import traceback
+ traceback.print_exc()
+ num_joints = chain.getNrOfJoints()
+ # 异常兜底:优先 last_solution,否则 clip(q_init) 到 URDF 限制
+ last_sol = self._get_last_solution(env_idx, chain_label)
+ if last_sol is not None:
+ fallback = last_sol
+ else:
+ # 使用 URDF 限制进行 clip
+ if chain_label in self._chain_joint_limits:
+ urdf_q_min, urdf_q_max = self._chain_joint_limits[chain_label]
+ fallback = [
+ float(
+ np.clip(q_init[i] if i < len(q_init) else 0.0, urdf_q_min[i] if i < len(urdf_q_min) else -np.pi,
+ urdf_q_max[i] if i < len(urdf_q_max) else np.pi)) for i in range(num_joints)
+ ]
+ else:
+ fallback = [float(np.clip(q_init[i] if i < len(q_init) else 0.0, -np.pi, np.pi)) for i in range(num_joints)]
+
+ self._set_last_solution(env_idx, chain_label, fallback)
+ return fallback
+
+ def _numpy_to_kdl_frame(self, T: np.ndarray) -> kdl.Frame:
+ """将 numpy 4x4 变换矩阵转换为 PyKDL Frame"""
+ rotation = kdl.Rotation(T[0, 0], T[0, 1], T[0, 2], T[1, 0], T[1, 1], T[1, 2], T[2, 0], T[2, 1], T[2, 2])
+ position = kdl.Vector(T[0, 3], T[1, 3], T[2, 3])
+ return kdl.Frame(rotation, position)
+
+ def _compute_errors(self, q_original: List[float], q_ik: Optional[List[float]], T_original: np.ndarray,
+ T_ik: Optional[np.ndarray]) -> Dict[str, any]:
+ """计算原始值和 IK 求解值之间的误差"""
+ if q_ik is None or T_ik is None:
+ return {'ik_success': False, 'joint_error_deg': None, 'position_error': None, 'orientation_error_deg': None}
+
+ # 关节角度误差(转换为度)
+ q_original_arr = np.array(q_original)
+ q_ik_arr = np.array(q_ik)
+ joint_error = np.linalg.norm(q_original_arr - q_ik_arr)
+ joint_error_deg = np.rad2deg(joint_error)
+
+ # 位置误差
+ pos_original = T_original[:3, 3]
+ pos_ik = T_ik[:3, 3]
+ position_error = np.linalg.norm(pos_original - pos_ik)
+
+ # 姿态误差(使用旋转矩阵的差异)
+ R_original = T_original[:3, :3]
+ R_ik = T_ik[:3, :3]
+ R_error = R_original.T @ R_ik
+ # 计算旋转角度
+ trace = np.trace(R_error)
+ angle_error = np.arccos(np.clip((trace - 1) / 2, -1, 1))
+ orientation_error_deg = np.rad2deg(angle_error)
+
+ return {
+ 'ik_success': True,
+ 'joint_error_deg': joint_error_deg,
+ 'position_error': position_error,
+ 'orientation_error_deg': orientation_error_deg,
+ 'q_original': q_original,
+ 'q_ik': q_ik
+ }
+
+ def process_episode(self, video_path: Path, parquet_path: Path, output_path: Path, verify_ik: bool = True):
+ print(f"开始处理 episode: {video_path.parent.name}")
+ df = pd.read_parquet(parquet_path)
+ #actions = df["action"].tolist()
+ #import pdb; pdb.set_trace()
+ actions = df["observation.state"].tolist()
+ cap = cv2.VideoCapture(str(video_path))
+ if not cap.isOpened():
+ raise FileNotFoundError(f"无法打开视频: {video_path}")
+
+ fps = int(cap.get(cv2.CAP_PROP_FPS))
+ # 修改:输出视频的分辨率应为处理后的 256x256
+ output_resolution = (256, 256)
+ #output_resolution = (1280, 800)
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
+ out = cv2.VideoWriter(str(output_path), fourcc, fps, output_resolution)
+
+ num_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
+ print(f"视频总帧数: {num_frames}, 动作数据总数: {len(actions)}")
+
+ # === IK 验证(在第一帧上执行)===
+ if verify_ik and len(actions) > 0:
+ print("\n执行 IK 验证(使用第一帧数据)...")
+ ik_results = self.verify_ik_solution(np.array(actions[0]), verbose=True)
+
+ for i in tqdm(range(min(num_frames, len(actions))), desc="处理视频帧"):
+ ok, frame = cap.read()
+ if not ok:
+ break
+
+ # 修改:将原始帧处理为 256x256
+ final_frame = process_img_cotrain(frame)
+
+ (left_pos, left_rot), (right_pos, right_rot) = self.process_frame_kinematics(np.array(actions[i]))
+
+ #import pdb; pdb.set_trace()
+
+ # 修改:在处理后的 256x256 图像上绘制点
+ self._draw_projection(i, final_frame, left_pos, left_rot, color=(0, 0, 255)) # 左手红色
+ self._draw_projection(i, final_frame, right_pos, right_rot, color=(255, 0, 0)) # 右手蓝色
+
+ out.write(final_frame)
+
+ cap.release()
+ out.release()
+ print(f"\n处理完成!新视频已保存到: {output_path}")
+
+ def _draw_projection(self, index, frame: np.ndarray, pos_3d: Optional[np.ndarray], orientation: Optional[np.ndarray],
+ color: Tuple[int, int, int]):
+ # 修改:此方法现在包含完整的投影和坐标变换逻辑
+ if pos_3d is None:
+ return
+ X, Y, Z = pos_3d
+
+ u_final, v_final = -1, -1
+ if Z > 0:
+ # 1. 投影到虚拟的 1280x800 图像上
+ u_orig = self.camera_intrinsics['fx'] * (X / Z) + self.camera_intrinsics['cx']
+ v_orig = self.camera_intrinsics['fy'] * (Y / Z) + self.camera_intrinsics['cy']
+
+ # 2. 将 2D 坐标点变换到 256x256 空间
+ u_final, v_final = transform_point_cotrain(u_orig, v_orig)
+ #u_final, v_final = int(u_orig), int(v_orig)
+
+ h, w, _ = frame.shape
+ #import pdb; pdb.set_trace()
+
+ if 0 <= u_final < w and 0 <= v_final < h:
+ cv2.circle(frame, (u_final, v_final), radius=5, color=color, thickness=-1)
+
+ if orientation is not None:
+ orientation_arr = np.asarray(orientation, dtype=np.float64)
+ orientation_mat = None
+ if orientation_arr.shape == (3, 3):
+ orientation_mat = orientation_arr
+ else:
+ flat = orientation_arr.reshape(-1)
+ if flat.size == 9:
+ orientation_mat = flat.reshape(3, 3)
+
+ axes_to_draw: List[Tuple[np.ndarray, Tuple[int, int, int]]] = []
+
+ if orientation_mat is not None:
+ for _, axis_vec, axis_color in self.hand_orientation_axes:
+ axis_cam = orientation_mat @ axis_vec
+ axes_to_draw.append((axis_cam, axis_color))
+ else:
+ flat = orientation_arr.reshape(-1)
+ if flat.size == 3:
+ axes_to_draw.append((flat, color))
+
+ for axis_cam, axis_color in axes_to_draw:
+ axis_cam = np.asarray(axis_cam, dtype=np.float64).reshape(-1)
+ if axis_cam.size != 3:
+ continue
+ axis_norm = np.linalg.norm(axis_cam)
+ if axis_norm <= 1e-6:
+ continue
+ axis_dir = axis_cam / axis_norm
+ base_pos = np.asarray(pos_3d, dtype=np.float64)
+
+ length = self.hand_orientation_length
+ for _ in range(5):
+ tip_pos = base_pos + length * axis_dir
+ if tip_pos[2] <= 1e-5:
+ length *= 0.5
+ continue
+
+ u_tip = self.camera_intrinsics['fx'] * (tip_pos[0] / tip_pos[2]) + self.camera_intrinsics['cx']
+ v_tip = self.camera_intrinsics['fy'] * (tip_pos[1] / tip_pos[2]) + self.camera_intrinsics['cy']
+ u_tip_final, v_tip_final = transform_point_cotrain(u_tip, v_tip)
+
+ if 0 <= u_tip_final < w and 0 <= v_tip_final < h:
+ cv2.arrowedLine(
+ frame,
+ (u_final, v_final),
+ (u_tip_final, v_tip_final),
+ axis_color,
+ thickness=2,
+ tipLength=0.2,
+ )
+ break
+ length *= 0.7
+
+
+def process_img_cotrain(img: np.ndarray) -> np.ndarray:
+ """
+ 将原始图像(1280x800)处理为最终输入模型的图像(256x256)。
+ 这个函数与 robocasa 中的 gymnasium_groot.py 里的实现完全一致。
+ """
+ # 确认输入是 1280x800 的原始图像
+ if not (img.shape[0] == 800 and img.shape[1] == 1280):
+ # 如果视频本身就是 256x256,直接返回
+ if img.shape[0] == 256 and img.shape[1] == 256:
+
+ #import pdb; pdb.set_trace()
+
+ # h_src, w_src = img.shape[:2]
+ # target_w, target_h = 1280, 800
+
+ # # 计算填充量(居中填充)
+ # pad_w_left = (target_w - w_src) // 2
+ # pad_w_right = target_w - w_src - pad_w_left
+ # pad_h_top = (target_h - h_src) // 2
+ # pad_h_bottom = target_h - h_src - pad_h_top
+
+ # # 填充到目标尺寸
+ # img = np.pad(
+ # img,
+ # ((pad_h_top, pad_h_bottom), (pad_w_left, pad_w_right), (0, 0)),
+ # mode="constant",
+ # constant_values=0,
+ # )
+
+ return img
+ raise ValueError(f"输入图像尺寸 {img.shape} 不符合预期的 1280x800")
+
+ oh, ow = 256, 256
+ # 定义一个裁剪区域 (top, bottom, left, right)
+ crop = (310, 770, 110, 1130)
+ # 步骤 1: 裁剪原始图像
+ img = img[crop[0]:crop[1], crop[2]:crop[3]]
+
+ # 步骤 2: 第一次缩放,将裁剪后的图像缩放到 720x480
+ img_resized = cv2.resize(img, (720, 480), cv2.INTER_AREA)
+
+ # 计算填充量,使其变为正方形
+ width_pad = (img_resized.shape[1] - img_resized.shape[0]) // 2
+ # 步骤 3: 填充黑边,使其变为 720x720 的正方形
+ img_pad = np.pad(
+ img_resized,
+ ((width_pad, width_pad), (0, 0), (0, 0)),
+ mode="constant",
+ constant_values=0,
+ )
+ # 步骤 4: 第二次缩放,将 720x720 的图像缩放到最终的 256x256
+ img_resized = cv2.resize(img_pad, (oh, ow), cv2.INTER_AREA)
+ return img_resized
+
+
+def transform_point_cotrain(u: float, v: float) -> tuple[int, int]:
+ """
+ 对投影到 1280x800 图像上的 2D 点应用与 process_img_cotrain 相同的几何变换。
+ """
+ # 步骤 1: 裁剪坐标
+ crop_bounds = (310, 770, 110, 1130) # top, bottom, left, right
+ u_cropped = u - crop_bounds[2]
+ v_cropped = v - crop_bounds[0]
+
+ # 步骤 2: 第一次缩放
+ original_cropped_size = (1020, 460) # width, height
+ resized1_size = (720, 480)
+ scale_u1 = resized1_size[0] / original_cropped_size[0]
+ scale_v1 = resized1_size[1] / original_cropped_size[1]
+ u_resized1 = u_cropped * scale_u1
+ v_resized1 = v_cropped * scale_v1
+
+ # 步骤 3: 填充坐标
+ pad_amount = (resized1_size[0] - resized1_size[1]) // 2 # 120
+ u_padded = u_resized1
+ v_padded = v_resized1 + pad_amount
+
+ # 步骤 4: 第二次缩放
+ padded_size = (720, 720)
+ final_size = (256, 256)
+ scale_u2 = final_size[0] / padded_size[0]
+ scale_v2 = final_size[1] / padded_size[1]
+ u_final = u_padded * scale_u2
+ v_final = v_padded * scale_v2
+
+ return int(u_final), int(v_final)
+
+
+def main():
+ parser = argparse.ArgumentParser(description="批量处理机器人视频,投影手部关节点 (v0 逻辑)。")
+ parser.add_argument(
+ "--dataset-root",
+ type=Path,
+ default=Path(
+ "/vla/users/lijiayi/robocasa_datasets_fewshots/gr1_unified.PosttrainPnPNovelFromCuttingboardToPanSplitA_GR1ArmsAndWaistFourierHands_100"
+ ))
+ parser.add_argument(
+ "--urdf-path",
+ type=Path,
+ default=Path("/vla/users/lijiayi/code/robot_retarget/retarget/body_retarget/GR1T2/urdf/GR1T2_fourier_hand_6dof.urdf"))
+ parser.add_argument("--output-dir",
+ type=Path,
+ default=Path("/vla/users/lijiayi/code/robot_retarget/retarget/body_retarget/output_videos"))
+ parser.add_argument("--verify-ik", action="store_true", default=True, help="是否执行 IK 验证")
+ parser.add_argument("--no-verify-ik", dest="verify_ik", action="store_false", help="禁用 IK 验证")
+ args = parser.parse_args()
+
+ args.output_dir.mkdir(parents=True, exist_ok=True)
+ camera_intrinsics = {'fx': 502.8689, 'fy': 502.8689, 'cx': 640.0, 'cy': 400.0}
+
+ retargeter = BodyRetargeter(urdf_path=args.urdf_path, camera_intrinsics=camera_intrinsics)
+
+ parquet_path = args.dataset_root / "data/chunk-000/episode_000098.parquet"
+ video_path = args.dataset_root / "videos/chunk-000/observation.images.ego_view/episode_000098.mp4"
+ output_path = args.output_dir / "episode_000093_projected_v8_logic.mp4"
+
+ retargeter.process_episode(video_path, parquet_path, output_path, verify_ik=args.verify_ik)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/Robocasa_tabletop/eval_files/infer_cosmos25_future_video.py b/examples/Robocasa_tabletop/eval_files/infer_cosmos25_future_video.py
new file mode 100644
index 0000000000000000000000000000000000000000..9cb98eda4542bdbeb5ff49a1d3c9c5ab39f1e091
--- /dev/null
+++ b/examples/Robocasa_tabletop/eval_files/infer_cosmos25_future_video.py
@@ -0,0 +1,739 @@
+#!/usr/bin/env python3
+"""Run Cosmos-Predict2.5 future-video inference for RoboCasa images.
+
+This script reads RoboCasa samples like training, then runs the official
+diffusers Cosmos2.5 Image2World-style call for video prediction.
+
+Dataset example:
+ python examples/Robocasa_tabletop/eval_files/infer_cosmos25_future_video.py \
+ --num-samples 8 \
+ --out-dir outputs/robocasa_cosmos25_dataset_infer
+
+Manual example:
+ python examples/Robocasa_tabletop/eval_files/infer_cosmos25_future_video.py \
+ --image current.png \
+ --instruction "pick up the cup and put it into the drawer" \
+ --gt gt.mp4 \
+ --out-dir outputs/robocasa_cosmos25_infer/cup_to_drawer
+"""
+
+from __future__ import annotations
+
+import argparse
+import inspect
+import json
+import os
+from pathlib import Path
+from typing import Iterable
+
+
+DEFAULT_COSMOS25_WEIGHT = (
+ "/mnt/workspace/users/yuanzhihao/code/starVLA/playground/Pretrained_models/"
+ "Cosmos-Predict2.5-2B-Post-Trained"
+)
+DEFAULT_CONFIG_YAML = "./examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml"
+DEFAULT_DATA_ROOT_DIR = "/mnt/workspace/datasets"
+DEFAULT_DATA_MIX = "robocasa_teleop_ee"
+DEFAULT_HEIGHT = 704
+DEFAULT_WIDTH = 704
+ROBOCASA_PROMPT_TEMPLATE = (
+ "Continue the given simulator image as a future robot manipulation video. "
+ "Keep the same camera, viewpoint, framing, lighting, room, surface materials, robot, and objects as the input image. "
+ "Only the existing robot hand, robot arm, and task-relevant movable objects should move. "
+ "All background surfaces and unrelated objects should remain static and unchanged. "
+ "Do not add text, labels, borders, logos, panels, signs, people, human hands, new objects, or new scene elements. "
+ "Do not change the camera, zoom, crop, pan, rotate, or redesign the scene. "
+ "Task instruction: {instruction}"
+)
+ROBOCASA_NEGATIVE_PROMPT = (
+ "human, person, human hand, fingers, skin, real-world kitchen, photorealistic kitchen, "
+ "text, letters, words, writing, handwriting, label, caption, title, logo, watermark, brand mark, sign, signage, "
+ "border, picture frame, poster, page, document, panel, user interface, split screen, "
+ "black dots, speckles, dotted countertop, spotted countertop, noisy countertop, dirt, stains, crumbs, grid pattern, checker pattern, "
+ "close-up, zoom in, camera zoom, camera pan, camera rotation, camera movement, camera cut, "
+ "wide-angle view, widened view, cropped view, changing viewpoint, changing field of view, scene change, new object, "
+ "parallel gripper, two-finger gripper, claw gripper, extra robot arm, extra dexterous hand, "
+ "duplicated robotic hand, deformed robotic hand, distorted robot, "
+ "blur, low quality, subtitles"
+)
+DEFAULT_NEGATIVE_PROMPT = (
+ ROBOCASA_NEGATIVE_PROMPT
+)
+
+
+class _DisabledCosmosSafetyChecker:
+ """No-op safety checker for local RoboCasa visualization."""
+
+ def to(self, *args, **kwargs):
+ return self
+
+ def check_text_safety(self, *args, **kwargs):
+ return True
+
+ def check_video_safety(self, video, *args, **kwargs):
+ return video
+
+
+def parse_args() -> argparse.Namespace:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--model-path", default=DEFAULT_COSMOS25_WEIGHT)
+ parser.add_argument("--revision", default=os.environ.get("COSMOS_PREDICT25_REVISION", "diffusers/base/post-trained"))
+ parser.add_argument(
+ "--image",
+ nargs="+",
+ default=None,
+ help="Optional manual current RGB image path(s). If omitted, samples are read from the RoboCasa training set.",
+ )
+ parser.add_argument("--instruction", default=None, help="Manual task instruction, or @path/to/instruction.txt.")
+ parser.add_argument("--gt", default=None, help="Optional manual GT image/video path for side-by-side comparison.")
+ parser.add_argument("--out-dir", default="outputs/robocasa_cosmos25_dataset_future_video")
+ parser.add_argument("--config-yaml", default=DEFAULT_CONFIG_YAML)
+ parser.add_argument("--data-root-dir", default=DEFAULT_DATA_ROOT_DIR)
+ parser.add_argument("--data-mix", default=DEFAULT_DATA_MIX)
+ parser.add_argument("--dataset-mode", default="train", choices=("train", "val"))
+ parser.add_argument("--num-samples", type=int, default=4)
+ parser.add_argument("--start-index", type=int, default=0)
+ parser.add_argument(
+ "--sample-indices",
+ default=None,
+ help="Comma-separated dataset indices. Overrides --num-samples/--start-index.",
+ )
+ parser.add_argument(
+ "--conditioning-mode",
+ choices=("auto", "image", "video", "text"),
+ default="image",
+ help="image uses current frame, video uses historical frames, text passes only the prompt.",
+ )
+ parser.add_argument("--view-index", type=int, default=0, help="RoboCasa camera view used for current image and GT future image.")
+ parser.add_argument("--condition-frames", type=int, default=5, help="Number of historical frames for --conditioning-mode video.")
+ parser.add_argument("--condition-stride", type=int, default=1, help="Stride in environment steps between historical frames.")
+ parser.add_argument("--height", type=int, default=DEFAULT_HEIGHT)
+ parser.add_argument("--width", type=int, default=DEFAULT_WIDTH)
+ parser.add_argument("--num-frames", type=int, default=93)
+ parser.add_argument("--num-inference-steps", type=int, default=36)
+ parser.add_argument("--guidance-scale", type=float, default=2.0)
+ parser.add_argument("--fps", type=int, default=16)
+ parser.add_argument("--seed", type=int, default=0)
+ parser.add_argument("--dtype", choices=("bf16", "fp16", "fp32"), default="bf16")
+ parser.add_argument("--device", default="cuda")
+ parser.add_argument("--cpu-offload", action="store_true")
+ parser.add_argument("--negative-prompt", default=DEFAULT_NEGATIVE_PROMPT)
+ parser.add_argument(
+ "--prompt-style",
+ default="raw",
+ choices=("raw", "empty", "robocasa"),
+ help="raw uses only the task instruction; empty uses no text prompt; robocasa wraps the instruction.",
+ )
+ parser.add_argument(
+ "--prompt-template",
+ default=None,
+ help="Optional format string with {instruction}; overrides --prompt-style robocasa template.",
+ )
+ parser.add_argument("--max-sequence-length", type=int, default=512)
+ parser.add_argument("--conditional-frame-timestep", type=float, default=0.1)
+ parser.add_argument("--num-latent-conditional-frames", type=int, default=2)
+ parser.add_argument(
+ "--compare-panels",
+ choices=("gt_pred", "current_gt_pred", "video_traj_pred"),
+ default="video_traj_pred",
+ help="Panels to write into compare.mp4 when --gt is provided.",
+ )
+ parser.add_argument("--enable-safety-checker", action="store_true")
+ parser.add_argument(
+ "--text-only",
+ action="store_true",
+ help="Alias for --conditioning-mode text.",
+ )
+ return parser.parse_args()
+
+
+def apply_arg_aliases(args: argparse.Namespace) -> argparse.Namespace:
+ if args.text_only:
+ args.conditioning_mode = "text"
+ return args
+
+
+def serializable_args(args: argparse.Namespace) -> dict:
+ return {key: value for key, value in vars(args).items() if not key.startswith("_")}
+
+
+def require_numpy():
+ try:
+ import numpy as np
+ except ImportError as exc:
+ raise ImportError("numpy is required. Please run this script in the starVLA environment.") from exc
+ return np
+
+
+def require_pil():
+ try:
+ from PIL import Image, ImageDraw, ImageFont
+ except ImportError as exc:
+ raise ImportError("pillow is required. Please run this script in the starVLA environment.") from exc
+ return Image, ImageDraw, ImageFont
+
+
+def require_av():
+ try:
+ import av
+ except ImportError as exc:
+ raise ImportError("av is required for video IO. Please run this script in the starVLA environment.") from exc
+ return av
+
+
+def require_torch():
+ try:
+ import torch
+ except ImportError as exc:
+ raise ImportError("torch is required for Cosmos inference. Please run this script in the starVLA environment.") from exc
+ return torch
+
+
+def maybe_torch():
+ try:
+ import torch
+ except ImportError:
+ return None
+ return torch
+
+
+def load_generation_pipeline(args: argparse.Namespace, dtype):
+ from diffusers import Cosmos2_5_PredictBasePipeline
+
+ load_kwargs = {"torch_dtype": dtype}
+ if args.revision and not os.path.isdir(args.model_path):
+ load_kwargs["revision"] = args.revision
+ return Cosmos2_5_PredictBasePipeline.from_pretrained(args.model_path, **load_kwargs)
+
+
+def pipeline_capabilities(pipe) -> dict:
+ signature = inspect.signature(pipe.__call__)
+ params = set(signature.parameters)
+ accepts_kwargs = any(param.kind == inspect.Parameter.VAR_KEYWORD for param in signature.parameters.values())
+ return {
+ "class": type(pipe).__name__,
+ "accepts_image": "image" in params or accepts_kwargs,
+ "accepts_video": "video" in params or accepts_kwargs,
+ "accepts_kwargs": accepts_kwargs,
+ }
+
+
+def read_instruction(value: str) -> str:
+ if value.startswith("@"):
+ return Path(value[1:]).read_text(encoding="utf-8").strip()
+ return value
+
+
+def build_prompt(args: argparse.Namespace, instruction: str) -> str:
+ if args.prompt_style == "raw":
+ return instruction
+ if args.prompt_style == "empty":
+ return ""
+ template = args.prompt_template or ROBOCASA_PROMPT_TEMPLATE
+ return template.format(instruction=instruction)
+
+
+def parse_sample_indices(args: argparse.Namespace) -> list[int]:
+ if args.sample_indices:
+ return [int(item.strip()) for item in args.sample_indices.split(",") if item.strip()]
+ return list(range(args.start_index, args.start_index + args.num_samples))
+
+
+def load_training_dataset(args: argparse.Namespace):
+ from omegaconf import OmegaConf
+
+ from starVLA.dataloader.lerobot_datasets import get_vla_dataset
+
+ cfg = OmegaConf.load(args.config_yaml)
+ cfg.datasets.vla_data.data_root_dir = args.data_root_dir
+ cfg.datasets.vla_data.data_mix = args.data_mix
+ cfg.datasets.vla_data.include_state = True
+ cfg.datasets.vla_data.per_device_batch_size = 1
+ return get_vla_dataset(data_cfg=cfg.datasets.vla_data, mode=args.dataset_mode)
+
+
+def resolve_sample_location(mixture_dataset, dataset_index: int) -> tuple:
+ """Mirror LeRobotMixtureDataset sampling so we can read temporal frames."""
+ dataset, trajectory_id, base_index = mixture_dataset.sample_step(dataset_index)
+ return dataset, int(trajectory_id), int(base_index)
+
+
+def load_image(path: str):
+ Image, _, _ = require_pil()
+ return Image.open(path).convert("RGB")
+
+
+def as_image_list(images) -> list:
+ if isinstance(images, (list, tuple)):
+ return list(images)
+ return [images]
+
+
+def to_pil_rgb(frame):
+ Image, _, _ = require_pil()
+ np = require_numpy()
+ torch = maybe_torch()
+
+ if isinstance(frame, Image.Image):
+ return frame.convert("RGB")
+ if torch is not None and torch.is_tensor(frame):
+ array = frame.detach().float().cpu().numpy()
+ else:
+ array = np.asarray(frame)
+
+ if array.ndim == 3 and array.shape[0] in (1, 3) and array.shape[-1] not in (1, 3):
+ array = np.transpose(array, (1, 2, 0))
+ if array.dtype != np.uint8:
+ if array.size and array.min() >= -1.0 and array.max() <= 1.0:
+ array = (array + 1.0) * 127.5
+ elif array.size and array.min() >= 0.0 and array.max() <= 1.0:
+ array = array * 255.0
+ array = np.clip(array, 0, 255).astype(np.uint8)
+ if array.ndim == 2:
+ array = np.repeat(array[..., None], 3, axis=-1)
+ if array.shape[-1] == 1:
+ array = np.repeat(array, 3, axis=-1)
+ return Image.fromarray(array[..., :3]).convert("RGB")
+
+
+def extract_frames(output) -> list:
+ np = require_numpy()
+ torch = maybe_torch()
+
+ videos = getattr(output, "frames", None)
+ if videos is None:
+ videos = getattr(output, "videos", None)
+ if videos is None:
+ videos = getattr(output, "images", None)
+ if videos is None and isinstance(output, tuple):
+ videos = output[0]
+ if videos is None:
+ videos = output
+
+ if torch is not None and torch.is_tensor(videos):
+ videos = videos.detach().cpu()
+ if videos.ndim == 5:
+ videos = videos[0]
+ return [to_pil_rgb(frame) for frame in videos]
+
+ if isinstance(videos, np.ndarray):
+ if videos.ndim == 5:
+ videos = videos[0]
+ return [to_pil_rgb(frame) for frame in videos]
+
+ if isinstance(videos, (list, tuple)) and videos:
+ first = videos[0]
+ if isinstance(first, (list, tuple)):
+ return [to_pil_rgb(frame) for frame in first]
+ if torch is not None and torch.is_tensor(first) and first.ndim >= 4:
+ return [to_pil_rgb(frame) for frame in first]
+ if isinstance(first, np.ndarray) and first.ndim >= 4:
+ return [to_pil_rgb(frame) for frame in first]
+ return [to_pil_rgb(frame) for frame in videos]
+
+ raise ValueError("Could not extract generated frames from Cosmos output.")
+
+
+def read_video(path: Path) -> list:
+ av = require_av()
+ frames = []
+ with av.open(str(path)) as container:
+ stream = container.streams.video[0]
+ for frame in container.decode(stream):
+ frames.append(frame.to_image().convert("RGB"))
+ if not frames:
+ raise ValueError(f"No frames decoded from {path}.")
+ return frames
+
+
+def read_gt(path: str, target_len: int) -> list:
+ np = require_numpy()
+ gt_path = Path(path)
+ if gt_path.suffix.lower() in {".png", ".jpg", ".jpeg", ".bmp", ".webp"}:
+ frame = load_image(str(gt_path))
+ return [frame.copy() for _ in range(target_len)]
+
+ frames = read_video(gt_path)
+ if len(frames) == target_len:
+ return frames
+ if len(frames) == 1:
+ return [frames[0].copy() for _ in range(target_len)]
+
+ indices = np.linspace(0, len(frames) - 1, target_len).round().astype(int)
+ return [frames[int(i)] for i in indices]
+
+
+def gt_frames_from_dataset(example: dict, target_len: int, view_index: int) -> list | None:
+ future_images = example.get("future_image")
+ if future_images is None:
+ return None
+ future_images = as_image_list(future_images)
+ if not future_images:
+ return None
+ view_index = min(max(int(view_index), 0), len(future_images) - 1)
+ frame = to_pil_rgb(future_images[view_index])
+ return [frame.copy() for _ in range(target_len)]
+
+
+def get_condition_video_frames(dataset, trajectory_id: int, base_index: int, args: argparse.Namespace) -> list:
+ """Read same-view history frames ending at base_index for Cosmos Video2World."""
+ np = require_numpy()
+
+ video_keys = list(dataset.modality_keys["video"])
+ if not video_keys:
+ raise ValueError("Dataset sample has no video keys.")
+ video_key = video_keys[min(max(args.view_index, 0), len(video_keys) - 1)]
+
+ # Ensure curr_traj_data is populated for timestamp-based frame lookup.
+ dataset.get_step_data(trajectory_id, base_index)
+ condition_frames = max(1, int(args.condition_frames))
+ stride = max(1, int(args.condition_stride))
+ offsets = np.arange(-(condition_frames - 1) * stride, 1, stride, dtype=np.int64)
+ old_delta_indices = dataset.delta_indices[video_key]
+ try:
+ dataset.delta_indices[video_key] = offsets
+ frames = dataset.get_video(trajectory_id, video_key, base_index)
+ finally:
+ dataset.delta_indices[video_key] = old_delta_indices
+
+ return [to_pil_rgb(frame) for frame in frames]
+
+
+def get_full_trajectory_video_frames(dataset, trajectory_id: int, base_index: int, args: argparse.Namespace) -> list:
+ """Read the full same-view RoboCasa trajectory for visualization only."""
+ np = require_numpy()
+
+ video_keys = list(dataset.modality_keys["video"])
+ if not video_keys:
+ raise ValueError("Dataset sample has no video keys.")
+ video_key = video_keys[min(max(args.view_index, 0), len(video_keys) - 1)]
+
+ # Ensure curr_traj_data is populated for timestamp-based frame lookup.
+ dataset.get_step_data(trajectory_id, base_index)
+ trajectory_index = dataset.get_trajectory_index(trajectory_id)
+ trajectory_length = int(dataset.trajectory_lengths[trajectory_index])
+ offsets = np.arange(trajectory_length, dtype=np.int64) - int(base_index)
+
+ old_delta_indices = dataset.delta_indices[video_key]
+ try:
+ dataset.delta_indices[video_key] = offsets
+ frames = dataset.get_video(trajectory_id, video_key, base_index)
+ finally:
+ dataset.delta_indices[video_key] = old_delta_indices
+
+ return [to_pil_rgb(frame) for frame in frames]
+
+
+def hold_last_to_length(frames: list, target_len: int, target_size) -> list:
+ if not frames:
+ return []
+ frames = [to_pil_rgb(frame).resize(target_size).copy() for frame in frames]
+ if len(frames) >= target_len:
+ return frames[:target_len]
+ return frames + [frames[-1].copy() for _ in range(target_len - len(frames))]
+
+
+def resample_to_length(frames: list, target_len: int, target_size) -> list:
+ np = require_numpy()
+ if not frames:
+ return []
+ frames = [to_pil_rgb(frame).resize(target_size).copy() for frame in frames]
+ if len(frames) == target_len:
+ return frames
+ if len(frames) == 1:
+ return [frames[0].copy() for _ in range(target_len)]
+ indices = np.linspace(0, len(frames) - 1, target_len).round().astype(int)
+ return [frames[int(index)] for index in indices]
+
+
+def add_label(frame, label: str):
+ _, ImageDraw, ImageFont = require_pil()
+ frame = frame.convert("RGB")
+ draw = ImageDraw.Draw(frame)
+ font = ImageFont.load_default()
+ try:
+ bbox = draw.textbbox((0, 0), label, font=font)
+ text_w, text_h = bbox[2] - bbox[0], bbox[3] - bbox[1]
+ except AttributeError:
+ text_w, text_h = draw.textsize(label, font=font)
+ pad = 8
+ draw.rectangle((0, 0, text_w + pad * 2, text_h + pad * 2), fill=(0, 0, 0))
+ draw.text((pad, pad), label, fill=(255, 255, 255), font=font)
+ return frame
+
+
+def make_compare_frames(
+ pred_frames: list,
+ gt_frames: list | None,
+ current_image,
+ compare_panels: str,
+ condition_frames: list | None = None,
+ trajectory_frames: list | None = None,
+) -> list:
+ if gt_frames is None and not (compare_panels == "video_traj_pred" and trajectory_frames):
+ return pred_frames
+
+ Image, _, _ = require_pil()
+ compare_frames = []
+ condition_video = []
+ trajectory_video = []
+ if compare_panels == "video_traj_pred":
+ target_size = pred_frames[0].size
+ condition_video = hold_last_to_length(condition_frames or [current_image], len(pred_frames), target_size)
+ trajectory_video = resample_to_length(trajectory_frames or gt_frames, len(pred_frames), target_size)
+
+ if gt_frames is None:
+ gt_frames = [pred_frames[-1] for _ in pred_frames]
+
+ for frame_idx, (pred, gt) in enumerate(zip(pred_frames, gt_frames)):
+ gt = gt.resize(pred.size)
+ panels = []
+ if compare_panels == "video_traj_pred":
+ cond_panel = condition_video[frame_idx] if condition_video else current_image.resize(pred.size)
+ traj_panel = trajectory_video[frame_idx] if trajectory_video else gt
+ panels.extend([add_label(cond_panel.copy(), "Input"), add_label(traj_panel.copy(), "Traj")])
+ elif compare_panels == "current_gt_pred":
+ panels.append(add_label(current_image.resize(pred.size).copy(), "Current"))
+ if compare_panels == "video_traj_pred":
+ panels.append(add_label(pred.copy(), "Cosmos"))
+ else:
+ panels.extend([add_label(gt.copy(), "GT"), add_label(pred.copy(), "Cosmos")])
+
+ canvas = Image.new("RGB", (pred.width * len(panels), pred.height))
+ for panel_idx, panel in enumerate(panels):
+ canvas.paste(panel, (pred.width * panel_idx, 0))
+ compare_frames.append(canvas)
+ return compare_frames
+
+
+def save_video(frames: Iterable, path: Path, fps: int) -> None:
+ frames = [frame.convert("RGB") for frame in frames]
+ if not frames:
+ raise ValueError(f"No frames to save for {path}.")
+
+ width, height = frames[0].size
+ encoded_width = width + (width % 2)
+ encoded_height = height + (height % 2)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ try:
+ save_video_with_codec(frames, path, fps, "h264", encoded_width, encoded_height)
+ except Exception:
+ save_video_with_codec(frames, path, fps, "mpeg4", encoded_width, encoded_height)
+
+
+def save_video_with_codec(frames: list, path: Path, fps: int, codec: str, width: int, height: int) -> None:
+ av = require_av()
+ Image, _, _ = require_pil()
+ with av.open(str(path), mode="w") as container:
+ stream = container.add_stream(codec, rate=fps)
+ stream.width = width
+ stream.height = height
+ stream.pix_fmt = "yuv420p"
+ for frame in frames:
+ if frame.size != (width, height):
+ canvas = Image.new("RGB", (width, height))
+ canvas.paste(frame, (0, 0))
+ frame = canvas
+ video_frame = av.VideoFrame.from_image(frame)
+ for packet in stream.encode(video_frame):
+ container.mux(packet)
+ for packet in stream.encode():
+ container.mux(packet)
+
+
+def build_generation_kwargs(args: argparse.Namespace, instruction: str, images: list, generator) -> dict:
+ generation_kwargs = {
+ "image": None,
+ "video": None,
+ "prompt": instruction,
+ "negative_prompt": args.negative_prompt,
+ "height": args.height,
+ "width": args.width,
+ "num_frames": args.num_frames,
+ "num_inference_steps": args.num_inference_steps,
+ "guidance_scale": args.guidance_scale,
+ "output_type": "pil",
+ "return_dict": True,
+ "max_sequence_length": args.max_sequence_length,
+ "conditional_frame_timestep": args.conditional_frame_timestep,
+ "num_latent_conditional_frames": args.num_latent_conditional_frames,
+ "generator": generator,
+ }
+
+ if args.conditioning_mode == "image":
+ view_index = min(max(args.view_index, 0), len(images) - 1)
+ generation_kwargs["image"] = images[view_index]
+ elif args.conditioning_mode == "video":
+ generation_kwargs["video"] = images
+ elif args.conditioning_mode == "text":
+ pass
+ else:
+ if len(images) == 1:
+ generation_kwargs["image"] = images[0]
+ else:
+ # Dataset samples store multiple camera views, not temporal frames.
+ # Use the selected view as the current frame unless the caller
+ # explicitly asks for --conditioning-mode video.
+ view_index = min(max(args.view_index, 0), len(images) - 1)
+ generation_kwargs["image"] = images[view_index]
+ return generation_kwargs
+
+
+def save_inference_outputs(
+ args: argparse.Namespace,
+ sample_out_dir: Path,
+ pred_frames: list,
+ gt_frames: list | None,
+ current_image,
+ metadata: dict,
+ condition_frames: list | None = None,
+ trajectory_frames: list | None = None,
+) -> None:
+ compare_frames = make_compare_frames(
+ pred_frames,
+ gt_frames,
+ current_image,
+ args.compare_panels,
+ condition_frames=condition_frames,
+ trajectory_frames=trajectory_frames,
+ )
+
+ pred_path = sample_out_dir / "pred.mp4"
+ input_path = sample_out_dir / "input.mp4"
+ traj_path = sample_out_dir / "traj.mp4"
+ compare_path = sample_out_dir / "compare.mp4"
+ last_path = sample_out_dir / "last_frame_compare.png"
+ meta_path = sample_out_dir / "sample_meta.json"
+
+ save_video(pred_frames, pred_path, args.fps)
+ if condition_frames:
+ save_video(condition_frames, input_path, args.fps)
+ if trajectory_frames:
+ save_video(trajectory_frames, traj_path, args.fps)
+ save_video(compare_frames, compare_path, args.fps)
+ compare_frames[-1].save(last_path)
+ meta_path.write_text(json.dumps(metadata, indent=2, ensure_ascii=False), encoding="utf-8")
+
+ print(f"Saved prediction video: {pred_path}")
+ if condition_frames:
+ print(f"Saved input video: {input_path}")
+ if trajectory_frames:
+ print(f"Saved trajectory video: {traj_path}")
+ print(f"Saved comparison video: {compare_path}")
+ print(f"Saved last-frame comparison: {last_path}")
+
+
+def main() -> None:
+ args = parse_args()
+ args = apply_arg_aliases(args)
+ out_dir = Path(args.out_dir)
+ out_dir.mkdir(parents=True, exist_ok=True)
+
+ if not args.enable_safety_checker:
+ from diffusers.pipelines.cosmos import pipeline_cosmos2_5_predict
+
+ pipeline_cosmos2_5_predict.CosmosSafetyChecker = _DisabledCosmosSafetyChecker
+
+ torch = require_torch()
+ dtype = {"bf16": torch.bfloat16, "fp16": torch.float16, "fp32": torch.float32}[args.dtype]
+ pipe = load_generation_pipeline(args, dtype)
+ if args.cpu_offload:
+ pipe.enable_model_cpu_offload()
+ else:
+ pipe.to(args.device)
+ args._pipe_call = pipe.__call__
+ print(f"Loaded Cosmos model={args.model_path}")
+ print(f"Pipeline capabilities: {pipeline_capabilities(pipe)}")
+ print(
+ "Generation config: "
+ f"height={args.height}, width={args.width}, "
+ f"num_frames={args.num_frames}, steps={args.num_inference_steps}, "
+ f"guidance_scale={args.guidance_scale}, conditioning_mode={args.conditioning_mode}"
+ )
+
+ if args.image is not None:
+ if args.instruction is None:
+ raise ValueError("--instruction is required when using manual --image input.")
+ images = [load_image(path) for path in args.image]
+ instruction = read_instruction(args.instruction)
+ prompt = build_prompt(args, instruction)
+ generator = torch.Generator().manual_seed(args.seed)
+ print(f"Instruction: {instruction}")
+ print(f"Prompt: {prompt}")
+ print(f"Negative prompt: {args.negative_prompt}")
+ with torch.inference_mode():
+ output = pipe(**build_generation_kwargs(args, prompt, images, generator))
+ pred_frames = extract_frames(output)
+ gt_frames = read_gt(args.gt, len(pred_frames)) if args.gt else None
+ save_inference_outputs(
+ args=args,
+ sample_out_dir=out_dir,
+ pred_frames=pred_frames,
+ gt_frames=gt_frames,
+ current_image=images[min(max(args.view_index, 0), len(images) - 1)],
+ metadata={
+ "args": serializable_args(args),
+ "instruction": instruction,
+ "prompt": prompt,
+ "negative_prompt": args.negative_prompt,
+ "prompt_style": args.prompt_style,
+ "manual_images": args.image,
+ },
+ condition_frames=images,
+ )
+ return
+
+ dataset = load_training_dataset(args)
+ sample_indices = parse_sample_indices(args)
+ (out_dir / "run_args.json").write_text(json.dumps(serializable_args(args), indent=2, ensure_ascii=False), encoding="utf-8")
+
+ for sample_ord, dataset_index in enumerate(sample_indices):
+ source_dataset, trajectory_id, base_index = resolve_sample_location(dataset, dataset_index)
+ example = dataset[dataset_index]
+ images = [to_pil_rgb(image) for image in as_image_list(example["image"])]
+ if args.conditioning_mode == "video":
+ images = get_condition_video_frames(source_dataset, trajectory_id, base_index, args)
+ instruction = str(example["lang"])
+ prompt = build_prompt(args, instruction)
+ sample_out_dir = out_dir / f"sample_{sample_ord:03d}_idx_{dataset_index:06d}"
+ sample_out_dir.mkdir(parents=True, exist_ok=True)
+
+ generator = torch.Generator().manual_seed(args.seed + sample_ord)
+ print(f"[{sample_ord + 1}/{len(sample_indices)}] dataset index={dataset_index}")
+ print(f"Instruction: {instruction}")
+ print(f"Prompt: {prompt}")
+ print(f"Negative prompt: {args.negative_prompt}")
+
+ with torch.inference_mode():
+ output = pipe(**build_generation_kwargs(args, prompt, images, generator))
+
+ pred_frames = extract_frames(output)
+ gt_frames = gt_frames_from_dataset(example, len(pred_frames), args.view_index)
+ trajectory_frames = get_full_trajectory_video_frames(source_dataset, trajectory_id, base_index, args)
+ save_inference_outputs(
+ args=args,
+ sample_out_dir=sample_out_dir,
+ pred_frames=pred_frames,
+ gt_frames=gt_frames,
+ current_image=images[min(max(args.view_index, 0), len(images) - 1)],
+ metadata={
+ "dataset_index": dataset_index,
+ "trajectory_id": trajectory_id,
+ "base_index": base_index,
+ "instruction": instruction,
+ "prompt": prompt,
+ "negative_prompt": args.negative_prompt,
+ "prompt_style": args.prompt_style,
+ "num_condition_images": len(images),
+ "conditioning_mode": args.conditioning_mode,
+ "view_index": args.view_index,
+ "condition_frames": args.condition_frames,
+ "condition_stride": args.condition_stride,
+ },
+ condition_frames=images,
+ trajectory_frames=trajectory_frames,
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/Robocasa_tabletop/eval_files/infer_cosmos25_official.py b/examples/Robocasa_tabletop/eval_files/infer_cosmos25_official.py
new file mode 100644
index 0000000000000000000000000000000000000000..908c239c08d56868267dfa4c769aa7a8f9da390d
--- /dev/null
+++ b/examples/Robocasa_tabletop/eval_files/infer_cosmos25_official.py
@@ -0,0 +1,708 @@
+#!/usr/bin/env python3
+"""Run official nvidia-cosmos/cosmos-predict2.5 on RoboCasa samples.
+
+This wrapper reads RoboCasa samples with the same dataset path as training,
+writes official Cosmos-Predict2.5 JSON inference requests, calls the native
+`examples/inference.py` entrypoint, then saves input/traj/pred/compare videos.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parents[3]
+if str(REPO_ROOT) not in sys.path:
+ sys.path.insert(0, str(REPO_ROOT))
+
+from examples.Robocasa_tabletop.eval_files.infer_cosmos25_future_video import (
+ add_label,
+ get_condition_video_frames,
+ get_full_trajectory_video_frames,
+ load_training_dataset,
+ parse_sample_indices,
+ read_video,
+ require_pil,
+ resolve_sample_location,
+ save_video,
+ to_pil_rgb,
+)
+from examples.Robocasa_tabletop.eval_files.infer_wan22_official import (
+ ROBOCASA_NEGATIVE_PROMPT,
+ build_prompt,
+)
+
+
+DEFAULT_COSMOS_REPO = "/mnt/workspace/users/yuanzhihao/code/cosmos-predict2.5"
+DEFAULT_COSMOS_CKPT_ROOT = "/mnt/workspace1/users/chidafeng/models/Cosmos-Predict2.5-2B"
+DEFAULT_COSMOS_CKPT = (
+ "/mnt/workspace1/users/chidafeng/models/Cosmos-Predict2.5-2B/"
+ "base/post-trained/81edfebe-bd6a-4039-8c1d-737df1a790bf_ema_bf16.pt"
+)
+DEFAULT_COSMOS_TOKENIZER_PATH = "/mnt/workspace1/users/chidafeng/models/Cosmos-Predict2-2B-Video2World/tokenizer/tokenizer.pth"
+
+
+def parse_args() -> argparse.Namespace:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--cosmos-repo", default=DEFAULT_COSMOS_REPO)
+ parser.add_argument("--ckpt-path", default=DEFAULT_COSMOS_CKPT_ROOT)
+ parser.add_argument("--python", default="python")
+ parser.add_argument("--out-dir", default="outputs/robocasa_cosmos25_official")
+ parser.add_argument("--config-yaml", default="./examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml")
+ parser.add_argument("--data-root-dir", default="/mnt/workspace/datasets")
+ parser.add_argument("--data-mix", default="robocasa_teleop_ee")
+ parser.add_argument("--dataset-mode", default="train", choices=("train", "val"))
+ parser.add_argument("--num-samples", type=int, default=1)
+ parser.add_argument("--start-index", type=int, default=0)
+ parser.add_argument("--sample-indices", default=None)
+ parser.add_argument("--view-index", type=int, default=0)
+ parser.add_argument("--conditioning-mode", choices=("image", "video"), default="image")
+ parser.add_argument("--condition-frames", type=int, default=2, help="Cosmos base supports 1 image frame or 2 latent video frames.")
+ parser.add_argument("--condition-stride", type=int, default=1)
+ parser.add_argument("--model", default="2B/post-trained")
+ parser.add_argument("--cosmos-tokenizer-path", default=DEFAULT_COSMOS_TOKENIZER_PATH)
+ parser.add_argument("--experiment", default=None)
+ parser.add_argument("--resolution", default="none", help='Official Cosmos resolution string, e.g. "704,1280"; "none" uses model default.')
+ parser.add_argument("--num-output-frames", type=int, default=77)
+ parser.add_argument("--num-steps", type=int, default=35)
+ parser.add_argument("--guidance", type=int, default=7)
+ parser.add_argument("--seed", type=int, default=0)
+ parser.add_argument("--fps", type=int, default=16)
+ parser.add_argument("--disable-guardrails", action=argparse.BooleanOptionalAction, default=True)
+ parser.add_argument("--offload-diffusion-model", action="store_true")
+ parser.add_argument("--offload-text-encoder", action="store_true")
+ parser.add_argument("--offload-tokenizer", action="store_true")
+ parser.add_argument("--cosmos-entrypoint", choices=("direct", "native"), default="direct")
+ parser.add_argument("--prompt", default=None, help="Override dataset instruction.")
+ parser.add_argument("--prompt-style", default="robocasa", choices=("robocasa", "raw"))
+ parser.add_argument("--prompt-template", default=None)
+ parser.add_argument("--negative-prompt", default=ROBOCASA_NEGATIVE_PROMPT)
+ parser.add_argument(
+ "--use-compat-sitecustomize",
+ action=argparse.BooleanOptionalAction,
+ default=True,
+ help="Inject local inference-only compatibility shims before importing official Cosmos.",
+ )
+ parser.add_argument(
+ "--patch-cosmos-repo",
+ action=argparse.BooleanOptionalAction,
+ default=False,
+ help="Patch the official Cosmos repo in-place. Off by default; the compat shim is preferred.",
+ )
+ parser.add_argument("--dry-run", action="store_true")
+ return parser.parse_args()
+
+
+def resolve_cosmos_ckpt(path: str) -> str:
+ root = Path(path)
+ if root.is_file():
+ return str(root)
+ candidate = root / "base/post-trained/81edfebe-bd6a-4039-8c1d-737df1a790bf_ema_bf16.pt"
+ if candidate.exists():
+ return str(candidate)
+ matches = sorted(root.glob("base/post-trained/*_ema_bf16.pt"))
+ if matches:
+ return str(matches[0])
+ return path
+
+
+def cosmos_pythonpath(cosmos_repo: str, env: dict[str, str]) -> str:
+ repo = Path(cosmos_repo)
+ paths = [
+ str(repo),
+ str(repo / "packages/cosmos-oss"),
+ str(repo / "packages/cosmos-cuda"),
+ ]
+ existing = env.get("PYTHONPATH")
+ if existing:
+ paths.append(existing)
+ return ":".join(paths)
+
+
+def write_cosmos_compat_sitecustomize(compat_dir: Path) -> Path:
+ """Create subprocess-only import shims for optional Cosmos training/storage deps."""
+ compat_dir.mkdir(parents=True, exist_ok=True)
+ sitecustomize = compat_dir / "sitecustomize.py"
+ sitecustomize.write_text(
+ r'''
+"""Inference-only compatibility shims for the official Cosmos-Predict2.5 CLI.
+
+The native entrypoint imports some training/cloud-storage modules at module load
+time. RoboCasa evaluation only needs local-file inference, so these shims keep
+optional dependencies from blocking import while still failing loudly if a
+training-only object is actually used.
+"""
+
+import math
+import sys
+import types
+import importlib.machinery
+
+try:
+ import importlib.metadata as importlib_metadata
+except Exception: # pragma: no cover
+ importlib_metadata = None
+
+
+def _unavailable(*args, **kwargs):
+ raise RuntimeError("This optional Cosmos dependency is not available in the inference shim.")
+
+
+try:
+ import torch
+ from torch import nn
+except Exception: # pragma: no cover
+ torch = None
+ nn = None
+
+
+if "transformer_engine" not in sys.modules:
+ te = types.ModuleType("transformer_engine")
+ te_pytorch = types.ModuleType("transformer_engine.pytorch")
+ te_attention = types.ModuleType("transformer_engine.pytorch.attention")
+ te_rope = types.ModuleType("transformer_engine.pytorch.attention.rope")
+ te_float8_tensor = types.ModuleType("transformer_engine.pytorch.float8_tensor")
+ te.__spec__ = importlib.machinery.ModuleSpec("transformer_engine", loader=None, is_package=True)
+ te_pytorch.__spec__ = importlib.machinery.ModuleSpec("transformer_engine.pytorch", loader=None, is_package=True)
+ te_attention.__spec__ = importlib.machinery.ModuleSpec(
+ "transformer_engine.pytorch.attention",
+ loader=None,
+ is_package=True,
+ )
+ te_rope.__spec__ = importlib.machinery.ModuleSpec("transformer_engine.pytorch.attention.rope", loader=None)
+ te_float8_tensor.__spec__ = importlib.machinery.ModuleSpec(
+ "transformer_engine.pytorch.float8_tensor",
+ loader=None,
+ )
+ te.__path__ = []
+ te_pytorch.__path__ = []
+ te_attention.__path__ = []
+
+ if nn is not None:
+ te_pytorch.RMSNorm = nn.RMSNorm
+ else:
+ te_pytorch.RMSNorm = _unavailable
+
+ class DotProductAttention(nn.Module if nn is not None else object):
+ def __init__(self, *args, **kwargs):
+ if nn is not None:
+ super().__init__()
+
+ def forward(self, query_layer, key_layer, value_layer, *args, **kwargs):
+ if torch is None:
+ return _unavailable()
+ q = query_layer
+ k = key_layer
+ v = value_layer
+ scale = 1.0 / math.sqrt(q.shape[-1])
+ scores = torch.matmul(q, k.transpose(-1, -2)) * scale
+ probs = torch.softmax(scores, dim=-1)
+ return torch.matmul(probs, v)
+
+ def apply_rotary_pos_emb(t, freqs, *args, **kwargs):
+ return t
+
+ class Float8Tensor:
+ pass
+
+ te_attention.DotProductAttention = DotProductAttention
+ te_attention.apply_rotary_pos_emb = apply_rotary_pos_emb
+ te_rope.apply_rotary_pos_emb = apply_rotary_pos_emb
+ te_float8_tensor.Float8Tensor = Float8Tensor
+ te_pytorch.attention = te_attention
+ te_pytorch.float8_tensor = te_float8_tensor
+ te.pytorch = te_pytorch
+ sys.modules["transformer_engine"] = te
+ sys.modules["transformer_engine.pytorch"] = te_pytorch
+ sys.modules["transformer_engine.pytorch.attention"] = te_attention
+ sys.modules["transformer_engine.pytorch.attention.rope"] = te_rope
+ sys.modules["transformer_engine.pytorch.float8_tensor"] = te_float8_tensor
+
+ if importlib_metadata is not None:
+ _orig_version = importlib_metadata.version
+ _orig_distribution = importlib_metadata.distribution
+
+ class _TransformerEngineDistribution:
+ version = "0.0.0"
+ metadata = {"Name": "transformer-engine", "Version": version}
+
+ def read_text(self, filename):
+ return ""
+
+ @property
+ def files(self):
+ return []
+
+ def _version(name):
+ normalized = name.replace("_", "-").lower()
+ if normalized in {"transformer-engine", "transformer-engine-torch"}:
+ return "0.0.0"
+ return _orig_version(name)
+
+ def _distribution(name):
+ normalized = name.replace("_", "-").lower()
+ if normalized in {"transformer-engine", "transformer-engine-torch"}:
+ return _TransformerEngineDistribution()
+ return _orig_distribution(name)
+
+ importlib_metadata.version = _version
+ importlib_metadata.distribution = _distribution
+
+
+if "transformer_engine_torch" not in sys.modules:
+ tex = types.ModuleType("transformer_engine_torch")
+ tex.__spec__ = importlib.machinery.ModuleSpec("transformer_engine_torch", loader=None)
+ tex.multi_tensor_adam = _unavailable
+ tex.multi_tensor_adam_capturable = _unavailable
+ tex.multi_tensor_adam_capturable_master = _unavailable
+ sys.modules["transformer_engine_torch"] = tex
+
+
+if "megatron.core.parallel_state" not in sys.modules:
+ megatron = types.ModuleType("megatron")
+ megatron_core = types.ModuleType("megatron.core")
+ parallel_state = types.ModuleType("megatron.core.parallel_state")
+ megatron.__spec__ = importlib.machinery.ModuleSpec("megatron", loader=None, is_package=True)
+ megatron_core.__spec__ = importlib.machinery.ModuleSpec("megatron.core", loader=None, is_package=True)
+ parallel_state.__spec__ = importlib.machinery.ModuleSpec("megatron.core.parallel_state", loader=None)
+ megatron.__path__ = []
+ megatron_core.__path__ = []
+
+ _MODEL_PARALLEL_INITIALIZED = False
+ parallel_state.cp_size_t = 1
+
+ class ModelParallelConfig:
+ def __init__(self, *args, **kwargs):
+ for key, value in kwargs.items():
+ setattr(self, key, value)
+
+ def initialize_model_parallel(*args, **kwargs):
+ global _MODEL_PARALLEL_INITIALIZED
+ _MODEL_PARALLEL_INITIALIZED = True
+
+ def destroy_model_parallel(*args, **kwargs):
+ global _MODEL_PARALLEL_INITIALIZED
+ _MODEL_PARALLEL_INITIALIZED = False
+
+ def is_initialized(*args, **kwargs):
+ return _MODEL_PARALLEL_INITIALIZED
+
+ def _none(*args, **kwargs):
+ return None
+
+ def _one(*args, **kwargs):
+ return 1
+
+ def _zero(*args, **kwargs):
+ return 0
+
+ parallel_state.initialize_model_parallel = initialize_model_parallel
+ parallel_state.destroy_model_parallel = destroy_model_parallel
+ parallel_state.is_initialized = is_initialized
+ parallel_state.get_context_parallel_group = _none
+ parallel_state.get_context_parallel_world_size = _one
+ parallel_state.get_context_parallel_rank = _zero
+ parallel_state.get_data_parallel_group = _none
+ parallel_state.get_data_parallel_world_size = _one
+ parallel_state.get_data_parallel_rank = _zero
+ parallel_state.get_tensor_model_parallel_group = _none
+ parallel_state.get_tensor_model_parallel_world_size = _one
+ parallel_state.get_tensor_model_parallel_rank = _zero
+ parallel_state.get_pipeline_model_parallel_group = _none
+ parallel_state.get_pipeline_model_parallel_world_size = _one
+ parallel_state.get_pipeline_model_parallel_rank = _zero
+ parallel_state.get_virtual_pipeline_model_parallel_rank = _zero
+ parallel_state.is_pipeline_first_stage = lambda *args, **kwargs: True
+ parallel_state.is_pipeline_last_stage = lambda *args, **kwargs: True
+ parallel_state.model_parallel_is_initialized = is_initialized
+
+ megatron_core.parallel_state = parallel_state
+ megatron_core.ModelParallelConfig = ModelParallelConfig
+ megatron.core = megatron_core
+ sys.modules["megatron"] = megatron
+ sys.modules["megatron.core"] = megatron_core
+ sys.modules["megatron.core.parallel_state"] = parallel_state
+
+
+if "multistorageclient" not in sys.modules:
+ msc = types.ModuleType("multistorageclient")
+
+ class StorageClient:
+ def __init__(self, *args, **kwargs):
+ _unavailable()
+
+ class StorageClientConfig:
+ def __init__(self, *args, **kwargs):
+ _unavailable()
+
+ msc.StorageClient = StorageClient
+ msc.StorageClientConfig = StorageClientConfig
+ sys.modules["multistorageclient"] = msc
+
+
+try:
+ import transformers.cache_utils as cache_utils
+
+ if not hasattr(cache_utils, "SlidingWindowCache"):
+ cache_utils.SlidingWindowCache = getattr(
+ cache_utils,
+ "DynamicCache",
+ getattr(cache_utils, "Cache", object),
+ )
+except Exception:
+ pass
+'''.lstrip(),
+ encoding="utf-8",
+ )
+ return sitecustomize
+
+
+def write_cosmos_direct_runner(compat_dir: Path) -> Path:
+ """Write a minimal local-file Cosmos runner that bypasses official Inference."""
+ compat_dir.mkdir(parents=True, exist_ok=True)
+ runner = compat_dir / "cosmos_direct_runner.py"
+ runner.write_text(
+ r'''
+from __future__ import annotations
+
+import argparse
+import json
+import os
+from fractions import Fraction
+from pathlib import Path
+
+import av
+import numpy as np
+import torch
+
+
+def parse_args():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--request", required=True)
+ parser.add_argument("--output-dir", required=True)
+ parser.add_argument("--model", default="2B/post-trained")
+ parser.add_argument("--checkpoint-path", required=True)
+ parser.add_argument("--tokenizer-path", default=None)
+ parser.add_argument("--experiment", default=None)
+ parser.add_argument("--config-file", default="cosmos_predict2/_src/predict2/configs/video2world/config.py")
+ parser.add_argument("--offload-diffusion-model", action="store_true")
+ parser.add_argument("--offload-text-encoder", action="store_true")
+ parser.add_argument("--offload-tokenizer", action="store_true")
+ return parser.parse_args()
+
+
+def save_video_av(frames: np.ndarray, path: Path, fps: int = 16) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with av.open(str(path), mode="w") as container:
+ stream = container.add_stream("libx264", rate=fps)
+ stream.width = int(frames.shape[2])
+ stream.height = int(frames.shape[1])
+ stream.pix_fmt = "yuv420p"
+ stream.time_base = Fraction(1, fps)
+ for frame in frames:
+ av_frame = av.VideoFrame.from_ndarray(frame, format="rgb24")
+ for packet in stream.encode(av_frame):
+ container.mux(packet)
+ for packet in stream.encode():
+ container.mux(packet)
+
+
+def resolve_setup(args):
+ from cosmos_predict2.config import SetupArguments
+
+ setup = SetupArguments.model_validate(
+ {
+ "output_dir": str(args.output_dir),
+ "model": args.model,
+ "checkpoint_path": args.checkpoint_path,
+ "experiment": args.experiment,
+ "config_file": args.config_file,
+ "disable_guardrails": True,
+ "offload_diffusion_model": args.offload_diffusion_model,
+ "offload_text_encoder": args.offload_text_encoder,
+ "offload_tokenizer": args.offload_tokenizer,
+ }
+ )
+ return setup
+
+
+def main():
+ args = parse_args()
+ output_dir = Path(args.output_dir)
+ output_dir.mkdir(parents=True, exist_ok=True)
+ args.output_dir = output_dir
+
+ request = json.loads(Path(args.request).read_text(encoding="utf-8"))
+ setup = resolve_setup(args)
+
+ from cosmos_predict2._src.predict2.inference.video2world import Video2WorldInference
+
+ experiment_opts = []
+ if setup.model_key.distilled:
+ experiment_opts.append("model.config.init_student_with_teacher=False")
+ if args.tokenizer_path:
+ experiment_opts.append(f"+model.config.tokenizer.vae_pth={args.tokenizer_path}")
+
+ torch.enable_grad(False)
+ pipe = Video2WorldInference(
+ experiment_name=setup.experiment,
+ ckpt_path=setup.checkpoint_path,
+ s3_credential_path="",
+ context_parallel_size=1,
+ config_file=setup.config_file,
+ experiment_opts=experiment_opts,
+ offload_diffusion_model=setup.offload_diffusion_model,
+ offload_text_encoder=setup.offload_text_encoder,
+ offload_tokenizer=setup.offload_tokenizer,
+ )
+
+ inference_type = str(request.get("inference_type", "video2world"))
+ num_input_frames = 1 if inference_type == "image2world" else 2
+ video = pipe.generate_vid2world(
+ prompt=request["prompt"],
+ input_path=request["input_path"],
+ guidance=int(request.get("guidance", 7)),
+ num_video_frames=int(request.get("num_output_frames", 77)),
+ num_latent_conditional_frames=num_input_frames,
+ resolution=request.get("resolution", "none"),
+ seed=int(request.get("seed", 0)),
+ negative_prompt=request.get("negative_prompt", ""),
+ num_steps=int(request.get("num_steps", 35)),
+ )
+ video = ((1.0 + video[0]) / 2.0).clamp(0.0, 1.0)
+ frames = (video * 255.0).to(torch.uint8).permute(1, 2, 3, 0).cpu().numpy()
+ save_path = output_dir / f"{request.get('name', 'pred')}.mp4"
+ save_video_av(frames, save_path, fps=16)
+ print(f"Saved video to {save_path}")
+
+
+if __name__ == "__main__":
+ main()
+'''.lstrip(),
+ encoding="utf-8",
+ )
+ return runner
+
+
+def patch_cosmos_lazy_guardrail_import(cosmos_repo: str) -> None:
+ """Avoid importing guardrail/easy_io storage backends when guardrails are disabled."""
+ inference_path = Path(cosmos_repo) / "cosmos_predict2/inference.py"
+ if not inference_path.exists():
+ return
+ text = inference_path.read_text(encoding="utf-8")
+ original = text
+ text = text.replace(
+ "from cosmos_predict2._src.imaginaire.auxiliary.guardrail.common import presets as guardrail_presets\n",
+ "",
+ )
+ marker = "from cosmos_predict2.config import InferenceArguments, SetupArguments, path_to_str\n"
+ replacement = marker + "\n\ndef get_guardrail_presets():\n from cosmos_predict2._src.imaginaire.auxiliary.guardrail.common import presets as guardrail_presets\n\n return guardrail_presets\n"
+ if "def get_guardrail_presets():" not in text and marker in text:
+ text = text.replace(marker, replacement)
+ text = text.replace(
+ " self.text_guardrail_runner = guardrail_presets.create_text_guardrail_runner(\n",
+ " guardrail_presets = get_guardrail_presets()\n self.text_guardrail_runner = guardrail_presets.create_text_guardrail_runner(\n",
+ )
+ text = text.replace(
+ " if not guardrail_presets.run_text_guardrail(sample.prompt, self.text_guardrail_runner):\n",
+ " guardrail_presets = get_guardrail_presets()\n if not guardrail_presets.run_text_guardrail(sample.prompt, self.text_guardrail_runner):\n",
+ )
+ text = text.replace(
+ " processed_frames = guardrail_presets.run_video_guardrail(frames, self.video_guardrail_runner)\n",
+ " guardrail_presets = get_guardrail_presets()\n processed_frames = guardrail_presets.run_video_guardrail(frames, self.video_guardrail_runner)\n",
+ )
+ if text != original:
+ inference_path.write_text(text, encoding="utf-8")
+ print(f"Patched Cosmos lazy guardrail import: {inference_path}")
+
+
+def save_compare_video(input_frames, traj_frames, pred_frames, save_path: Path, fps: int) -> None:
+ Image, _, _ = require_pil()
+ target_size = pred_frames[0].size
+ input_video = [to_pil_rgb(input_frames[min(i, len(input_frames) - 1)]).resize(target_size) for i in range(len(pred_frames))]
+ if len(traj_frames) == 1:
+ traj_video = [to_pil_rgb(traj_frames[0]).resize(target_size) for _ in pred_frames]
+ else:
+ traj_video = [
+ to_pil_rgb(traj_frames[round(i * (len(traj_frames) - 1) / max(len(pred_frames) - 1, 1))]).resize(target_size)
+ for i in range(len(pred_frames))
+ ]
+
+ compare_frames = []
+ for input_frame, traj_frame, pred_frame in zip(input_video, traj_video, pred_frames):
+ panels = [
+ add_label(input_frame.copy(), "Input"),
+ add_label(traj_frame.copy(), "Traj"),
+ add_label(pred_frame.copy(), "Cosmos"),
+ ]
+ canvas = Image.new("RGB", (target_size[0] * 3, target_size[1]))
+ for idx, panel in enumerate(panels):
+ canvas.paste(panel, (idx * target_size[0], 0))
+ compare_frames.append(canvas)
+ save_video(compare_frames, save_path, fps=fps)
+
+
+def build_cosmos_command(
+ args: argparse.Namespace,
+ request_path: Path,
+ native_out_dir: Path,
+ direct_runner_path: Path | None = None,
+) -> list[str]:
+ if args.cosmos_entrypoint == "direct":
+ if direct_runner_path is None:
+ raise ValueError("direct_runner_path is required for --cosmos-entrypoint direct")
+ cmd = [
+ args.python,
+ str(direct_runner_path),
+ "--request",
+ str(request_path),
+ "--output-dir",
+ str(native_out_dir),
+ "--model",
+ args.model,
+ "--checkpoint-path",
+ args.ckpt_path,
+ ]
+ if args.cosmos_tokenizer_path:
+ cmd.extend(["--tokenizer-path", args.cosmos_tokenizer_path])
+ else:
+ cmd = [
+ args.python,
+ "examples/inference.py",
+ "-i",
+ str(request_path),
+ "-o",
+ str(native_out_dir),
+ "--model",
+ args.model,
+ "--checkpoint-path",
+ args.ckpt_path,
+ ]
+ if args.experiment:
+ cmd.extend(["--experiment", args.experiment])
+ if args.cosmos_entrypoint == "native" and args.disable_guardrails:
+ cmd.append("--disable-guardrails")
+ if args.offload_diffusion_model:
+ cmd.append("--offload-diffusion-model")
+ if args.offload_text_encoder:
+ cmd.append("--offload-text-encoder")
+ if args.offload_tokenizer:
+ cmd.append("--offload-tokenizer")
+ return cmd
+
+
+def main() -> None:
+ args = parse_args()
+ args.ckpt_path = resolve_cosmos_ckpt(args.ckpt_path)
+ if args.patch_cosmos_repo and args.disable_guardrails:
+ patch_cosmos_lazy_guardrail_import(args.cosmos_repo)
+ out_dir = Path(args.out_dir).resolve()
+ out_dir.mkdir(parents=True, exist_ok=True)
+ compat_dir = out_dir / "_cosmos_compat"
+ direct_runner_path = None
+ if args.use_compat_sitecustomize:
+ sitecustomize_path = write_cosmos_compat_sitecustomize(compat_dir)
+ print(f"Using Cosmos compat shim: {sitecustomize_path}")
+ if args.cosmos_entrypoint == "direct":
+ direct_runner_path = write_cosmos_direct_runner(compat_dir)
+ print(f"Using direct Cosmos runner: {direct_runner_path}")
+ (out_dir / "run_args.json").write_text(json.dumps(vars(args), indent=2, ensure_ascii=False), encoding="utf-8")
+
+ dataset = load_training_dataset(args)
+ sample_indices = parse_sample_indices(args)
+
+ for sample_ord, dataset_index in enumerate(sample_indices):
+ source_dataset, trajectory_id, base_index = resolve_sample_location(dataset, dataset_index)
+ example = dataset[dataset_index]
+
+ sample_out_dir = out_dir / f"sample_{sample_ord:03d}_idx_{dataset_index:06d}"
+ sample_out_dir.mkdir(parents=True, exist_ok=True)
+ native_out_dir = sample_out_dir / "native_outputs"
+ native_out_dir.mkdir(parents=True, exist_ok=True)
+
+ raw_instruction = args.prompt or str(example["lang"])
+ prompt = build_prompt(args, raw_instruction)
+ condition_args = argparse.Namespace(**vars(args))
+ if args.conditioning_mode == "image":
+ condition_args.condition_frames = 1
+ else:
+ condition_args.condition_frames = 2
+ condition_frames = get_condition_video_frames(source_dataset, trajectory_id, base_index, condition_args)
+ traj_frames = get_full_trajectory_video_frames(source_dataset, trajectory_id, base_index, args)
+
+ input_path = sample_out_dir / ("cosmos_input.mp4" if args.conditioning_mode == "video" else "cosmos_input.png")
+ if args.conditioning_mode == "video":
+ save_video(condition_frames, input_path, fps=args.fps)
+ inference_type = "video2world"
+ else:
+ condition_frames[-1].save(input_path)
+ inference_type = "image2world"
+ save_video(condition_frames, sample_out_dir / "input.mp4", fps=args.fps)
+ save_video(traj_frames, sample_out_dir / "traj.mp4", fps=args.fps)
+
+ request = {
+ "inference_type": inference_type,
+ "name": "pred",
+ "input_path": str(input_path),
+ "prompt": prompt,
+ "negative_prompt": args.negative_prompt,
+ "seed": int(args.seed) + sample_ord,
+ "guidance": int(args.guidance),
+ "resolution": args.resolution,
+ "num_output_frames": int(args.num_output_frames),
+ "num_steps": int(args.num_steps),
+ }
+ request_path = sample_out_dir / "cosmos_request.json"
+ request_path.write_text(json.dumps(request, indent=2, ensure_ascii=False), encoding="utf-8")
+
+ cmd = build_cosmos_command(
+ args,
+ request_path=request_path,
+ native_out_dir=native_out_dir,
+ direct_runner_path=direct_runner_path,
+ )
+ meta = {
+ "dataset_index": dataset_index,
+ "trajectory_id": trajectory_id,
+ "base_index": base_index,
+ "instruction": raw_instruction,
+ "cosmos_prompt": prompt,
+ "cosmos_negative_prompt": args.negative_prompt,
+ "request": request,
+ "cosmos_command": cmd,
+ }
+ (sample_out_dir / "sample_meta.json").write_text(json.dumps(meta, indent=2, ensure_ascii=False), encoding="utf-8")
+
+ print(f"[{sample_ord + 1}/{len(sample_indices)}] dataset index={dataset_index}")
+ print(f"Instruction: {raw_instruction}")
+ print(f"Cosmos prompt: {prompt}")
+ print("Cosmos command:")
+ print(" ".join(cmd))
+ if args.dry_run:
+ continue
+
+ env = os.environ.copy()
+ env["PYTHONPATH"] = cosmos_pythonpath(args.cosmos_repo, env)
+ if args.use_compat_sitecustomize:
+ env["PYTHONPATH"] = f"{compat_dir}:{env['PYTHONPATH']}"
+ subprocess.run(cmd, cwd=args.cosmos_repo, env=env, check=True)
+
+ native_pred_path = native_out_dir / "pred.mp4"
+ if not native_pred_path.exists():
+ candidates = sorted(native_out_dir.glob("pred*.mp4"))
+ if not candidates:
+ raise FileNotFoundError(f"Could not find Cosmos output under {native_out_dir}")
+ native_pred_path = candidates[0]
+ pred_frames = [to_pil_rgb(frame) for frame in read_video(native_pred_path)]
+ save_video(pred_frames, sample_out_dir / "pred.mp4", fps=args.fps)
+ save_compare_video(condition_frames, traj_frames, pred_frames, sample_out_dir / "compare.mp4", fps=args.fps)
+ print(f"Saved prediction video: {sample_out_dir / 'pred.mp4'}")
+ print(f"Saved comparison video: {sample_out_dir / 'compare.mp4'}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/Robocasa_tabletop/eval_files/infer_wan22_official.py b/examples/Robocasa_tabletop/eval_files/infer_wan22_official.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ee06dee583c55f5db9bc7094c26fef7df00b612
--- /dev/null
+++ b/examples/Robocasa_tabletop/eval_files/infer_wan22_official.py
@@ -0,0 +1,372 @@
+#!/usr/bin/env python3
+"""Run official Wan2.2 TI2V code on RoboCasa dataset samples.
+
+This script does not use diffusers.WanPipeline. It reads RoboCasa samples with
+the starVLA dataloader, saves input/trajectory previews, then calls the official
+Wan2.2 repository's generate.py with --task ti2v-5B and --image.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import subprocess
+import sys
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parents[3]
+if str(REPO_ROOT) not in sys.path:
+ sys.path.insert(0, str(REPO_ROOT))
+
+from examples.Robocasa_tabletop.eval_files.infer_cosmos25_future_video import (
+ add_label,
+ as_image_list,
+ get_condition_video_frames,
+ get_full_trajectory_video_frames,
+ load_training_dataset,
+ parse_sample_indices,
+ read_video,
+ require_pil,
+ resample_to_length,
+ resolve_sample_location,
+ save_video,
+ to_pil_rgb,
+)
+
+
+DEFAULT_WAN_REPO = "/mnt/workspace/users/yuanzhihao/code/Wan2.2"
+DEFAULT_WAN_CKPT = "/mnt/workspace1/share/hf_models/Wan-AI/Wan2.2-TI2V-5B"
+VALID_WAN_SIZES = (
+ "720*1280",
+ "1280*720",
+ "480*832",
+ "832*480",
+ "704*1280",
+ "1280*704",
+ "1024*704",
+ "704*1024",
+)
+ROBOCASA_PROMPT_TEMPLATE = (
+ "A fixed-view RoboCasa simulation trajectory prediction. "
+ "The input image is the first reference frame. Generate future frames as a continuation of the same robot rollout. "
+ "Keep the background, tabletop workspace, robot, task-relevant objects, object identities, object colors, object shapes, camera pose, "
+ "camera scale, image framing, and field of view identical to the first frame. "
+ "The scene is a low-texture simulated robotics environment, not a real kitchen video. "
+ "The robot end effector is a black five-finger robotic dexterous hand, similar in shape to a human hand but clearly mechanical. "
+ "Only the black five-finger robotic dexterous hand, robot arm, and task-relevant movable objects are allowed to move. "
+ "Predict how the robot executes the task while all unrelated background objects remain static. "
+ "Do not zoom in, do not crop, do not pan, do not rotate the camera, and do not cut to a close-up. "
+ "No human, no human hand, no fingers, no skin, no real-world kitchen, no extra arm, no scene change. "
+ "Task instruction: {instruction}"
+)
+ROBOCASA_NEGATIVE_PROMPT = (
+ "human, person, human hand, fingers, skin, real-world kitchen, photorealistic kitchen, "
+ "close-up, zoom in, camera zoom, camera pan, camera rotation, camera movement, camera cut, "
+ "cropped view, changing viewpoint, changing field of view, scene change, new object, "
+ "parallel gripper, two-finger gripper, claw gripper, extra robot arm, extra dexterous hand, "
+ "duplicated robotic hand, deformed robotic hand, distorted robot, "
+ "blur, low quality, text, watermark, subtitles"
+)
+
+
+def parse_args() -> argparse.Namespace:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--wan-repo", default=DEFAULT_WAN_REPO)
+ parser.add_argument("--ckpt-dir", default=DEFAULT_WAN_CKPT)
+ parser.add_argument("--python", default="python")
+ parser.add_argument("--out-dir", default="outputs/robocasa_wan22_official_ti2v")
+ parser.add_argument("--config-yaml", default="./examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml")
+ parser.add_argument("--data-root-dir", default="/mnt/workspace/datasets")
+ parser.add_argument("--data-mix", default="robocasa_teleop_ee")
+ parser.add_argument("--dataset-mode", default="train", choices=("train", "val"))
+ parser.add_argument("--num-samples", type=int, default=1)
+ parser.add_argument("--start-index", type=int, default=0)
+ parser.add_argument("--sample-indices", default=None)
+ parser.add_argument("--view-index", type=int, default=0)
+ parser.add_argument(
+ "--condition-frames",
+ type=int,
+ default=1,
+ help="Number of dataset frames to save for visualization. Official Wan TI2V conditions on the latest frame only.",
+ )
+ parser.add_argument("--condition-stride", type=int, default=1)
+ parser.add_argument(
+ "--size",
+ default="1280*704",
+ choices=VALID_WAN_SIZES,
+ help="Official Wan size bucket. For I2V, output aspect ratio follows --image; this is not an exact output size.",
+ )
+ parser.add_argument(
+ "--wan-image-mode",
+ default="letterbox",
+ choices=("letterbox", "stretch", "raw"),
+ help="How to adapt the square RoboCasa frame before passing it to official Wan TI2V.",
+ )
+ parser.add_argument("--frame-num", type=int, default=81)
+ parser.add_argument("--sample-steps", type=int, default=50)
+ parser.add_argument("--sample-guide-scale", type=float, default=None)
+ parser.add_argument("--sample-shift", type=float, default=None)
+ parser.add_argument("--sample-solver", default="unipc", choices=("unipc", "dpm++"))
+ parser.add_argument("--seed", type=int, default=0)
+ parser.add_argument("--offload-model", default="True", choices=("True", "False", "true", "false"))
+ parser.add_argument("--t5-cpu", action="store_true")
+ parser.add_argument("--convert-model-dtype", action="store_true")
+ parser.add_argument("--prompt", default=None, help="Override dataset instruction.")
+ parser.add_argument(
+ "--prompt-style",
+ default="robocasa",
+ choices=("robocasa", "raw"),
+ help="robocasa wraps the instruction to bias Wan toward simulated robot trajectory prediction.",
+ )
+ parser.add_argument(
+ "--prompt-template",
+ default=None,
+ help="Optional format string with {instruction}; overrides --prompt-style robocasa template.",
+ )
+ parser.add_argument(
+ "--negative-prompt",
+ default=ROBOCASA_NEGATIVE_PROMPT,
+ help="Negative prompt passed to official Wan. Defaults to RoboCasa-specific camera/hand artifacts.",
+ )
+ parser.add_argument("--dry-run", action="store_true")
+ return parser.parse_args()
+
+
+def resolve_ckpt_dir(ckpt_dir: str) -> str:
+ root = Path(ckpt_dir)
+ nested = root / "Wan2.2-TI2V-5B"
+ if nested.is_dir() and (nested / "Wan2.2_VAE.pth").exists():
+ return str(nested)
+ return str(root)
+
+
+def patch_wan_imageio_quality(wan_repo: str) -> None:
+ """Patch official Wan save_video for imageio/PyAV versions without quality=."""
+ utils_path = Path(wan_repo) / "wan" / "utils" / "utils.py"
+ if not utils_path.exists():
+ return
+ text = utils_path.read_text(encoding="utf-8")
+ old = "cache_file, fps=fps, codec='libx264', quality=8)"
+ new = "cache_file, fps=fps, codec='libx264')"
+ if old in text:
+ utils_path.write_text(text.replace(old, new), encoding="utf-8")
+ print(f"Patched Wan save_video imageio quality arg: {utils_path}")
+
+
+def patch_wan_negative_prompt_arg(wan_repo: str) -> None:
+ """Expose WanTI2V.generate(..., n_prompt=...) through official generate.py."""
+ generate_path = Path(wan_repo) / "generate.py"
+ if not generate_path.exists():
+ return
+ text = generate_path.read_text(encoding="utf-8")
+ original = text
+
+ prompt_arg = ''' parser.add_argument(
+ "--prompt",
+ type=str,
+ default=None,
+ help="The prompt to generate the video from.")
+'''
+ negative_arg = prompt_arg + ''' parser.add_argument(
+ "--negative_prompt",
+ type=str,
+ default=None,
+ help="The negative prompt to avoid unwanted content.")
+'''
+ if "--negative_prompt" not in text and prompt_arg in text:
+ text = text.replace(prompt_arg, negative_arg)
+
+ if "wan_ti2v.generate" in text and "n_prompt=args.negative_prompt" not in text:
+ marker = " video = wan_ti2v.generate(\n"
+ start = text.find(marker)
+ if start != -1:
+ end = text.find("\n )", start)
+ if end != -1:
+ end += len("\n )")
+ call = text[start:end]
+ old = " guide_scale=args.sample_guide_scale,\n seed=args.base_seed,"
+ new = " guide_scale=args.sample_guide_scale,\n n_prompt=args.negative_prompt or \"\",\n seed=args.base_seed,"
+ if old in call:
+ text = text[:start] + call.replace(old, new) + text[end:]
+
+ if "--negative_prompt" not in text or "n_prompt=args.negative_prompt" not in text:
+ raise RuntimeError(f"Failed to patch Wan negative_prompt support in {generate_path}")
+
+ if text != original:
+ generate_path.write_text(text, encoding="utf-8")
+ print(f"Patched Wan generate.py negative_prompt arg: {generate_path}")
+
+
+def parse_wan_size(size: str) -> tuple[int, int]:
+ width, height = size.lower().split("*")
+ return int(width), int(height)
+
+
+def fit_frame_to_size(frame, target_size: tuple[int, int], mode: str = "letterbox"):
+ Image, _, _ = require_pil()
+ frame = to_pil_rgb(frame)
+ if mode == "raw":
+ return frame.copy()
+ if mode == "stretch":
+ return frame.resize(target_size)
+ if mode != "letterbox":
+ raise ValueError(f"Unknown frame fit mode: {mode}")
+
+ target_w, target_h = target_size
+ scale = min(target_w / frame.width, target_h / frame.height)
+ resized = frame.resize((max(1, round(frame.width * scale)), max(1, round(frame.height * scale))))
+ canvas = Image.new("RGB", target_size, (0, 0, 0))
+ paste_xy = ((target_w - resized.width) // 2, (target_h - resized.height) // 2)
+ canvas.paste(resized, paste_xy)
+ return canvas
+
+
+def resample_and_fit_frames(frames: list, target_len: int, target_size: tuple[int, int], mode: str = "letterbox") -> list:
+ if not frames:
+ return []
+ if len(frames) == 1:
+ sampled = [frames[0]] * target_len
+ else:
+ sampled = [frames[round(i * (len(frames) - 1) / max(target_len - 1, 1))] for i in range(target_len)]
+ return [fit_frame_to_size(frame, target_size, mode=mode) for frame in sampled]
+
+
+def save_compare_video(input_frames, traj_frames, pred_frames, save_path: Path, fps: int = 16) -> None:
+ Image, _, _ = require_pil()
+ target_size = pred_frames[0].size
+ input_video = resample_and_fit_frames(input_frames, len(pred_frames), target_size)
+ traj_video = resample_and_fit_frames(traj_frames, len(pred_frames), target_size)
+
+ compare_frames = []
+ for input_frame, traj_frame, pred_frame in zip(input_video, traj_video, pred_frames):
+ panels = [
+ add_label(input_frame.copy(), "Input"),
+ add_label(traj_frame.copy(), "Traj"),
+ add_label(pred_frame.copy(), "Wan"),
+ ]
+ canvas = Image.new("RGB", (target_size[0] * len(panels), target_size[1]))
+ for idx, panel in enumerate(panels):
+ canvas.paste(panel, (idx * target_size[0], 0))
+ compare_frames.append(canvas)
+ save_video(compare_frames, save_path, fps=fps)
+
+
+def build_prompt(args: argparse.Namespace, instruction: str) -> str:
+ if args.prompt_style == "raw":
+ return instruction
+ template = args.prompt_template or ROBOCASA_PROMPT_TEMPLATE
+ return template.format(instruction=instruction)
+
+
+def build_wan_command(args: argparse.Namespace, image_path: Path, prompt: str, save_file: Path) -> list[str]:
+ cmd = [
+ args.python,
+ "generate.py",
+ "--task",
+ "ti2v-5B",
+ "--ckpt_dir",
+ args.ckpt_dir,
+ "--image",
+ str(image_path),
+ "--prompt",
+ prompt,
+ "--negative_prompt",
+ args.negative_prompt,
+ "--size",
+ args.size,
+ "--frame_num",
+ str(args.frame_num),
+ "--sample_steps",
+ str(args.sample_steps),
+ "--sample_solver",
+ args.sample_solver,
+ "--base_seed",
+ str(args.seed),
+ "--offload_model",
+ args.offload_model,
+ "--save_file",
+ str(save_file),
+ ]
+ if args.sample_guide_scale is not None:
+ cmd.extend(["--sample_guide_scale", str(args.sample_guide_scale)])
+ if args.sample_shift is not None:
+ cmd.extend(["--sample_shift", str(args.sample_shift)])
+ if args.t5_cpu:
+ cmd.append("--t5_cpu")
+ if args.convert_model_dtype:
+ cmd.append("--convert_model_dtype")
+ return cmd
+
+
+def main() -> None:
+ args = parse_args()
+ args.ckpt_dir = resolve_ckpt_dir(args.ckpt_dir)
+ patch_wan_imageio_quality(args.wan_repo)
+ patch_wan_negative_prompt_arg(args.wan_repo)
+ out_dir = Path(args.out_dir).resolve()
+ out_dir.mkdir(parents=True, exist_ok=True)
+ (out_dir / "run_args.json").write_text(json.dumps(vars(args), indent=2, ensure_ascii=False), encoding="utf-8")
+
+ dataset = load_training_dataset(args)
+ sample_indices = parse_sample_indices(args)
+
+ for sample_ord, dataset_index in enumerate(sample_indices):
+ source_dataset, trajectory_id, base_index = resolve_sample_location(dataset, dataset_index)
+ example = dataset[dataset_index]
+ condition_frames = get_condition_video_frames(source_dataset, trajectory_id, base_index, args)
+ traj_frames = get_full_trajectory_video_frames(source_dataset, trajectory_id, base_index, args)
+ raw_instruction = args.prompt or str(example["lang"])
+ prompt = build_prompt(args, raw_instruction)
+
+ sample_out_dir = out_dir / f"sample_{sample_ord:03d}_idx_{dataset_index:06d}"
+ sample_out_dir.mkdir(parents=True, exist_ok=True)
+ image_path = sample_out_dir / "wan_input.png"
+ input_video_path = sample_out_dir / "input.mp4"
+ traj_video_path = sample_out_dir / "traj.mp4"
+ pred_path = sample_out_dir / "pred.mp4"
+ compare_path = sample_out_dir / "compare.mp4"
+ meta_path = sample_out_dir / "sample_meta.json"
+
+ # Official TI2V accepts one image. Use the latest dataset frame as the
+ # actual condition; input.mp4 is only kept for visualization.
+ wan_input_size = parse_wan_size(args.size)
+ wan_input_frame = fit_frame_to_size(condition_frames[-1], wan_input_size, mode=args.wan_image_mode)
+ wan_input_frame.save(image_path)
+ save_video(condition_frames, input_video_path, fps=16)
+ save_video(traj_frames, traj_video_path, fps=16)
+
+ cmd = build_wan_command(args, image_path=image_path, prompt=prompt, save_file=pred_path)
+ meta_path.write_text(
+ json.dumps(
+ {
+ "dataset_index": dataset_index,
+ "trajectory_id": trajectory_id,
+ "base_index": base_index,
+ "instruction": raw_instruction,
+ "wan_prompt": prompt,
+ "wan_negative_prompt": args.negative_prompt,
+ "prompt_style": args.prompt_style,
+ "wan_command": cmd,
+ },
+ indent=2,
+ ensure_ascii=False,
+ ),
+ encoding="utf-8",
+ )
+
+ print(f"[{sample_ord + 1}/{len(sample_indices)}] dataset index={dataset_index}")
+ print(f"Instruction: {raw_instruction}")
+ print(f"Wan prompt: {prompt}")
+ print(f"Wan negative prompt: {args.negative_prompt}")
+ print("Conditioning: official Wan TI2V receives only wan_input.png; input.mp4 is visualization only.")
+ print("Wan command:")
+ print(" ".join(cmd))
+ if not args.dry_run:
+ subprocess.run(cmd, cwd=args.wan_repo, check=True)
+ pred_frames = [to_pil_rgb(frame) for frame in read_video(pred_path)]
+ save_compare_video(condition_frames, traj_frames, pred_frames, compare_path)
+ print(f"Saved comparison video: {compare_path}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/Robocasa_tabletop/eval_files/infer_wan22_official_chunked.py b/examples/Robocasa_tabletop/eval_files/infer_wan22_official_chunked.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd4185b5faf6b3648912d7599bdcaedce6830557
--- /dev/null
+++ b/examples/Robocasa_tabletop/eval_files/infer_wan22_official_chunked.py
@@ -0,0 +1,202 @@
+#!/usr/bin/env python3
+"""Run official Wan2.2 TI2V in short teacher-forced chunks on RoboCasa.
+
+Each chunk conditions on the current GT frame, generates chunk_size + 1 frames,
+drops the first generated frame, and appends the remaining chunk_size future
+frames. This gives a stitched long rollout while avoiding long open-loop Wan
+generation from only the initial frame.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import subprocess
+import sys
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parents[3]
+if str(REPO_ROOT) not in sys.path:
+ sys.path.insert(0, str(REPO_ROOT))
+
+from examples.Robocasa_tabletop.eval_files.infer_cosmos25_future_video import (
+ add_label,
+ get_full_trajectory_video_frames,
+ load_training_dataset,
+ parse_sample_indices,
+ read_video,
+ require_pil,
+ resolve_sample_location,
+ save_video,
+ to_pil_rgb,
+)
+from examples.Robocasa_tabletop.eval_files.infer_wan22_official import (
+ DEFAULT_WAN_CKPT,
+ DEFAULT_WAN_REPO,
+ ROBOCASA_NEGATIVE_PROMPT,
+ VALID_WAN_SIZES,
+ build_prompt,
+ build_wan_command,
+ fit_frame_to_size,
+ parse_wan_size,
+ patch_wan_imageio_quality,
+ patch_wan_negative_prompt_arg,
+ resolve_ckpt_dir,
+)
+
+
+def parse_args() -> argparse.Namespace:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--wan-repo", default=DEFAULT_WAN_REPO)
+ parser.add_argument("--ckpt-dir", default=DEFAULT_WAN_CKPT)
+ parser.add_argument("--python", default="python")
+ parser.add_argument("--out-dir", default="outputs/robocasa_wan22_official_chunked")
+ parser.add_argument("--config-yaml", default="./examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml")
+ parser.add_argument("--data-root-dir", default="/mnt/workspace/datasets")
+ parser.add_argument("--data-mix", default="robocasa_teleop_ee")
+ parser.add_argument("--dataset-mode", default="train", choices=("train", "val"))
+ parser.add_argument("--num-samples", type=int, default=1)
+ parser.add_argument("--start-index", type=int, default=0)
+ parser.add_argument("--sample-indices", default=None)
+ parser.add_argument("--view-index", type=int, default=0)
+ parser.add_argument("--condition-frames", type=int, default=1, help="Kept for dataset helper compatibility; Wan uses one GT frame per chunk.")
+ parser.add_argument("--condition-stride", type=int, default=1)
+ parser.add_argument("--size", default="1280*704", choices=VALID_WAN_SIZES)
+ parser.add_argument("--wan-image-mode", default="letterbox", choices=("letterbox", "stretch", "raw"))
+ parser.add_argument("--chunk-size", type=int, default=16, help="Number of future frames kept from each Wan chunk.")
+ parser.add_argument("--max-rollout-frames", type=int, default=None, help="Optional cap including the initial GT condition frame.")
+ parser.add_argument("--sample-steps", type=int, default=50)
+ parser.add_argument("--sample-guide-scale", type=float, default=None)
+ parser.add_argument("--sample-shift", type=float, default=None)
+ parser.add_argument("--sample-solver", default="unipc", choices=("unipc", "dpm++"))
+ parser.add_argument("--seed", type=int, default=0)
+ parser.add_argument("--seed-stride", type=int, default=1, help="Added to --seed for each successive chunk.")
+ parser.add_argument("--offload-model", default="True", choices=("True", "False", "true", "false"))
+ parser.add_argument("--t5-cpu", action="store_true")
+ parser.add_argument("--convert-model-dtype", action="store_true")
+ parser.add_argument("--prompt", default=None, help="Override dataset instruction.")
+ parser.add_argument("--prompt-style", default="robocasa", choices=("robocasa", "raw"))
+ parser.add_argument("--prompt-template", default=None)
+ parser.add_argument("--negative-prompt", default=ROBOCASA_NEGATIVE_PROMPT)
+ parser.add_argument("--fps", type=int, default=24)
+ parser.add_argument("--dry-run", action="store_true")
+ return parser.parse_args()
+
+
+def validate_args(args: argparse.Namespace) -> None:
+ if args.chunk_size <= 0:
+ raise ValueError("--chunk-size must be positive.")
+ if args.chunk_size % 4 != 0:
+ raise ValueError("Wan frame_num must be 4n+1, so --chunk-size must be a multiple of 4.")
+ args.frame_num = args.chunk_size + 1
+
+
+def save_rollout_compare(gt_frames: list, pred_frames: list, save_path: Path, fps: int) -> None:
+ Image, _, _ = require_pil()
+ target_size = pred_frames[0].size
+ frames = []
+ for gt, pred in zip(gt_frames, pred_frames):
+ gt_panel = add_label(fit_frame_to_size(gt, target_size, mode="letterbox"), "GT")
+ pred_panel = add_label(to_pil_rgb(pred).resize(target_size).copy(), "Wan Chunked")
+ canvas = Image.new("RGB", (target_size[0] * 2, target_size[1]))
+ canvas.paste(gt_panel, (0, 0))
+ canvas.paste(pred_panel, (target_size[0], 0))
+ frames.append(canvas)
+ save_video(frames, save_path, fps=fps)
+
+
+def run_chunk(args: argparse.Namespace, chunk_dir: Path, condition_frame, prompt: str, chunk_index: int) -> list:
+ image_path = chunk_dir / "wan_input.png"
+ pred_path = chunk_dir / "pred.mp4"
+ chunk_dir.mkdir(parents=True, exist_ok=True)
+
+ wan_input_size = parse_wan_size(args.size)
+ wan_input_frame = fit_frame_to_size(condition_frame, wan_input_size, mode=args.wan_image_mode)
+ wan_input_frame.save(image_path)
+
+ chunk_args = argparse.Namespace(**vars(args))
+ chunk_args.seed = int(args.seed) + chunk_index * int(args.seed_stride)
+ chunk_args.frame_num = int(args.chunk_size) + 1
+ cmd = build_wan_command(chunk_args, image_path=image_path, prompt=prompt, save_file=pred_path)
+ (chunk_dir / "wan_command.json").write_text(json.dumps(cmd, indent=2, ensure_ascii=False), encoding="utf-8")
+
+ print(f"Chunk {chunk_index:03d}: condition={image_path}")
+ print(" ".join(cmd))
+ if args.dry_run:
+ return []
+ subprocess.run(cmd, cwd=args.wan_repo, check=True)
+ return [to_pil_rgb(frame) for frame in read_video(pred_path)]
+
+
+def main() -> None:
+ args = parse_args()
+ validate_args(args)
+ args.ckpt_dir = resolve_ckpt_dir(args.ckpt_dir)
+ patch_wan_imageio_quality(args.wan_repo)
+ patch_wan_negative_prompt_arg(args.wan_repo)
+
+ out_dir = Path(args.out_dir).resolve()
+ out_dir.mkdir(parents=True, exist_ok=True)
+ (out_dir / "run_args.json").write_text(json.dumps(vars(args), indent=2, ensure_ascii=False), encoding="utf-8")
+
+ dataset = load_training_dataset(args)
+ sample_indices = parse_sample_indices(args)
+
+ for sample_ord, dataset_index in enumerate(sample_indices):
+ source_dataset, trajectory_id, base_index = resolve_sample_location(dataset, dataset_index)
+ example = dataset[dataset_index]
+ all_traj_frames = get_full_trajectory_video_frames(source_dataset, trajectory_id, base_index, args)
+ rollout_frames = all_traj_frames[int(base_index):]
+ if args.max_rollout_frames is not None:
+ rollout_frames = rollout_frames[: max(1, int(args.max_rollout_frames))]
+ if len(rollout_frames) < 2:
+ raise ValueError(f"Need at least two rollout frames, got {len(rollout_frames)}.")
+
+ raw_instruction = args.prompt or str(example["lang"])
+ prompt = build_prompt(args, raw_instruction)
+ sample_out_dir = out_dir / f"sample_{sample_ord:03d}_idx_{dataset_index:06d}"
+ sample_out_dir.mkdir(parents=True, exist_ok=True)
+
+ stitched_pred = []
+ chunks_meta = []
+ cursor = 0
+ chunk_index = 0
+ while cursor < len(rollout_frames) - 1:
+ keep = min(args.chunk_size, len(rollout_frames) - 1 - cursor)
+ chunk_dir = sample_out_dir / f"chunk_{chunk_index:03d}_gt_{cursor:06d}"
+ pred_chunk = run_chunk(args, chunk_dir, rollout_frames[cursor], prompt, chunk_index)
+ chunks_meta.append({"chunk_index": chunk_index, "gt_start_frame": cursor, "kept_future_frames": keep, "chunk_dir": str(chunk_dir)})
+ if not args.dry_run:
+ if len(pred_chunk) < keep + 1:
+ raise ValueError(f"Chunk {chunk_index} returned {len(pred_chunk)} frames, need at least {keep + 1}.")
+ if not stitched_pred:
+ stitched_pred.append(fit_frame_to_size(rollout_frames[0], pred_chunk[0].size, mode="letterbox"))
+ stitched_pred.extend(pred_chunk[1: keep + 1])
+ cursor += keep
+ chunk_index += 1
+
+ meta = {
+ "dataset_index": dataset_index,
+ "trajectory_id": trajectory_id,
+ "base_index": base_index,
+ "instruction": raw_instruction,
+ "wan_prompt": prompt,
+ "wan_negative_prompt": args.negative_prompt,
+ "chunk_size": args.chunk_size,
+ "frame_num_per_chunk": args.frame_num,
+ "rollout_frames": len(rollout_frames),
+ "chunks": chunks_meta,
+ }
+ (sample_out_dir / "sample_meta.json").write_text(json.dumps(meta, indent=2, ensure_ascii=False), encoding="utf-8")
+
+ save_video(rollout_frames, sample_out_dir / "gt_rollout.mp4", fps=args.fps)
+ if not args.dry_run:
+ stitched_pred = stitched_pred[: len(rollout_frames)]
+ save_video(stitched_pred, sample_out_dir / "stitched_pred.mp4", fps=args.fps)
+ save_rollout_compare(rollout_frames, stitched_pred, sample_out_dir / "compare.mp4", fps=args.fps)
+ print(f"Saved stitched prediction: {sample_out_dir / 'stitched_pred.mp4'}")
+ print(f"Saved comparison video: {sample_out_dir / 'compare.mp4'}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/Robocasa_tabletop/eval_files/model2robocasa_interface.py b/examples/Robocasa_tabletop/eval_files/model2robocasa_interface.py
new file mode 100644
index 0000000000000000000000000000000000000000..35267bedfb2352c5a70fa172b4f3afa8440fd265
--- /dev/null
+++ b/examples/Robocasa_tabletop/eval_files/model2robocasa_interface.py
@@ -0,0 +1,306 @@
+from collections import deque
+from typing import Optional, Sequence
+import os
+import cv2 as cv
+import matplotlib.pyplot as plt
+import numpy as np
+
+from deployment.model_server.tools.websocket_policy_client import WebsocketClientPolicy
+
+from examples.Robocasa_tabletop.eval_files.adaptive_ensemble import AdaptiveEnsembler
+from typing import Dict
+import numpy as np
+from pathlib import Path
+
+from starVLA.model.framework.share_tools import read_mode_config
+
+
+class PolicyWarper:
+
+ def __init__(
+ self,
+ policy_ckpt_path,
+ unnorm_key: Optional[str] = None,
+ policy_setup: str = "franka",
+ horizon: int = 0,
+ action_ensemble=False, # @Jinhui
+ action_ensemble_horizon: Optional[int] = 3, # different cross sim
+ image_size: list[int] = [224, 224],
+ use_ddim: bool = True,
+ num_ddim_steps: int = 10,
+ adaptive_ensemble_alpha=0.1,
+ host="0.0.0.0",
+ port=10095,
+ n_action_steps=2,
+ ) -> None:
+
+ # build client to connect server policy
+ self.client = WebsocketClientPolicy(host, port)
+ self.policy_setup = policy_setup
+ self.unnorm_key = unnorm_key
+
+ print(f"*** policy_setup: {policy_setup}, unnorm_key: {unnorm_key} ***")
+ self.use_ddim = use_ddim
+ self.num_ddim_steps = num_ddim_steps
+ self.image_size = image_size
+ self.horizon = horizon #0
+ self.action_ensemble = action_ensemble
+ self.adaptive_ensemble_alpha = adaptive_ensemble_alpha
+ self.action_ensemble_horizon = action_ensemble_horizon
+ self.sticky_action_is_on = False
+ self.gripper_action_repeat = 0
+ self.sticky_gripper_action = 0.0
+ self.previous_gripper_action = None
+ self.n_action_steps = n_action_steps
+
+ self.task_description = None
+ self.image_history = deque(maxlen=self.horizon)
+ if self.action_ensemble:
+ self.action_ensembler = AdaptiveEnsembler(self.action_ensemble_horizon, self.adaptive_ensemble_alpha)
+ else:
+ self.action_ensembler = None
+ self.num_image_history = 0
+
+ self.action_norm_stats = self.get_action_stats(self.unnorm_key, policy_ckpt_path=policy_ckpt_path)
+
+ def _add_image_to_history(self, image: np.ndarray) -> None:
+ self.image_history.append(image)
+ self.num_image_history = min(self.num_image_history + 1, self.horizon)
+
+ def reset(self, task_description: str or tuple) -> None:
+
+ self.task_description = task_description
+ self.image_history.clear()
+ if self.action_ensemble:
+ self.action_ensembler.reset()
+ self.num_image_history = 0
+
+ self.sticky_action_is_on = False
+ self.gripper_action_repeat = 0
+ self.sticky_gripper_action = 0.0
+ self.previous_gripper_action = None
+
+ def step(self, observations, **kwargs) -> tuple[dict[str, np.ndarray], dict[str, np.ndarray]]:
+ """
+ 执行一步推理
+ :param image: 输入图像 (H, W, 3) uint8格式
+ :param task_description: 任务描述文本
+ :return: (原始动作, 处理后的动作)
+ """
+
+ task_description = observations['annotation.human.coarse_action'][0] # tuple
+ ego_view = observations['video.ego_view'] # (N, 1, H, W, 3)
+ images = ego_view
+ state = {}
+ state['left_arm'] = observations['state.left_arm']
+ state['right_arm'] = observations['state.right_arm'] # (N, 1, 7)
+ state['left_hand'] = observations['state.left_hand'] # (N, 1, 6)
+ state['right_hand'] = observations['state.right_hand'] # (N, 1, 6)
+ state['waist'] = observations['state.waist'] # (N, 1, 3)
+
+ state = self.normalize_state(state)
+ input_state = []
+ for key in state.keys():
+ input_state.append(state[key])
+ input_state = np.concatenate(input_state, axis=-1)
+
+ if task_description is not None:
+ if task_description != self.task_description:
+ self.reset(task_description)
+
+ # image: Image.Image = Image.fromarray(image)
+
+ images = [[self._resize_image(img) for img in sample] for sample in images] # (B, N_view, H, W, 3)
+ input_state = [input_s for input_s in input_state] # B, state_dim*(sin, cos)
+
+ # prepare vla input
+ examples = []
+ batch_size = len(images)
+ instructions = [self.task_description] if isinstance(self.task_description, str) else self.task_description
+ for b in range(batch_size):
+ example = {
+ "image": images[b], # A list of multi-view images for a single sample
+ "lang": instructions[b] if isinstance(instructions, list) else instructions,
+ # "state": input_state[b], # N_history, 58 #Hack BUG
+ }
+ examples.append(example)
+
+ vla_input = {
+ "examples": examples,
+ "do_sample": False,
+ "use_ddim": self.use_ddim,
+ "num_ddim_steps": self.num_ddim_steps,
+ }
+
+ response = self.client.predict_action(vla_input)
+ # print(response)
+
+ # unnormalize the action
+ normalized_actions = response["data"]["normalized_actions"] # B, chunk, D
+ normalized_actions = normalized_actions[:, :, [i for i in range(31) if i not in (14, 15)]]
+
+ # unnormalize actions in batch form
+ raw_actions = self.unnormalize_actions(normalized_actions=normalized_actions,
+ action_norm_stats=self.action_norm_stats)
+
+ # raw_actions shape: (B, chunk, D)
+ if self.action_ensemble:
+ # 对batch中的每个样本进行ensemble
+ batch_size = raw_actions.shape[0]
+ ensembled_actions = []
+ for b in range(batch_size):
+ ensembled = self.action_ensembler.ensemble_action(raw_actions[b])[None] # (1, D)
+ ensembled_actions.append(ensembled)
+ raw_actions = np.stack(ensembled_actions, axis=0) # (B, 1, D)
+
+ raw_action = {
+ "action.left_arm": raw_actions[:, :self.n_action_steps, :7], # (B, n_action_steps, 7)
+ "action.right_arm": raw_actions[:, :self.n_action_steps, 7:14], # (B, n_action_steps, 7)
+ "action.left_hand": raw_actions[:, :self.n_action_steps, 14:20], # (B, n_action_steps, 6)
+ "action.right_hand": raw_actions[:, :self.n_action_steps, 20:26], # (B, n_action_steps, 6)
+ "action.waist": raw_actions[:, :self.n_action_steps, 26:29], # (B, n_action_steps, 3)
+ }
+
+ return {"actions": raw_action}
+
+ @staticmethod
+ def unnormalize_actions(normalized_actions: np.ndarray, action_norm_stats: Dict[str, np.ndarray]) -> np.ndarray:
+ """
+ Args:
+ normalized_actions: shape (B, chunk, D) (chunk, D)
+ action_norm_stats:
+ Returns:
+ actions
+ """
+ mask = action_norm_stats.get("mask", np.ones_like(action_norm_stats["min"], dtype=bool))
+ normalized_actions_dim = normalized_actions.shape[-1]
+ if len(mask) < normalized_actions_dim:
+ # 只保留有效动作维度
+ valid_action_dim = len(mask)
+ # 取normalized_actions的前valid_action_dim维度
+ normalized_actions = normalized_actions[:, :, :valid_action_dim]
+ action_high, action_low = np.array(action_norm_stats["max"]), np.array(action_norm_stats["min"])
+
+ normalized_actions = np.clip(normalized_actions, -1, 1)
+
+ actions = np.where(
+ mask,
+ (normalized_actions + 1) / 2 * (action_high - action_low) + action_low,
+ normalized_actions,
+ )
+
+ return actions
+
+ @staticmethod
+ def get_action_stats(unnorm_key: str, policy_ckpt_path) -> dict:
+ """
+ Duplicate stats accessor (retained for backward compatibility).
+ """
+ policy_ckpt_path = Path(policy_ckpt_path)
+ model_config, norm_stats = read_mode_config(policy_ckpt_path) # read config and norm_stats
+
+ unnorm_key = PolicyWarper._check_unnorm_key(norm_stats, unnorm_key)
+ return norm_stats[unnorm_key]["action"]
+
+ #注意修改_resize_image,这个取决于训练时有没有使用VideoResizePad,若使用,则使用第二个_resize_image
+ # def _resize_image(self, image: np.ndarray) -> np.ndarray:
+ # image = cv.resize(image, tuple(self.image_size), interpolation=cv.INTER_AREA)
+ # return image
+ def _resize_image(self, image: np.ndarray) -> np.ndarray:
+ """
+ Resize image with padding to keep aspect ratio, matching VideoResizePad behavior.
+
+ Args:
+ image: Input image of shape (H, W, C)
+
+ Returns:
+ Resized and padded image of shape (target_size, target_size, C)
+ """
+ H, W = image.shape[:2]
+ target_size = self.image_size[0] # Assuming square target size
+
+ # Calculate scaling factor (scale longest edge to target size)
+ scale = target_size / max(H, W)
+ new_h = int(H * scale)
+ new_w = int(W * scale)
+
+ # Resize with aspect ratio preserved
+ resized = cv.resize(image, (new_w, new_h), interpolation=cv.INTER_AREA)
+
+ # Calculate padding to center the image
+ pad_h = target_size - new_h
+ pad_w = target_size - new_w
+ pad_top = pad_h // 2
+ pad_bottom = pad_h - pad_top
+ pad_left = pad_w // 2
+ pad_right = pad_w - pad_left
+
+ # Pad with black (0) to match VideoResizePad's default fill_value=0.0
+ padded = cv.copyMakeBorder(
+ resized,
+ pad_top,
+ pad_bottom,
+ pad_left,
+ pad_right,
+ cv.BORDER_CONSTANT,
+ value=0 # Black padding
+ )
+
+ return padded
+
+ def visualize_epoch(self, predicted_raw_actions: Sequence[np.ndarray], images: Sequence[np.ndarray],
+ save_path: str) -> None:
+ images = [self._resize_image(image) for image in images]
+ ACTION_DIM_LABELS = ["x", "y", "z", "roll", "pitch", "yaw", "grasp"]
+
+ img_strip = np.concatenate(np.array(images[::3]), axis=1)
+
+ # set up plt figure
+ figure_layout = [["image"] * len(ACTION_DIM_LABELS), ACTION_DIM_LABELS]
+ plt.rcParams.update({"font.size": 12})
+ fig, axs = plt.subplot_mosaic(figure_layout)
+ fig.set_size_inches([45, 10])
+
+ # plot actions
+ pred_actions = np.array([
+ np.concatenate([a["world_vector"], a["rotation_delta"], a["open_gripper"]], axis=-1)
+ for a in predicted_raw_actions
+ ])
+ for action_dim, action_label in enumerate(ACTION_DIM_LABELS):
+ # actions have batch, horizon, dim, in this example we just take the first action for simplicity
+ axs[action_label].plot(pred_actions[:, action_dim], label="predicted action")
+ axs[action_label].set_title(action_label)
+ axs[action_label].set_xlabel("Time in one episode")
+
+ axs["image"].imshow(img_strip)
+ axs["image"].set_xlabel("Time in one episode (subsampled)")
+ plt.legend()
+ plt.savefig(save_path)
+
+ @staticmethod
+ def _check_unnorm_key(norm_stats, unnorm_key):
+ """
+ Duplicate helper (retained for backward compatibility).
+ See primary _check_unnorm_key above.
+ """
+ if unnorm_key is None:
+ assert len(norm_stats) == 1, (
+ f"Your model was trained on more than one dataset, "
+ f"please pass a `unnorm_key` from the following options to choose the statistics "
+ f"used for un-normalizing actions: {norm_stats.keys()}")
+ unnorm_key = next(iter(norm_stats.keys()))
+
+ assert unnorm_key in norm_stats, (
+ f"The `unnorm_key` you chose is not in the set of available dataset statistics, "
+ f"please choose from: {norm_stats.keys()}")
+ return unnorm_key
+
+ def normalize_state(self, state: dict[str, np.ndarray]) -> dict[str, np.ndarray]:
+ """
+ Normalize the state
+ """
+ for key in state.keys():
+ sin_state = np.sin(state[key])
+ cos_state = np.cos(state[key])
+ state[key] = np.concatenate([sin_state, cos_state], axis=-1)
+ return state
diff --git a/examples/Robocasa_tabletop/eval_files/model2robocasa_interface_ee.py b/examples/Robocasa_tabletop/eval_files/model2robocasa_interface_ee.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69f7a0cb4b15c086b1fde2a773729586c12bbdd
--- /dev/null
+++ b/examples/Robocasa_tabletop/eval_files/model2robocasa_interface_ee.py
@@ -0,0 +1,493 @@
+from collections import deque
+from typing import Optional, Sequence
+import os
+import cv2 as cv
+import matplotlib.pyplot as plt
+import numpy as np
+from deployment.model_server.tools.websocket_policy_client import WebsocketClientPolicy
+from examples.Robocasa_tabletop.eval_files.adaptive_ensemble import AdaptiveEnsembler
+from typing import Dict
+import numpy as np
+from pathlib import Path
+from release.config import read_mode_config
+class PolicyWarper:
+ def __init__(
+ self,
+ policy_ckpt_path,
+ unnorm_key: Optional[str] = "gr1",
+ policy_setup: str = "franka",
+ horizon: int = 0,
+ action_ensemble = False, # @Jinhui
+ action_ensemble_horizon: Optional[int] = 3, # different cross sim
+ image_size: list[int] = [224, 224],
+ use_ddim: bool = True,
+ num_ddim_steps: int = 10,
+ adaptive_ensemble_alpha = 0.1,
+ host="0.0.0.0",
+ port=10095,
+ n_action_steps=2,
+ prompt_speed: int = 2500,
+ ) -> None:
+
+ # build client to connect server policy
+ self.client = WebsocketClientPolicy(host, port)
+ self.policy_setup = policy_setup
+ self.unnorm_key = unnorm_key
+ print(f"*** policy_setup: {policy_setup}, unnorm_key: {unnorm_key} ***")
+ self.use_ddim = use_ddim
+ self.num_ddim_steps = num_ddim_steps
+ self.image_size = image_size
+ self.horizon = horizon #0
+ self.action_ensemble = action_ensemble
+ self.adaptive_ensemble_alpha = adaptive_ensemble_alpha
+ self.action_ensemble_horizon = action_ensemble_horizon
+ self.sticky_action_is_on = False
+ self.gripper_action_repeat = 0
+ self.sticky_gripper_action = 0.0
+ self.previous_gripper_action = None
+ self.n_action_steps = n_action_steps
+ self.prompt_speed = prompt_speed
+ self.use_eepose = True
+ self.effective_dim = 29
+ self.task_description = None
+ self._has_logged_prompt = False
+ self._debug_action_count = 0
+ self.image_history = deque(maxlen=self.horizon)
+ if self.action_ensemble:
+ self.action_ensembler = AdaptiveEnsembler(self.action_ensemble_horizon, self.adaptive_ensemble_alpha)
+ else:
+ self.action_ensembler = None
+ self.num_image_history = 0
+ self.action_norm_stats = self.get_action_stats(self.unnorm_key, policy_ckpt_path=policy_ckpt_path)
+ self.state_norm_stats = self.get_state_stats(self.unnorm_key, policy_ckpt_path=policy_ckpt_path)
+
+ print(f"DEBUG: use_eepose = {self.use_eepose}")
+ if self.use_eepose:
+ print("DEBUG: Entering if self.use_eepose block")
+ try:
+ print("DEBUG: About to import gr1_pos_transform")
+ from examples.Robocasa_tabletop.eval_files.gr1_pos_transform_new import BodyRetargeter, GR1RetargetConfig
+ print("DEBUG: Import successful, creating GR1RetargetConfig")
+ gr1_config = GR1RetargetConfig()
+ print("DEBUG: GR1RetargetConfig created, creating BodyRetargeter")
+
+ # 然后,通过这个实例来访问属性
+ self.body_retargeter = BodyRetargeter(
+ urdf_path=Path(gr1_config.urdf_path),
+ camera_intrinsics=gr1_config.camera_intrinsics
+ )
+ print("Enabled EEPose processing in Gr00tPolicy.")
+ except Exception as e:
+ import traceback
+ print(f"Warning: Failed to initialize EEPose processing: {e}")
+ print(f"Traceback: {traceback.format_exc()}")
+ self.use_eepose = False
+ else:
+ print(f"DEBUG: use_eepose is False, skipping initialization")
+
+ def _add_image_to_history(self, image: np.ndarray) -> None:
+ self.image_history.append(image)
+ self.num_image_history = min(self.num_image_history + 1, self.horizon)
+ def reset(self, task_description: str or tuple) -> None:
+
+ self.task_description = task_description
+ self.image_history.clear()
+ if self.action_ensemble:
+ self.action_ensembler.reset()
+ self.num_image_history = 0
+ self.sticky_action_is_on = False
+ self.gripper_action_repeat = 0
+ self.sticky_gripper_action = 0.0
+ self.previous_gripper_action = None
+
+ def _format_prompt(self, task_text: str) -> str:
+ task_text = str(task_text).strip().rstrip(".")
+ return f"Task: {task_text}."
+ return (
+ f"Task: {task_text}. "
+ f"Speed: {self.prompt_speed}. "
+ f"Mistake: false. "
+ f"Control Mode: ee."
+ )
+
+ def _build_instructions(self, batch_size: int) -> list[str]:
+ task_description = self.task_description
+ if isinstance(task_description, str):
+ task_texts = [task_description] * batch_size
+ elif isinstance(task_description, Sequence):
+ task_texts = list(task_description)
+ if len(task_texts) == 1 and batch_size > 1:
+ task_texts = task_texts * batch_size
+ elif len(task_texts) != batch_size:
+ raise ValueError(
+ f"Task description batch size mismatch: got {len(task_texts)} tasks for batch size {batch_size}"
+ )
+ else:
+ raise TypeError(f"Unsupported task_description type: {type(task_description)}")
+
+ instructions = [self._format_prompt(task_text) for task_text in task_texts]
+ if not self._has_logged_prompt and len(instructions) > 0:
+ print(f"Inference prompt: {instructions[0]}")
+ self._has_logged_prompt = True
+ return instructions
+
+ def step(
+ self,
+ observations,
+ **kwargs
+ ) -> tuple[dict[str, np.ndarray], dict[str, np.ndarray]]:
+ """
+ 执行一步推理
+ :param image: 输入图像 (H, W, 3) uint8格式
+ :param task_description: 任务描述文本
+ :return: (原始动作, 处理后的动作)
+ """
+ task_description = observations['annotation.human.coarse_action'][0] # tuple
+ ego_view = observations['video.ego_view'] # (N, 1, H, W, 3)
+ images = ego_view # (N, 1, 3)
+
+ if self.use_eepose:
+ # 1. 使用 BodyRetargeter 将 EEpose 转换为标准状态表示
+ obs_copy = observations.copy()
+ full_44dof_vector = self._build_full_44dof_vector(obs_copy)
+ (left_hand_positions, left_hand_axisangles), (right_hand_positions, right_hand_axisangles), (left_qpos_states, right_qpos_states) = self.body_retargeter.process_frame_kinematics_axisangle(full_44dof_vector)
+ #print(f"Left hand positions shape: {left_hand_positions.shape}, axis-angles shape: {left_hand_axisangles.shape}")
+ # 2. 将转换后的状态添加回 obs_copy
+ left_arm_state = obs_copy.get("state.left_arm", None)
+ right_arm_state = obs_copy.get("state.right_arm", None)
+ # 拼接两个 (bs, 3) 的数组,得到一个 (bs, 6) 的二维数组
+ left_eepose_2d = np.concatenate((left_hand_positions, left_hand_axisangles), axis=-1)
+ right_eepose_2d = np.concatenate((right_hand_positions, right_hand_axisangles), axis=-1)
+ # 使用 np.newaxis 恢复时间维度,将其从 (bs, 6) 变为 (bs, 1, 6)
+ observations["state.left_arm"] = left_eepose_2d[:, np.newaxis, :]
+ observations["state.right_arm"] = right_eepose_2d[:, np.newaxis, :]
+ state = {}
+ state['left_arm'] = observations['state.left_arm'] # (B, 1, 6)
+ state['right_arm'] = observations['state.right_arm'] # (B, 1, 6)
+ state['left_hand'] = observations['state.left_hand'] # (B, 1, 6)
+ state['right_hand'] = observations['state.right_hand'] # (B, 1, 6)
+ state['waist'] = observations['state.waist'] # (B, 1, 3)
+ # 1) 先按实际使用的27维顺序拼接
+ state_27 = np.concatenate([
+ state['left_arm'], # 0:6
+ state['right_arm'], # 6:12
+ state['left_hand'], # 12:18
+ state['right_hand'], # 18:24
+ state['waist'], # 24:27
+ ], axis=-1)
+ # 2) 用27维 stats 做 min-max normalize
+ state_27 = self.normalize_state_minmax(state_27, self.state_norm_stats)
+ # 3) 再插入 gripper 两维,恢复到训练时的29维布局
+ bs = state_27.shape[0]
+ dtype = state_27.dtype
+ input_state = np.concatenate([
+ state_27[:, :, 0:6], # left_arm
+ state_27[:, :, 6:12], # right_arm
+ np.zeros((bs, 1, 1), dtype=dtype), # left_gripper
+ np.zeros((bs, 1, 1), dtype=dtype), # right_gripper
+ state_27[:, :, 12:18], # left_hand
+ state_27[:, :, 18:24], # right_hand
+ state_27[:, :, 24:27], # waist
+ ], axis=-1)
+ # 4) pad 到 64 维
+ if input_state.shape[2] != 64:
+ zero_pad = np.zeros((input_state.shape[0], 1, 64 - input_state.shape[2]), dtype=input_state.dtype)
+ input_state = np.concatenate([input_state, zero_pad], axis=-1)
+ if task_description is not None:
+ if task_description != self.task_description:
+ self.reset(task_description)
+ # image: Image.Image = Image.fromarray(image)
+ images = [[self._resize_image(img) for img in sample] for sample in images] # (B, N_view, H, W, 3)
+ # input_state = [input_s for input_s in input_state] # B, state_dim*(sin, cos)
+ # prepare vla input
+ examples = []
+ batch_size = len(images)
+ instructions = self._build_instructions(batch_size)
+ #print(input_state)
+ #import pdb; pdb.set_trace()
+ for b in range(batch_size):
+ example = {
+ "image": images[b], # A list of multi-view images for a single sample
+ "lang": instructions[b],
+ "state": input_state[b], # N_history, 58 #Hack BUG
+ "embodiment_tag": 24, # GR1, matches robocasa_teleop_ee training samples.
+ }
+ examples.append(example)
+
+ vla_input = {
+ "examples": examples,
+ "do_sample": False,
+ "use_ddim": self.use_ddim,
+ "num_ddim_steps": self.num_ddim_steps,
+ }
+ self._update_vla_input(vla_input)
+
+ response = self.client.predict_action(vla_input)
+ self._handle_model_response(response, images)
+
+
+ # unnormalize the action
+ normalized_actions = response["data"]["normalized_actions"] # B, chunk, D
+ # normalized_actions = normalized_actions[:, :, :self.effective_dim]
+ self._log_action_debug("normalized_actions_model", normalized_actions)
+ normalized_actions = normalized_actions[:, :, [i for i in range(self.effective_dim) if i not in (12, 13)]]
+ self._log_action_debug("normalized_actions_exec", normalized_actions)
+
+ # unnormalize actions in batch form
+ raw_actions = self.unnormalize_actions(normalized_actions=normalized_actions, action_norm_stats=self.action_norm_stats)
+ self._log_action_debug("raw_actions_exec", raw_actions)
+ # raw_actions shape: (B, chunk, D)
+ if self.action_ensemble:
+ # 对batch中的每个样本进行ensemble
+ batch_size = raw_actions.shape[0]
+ ensembled_actions = []
+ for b in range(batch_size):
+ ensembled = self.action_ensembler.ensemble_action(raw_actions[b])[None] # (1, D)
+ ensembled_actions.append(ensembled)
+ raw_actions = np.stack(ensembled_actions, axis=0) # (B, 1, D)
+ if self.use_eepose:
+ raw_action = {
+ "action.left_arm": raw_actions[:, :self.n_action_steps, :6], # (B, n_action_steps, 7)
+ "action.right_arm": raw_actions[:, :self.n_action_steps, 6:12], # (B, n_action_steps, 7)
+ "action.left_hand": raw_actions[:, :self.n_action_steps, 12:18], # (B, n_action_steps, 6)
+ "action.right_hand": raw_actions[:, :self.n_action_steps, 18:24], # (B, n_action_steps, 6)
+ "action.waist": raw_actions[:, :self.n_action_steps, 24:27], # (B, n_action_steps, 3)
+ }
+ # 从模型输出的6-DoF EE Pose动作中提取 pos 和 axis-angle
+ pred_left_eepose_seq = raw_action["action.left_arm"]
+ pred_right_eepose_seq = raw_action["action.right_arm"]
+
+ batch_size, horizon, _ = pred_left_eepose_seq.shape
+
+ # 初始化用于存储IK结果的数组
+ q_left_arm_seq = np.zeros((batch_size, horizon, 7)) # 目标是7-DoF
+ q_right_arm_seq = np.zeros((batch_size, horizon, 7)) # 目标是7-DoF
+ # 使用输入时的原始7-DoF手臂状态作为第一个时间步的IK初始猜测
+ # 形状从 (B, 1, 7) 变为 (B, 7)
+ q_init_left = left_arm_state[:, -1, :] if left_arm_state is not None else None
+ q_init_right = right_arm_state[:, -1, :] if right_arm_state is not None else None
+ # 遍历动作序列的每一个时间步 (从 0 到 15)
+ for t in range(horizon):
+ # 提取当前时间步 t 的EE Pose动作,形状为 (B, 6)
+ left_eepose_t = pred_left_eepose_seq[:, t, :]
+ right_eepose_t = pred_right_eepose_seq[:, t, :]
+ #print(f"Time step {t}: Left EE Pose shape: {left_eepose_t.shape}, Right EE Pose shape: {right_eepose_t.shape}")
+ # 将EE Pose分解为位置和轴角
+ left_hand_pos = left_eepose_t[:, :3]
+ left_hand_axisangle = left_eepose_t[:, 3:6]
+ right_hand_pos = right_eepose_t[:, :3]
+ right_hand_axisangle = right_eepose_t[:, 3:6]
+ # 执行IK计算,输入是 (B, 3),输出是 (B, 7)
+ q_left_arm_t, q_right_arm_t = self.body_retargeter.inverse_kinematics_from_camera_axisangle(
+ left_hand_pos=left_hand_pos,
+ left_hand_axisangle=left_hand_axisangle,
+ right_hand_pos=right_hand_pos,
+ right_hand_axisangle=right_hand_axisangle,
+ current_action_vector=full_44dof_vector,
+ q_init_left=q_init_left,
+ q_init_right=q_init_right
+ )
+ # 将计算出的关节角存储到结果序列中
+ if q_left_arm_t is not None:
+ q_left_arm_seq[:, t, :] = q_left_arm_t
+ if q_right_arm_t is not None:
+ q_right_arm_seq[:, t, :] = q_right_arm_t
+
+ # 使用当前步的IK解作为下一步的初始猜测,以保证动作的连续性
+ q_init_left = q_left_arm_t
+ q_init_right = q_right_arm_t
+ # 将完整的关节角序列更新回 raw_action 字典
+ raw_action["action.left_arm"] = q_left_arm_seq
+ raw_action["action.right_arm"] = q_right_arm_seq
+
+ else:
+ raw_action = {
+ "action.left_arm": raw_actions[:, :self.n_action_steps, :7], # (B, n_action_steps, 7)
+ "action.right_arm": raw_actions[:, :self.n_action_steps, 7:14], # (B, n_action_steps, 7)
+ "action.left_hand": raw_actions[:, :self.n_action_steps, 14:20], # (B, n_action_steps, 6)
+ "action.right_hand": raw_actions[:, :self.n_action_steps, 20:26], # (B, n_action_steps, 6)
+ "action.waist": raw_actions[:, :self.n_action_steps, 26:29], # (B, n_action_steps, 3)
+ }
+ return {"actions": raw_action}
+
+ def _handle_model_response(self, response: dict, images) -> None:
+ return
+
+ def _update_vla_input(self, vla_input: dict) -> None:
+ return
+
+ def _log_action_debug(self, name: str, actions: np.ndarray) -> None:
+ if os.getenv("STARVLA_ACTION_DEBUG", "0").lower() not in {"1", "true", "yes", "on"}:
+ return
+ max_logs = int(os.getenv("STARVLA_ACTION_DEBUG_MAX", "20"))
+ if self._debug_action_count >= max_logs:
+ return
+ arr = np.asarray(actions, dtype=np.float32)
+ print(
+ f"[ACTION_DEBUG] {name}: shape={arr.shape}, "
+ f"mean={arr.mean():.4g}, std={arr.std():.4g}, "
+ f"min={arr.min():.4g}, max={arr.max():.4g}, "
+ f"first={arr.reshape(-1, arr.shape[-1])[0].tolist()}",
+ flush=True,
+ )
+ if name == "raw_actions_exec":
+ self._debug_action_count += 1
+
+ @staticmethod
+ def unnormalize_actions(normalized_actions: np.ndarray, action_norm_stats: Dict[str, np.ndarray]) -> np.ndarray:
+ """
+ Args:
+ normalized_actions: shape (B, chunk, D) (chunk, D)
+ action_norm_stats:
+ Returns:
+ actions
+ """
+ mask = action_norm_stats.get("mask", np.ones_like(action_norm_stats["min"], dtype=bool))
+ action_high, action_low = np.array(action_norm_stats["max"]), np.array(action_norm_stats["min"])
+
+ normalized_actions = np.clip(normalized_actions, -1, 1)
+
+ actions = np.where(
+ mask,
+ (normalized_actions + 1) / 2 * (action_high - action_low) + action_low,
+ normalized_actions,
+ )
+
+ return actions
+ @staticmethod
+ def get_action_stats(unnorm_key: str, policy_ckpt_path) -> dict:
+ """
+ Duplicate stats accessor (retained for backward compatibility).
+ """
+ policy_ckpt_path = Path(policy_ckpt_path)
+ model_config, norm_stats = read_mode_config(policy_ckpt_path) # read config and norm_stats
+ unnorm_key = PolicyWarper._check_unnorm_key(norm_stats, unnorm_key)
+ return norm_stats[unnorm_key]["action"]
+ @staticmethod
+ def get_state_stats(unnorm_key: str, policy_ckpt_path) -> dict:
+ """
+ Duplicate stats accessor (retained for backward compatibility).
+ """
+ policy_ckpt_path = Path(policy_ckpt_path)
+ model_config, norm_stats = read_mode_config(policy_ckpt_path) # read config and norm_stats
+ unnorm_key = PolicyWarper._check_unnorm_key(norm_stats, unnorm_key)
+ return norm_stats[unnorm_key]["state"]
+ def _resize_image(self, image: np.ndarray) -> np.ndarray:
+ # Keep evaluation preprocessing aligned with the current training
+ # dataset path, which uses PIL resize((224, 224)) instead of
+ # aspect-ratio-preserving VideoResizePad.
+ return cv.resize(image, tuple(self.image_size), interpolation=cv.INTER_AREA)
+ def visualize_epoch(
+ self, predicted_raw_actions: Sequence[np.ndarray], images: Sequence[np.ndarray], save_path: str
+ ) -> None:
+ images = [self._resize_image(image) for image in images]
+ ACTION_DIM_LABELS = ["x", "y", "z", "roll", "pitch", "yaw", "grasp"]
+ img_strip = np.concatenate(np.array(images[::3]), axis=1)
+ # set up plt figure
+ figure_layout = [["image"] * len(ACTION_DIM_LABELS), ACTION_DIM_LABELS]
+ plt.rcParams.update({"font.size": 12})
+ fig, axs = plt.subplot_mosaic(figure_layout)
+ fig.set_size_inches([45, 10])
+ # plot actions
+ pred_actions = np.array(
+ [
+ np.concatenate([a["world_vector"], a["rotation_delta"], a["open_gripper"]], axis=-1)
+ for a in predicted_raw_actions
+ ]
+ )
+ for action_dim, action_label in enumerate(ACTION_DIM_LABELS):
+ # actions have batch, horizon, dim, in this example we just take the first action for simplicity
+ axs[action_label].plot(pred_actions[:, action_dim], label="predicted action")
+ axs[action_label].set_title(action_label)
+ axs[action_label].set_xlabel("Time in one episode")
+ axs["image"].imshow(img_strip)
+ axs["image"].set_xlabel("Time in one episode (subsampled)")
+ plt.legend()
+ plt.savefig(save_path)
+
+ @staticmethod
+ def _check_unnorm_key(norm_stats, unnorm_key):
+ """
+ Duplicate helper (retained for backward compatibility).
+ See primary _check_unnorm_key above.
+ """
+ if unnorm_key is None:
+ assert len(norm_stats) == 1, (
+ f"Your model was trained on more than one dataset, "
+ f"please pass a `unnorm_key` from the following options to choose the statistics "
+ f"used for un-normalizing actions: {norm_stats.keys()}"
+ )
+ unnorm_key = next(iter(norm_stats.keys()))
+ assert unnorm_key in norm_stats, (
+ f"The `unnorm_key` you chose is not in the set of available dataset statistics, "
+ f"please choose from: {norm_stats.keys()}"
+ )
+ return unnorm_key
+
+ def normalize_state(self, state: dict[str, np.ndarray]) -> dict[str, np.ndarray]:
+ """
+ Normalize the state
+ """
+ for key in state.keys():
+ sin_state = np.sin(state[key])
+ cos_state = np.cos(state[key])
+ state[key] = np.concatenate([sin_state, cos_state], axis=-1)
+ return state
+ @staticmethod
+ def normalize_state_minmax(state: np.ndarray, state_norm_stats: Dict[str, np.ndarray]) -> np.ndarray:
+ state_min = np.asarray(state_norm_stats["min"], dtype=np.float32)
+ state_max = np.asarray(state_norm_stats["max"], dtype=np.float32)
+ state = 2 * (state - state_min) / (state_max - state_min) - 1
+ return state
+ # 组成44DOF向量的辅助函数
+ # 组成44DOF向量的辅助函数
+ @staticmethod
+ def _build_full_44dof_vector(obs_dict):
+ """
+ 从包含批处理数据的观测字典中构建一个 (batch_size, 44) 的完整状态向量。
+
+ Args:
+ obs_dict (Dict[str, np.ndarray]): 观测字典,其中 state 的形状为 (B, T, D)。
+ B 是批次大小 (环境数量), T 是时间步, D 是特征维度。
+ Returns:
+ np.ndarray: 形状为 (B, 44) 的状态向量。
+ """
+ # 定义44-DoF向量中每个部分的起始和结束索引
+ layout_44dof = {
+ "left_arm": (0, 7), "left_hand": (7, 13), "left_leg": (13, 19),
+ "neck": (19, 22), "right_arm": (22, 29), "right_hand": (29, 35),
+ "right_leg": (35, 41), "waist": (41, 44),
+ }
+ # 从任意一个存在的状态键确定批次大小
+ batch_size = 0
+ for key in obs_dict:
+ if key.startswith("state."):
+ batch_size = obs_dict[key].shape[0]
+ break
+
+ if batch_size == 0:
+ # 如果没有找到任何 state key,无法确定批次大小,返回空数组或抛出错误
+ # 这里我们假设至少会有一个 state key
+ # 如果可能完全没有state,则需要根据具体情况处理
+ # 例如,可以尝试从 "video" key 获取 batch_size
+ if "video.ego_view" in obs_dict:
+ batch_size = obs_dict["video.ego_view"].shape[0]
+ else: # 默认返回一个 (1, 44) 的零向量
+ return np.zeros((1, 44), dtype=np.float64)
+ # 初始化一个 (batch_size, 44) 的零矩阵
+ full_vector = np.zeros((batch_size, 44), dtype=np.float64)
+ # 遍历布局,填充 full_vector
+ for part_name, (start, end) in layout_44dof.items():
+ obs_key = f"state.{part_name}"
+
+ if obs_key in obs_dict:
+ # 提取数据,形状为 (B, T, D)
+ data = np.asarray(obs_dict[obs_key])
+
+ # 我们只关心最后一个时间步的数据,其形状为 (B, D)
+ last_time_step_data = data[:, -1, :]
+
+ # 将数据填充到 full_vector 的正确位置
+ full_vector[:, start:end] = last_time_step_data
+ # 如果 obs_key 不在字典中,则该部分将保持为零,符合要求
+ return full_vector
diff --git a/examples/Robocasa_tabletop/eval_files/model2robocasa_interface_ee_wm.py b/examples/Robocasa_tabletop/eval_files/model2robocasa_interface_ee_wm.py
new file mode 100644
index 0000000000000000000000000000000000000000..4c188feaeea808bf9f256f75476394b9c1381c99
--- /dev/null
+++ b/examples/Robocasa_tabletop/eval_files/model2robocasa_interface_ee_wm.py
@@ -0,0 +1,252 @@
+from pathlib import Path
+from typing import Optional
+
+import cv2 as cv
+import numpy as np
+
+from examples.Robocasa_tabletop.eval_files.model2robocasa_interface_ee import (
+ PolicyWarper as BasePolicyWarper,
+)
+from examples.Robocasa_tabletop.eval_files.wrappers.video_recording_wrapper import (
+ VideoRecorder,
+)
+
+
+class PolicyWarper(BasePolicyWarper):
+ """EE policy wrapper with WM future-image visualization.
+
+ This keeps the default VLM-based eval wrapper free of WM-only response
+ handling while still allowing Cosmos/Wan policy models to save predicted
+ future images during simulation.
+ """
+
+ def __init__(
+ self,
+ *args,
+ wm_future_image_dir: Optional[str] = None,
+ num_inference_steps: Optional[int] = None,
+ shift: Optional[float] = None,
+ **kwargs,
+ ) -> None:
+ super().__init__(*args, **kwargs)
+ self.wm_future_image_dir = Path(wm_future_image_dir) if wm_future_image_dir else None
+ self.wm_episode_ids = [0]
+ self.wm_env_step_indices = [0]
+ self.wm_video_file_stem = None
+ self._wm_video_writers = {}
+ self.num_inference_steps = num_inference_steps
+ self.shift = shift
+ if self.wm_future_image_dir is not None:
+ self.wm_future_image_dir.mkdir(parents=True, exist_ok=True)
+
+ def set_eval_context(
+ self,
+ episode_ids=None,
+ env_step_indices=None,
+ completed_episodes: int = 0,
+ video_file_stem: Optional[str] = None,
+ ) -> None:
+ if episode_ids is not None:
+ self.wm_episode_ids = list(episode_ids)
+ if env_step_indices is not None:
+ self.wm_env_step_indices = list(env_step_indices)
+ if video_file_stem is not None:
+ self.wm_video_file_stem = str(video_file_stem)
+
+ def _handle_model_response(self, response: dict, images) -> None:
+ self._save_wm_future_images(response.get("data", {}), images)
+
+ def _update_vla_input(self, vla_input: dict) -> None:
+ if self.num_inference_steps is not None:
+ vla_input["num_inference_steps"] = int(self.num_inference_steps)
+ if self.shift is not None:
+ vla_input["shift"] = float(self.shift)
+ future_cfg = dict(vla_input.get("future_image_generation", {}))
+ future_cfg.setdefault("enabled", True)
+ future_cfg.setdefault("return_full_video", False)
+ future_cfg.setdefault("num_frames", 9)
+ future_cfg.setdefault("future_frame_index", -1)
+ future_cfg.setdefault("height", 224)
+ future_cfg.setdefault("width", "auto")
+ future_cfg.setdefault("num_latent_conditional_frames", 1)
+ future_cfg.setdefault("num_inference_steps", 1)
+ vla_input["future_image_generation"] = future_cfg
+
+ def _save_wm_future_images(self, response_data: dict, obs_images) -> None:
+ if self.wm_future_image_dir is None:
+ return
+
+ future_images = response_data.get("pred_future_images")
+ if future_images is None:
+ return
+
+ future_batches = self._as_batch_sequences(future_images, batch_size=len(obs_images))
+ for batch_idx, future_sequence in enumerate(future_batches):
+ try:
+ if not future_sequence:
+ continue
+ episode_id = self.wm_episode_ids[batch_idx] if batch_idx < len(self.wm_episode_ids) else batch_idx
+ compare_frames = []
+ if batch_idx < len(obs_images) and len(obs_images[batch_idx]) > 0:
+ obs_image = self._as_uint8_rgb(obs_images[batch_idx][0])
+ else:
+ obs_image = None
+
+ if obs_image is not None and len(future_sequence) > 1:
+ first_future = self._as_uint8_rgb(future_sequence[0])
+ future_sequence[0] = cv.resize(
+ obs_image,
+ (first_future.shape[1], first_future.shape[0]),
+ interpolation=cv.INTER_AREA,
+ )
+
+ for future_image in future_sequence:
+ future_image = self._as_uint8_rgb(future_image)
+ save_image = future_image
+ if obs_image is not None:
+ obs_panel, future_panel = self._fit_panels_to_common_canvas([obs_image, future_image])
+ if future_image.shape[1] > future_image.shape[0]:
+ save_image = np.concatenate([obs_panel, future_panel], axis=0)
+ else:
+ save_image = np.concatenate([obs_panel, future_panel], axis=1)
+ compare_frames.append(self._pad_to_even_size(save_image))
+
+ recorder = self._get_wm_video_recorder(batch_idx, episode_id, compare_frames[0].shape)
+ for save_image in compare_frames:
+ recorder.write_frame(save_image)
+ latest_path = self.wm_future_image_dir / f"latest_batch_{batch_idx:02d}.png"
+ cv.imwrite(str(latest_path), cv.cvtColor(compare_frames[-1], cv.COLOR_RGB2BGR))
+ except Exception as exc:
+ print(f"Warning: failed to save WM future video frame: {exc}")
+
+ def _get_wm_video_recorder(self, batch_idx: int, episode_id: int, image_shape) -> VideoRecorder:
+ height, width = int(image_shape[0]), int(image_shape[1])
+ frame_size = (width, height)
+ current = self._wm_video_writers.get(batch_idx)
+ video_stem = self.wm_video_file_stem or f"episode_{int(episode_id):03d}"
+ if current is not None:
+ current_episode_id, current_frame_size, current_video_stem, current_recorder = current
+ if (
+ current_episode_id == int(episode_id)
+ and current_frame_size == frame_size
+ and current_video_stem == video_stem
+ ):
+ return current_recorder
+ current_recorder.stop()
+ stale_path = self.wm_future_image_dir / f"{current_video_stem}.mp4"
+ if stale_path.exists():
+ stale_path.unlink()
+
+ video_path = self.wm_future_image_dir / f"{video_stem}.mp4"
+ recorder = VideoRecorder.create_h264(
+ fps=1,
+ codec="h264",
+ input_pix_fmt="rgb24",
+ crf=22,
+ thread_type="FRAME",
+ thread_count=1,
+ )
+ recorder.start(str(video_path))
+ self._wm_video_writers[batch_idx] = (int(episode_id), frame_size, video_stem, recorder)
+ return recorder
+
+ def finish_eval_episode(self, env_idx: int, episode_id: int, success: bool) -> None:
+ current = self._wm_video_writers.pop(env_idx, None)
+ if current is None or self.wm_future_image_dir is None:
+ return
+
+ _, _, video_stem, recorder = current
+ recorder.stop()
+ video_path = self.wm_future_image_dir / f"{video_stem}.mp4"
+ final_path = self.wm_future_image_dir / f"{video_stem}_success{int(success)}.mp4"
+ if video_path.exists():
+ video_path.rename(final_path)
+ if video_path.exists():
+ video_path.unlink()
+
+ def close_wm_videos(self) -> None:
+ writers = getattr(self, '_wm_video_writers', None)
+ if not writers:
+ return
+ for _, _, _, recorder in writers.values():
+ recorder.stop()
+ writers.clear()
+
+ def __del__(self):
+ self.close_wm_videos()
+
+ @staticmethod
+ def _as_uint8_rgb(image) -> np.ndarray:
+ image = np.asarray(image)
+ while image.ndim > 3 and image.shape[0] == 1:
+ image = image[0]
+ if image.ndim == 3 and image.shape[0] in (1, 3, 4):
+ image = np.moveaxis(image, 0, -1)
+ if image.ndim == 2:
+ image = np.repeat(image[..., None], 3, axis=-1)
+ if image.ndim != 3:
+ raise ValueError(f"Expected image with 2 or 3 dims, got shape {image.shape}")
+ if image.shape[-1] == 4:
+ image = image[..., :3]
+ if image.shape[-1] == 1:
+ image = np.repeat(image, 3, axis=-1)
+ if image.dtype != np.uint8:
+ if image.size and np.nanmax(image) <= 1.0 and np.nanmin(image) >= 0.0:
+ image = image * 255.0
+ elif image.size and np.nanmin(image) < 0.0:
+ image = (image + 1.0) * 127.5
+ image = np.clip(image, 0, 255).astype(np.uint8)
+ return image
+
+ @classmethod
+ def _as_frame_sequence(cls, images) -> list[np.ndarray]:
+ images = np.asarray(images)
+ if images.ndim == 3:
+ return [cls._as_uint8_rgb(images)]
+ if images.ndim != 4:
+ raise ValueError(f"Expected image/video with 3 or 4 dims, got shape {images.shape}")
+ return [cls._as_uint8_rgb(frame) for frame in images]
+
+ @classmethod
+ def _as_batch_sequences(cls, future_images, batch_size: int) -> list[list[np.ndarray]]:
+ future_images = np.asarray(future_images)
+ if future_images.ndim == 5:
+ return [cls._as_frame_sequence(future_images[batch_idx]) for batch_idx in range(future_images.shape[0])]
+ if future_images.ndim == 4 and future_images.shape[0] == batch_size and (
+ future_images.shape[-1] in (1, 3, 4) or future_images.shape[1] in (1, 3, 4)
+ ):
+ return [[cls._as_uint8_rgb(future_images[batch_idx])] for batch_idx in range(future_images.shape[0])]
+ if future_images.ndim in (3, 4):
+ return [cls._as_frame_sequence(future_images)]
+ raise ValueError(f"Unsupported pred_future_images shape {future_images.shape}")
+
+ @staticmethod
+ def _fit_panels_to_common_canvas(images: list[np.ndarray]) -> list[np.ndarray]:
+ panel_height = max(image.shape[0] for image in images)
+ panel_width = max(image.shape[1] for image in images)
+ panels = []
+ for image in images:
+ height, width = image.shape[:2]
+ scale = min(panel_width / width, panel_height / height)
+ resized_width = max(1, int(round(width * scale)))
+ resized_height = max(1, int(round(height * scale)))
+ resized = cv.resize(image, (resized_width, resized_height), interpolation=cv.INTER_AREA)
+ canvas = np.zeros((panel_height, panel_width, 3), dtype=np.uint8)
+ y0 = (panel_height - resized_height) // 2
+ x0 = (panel_width - resized_width) // 2
+ canvas[y0:y0 + resized_height, x0:x0 + resized_width] = resized
+ panels.append(canvas)
+ return panels
+
+ @staticmethod
+ def _pad_to_even_size(image: np.ndarray) -> np.ndarray:
+ height, width = image.shape[:2]
+ pad_bottom = height % 2
+ pad_right = width % 2
+ if pad_bottom == 0 and pad_right == 0:
+ return image
+ return np.pad(
+ image,
+ ((0, pad_bottom), (0, pad_right), (0, 0)),
+ mode="edge",
+ )
diff --git a/examples/Robocasa_tabletop/eval_files/readme.md b/examples/Robocasa_tabletop/eval_files/readme.md
new file mode 100644
index 0000000000000000000000000000000000000000..9e56e6e9328813cafb3c73cf35023945eeaef63c
--- /dev/null
+++ b/examples/Robocasa_tabletop/eval_files/readme.md
@@ -0,0 +1 @@
+注意修改JoyRA/examples/Robocasa_tabletop/eval_files/model2robocasa_interface.py中的_resize_image函数,若data_config.py中训练数据使用VideoResizePad,则使用第二个_resize_image函数(目前是这个)
\ No newline at end of file
diff --git a/examples/Robocasa_tabletop/eval_files/simulation_env.py b/examples/Robocasa_tabletop/eval_files/simulation_env.py
new file mode 100644
index 0000000000000000000000000000000000000000..696e6d5f690974782bf23686bd0f485a42a2862b
--- /dev/null
+++ b/examples/Robocasa_tabletop/eval_files/simulation_env.py
@@ -0,0 +1,364 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import time
+from dataclasses import dataclass, field
+from functools import partial
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Tuple
+
+import gymnasium as gym
+import numpy as np
+import tyro
+import dataclasses
+import json
+import logging
+import os
+
+# Required for robocasa environments
+import robocasa # noqa: F401
+import robosuite # noqa: F401
+from robocasa.utils.gym_utils import GrootRoboCasaEnv # noqa: F401
+from examples.Robocasa_tabletop.eval_files.base_config import ModalityConfig
+from examples.Robocasa_tabletop.eval_files.base_config import BasePolicy
+from examples.Robocasa_tabletop.eval_files.wrappers.multistep_wrapper import MultiStepWrapper
+from examples.Robocasa_tabletop.eval_files.wrappers.video_recording_wrapper import (
+ VideoRecorder,
+ VideoRecordingWrapper,
+)
+
+from examples.Robocasa_tabletop.eval_files.model2robocasa_interface_ee import PolicyWarper
+# from examples.Robocasa_tabletop.eval_files.model2robocasa_interface import PolicyWarper
+
+
+@dataclass
+class VideoConfig:
+ """Configuration for video recording settings."""
+
+ video_dir: Optional[str] = None
+ steps_per_render: int = 2 # 和10 是什么关系
+ fps: int = 10 # BUG 数据集中应该是 20?
+ codec: str = "h264"
+ input_pix_fmt: str = "rgb24"
+ crf: int = 22
+ thread_type: str = "FRAME"
+ thread_count: int = 1
+
+
+@dataclass
+class MultiStepConfig:
+ """Configuration for multi-step environment settings."""
+
+ video_delta_indices: np.ndarray = field(default=np.array([0]))
+ state_delta_indices: np.ndarray = field(default=np.array([0]))
+ n_action_steps: int = 16
+ max_episode_steps: int = 1440
+
+
+@dataclass
+class SimulationConfig:
+ """Main configuration for simulation environment."""
+
+ env_name: str
+ n_episodes: int = 2
+ n_envs: int = 1
+ video: VideoConfig = field(default_factory=VideoConfig)
+ multistep: MultiStepConfig = field(default_factory=MultiStepConfig)
+
+
+class SimulationInferenceEnv:
+ """Client for running simulations with a model."""
+
+ def __init__(self, model: Optional[BasePolicy] = None):
+ """Initialize the simulation client with a model."""
+ self.model = model
+ self.env = None
+
+ def get_action(self, observations: Dict[str, Any]) -> Dict[str, Any]:
+ """Get action from the model based on observations."""
+ # NOTE(YL)!
+ # hot fix to change the video.ego_view_bg_crop_pad_res256_freq20 to video.ego_view
+ if "video.ego_view_bg_crop_pad_res256_freq20" in observations: # BUG @JinhuiYE here only one viwes
+ observations["video.ego_view"] = observations.pop(
+ "video.ego_view_bg_crop_pad_res256_freq20"
+ )
+ return self.model.step(observations)
+
+ def get_modality_config(self) -> Dict[str, ModalityConfig]:
+ """Get modality configuration from the model."""
+ return self.model.get_modality_config()
+
+ def setup_environment(self, config: SimulationConfig) -> gym.vector.VectorEnv:
+ """Set up the simulation environment based on the provided configuration."""
+ # Create environment functions for each parallel environment
+ env_fns = [partial(_create_single_env, config=config, idx=i) for i in range(config.n_envs)]
+ # Create vector environment (sync for single env, async for multiple)
+ if config.n_envs == 1:
+ return gym.vector.SyncVectorEnv(env_fns)
+ else:
+ return gym.vector.AsyncVectorEnv(
+ env_fns,
+ shared_memory=False,
+ context="spawn",
+ )
+
+ def run_simulation(self, config: SimulationConfig, model: Optional[BasePolicy] = None) -> Tuple[str, List[bool]]:
+ """Run the simulation for the specified number of episodes.
+
+ Args:
+ config: Configuration for the simulation
+ model: The model to use for inference. If None, uses the model from __init__
+ """
+ # Use the provided model or fall back to the instance model
+ if model is not None:
+ self.model = model
+
+ if self.model is None:
+ raise ValueError("No model provided. Please provide a model either in __init__ or run_simulation")
+
+ start_time = time.time()
+ print(
+ f"Running {config.n_episodes} episodes for {config.env_name} with {config.n_envs} environments"
+ )
+ # Set up the environment
+ self.env = self.setup_environment(config)
+ # Initialize tracking variables
+ episode_lengths = []
+ current_rewards = [0] * config.n_envs
+ current_lengths = [0] * config.n_envs
+ current_episode_ids = list(range(config.n_envs))
+ completed_episodes = 0
+ current_successes = [False] * config.n_envs
+ episode_successes = []
+ # Initial environment reset
+ obs, _ = self.env.reset()
+ # Main simulation loop
+ while completed_episodes < config.n_episodes:
+ if hasattr(self.model, "set_eval_context"):
+ context = {
+ "episode_ids": current_episode_ids,
+ "env_step_indices": current_lengths,
+ "completed_episodes": completed_episodes,
+ "video_file_stem": self._get_current_video_stem(),
+ }
+ try:
+ self.model.set_eval_context(**context)
+ except TypeError:
+ context.pop("video_file_stem")
+ self.model.set_eval_context(**context)
+ # Process observations and get actions from the model
+ actions = self._get_actions_from_model(obs)
+ # Step the environment
+ next_obs, rewards, terminations, truncations, env_infos = self.env.step(actions)
+ # Update episode tracking
+ for env_idx in range(config.n_envs):
+ current_successes[env_idx] |= bool(env_infos["success"][env_idx][0])
+ current_rewards[env_idx] += rewards[env_idx]
+ current_lengths[env_idx] += 1
+ # If episode ended, store results
+ if terminations[env_idx] or truncations[env_idx]:
+ episode_lengths.append(current_lengths[env_idx])
+ episode_successes.append(current_successes[env_idx])
+ if hasattr(self.model, "finish_eval_episode"):
+ self.model.finish_eval_episode(
+ env_idx=env_idx,
+ episode_id=current_episode_ids[env_idx],
+ success=current_successes[env_idx],
+ )
+ current_successes[env_idx] = False
+ completed_episodes += 1
+ current_episode_ids[env_idx] = completed_episodes + config.n_envs - 1
+ # Reset trackers for this environment
+ current_rewards[env_idx] = 0
+ current_lengths[env_idx] = 0
+ obs = next_obs
+ # Clean up
+ if hasattr(self.model, "close_wm_videos"):
+ self.model.close_wm_videos()
+ self.env.reset()
+ self.env.close()
+ self.env = None
+ print(
+ f"Collecting {config.n_episodes} episodes took {time.time() - start_time:.2f} seconds"
+ )
+ assert (
+ len(episode_successes) >= config.n_episodes
+ ), f"Expected at least {config.n_episodes} episodes, got {len(episode_successes)}"
+ return config.env_name, episode_successes
+
+ def _get_actions_from_model(self, observations: Dict[str, Any]) -> Dict[str, Any]:
+ """Process observations and get actions from the model."""
+ # Get actions from the model
+ action_dict = self.get_action(observations)
+ # Extract actions from the response
+ if "actions" in action_dict:
+ actions = action_dict["actions"]
+ else:
+ actions = action_dict
+ # Add batch dimension to actions
+ return actions
+
+ def _get_current_video_stem(self) -> Optional[str]:
+ """Return the active rollout video stem for n_envs=1."""
+ if self.env is None:
+ return None
+
+ if hasattr(self.env, "envs") and len(self.env.envs) > 0:
+ file_path = self._get_single_env_attr(self.env.envs[0], "file_path")
+ return Path(file_path).stem if file_path is not None else None
+ return None
+
+ @staticmethod
+ def _get_single_env_attr(env, name: str):
+ current = env
+ while current is not None:
+ if hasattr(current, name):
+ return getattr(current, name)
+ current = getattr(current, "env", None)
+ return None
+
+
+def _create_single_env(config: SimulationConfig, idx: int) -> gym.Env:
+ """Create a single environment with appropriate wrappers."""
+ # Create base environment
+ env = gym.make(config.env_name, enable_render=True)
+ # Add video recording wrapper if needed (only for the first environment)
+ if config.video.video_dir is not None:
+ video_recorder = VideoRecorder.create_h264(
+ fps=config.video.fps,
+ codec=config.video.codec,
+ input_pix_fmt=config.video.input_pix_fmt,
+ crf=config.video.crf,
+ thread_type=config.video.thread_type,
+ thread_count=config.video.thread_count,
+ )
+ env = VideoRecordingWrapper(
+ env,
+ video_recorder,
+ video_dir=Path(config.video.video_dir),
+ steps_per_render=config.video.steps_per_render,
+ )
+ # Add multi-step wrapper
+ env = MultiStepWrapper(
+ env,
+ video_delta_indices=config.multistep.video_delta_indices,
+ state_delta_indices=config.multistep.state_delta_indices,
+ n_action_steps=config.multistep.n_action_steps,
+ max_episode_steps=config.multistep.max_episode_steps,
+ )
+ return env
+
+
+def run_evaluation(
+ env_name: str,
+ model: BasePolicy,
+ video_dir: Optional[str] = None,
+ n_episodes: int = 2,
+ n_envs: int = 1,
+ n_action_steps: int = 2,
+ max_episode_steps: int = 100,
+) -> Tuple[str, List[bool]]:
+ """
+ Simple entry point to run a simulation evaluation.
+ Args:
+ env_name: Name of the environment to run
+ model: The model to use for inference
+ video_dir: Directory to save videos (None for no videos)
+ n_episodes: Number of episodes to run
+ n_envs: Number of parallel environments
+ n_action_steps: Number of action steps per environment step
+ max_episode_steps: Maximum number of steps per episode
+ Returns:
+ Tuple of environment name and list of episode success flags
+ """
+ # Create configuration
+ config = SimulationConfig(
+ env_name=env_name,
+ n_episodes=n_episodes,
+ n_envs=n_envs,
+ video=VideoConfig(video_dir=video_dir),
+ multistep=MultiStepConfig(
+ n_action_steps=n_action_steps, max_episode_steps=max_episode_steps
+ ),
+ )
+ # Create client and run simulation
+ client = SimulationInferenceEnv(model=model)
+ results = client.run_simulation(config)
+ # Print results
+ print(f"Results for {env_name}:")
+ print(f"Success rate: {np.mean(results[1]):.2f}")
+ return results
+
+
+@dataclasses.dataclass
+class Args:
+ host: str = "127.0.0.1"
+ port: int = 5678
+ resize_size = [224,224]
+
+ #################################################################################################################
+ # LIBERO environment-specific parameters
+ #################################################################################################################
+ env_name: str = "gr1_unified/PnPMilkToMicrowaveClose_GR1ArmsAndWaistFourierHands_Env" # Task suite. Options: libero_spatial, libero_object, libero_goal, libero_10, libero_90
+ n_episodes: int = 50 # Number of steps to wait for objects to stabilize i n sim
+ n_envs: int = 1 # Number of rollouts per task
+ max_episode_steps: int = 360 #
+ n_action_steps: int = 3
+ num_inference_steps: int = 1
+ shift: float = 5.0
+
+ #################################################################################################################
+ # Utils
+ #################################################################################################################
+ video_out_path: str = "experiments/1029_qwenGR00T_fourier_gr1_unified_1000_PnPMilkToMicrowaveClose_gpus_woPretrain_wState/checkpoints/steps_20000_pytorch_model.pt.log/gr1_unified/logs/PnPMilkToMicrowaveClose_GR1ArmsAndWaistFourierHands_Env" # Path to save videos
+
+ seed: int = 7 # Random Seed (for reproducibility)
+
+ pretrained_path: str = "results/Checkpoints/1029_qwenGR00T_fourier_gr1_unified_1000_PnPMilkToMicrowaveClose_gpus_woPretrain_wState/checkpoints/steps_20000_pytorch_model.pt"
+
+
+
+def eval_gr1_unified(args: Args) -> None:
+ logging.info(f"Arguments: {json.dumps(dataclasses.asdict(args), indent=4)}")
+ if os.getenv("DEBUG", False):
+ start_debugpy_once()
+
+ model = PolicyWarper(
+ policy_ckpt_path=args.pretrained_path, # to get unnormalization stats
+ host=args.host,
+ port=args.port,
+ image_size=args.resize_size,
+ n_action_steps=args.n_action_steps,
+ )
+ run_evaluation(
+ env_name=args.env_name,
+ model=model,
+ video_dir=args.video_out_path,
+ n_episodes=args.n_episodes,
+ n_envs=args.n_envs,
+ n_action_steps=args.n_action_steps,
+ max_episode_steps=args.max_episode_steps,
+ )
+
+def start_debugpy_once():
+ import debugpy
+ if getattr(start_debugpy_once, "_started", False):
+ return
+ debugpy.listen(("0.0.0.0", 10092))
+ print("🔍 Waiting for VSCode attach on 0.0.0.0:10092 ...")
+ debugpy.wait_for_client()
+ start_debugpy_once._started = True
+
+if __name__ == "__main__":
+ tyro.cli(eval_gr1_unified)
diff --git a/examples/Robocasa_tabletop/eval_files/simulation_env_wm.py b/examples/Robocasa_tabletop/eval_files/simulation_env_wm.py
new file mode 100644
index 0000000000000000000000000000000000000000..85ef05acfa6be8966dc9e3e956ec518a9558fd4b
--- /dev/null
+++ b/examples/Robocasa_tabletop/eval_files/simulation_env_wm.py
@@ -0,0 +1,47 @@
+import dataclasses
+import json
+import logging
+import os
+from pathlib import Path
+
+import tyro
+
+from examples.Robocasa_tabletop.eval_files.model2robocasa_interface_ee_wm import PolicyWarper
+from examples.Robocasa_tabletop.eval_files.simulation_env import (
+ Args,
+ run_evaluation,
+ start_debugpy_once,
+)
+
+
+def eval_gr1_unified(args: Args) -> None:
+ logging.info(f"Arguments: {json.dumps(dataclasses.asdict(args), indent=4)}")
+ if os.getenv("DEBUG", False):
+ start_debugpy_once()
+
+ model = PolicyWarper(
+ policy_ckpt_path=args.pretrained_path,
+ host=args.host,
+ port=args.port,
+ image_size=args.resize_size,
+ n_action_steps=args.n_action_steps,
+ num_inference_steps=args.num_inference_steps,
+ shift=args.shift,
+ wm_future_image_dir=str(Path(args.video_out_path) / "wm_future_images"),
+ )
+ try:
+ run_evaluation(
+ env_name=args.env_name,
+ model=model,
+ video_dir=args.video_out_path,
+ n_episodes=args.n_episodes,
+ n_envs=args.n_envs,
+ n_action_steps=args.n_action_steps,
+ max_episode_steps=args.max_episode_steps,
+ )
+ finally:
+ model.close_wm_videos()
+
+
+if __name__ == "__main__":
+ tyro.cli(eval_gr1_unified)
diff --git a/examples/Robocasa_tabletop/eval_files/th_eval.sh b/examples/Robocasa_tabletop/eval_files/th_eval.sh
new file mode 100644
index 0000000000000000000000000000000000000000..57c079900f881da54dcf4c4f7a2e31f88f501ccb
--- /dev/null
+++ b/examples/Robocasa_tabletop/eval_files/th_eval.sh
@@ -0,0 +1,203 @@
+#!/bin/bash
+
+# ============================================================
+# Argument Parsing
+# ============================================================
+###########################################################################################
+# === Please modify the paths to Python executables in conda environments ===
+
+export OMP_NUM_THREADS=1
+export MKL_NUM_THREADS=1
+export OPENBLAS_NUM_THREADS=1
+
+
+# export LD_LIBRARY_PATH=/tmp/nvidia-gl-extract/usr/lib/x86_64-linux-gnu:$LD_LIBRARY_PATH
+# export VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/nvidia_icd.json
+
+# NVIDIA H200 EGL Rendering Path
+export LD_LIBRARY_PATH=/mnt/workspace/lib/nvidia_egl:\$LD_LIBRARY_PATH
+export PYOPENGL_PLATFORM=egl
+export __GLX_VENDOR_LIBRARY_NAME=nvidia
+export MUJOCO_GL=egl
+
+cd /mnt/workspace/users/yuanzhihao/code/starVLA
+starVLA_PYTHON=/mnt/workspace/envs/conda3/envs/starVLA_1/bin/python
+ROBOCASA_PYTHON=/mnt/workspace/envs/conda3/envs/robocasa/bin/python
+export PYTHONPATH=$(pwd):${PYTHONPATH}
+CKPT_DEFAULT="/mnt/workspace/users/yuanzhihao/code/starVLA/outputs/robocasa_teleop_ee_pre_sq_ego-f_robocasa-f/checkpoints/steps_300000_pytorch_model.pt"
+# CKPT_DEFAULT="/mnt/workspace/users/yuanzhihao/code/starVLA/outputs/StarVLA_Qwen3_VL_GR00T_Robocasa_gr1/checkpoints/steps_90000_pytorch_model.pt"
+
+# === End of environment variable configuration ===
+###########################################################################################
+
+N_ENVS_DEFAULT=1
+MAX_EPISODE_STEPS_DEFAULT=720
+N_ACTION_STEPS_DEFAULT=12
+
+BASE_PORT=9999
+NUM_GPUS=4
+
+# Parse command-line arguments
+CKPT_PATH=${1:-$CKPT_DEFAULT}
+N_ENVS=${2:-$N_ENVS_DEFAULT}
+MAX_EPISODE_STEPS=${3:-$MAX_EPISODE_STEPS_DEFAULT}
+N_ACTION_STEPS=${4:-$N_ACTION_STEPS_DEFAULT}
+
+
+echo "=== Evaluation Configuration ==="
+echo "Checkpoint Path : ${CKPT_PATH}"
+echo "Number of Envs : ${N_ENVS}"
+echo "Max Episode Steps : ${MAX_EPISODE_STEPS}"
+echo "Action Chunk Length : ${N_ACTION_STEPS}"
+echo "================================"
+
+# ============================================================
+# Evaluation Function
+# ============================================================
+
+EvalEnv() {
+ local GPU_ID=$1
+ local PORT=$2
+ local ENV_NAME=$3
+ local CKPT_PATH=$4
+ local LOG_DIR=$5
+ local ROBOCASA_PYTHON=$6
+ local N_ENVS=$7
+ local MAX_EPISODE_STEPS=$8
+ local N_ACTION_STEPS=$9
+ # save root CKPT_PATH 的 parent 文件夹
+ local SAVE_ROOT=$(dirname "$(dirname "$CKPT_PATH")")
+ local ckpt_name=$(basename "$CKPT_PATH" .pt)
+ local VIDEO_OUT_PATH="${SAVE_ROOT}/videos/${ckpt_name}/n_action_steps_${N_ACTION_STEPS}_max_episode_steps_${MAX_EPISODE_STEPS}_n_envs_${N_ENVS}_${ENV_NAME}"
+ mkdir -p "${VIDEO_OUT_PATH}"
+
+ echo "Launching evaluation | GPU ${GPU_ID} | Port ${PORT} | Env ${ENV_NAME}"
+
+ CUDA_VISIBLE_DEVICES=${GPU_ID} \
+ MUJOCO_GL=egl \
+ PYOPENGL_PLATFORM=egl \
+ EGL_VISIBLE_DEVICES=0 \
+ MUJOCO_EGL_DEVICE_ID=0 \
+ ${ROBOCASA_PYTHON} examples/Robocasa_tabletop/eval_files/simulation_env.py \
+ --args.env_name "${ENV_NAME}" \
+ --args.port "${PORT}" \
+ --args.n_episodes 50 \
+ --args.n_envs "${N_ENVS}" \
+ --args.max_episode_steps "${MAX_EPISODE_STEPS}" \
+ --args.n_action_steps "${N_ACTION_STEPS}" \
+ --args.video_out_path "${VIDEO_OUT_PATH}" \
+ --args.pretrained_path "${CKPT_PATH}" \
+ > "${LOG_DIR}/eval_env_${ENV_NAME//\//_}_gpu${GPU_ID}.log" 2>&1
+}
+
+# ============================================================
+# Environment List
+# ============================================================
+
+ENV_NAMES=(
+ gr1_unified/PnPCupToDrawerClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPPotatoToMicrowaveClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPMilkToMicrowaveClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPBottleToCabinetClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPWineToCabinetClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPCanToDrawerClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToBasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToPanSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToPotSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToTieredbasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToBasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToBowlSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToPlateSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToTieredshelfSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToBowlSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToPanSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToPlateSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToPlateSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToPotSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToTieredbasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToTieredshelfSplitA_GR1ArmsAndWaistFourierHands_Env
+)
+
+# ============================================================
+# Runtime Configuration
+# ============================================================
+
+
+
+LOG_DIR="${CKPT_PATH}.log/eval_$(date +%Y%m%d_%H%M%S)"
+mkdir -p "${LOG_DIR}"
+
+echo "=== Launching Multi-GPU Evaluation ==="
+echo "GPUs : ${NUM_GPUS}"
+echo "Num Environments: ${#ENV_NAMES[@]}"
+echo "Log Directory : ${LOG_DIR}"
+
+# ============================================================
+# Step 1: Launch Policy Servers
+# ============================================================
+
+SERVER_PIDS=()
+
+for GPU_ID in $(seq 0 $((NUM_GPUS - 1))); do
+ PORT=$((BASE_PORT + GPU_ID))
+ echo "Starting policy server | GPU ${GPU_ID} | Port ${PORT}"
+
+ CUDA_VISIBLE_DEVICES=${GPU_ID} \
+ ${starVLA_PYTHON} deployment/model_server/server_policy.py \
+ --ckpt_path "${CKPT_PATH}" \
+ --port "${PORT}" \
+ --use_bf16 \
+ > "${LOG_DIR}/server_gpu${GPU_ID}_port${PORT}.log" 2>&1 &
+
+ SERVER_PIDS[$GPU_ID]=$!
+
+ sleep 10
+done
+
+sleep 30
+
+# ============================================================
+# Step 2: Dispatch Environments to GPUs
+# ============================================================
+
+COUNT=0
+for ENV_NAME in "${ENV_NAMES[@]}"; do
+ GPU_ID=$((COUNT % NUM_GPUS))
+ PORT=$((BASE_PORT + GPU_ID))
+
+ if (( (COUNT + 1) % NUM_GPUS == 0 )); then
+ EvalEnv "${GPU_ID}" "${PORT}" "${ENV_NAME}" "${CKPT_PATH}" "${LOG_DIR}" \
+ "${ROBOCASA_PYTHON}" "${N_ENVS}" "${MAX_EPISODE_STEPS}" "${N_ACTION_STEPS}"
+ else
+ EvalEnv "${GPU_ID}" "${PORT}" "${ENV_NAME}" "${CKPT_PATH}" "${LOG_DIR}" \
+ "${ROBOCASA_PYTHON}" "${N_ENVS}" "${MAX_EPISODE_STEPS}" "${N_ACTION_STEPS}" &
+ fi
+
+ COUNT=$((COUNT + 1))
+
+ sleep 2
+done
+
+# ============================================================
+# Step 3: Cleanup
+# ============================================================
+
+# 判断是否还有 examples/Robocasa_tabletop/eval_files/simulation_env.py
+while pgrep -f "examples/Robocasa_tabletop/eval_files/simulation_env.py" > /dev/null; do
+ echo "Waiting for all evaluation environments to finish..."
+ sleep 30
+done
+
+echo ""
+echo "Shutting down policy servers..."
+
+for PID in "${SERVER_PIDS[@]}"; do
+ kill "${PID}" 2>/dev/null && echo "Killed server PID ${PID}"
+done
+
+echo "=== Evaluation Finished ==="
+
+python summarize_eval_logs.py ${LOG_DIR}
\ No newline at end of file
diff --git a/examples/Robocasa_tabletop/eval_files/wrappers/multistep_wrapper.py b/examples/Robocasa_tabletop/eval_files/wrappers/multistep_wrapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..ab3196decc869df0415a15307aa762c5fc3d068c
--- /dev/null
+++ b/examples/Robocasa_tabletop/eval_files/wrappers/multistep_wrapper.py
@@ -0,0 +1,296 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from collections import defaultdict, deque
+
+import gymnasium as gym
+import numpy as np
+from gymnasium import spaces
+
+
+def stack_repeated(x, n, loc):
+ return np.repeat(np.expand_dims(x, axis=loc), n, axis=loc)
+
+
+def repeated_box(box_space, n, loc):
+ return spaces.Box(
+ low=stack_repeated(box_space.low, n, loc),
+ high=stack_repeated(box_space.high, n, loc),
+ shape=box_space.shape[:loc] + (n,) + box_space.shape[loc:],
+ dtype=box_space.dtype,
+ )
+
+
+def repeated_space(space, n, loc=0):
+ if isinstance(space, spaces.Box):
+ return repeated_box(space, n, loc)
+ elif isinstance(space, spaces.Dict):
+ result_space = spaces.Dict()
+ for key, value in space.items():
+ result_space[key] = repeated_space(value, n, loc)
+ return result_space
+ elif isinstance(space, spaces.Discrete):
+ return spaces.MultiDiscrete([[space.n] for _ in range(n)])
+ elif isinstance(space, spaces.Text): # For language, we don't repeat and only keep the last one
+ return space
+ else:
+ raise RuntimeError(f"Unsupported space type {type(space)}")
+
+
+def take_last_n(x, n):
+ x = list(x)
+ n = min(len(x), n)
+ return np.array(x[-n:])
+
+
+def dict_take_last_n(x, n):
+ result = dict()
+ for key, value in x.items():
+ result[key] = take_last_n(value, n)
+ return result
+
+
+def aggregate(data, method="max"):
+ if method == "max":
+ # equivalent to any
+ return np.max(data)
+ elif method == "min":
+ # equivalent to all
+ return np.min(data)
+ elif method == "mean":
+ return np.mean(data)
+ elif method == "sum":
+ return np.sum(data)
+ else:
+ raise NotImplementedError()
+
+
+class MultiStepWrapper(gym.Wrapper):
+ def __init__(
+ self,
+ env,
+ video_delta_indices,
+ state_delta_indices,
+ n_action_steps,
+ max_episode_steps=None,
+ reward_agg_method="max",
+ ):
+ """
+ video_delta_indices: np.ndarray[int], please check `assert_delta_indices` to see the requirements
+ state_delta_indices: np.ndarray[int] | None, please check `assert_delta_indices` to see the requirements
+ if None, it means the model is vision-only
+ """
+ super().__init__(env)
+ # Assign action space
+ self._action_space = repeated_space(env.action_space, n_action_steps)
+
+ # Assign delta indices and horizons
+ self.video_delta_indices = video_delta_indices
+ self.video_horizon = len(video_delta_indices)
+ self.assert_delta_indices(self.video_delta_indices, self.video_horizon)
+ if state_delta_indices is not None:
+ self.state_delta_indices = state_delta_indices
+ self.state_horizon = len(state_delta_indices)
+ self.assert_delta_indices(self.state_delta_indices, self.state_horizon)
+ else:
+ self.state_horizon = None
+ self.state_delta_indices = None
+
+ # Assign observation space
+ self._observation_space = self.convert_observation_space(
+ self.observation_space,
+ self.video_horizon,
+ self.state_horizon,
+ )
+
+ # Assign other attributes
+ self.max_episode_steps = max_episode_steps
+ self.n_action_steps = n_action_steps
+ self.reward_agg_method = reward_agg_method
+ self.max_steps_needed = self.get_max_steps_needed()
+
+ self.obs = deque(maxlen=self.max_steps_needed + 1)
+ self.reward = list()
+ self.done = list()
+ self.info = defaultdict(lambda: deque(maxlen=self.max_steps_needed + 1))
+
+ def convert_observation_space(self, observation_space, video_horizon, state_horizon):
+ """
+ For video, the observation space will be (video_horizon,) + original shape
+ For state (if not None), the observation space will be (state_horizon,) + original shape
+ """
+ new_observation_space = {}
+ for k in observation_space.keys():
+ if k.startswith("video"):
+ box = observation_space[k]
+ horizon = video_horizon
+ new_observation_space[k] = repeated_space(box, horizon)
+ elif k.startswith("state"):
+ box = observation_space[k]
+ if state_horizon is not None:
+ horizon = state_horizon
+ else:
+ # Don't include the state in the observation space
+ continue
+ new_observation_space[k] = repeated_space(box, horizon)
+ elif k.startswith("annotation"):
+ text = observation_space[k]
+ new_observation_space[k] = text
+ else:
+ raise ValueError(f"Unknown key: {k}") # NOTE: We might add "language" in the future
+
+ return spaces.Dict(new_observation_space)
+
+ def get_max_steps_needed(self):
+ """
+ Get the maximum number of steps that we need to cache.
+ """
+ video_max_steps_needed = (
+ np.max(self.video_delta_indices) - np.min(self.video_delta_indices) + 1
+ )
+ if self.state_delta_indices is not None:
+ state_max_steps_needed = (
+ np.max(self.state_delta_indices) - np.min(self.state_delta_indices) + 1
+ )
+ else:
+ state_max_steps_needed = 0
+ return int(max(video_max_steps_needed, state_max_steps_needed))
+
+ def assert_delta_indices(self, delta_indices: np.ndarray, horizon: int):
+ # Check the length
+ # (In this wrapper, this seems redundant because we get the horizon from the delta indices. But in the policy, the horizon is not derived from the delta indices but we need to make it consistent. To make the function consistent, we keep the check here.)
+ assert len(delta_indices) == horizon, f"{delta_indices=}, {horizon=}"
+ # All delta indices should be non-positive because there's no way to get the future observations
+ assert np.all(delta_indices <= 0), f"{delta_indices=}"
+ # The last delta index should be 0 because it doesn't make sense to not use the latest observation
+ assert delta_indices[-1] == 0, f"{delta_indices=}"
+ if len(delta_indices) > 1:
+ # The step is consistent (because in real robot experiments, we actually use the dt to get the observations, which requires the step to be consistent)
+ assert np.all(
+ np.diff(delta_indices) == delta_indices[1] - delta_indices[0]
+ ), f"{delta_indices=}"
+ # And the step is positive
+ assert (delta_indices[1] - delta_indices[0]) > 0, f"{delta_indices=}"
+
+ def reset(self, seed=None, options=None):
+ """Resets the environment using kwargs."""
+ obs, info = super().reset(seed=seed, options=options)
+
+ self.obs = deque([obs] * (self.max_steps_needed + 1), maxlen=self.max_steps_needed + 1)
+ self.reward = list()
+ self.done = list()
+ self.info = defaultdict(lambda: deque(maxlen=self.max_steps_needed + 1))
+
+ obs = self._get_obs(self.video_delta_indices, self.state_delta_indices)
+ info = {k: [v] for k, v in info.items()}
+ return obs, info
+
+ def step(self, action):
+ """
+ action: dict: key-value pairs where the values are of shape (n_action_steps,) + action_shape
+ """
+ states = []
+ rewards = []
+ dones = []
+ for step in range(self.n_action_steps):
+ act = {}
+ for key, value in action.items():
+ act[key] = value[step, :]
+ if len(self.done) > 0 and self.done[-1]:
+ # termination
+ break
+ observation, reward, done, truncated, info = super().step(act)
+ env_state = {"states": [], "model": []}
+ states.append(env_state["states"])
+ rewards.append(reward)
+ dones.append(done)
+ self.obs.append(observation)
+ self.reward.append(reward)
+ if (self.max_episode_steps is not None) and (
+ len(self.reward) >= self.max_episode_steps
+ ):
+ # truncation
+ done = True
+ self.done.append(done)
+ self._add_info(info)
+
+ observation = self._get_obs(self.video_delta_indices, self.state_delta_indices)
+ reward = aggregate(self.reward, self.reward_agg_method)
+ done = aggregate(self.done, "max")
+ info = dict_take_last_n(self.info, self.max_steps_needed)
+ states = np.array(states)
+ rewards = np.array(rewards)
+ dones = np.array(dones)
+ info["states"] = states
+ info["rewards"] = rewards
+ info["model"] = env_state["model"]
+ info["actions"] = action
+ info["dones"] = dones
+ return observation, reward, done, truncated, info
+
+ def _get_obs(self, video_delta_indices, state_delta_indices):
+ """
+ Output:
+ For video: (video_horizon,) + obs_shape
+ For state (if not None): (state_horizon,) + obs_shape
+ """
+ assert len(self.obs) > 0
+ if isinstance(self.observation_space, spaces.Dict):
+ result = dict()
+ for key in self.observation_space.keys():
+ if key.startswith("video"):
+ """
+ NOTE:
+ We need to subtract 1 because video_delta_indices is 0-indexed.
+ E.g., video_delta_indices = np.array([-4, -3, -2, -1, 0])
+ Then when we select the observation,
+ it should be [obs[-5], obs[-4], obs[-3], obs[-2], obs[-1]]
+ (i.e., the latest observation is at the last index)
+ """
+ delta_indices = video_delta_indices - 1
+ this_obs = [self.obs[i][key] for i in delta_indices]
+ result[key] = np.stack(this_obs, axis=0)
+ elif key.startswith("state"):
+ if state_delta_indices is not None:
+ delta_indices = state_delta_indices - 1
+ else:
+ raise ValueError(
+ f"state_delta_indices is None but `state` is still in the {self.observation_space=}"
+ )
+ this_obs = [self.obs[i][key] for i in delta_indices]
+ result[key] = np.stack(this_obs, axis=0)
+ elif key.startswith("annotation"):
+ result[key] = self.obs[-1][key]
+ else:
+ raise ValueError(f"Unknown key: {key}")
+ return result
+ else:
+ raise RuntimeError(f"Unsupported space type: {type(self.observation_space)=}")
+
+ def _add_info(self, info):
+ for key, value in info.items():
+ self.info[key].append(value)
+
+ def get_rewards(self):
+ return self.reward
+
+ def get_attr(self, name):
+ return getattr(self, name)
+
+ def get_infos(self):
+ result = dict()
+ for k, v in self.info.items():
+ result[k] = list(v)
+ return result
diff --git a/examples/Robocasa_tabletop/eval_files/wrappers/obs_index_selection_wrapper.py b/examples/Robocasa_tabletop/eval_files/wrappers/obs_index_selection_wrapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..8fdb9b2286c15ab0afda60f7ff72f93ef0c6f951
--- /dev/null
+++ b/examples/Robocasa_tabletop/eval_files/wrappers/obs_index_selection_wrapper.py
@@ -0,0 +1,114 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import gymnasium as gym
+import numpy as np
+
+
+class ObsIndexSelectionWrapper(gym.Wrapper):
+ def __init__(self, env, video_delta_indices, state_delta_indices):
+ super().__init__(env)
+ self.video_delta_indices = video_delta_indices
+ self.video_horizon = len(video_delta_indices)
+ self.assert_delta_indices(self.video_delta_indices, self.video_horizon)
+
+ if state_delta_indices is not None:
+ self.state_delta_indices = state_delta_indices
+ self.state_horizon = len(state_delta_indices)
+ self.assert_delta_indices(self.state_delta_indices, self.state_horizon)
+ else:
+ self.state_horizon = None
+ self.state_delta_indices = None
+
+ self._observation_space = self.convert_observation_space(
+ self.observation_space,
+ self.video_horizon,
+ self.state_horizon,
+ )
+
+ def assert_delta_indices(self, delta_indices: np.ndarray, horizon: int):
+ # Check the length
+ # (In this wrapper, this seems redundant because we get the horizon from the delta indices. But in the policy, the horizon is not derived from the delta indices but we need to make it consistent. To make the function consistent, we keep the check here.)
+ assert len(delta_indices) == horizon, f"{delta_indices=}, {horizon=}"
+ # All delta indices should be non-positive because there's no way to get the future observations
+ assert np.all(delta_indices <= 0), f"{delta_indices=}"
+ # The last delta index should be 0 because it doesn't make sense to not use the latest observation
+ assert delta_indices[-1] == 0, f"{delta_indices=}"
+ if len(delta_indices) > 1:
+ # The step is consistent (because in real robot experiments, we actually use the dt to get the observations, which requires the step to be consistent)
+ assert np.all(
+ np.diff(delta_indices) == delta_indices[1] - delta_indices[0]
+ ), f"{delta_indices=}"
+ # And the step is positive
+ assert (delta_indices[1] - delta_indices[0]) > 0, f"{delta_indices=}"
+
+ def select_steps_for_values(self, data_value, delta_indices):
+ """
+ data_value: [L, ...]
+ delta_indices: np.ndarray[int], please check `assert_delta_indices` to see the requirements
+ """
+ L = data_value.shape[0]
+ assert L >= len(delta_indices), f"{L=}, {len(delta_indices)=}"
+ selected_indices = (L - 1) + delta_indices
+ assert selected_indices[0] >= 0, f"{L=}, {selected_indices=}"
+ return data_value[selected_indices]
+
+ def select_steps_for_obs(self, obs):
+ new_obs = {}
+ for k in obs.keys():
+ if k.startswith("video"):
+ new_obs[k] = self.select_steps_for_values(obs[k], self.video_delta_indices)
+ elif k.startswith("state"):
+ if self.state_delta_indices is not None:
+ new_obs[k] = self.select_steps_for_values(obs[k], self.state_delta_indices)
+ else:
+ # Don't include the state in the observation
+ continue
+ else:
+ raise ValueError(f"Unknown key: {k}")
+ return new_obs
+
+ def convert_observation_space(self, observation_space, video_horizon, state_horizon):
+ new_observation_space = {}
+ for k in observation_space.keys():
+ box = observation_space[k]
+ if k.startswith("video"):
+ horizon = video_horizon
+ elif k.startswith("state"):
+ if state_horizon is not None:
+ horizon = state_horizon
+ else:
+ # Don't include the state in the observation space
+ continue
+ else:
+ raise ValueError(f"Unknown key: {k}")
+
+ new_observation_space[k] = gym.spaces.Box(
+ low=box.low[:horizon],
+ high=box.high[:horizon],
+ shape=(horizon, *box.shape[1:]),
+ dtype=box.dtype,
+ )
+ return gym.spaces.Dict(new_observation_space)
+
+ def reset(self, seed=None, options=None):
+ obs, info = super().reset(seed=seed, options=options)
+ obs = self.select_steps_for_obs(obs)
+ return obs, info
+
+ def step(self, action):
+ obs, reward, terminated, truncated, info = super().step(action)
+ obs = self.select_steps_for_obs(obs)
+ return obs, reward, terminated, truncated, info
diff --git a/examples/Robocasa_tabletop/eval_files/wrappers/video_recording_wrapper.py b/examples/Robocasa_tabletop/eval_files/wrappers/video_recording_wrapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd92b6eb41f2efe40350507c740f50b7341f7356
--- /dev/null
+++ b/examples/Robocasa_tabletop/eval_files/wrappers/video_recording_wrapper.py
@@ -0,0 +1,238 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+import uuid
+from pathlib import Path
+
+import av
+import gymnasium as gym
+import numpy as np
+
+
+def get_accumulate_timestamp_idxs(
+ timestamps: list[float],
+ start_time: float,
+ dt: float,
+ eps: float = 1e-5,
+ next_global_idx: int | None = 0,
+ allow_negative: bool = False,
+) -> tuple[list[int], list[int], int]:
+ """
+ For each dt window, choose the first timestamp in the window.
+ Assumes timestamps sorted. One timestamp might be chosen multiple times due to dropped frames.
+ next_global_idx should start at 0 normally, and then use the returned next_global_idx.
+ However, when overwiting previous values are desired, set last_global_idx to None.
+
+ Returns:
+ local_idxs: which index in the given timestamps array to chose from
+ global_idxs: the global index of each chosen timestamp
+ next_global_idx: used for next call.
+ """
+ local_idxs = list()
+ global_idxs = list()
+ for local_idx, ts in enumerate(timestamps):
+ # add eps * dt to timestamps so that when ts == start_time + k * dt
+ # is always recorded as kth element (avoiding floating point errors)
+ global_idx = np.floor((ts - start_time) / dt + eps)
+ if (not allow_negative) and (global_idx < 0):
+ continue
+ if next_global_idx is None:
+ next_global_idx = global_idx
+
+ n_repeats = max(0, global_idx - next_global_idx + 1)
+ for i in range(n_repeats):
+ local_idxs.append(local_idx)
+ global_idxs.append(next_global_idx + i)
+ next_global_idx += n_repeats
+ return local_idxs, global_idxs, next_global_idx
+
+
+class VideoRecorder:
+ def __init__(
+ self,
+ fps,
+ codec,
+ input_pix_fmt,
+ # options for codec
+ **kwargs,
+ ):
+ """
+ input_pix_fmt: rgb24, bgr24 see https://github.com/PyAV-Org/PyAV/blob/bc4eedd5fc474e0f25b22102b2771fe5a42bb1c7/av/video/frame.pyx#L352
+ """
+
+ self.fps = fps
+ self.codec = codec
+ self.input_pix_fmt = input_pix_fmt
+ self.kwargs = kwargs
+ # runtime set
+ self._reset_state()
+
+ def _reset_state(self):
+ self.container = None
+ self.stream = None
+ self.shape = None
+ self.dtype = None
+ self.start_time = None
+ self.next_global_idx = 0
+
+ @classmethod
+ def create_h264(
+ cls,
+ fps,
+ codec="h264",
+ input_pix_fmt="rgb24",
+ output_pix_fmt="yuv420p",
+ crf=18,
+ profile="high",
+ **kwargs,
+ ):
+ obj = cls(
+ fps=fps,
+ codec=codec,
+ input_pix_fmt=input_pix_fmt,
+ pix_fmt=output_pix_fmt,
+ options={"crf": str(crf), "profile:v": "high"},
+ **kwargs,
+ )
+ return obj
+
+ def __del__(self):
+ self.stop()
+
+ def is_ready(self):
+ return self.stream is not None
+
+ def start(self, file_path, start_time=None):
+ if self.is_ready():
+ # if still recording, stop first and start anew.
+ self.stop()
+
+ self.container = av.open(file_path, mode="w")
+ self.stream = self.container.add_stream(self.codec, rate=self.fps)
+ codec_context = self.stream.codec_context
+ for k, v in self.kwargs.items():
+ setattr(codec_context, k, v)
+ self.start_time = start_time
+
+ def write_frame(self, img: np.ndarray, frame_time=None):
+ if not self.is_ready():
+ raise RuntimeError("Must run start() before writing!")
+
+ n_repeats = 1
+ if self.start_time is not None:
+ local_idxs, global_idxs, self.next_global_idx = get_accumulate_timestamp_idxs(
+ # only one timestamp
+ timestamps=[frame_time],
+ start_time=self.start_time,
+ dt=1 / self.fps,
+ next_global_idx=self.next_global_idx,
+ )
+ # number of appearance means repeats
+ n_repeats = len(local_idxs)
+
+ if self.shape is None:
+ self.shape = img.shape
+ self.dtype = img.dtype
+ h, w, c = img.shape
+ self.stream.width = w
+ self.stream.height = h
+ assert img.shape == self.shape
+ assert img.dtype == self.dtype
+
+ frame = av.VideoFrame.from_ndarray(img, format=self.input_pix_fmt)
+ for i in range(n_repeats):
+ for packet in self.stream.encode(frame):
+ self.container.mux(packet)
+
+ def stop(self):
+ if not self.is_ready():
+ return
+
+ # Flush stream
+ for packet in self.stream.encode():
+ self.container.mux(packet)
+
+ # Close the file
+ self.container.close()
+
+ # reset runtime parameters
+ self._reset_state()
+
+
+class VideoRecordingWrapper(gym.Wrapper):
+ def __init__(
+ self,
+ env,
+ video_recorder: VideoRecorder,
+ mode="rgb_array",
+ video_dir: Path | None = None,
+ steps_per_render=1,
+ **kwargs,
+ ):
+ """
+ When file_path is None, don't record.
+ """
+ super().__init__(env)
+
+ if video_dir is not None:
+ video_dir.mkdir(parents=True, exist_ok=True)
+
+ self.mode = mode
+ self.render_kwargs = kwargs
+ self.steps_per_render = steps_per_render
+ self.video_dir = video_dir
+ self.video_recorder = video_recorder
+ self.file_path = None
+
+ self.step_count = 0
+
+ self.is_success = False
+
+ def reset(self, **kwargs):
+ result = super().reset(**kwargs)
+ self.frames = list()
+ self.step_count = 1
+ self.video_recorder.stop()
+
+ if self.video_dir is not None and self.file_path is not None:
+ # rename the file to indicate success or failure
+ original_filestem = self.file_path.stem
+ new_filestem = f"{original_filestem}_success{int(self.is_success)}"
+ new_file_path = self.video_dir / f"{new_filestem}.mp4"
+ os.rename(self.file_path, new_file_path)
+
+ self.is_success = False
+ if self.video_dir is not None:
+ self.file_path = self.video_dir / f"{uuid.uuid4()}.mp4"
+ return result
+
+ def step(self, action):
+ result = super().step(action)
+ self.step_count += 1
+ if self.file_path is not None and ((self.step_count % self.steps_per_render) == 0):
+ if not self.video_recorder.is_ready():
+ self.video_recorder.start(self.file_path)
+
+ frame = self.env.render()
+ assert frame.dtype == np.uint8
+ self.video_recorder.write_frame(frame)
+ self.is_success = result[-1]["success"]
+ return result
+
+ def render(self, mode="rgb_array", **kwargs):
+ if self.video_recorder.is_ready():
+ self.video_recorder.stop()
+ return self.file_path
diff --git a/examples/Robocasa_tabletop/train_files/.ipynb_checkpoints/run_yzh_cosmos25_perceiver_vjepa2_ac-checkpoint.sh b/examples/Robocasa_tabletop/train_files/.ipynb_checkpoints/run_yzh_cosmos25_perceiver_vjepa2_ac-checkpoint.sh
new file mode 100644
index 0000000000000000000000000000000000000000..717f5082552e6555dc6fa183992efe329c5ac53c
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files/.ipynb_checkpoints/run_yzh_cosmos25_perceiver_vjepa2_ac-checkpoint.sh
@@ -0,0 +1,131 @@
+#!/usr/bin/env zsh
+set -euo pipefail
+
+# Cosmos-Predict2.5 Perceiver training with eval-time future-image visualization.
+# Action training uses Cosmos hidden states + Perceiver; eval additionally runs
+# the Cosmos2.5 decoder/generation path and saves pred future images.
+
+if [ -d /sys/class/infiniband ]; then
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
+else
+ RDMA_DEVICES=""
+fi
+
+if [ -n "${RDMA_DEVICES}" ]; then
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
+ export NCCL_IB_HCA
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
+ export NCCL_IB_DISABLE=0
+ export NCCL_NET_GDR_LEVEL=2
+else
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
+ export NCCL_IB_DISABLE=1
+fi
+
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS || true
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+
+if [ -f /mnt/workspace/envs/conda3/bin/activate ]; then
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+fi
+
+NUM_GPUS_PER_NODE=${1:-8} # mytest
+
+Framework_name=CosmoPredict25PerceiverVJEPA2AC
+base_wm=/mnt/workspace/users/maxiangkai/models/Cosmos-Predict2.5-2B-Post-Trained
+cosmos_revision=${COSMOS_PREDICT25_REVISION-diffusers/base/post-trained}
+base_vlm=${base_wm}
+freeze_module_list=''
+DIT_TYPE="DiT-B"
+data_root_dir=/mnt/workspace/datasets/
+data_mix=robocasa_teleop_ee
+
+action_dim=32
+state_dim=64
+action_hidden_dim=1024
+cross_attention_dim=2048
+
+run_root_dir=/mnt/workspace/users/maxiangkai/projects/WM4A/outputs/cosmopredict25_vjepa
+run_id=robocasa
+
+export PYTHONPATH="${PYTHONPATH}:/mnt/workspace/users/maxiangkai/projects/WM4A"
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p "${output_dir}"
+export WANDB_MODE=offline
+export WANDB_DIR="${output_dir}/wandb"
+mkdir -p "${WANDB_DIR}"
+cp "$0" "${output_dir}/"
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
+ /mnt/workspace/users/maxiangkai/projects/WM4A/starVLA/training/train_starvla.py \
+ --config_yaml /mnt/workspace/users/maxiangkai/projects/WM4A/examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr2.yaml \
+ --framework.name ${Framework_name} \
+ --framework.world_model.base_wm "${base_wm}" \
+ --framework.world_model.revision "${cosmos_revision}" \
+ --framework.world_model.extract_layers "[-1]" \
+ --framework.world_model.height 224 \
+ --framework.world_model.width 224 \
+ --framework.world_model.conditional_frame_timestep 0.1 \
+ --framework.qwenvl.base_vlm "${base_vlm}" \
+ --framework.qwenvl.vl_hidden_dim 2048 \
+ --framework.action_model.action_model_type ${DIT_TYPE} \
+ --framework.action_model.action_dim ${action_dim} \
+ --framework.action_model.state_dim ${state_dim} \
+ --framework.action_model.action_hidden_dim ${action_hidden_dim} \
+ --framework.action_model.hidden_size ${action_hidden_dim} \
+ --framework.action_model.diffusion_model_cfg.cross_attention_dim ${cross_attention_dim} \
+ --framework.action_model.diffusion_model_cfg.output_dim ${action_hidden_dim} \
+ --framework.vjepa2_ac.repo_dir /mnt/workspace/users/maxiangkai/projects/WM4A/starVLA/facebookresearch_vjepa2_main \
+ --framework.vjepa2_ac.pretrained /mnt/workspace/users/maxiangkai/models/VJEPA2-AC/vjepa2-ac-vitg.pt \
+ --framework.future_latent_training.enabled true \
+ --framework.future_latent_training.loss_weight 0.1 \
+ --framework.future_latent_training.train_time_distribution logitnormal \
+ --framework.future_latent_training.shift 5.0 \
+ --framework.future_image_training.enabled false \
+ --framework.future_image_training.loss_weight 1.0 \
+ --framework.future_image_training.train_time_distribution logitnormal \
+ --framework.future_image_training.shift 5.0 \
+ --framework.future_image_generation.enabled false \
+ --framework.future_image_generation.conditioning_mode auto \
+ --framework.future_image_generation.max_samples 1 \
+ --framework.future_image_generation.height 224 \
+ --framework.future_image_generation.width 224 \
+ --framework.future_image_generation.num_frames 93 \
+ --framework.future_image_generation.num_inference_steps 20 \
+ --framework.future_image_generation.guidance_scale 7.0 \
+ --framework.future_image_generation.output_type pil \
+ --framework.future_image_generation.future_frame_index -1 \
+ --framework.future_image_generation.return_full_video false \
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
+ --datasets.vla_data.data_mix "${data_mix}" \
+ --datasets.vla_data.include_state true \
+ --datasets.vla_data.per_device_batch_size 32 \
+ --trainer.freeze_modules "${freeze_module_list}" \
+ --trainer.max_train_steps 300000 \
+ --trainer.save_interval 5000 \
+ --trainer.logging_frequency 200 \
+ --trainer.eval_interval 200 \
+ --trainer.num_warmup_steps 1000 \
+ --trainer.learning_rate.base 1e-5 \
+ --trainer.learning_rate.vjepa_predictor 1.0e-04 \
+ --trainer.learning_rate.state_projector 1.0e-04 \
+ --trainer.learning_rate.action_projector 1.0e-04 \
+ --trainer.scheduler_specific_kwargs.min_lr 1.2e-6 \
+ --trainer.optimizer.betas "[0.9,0.999]" \
+ --trainer.optimizer.weight_decay 0.1 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project joyRA_robocasa_mxk \
+ --wandb_entity mxk \
+ 2>&1 | tee -a "${output_dir}/train.log"
diff --git a/examples/Robocasa_tabletop/train_files/.ipynb_checkpoints/run_yzh_cosmos25_perceiver_vjepa2_ac_resume_back-checkpoint.sh b/examples/Robocasa_tabletop/train_files/.ipynb_checkpoints/run_yzh_cosmos25_perceiver_vjepa2_ac_resume_back-checkpoint.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b6f3baf0d58351d3fb52f8daa38cadcb7747e7e2
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files/.ipynb_checkpoints/run_yzh_cosmos25_perceiver_vjepa2_ac_resume_back-checkpoint.sh
@@ -0,0 +1,38 @@
+#!/bin/bash
+
+EVAL_SCRIPT="$(cd "$(dirname "$0")" && pwd)/run_yzh_cosmos25_perceiver_vjepa2_ac_resume.sh"
+LOG_FILE="/mnt/workspace/users/maxiangkai/projects/WM4A/outputs/cosmopredict25_vjepa_ImageLatent/train_back_$(date +%Y%m%d_%H%M%S).log"
+mkdir -p "$(dirname "${LOG_FILE}")"
+
+if [ ! -f "${EVAL_SCRIPT}" ]; then
+ echo "ERROR: cannot find ${EVAL_SCRIPT}" >&2; exit 1
+fi
+
+nohup setsid bash "${EVAL_SCRIPT}" "$@" >"${LOG_FILE}" 2>&1 &
+EVAL_PID=$!
+disown "${EVAL_PID}" 2>/dev/null || true
+sleep 1
+
+ABS_LOG_FILE="$(cd "$(dirname "${LOG_FILE}")" && pwd)/$(basename "${LOG_FILE}")"
+
+cat </dev/null; echo ""; echo "Detached from log. Eval PID=${EVAL_PID} still running."; echo " Re-attach: tail -F ${ABS_LOG_FILE}"; exit 0' INT
+wait "${TAIL_PID}"
\ No newline at end of file
diff --git a/examples/Robocasa_tabletop/train_files/cosmos25_perceiver_posttrain.sh b/examples/Robocasa_tabletop/train_files/cosmos25_perceiver_posttrain.sh
new file mode 100644
index 0000000000000000000000000000000000000000..51110b230231337ad085c199a6ad1d4cf8272c4d
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files/cosmos25_perceiver_posttrain.sh
@@ -0,0 +1,141 @@
+#!/usr/bin/env zsh
+set -euo pipefail
+
+# Cosmos-Predict2.5 Perceiver training with DiT4DiT-style video-action fusion.
+# Keeps the starVLA Perceiver action head, while training Cosmos video dynamics
+# with a tri-timestep scheme and using fixed-timestep Cosmos hidden states as
+# the action condition.
+
+if [ -d /sys/class/infiniband ]; then
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
+else
+ RDMA_DEVICES=""
+fi
+
+if [ -n "${RDMA_DEVICES}" ]; then
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
+ export NCCL_IB_HCA
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
+ export NCCL_IB_DISABLE=0
+ export NCCL_NET_GDR_LEVEL=2
+else
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
+ export NCCL_IB_DISABLE=1
+fi
+
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS || true
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+
+if [ -f /mnt/workspace/envs/conda3/bin/activate ]; then
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+fi
+
+NUM_GPUS_PER_NODE=${1:-8}
+
+Framework_name=CosmoPredict25PerceiverDiT4DiT
+base_wm=/mnt/workspace/users/yuanzhihao/code/starVLA/playground/Pretrained_models/Cosmos-Predict2.5-2B-Post-Trained
+cosmos_revision=${COSMOS_PREDICT25_REVISION-diffusers/base/post-trained}
+base_vlm=${base_wm}
+freeze_module_list=''
+DIT_TYPE="DiT-B"
+data_root_dir=/mnt/workspace/datasets/
+data_mix=robocasa_teleop_ee
+pretrained_checkpoint="/mnt/workspace/users/yuanzhihao/code/starVLA/outputs/cosmopredict25_perceiver_dit4dit/pretrain/sq_robocasa/checkpoints/steps_50000_pytorch_model.pt"
+
+
+action_dim=32
+state_dim=64
+action_hidden_dim=2560
+cross_attention_dim=2048
+
+run_root_dir=./outputs1/cosmopredict25_perceiver_dit4dit/posttrain
+run_id=robocasa_pre_sq_robocasa
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p "${output_dir}"
+export WANDB_MODE=offline
+export WANDB_DIR="${output_dir}/wandb"
+mkdir -p "${WANDB_DIR}"
+cp "$0" "${output_dir}/"
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29600} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
+ starVLA/training/train_starvla.py \
+ --config_yaml ./examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml \
+ --framework.name ${Framework_name} \
+ --framework.world_model.base_wm "${base_wm}" \
+ --framework.world_model.revision "${cosmos_revision}" \
+ --framework.world_model.attn_implementation flash_attention_2 \
+ --framework.world_model.extract_layers "[17]" \
+ --framework.world_model.height 224 \
+ --framework.world_model.width 224 \
+ --framework.world_model.conditional_frame_timestep 0.0001 \
+ --framework.qwenvl.base_vlm "${base_vlm}" \
+ --framework.qwenvl.vl_hidden_dim 2048 \
+ --framework.action_model.action_model_type ${DIT_TYPE} \
+ --framework.action_model.action_dim ${action_dim} \
+ --framework.action_model.state_dim ${state_dim} \
+ --framework.action_model.action_hidden_dim ${action_hidden_dim} \
+ --framework.action_model.hidden_size ${action_hidden_dim} \
+ --framework.action_model.diffusion_model_cfg.cross_attention_dim ${cross_attention_dim} \
+ --framework.action_model.diffusion_model_cfg.output_dim ${action_hidden_dim} \
+ --framework.action_model.num_inference_timesteps 4 \
+ --framework.dit4dit_video.enabled true \
+ --framework.dit4dit_video.training joint \
+ --framework.dit4dit_video.future_loss_type flow_matching \
+ --framework.dit4dit_video.future_loss_weight 1.0 \
+ --framework.dit4dit_video.future_num_inference_steps 1 \
+ --framework.dit4dit_action_head.enabled true \
+ --framework.dit4dit_video.conditional_frame_timestep 0.0001 \
+ --framework.dit4dit_video.height 224 \
+ --framework.dit4dit_video.width auto \
+ --framework.dit4dit_video.tri_timestep.video_time_distribution logit_normal \
+ --framework.dit4dit_video.tri_timestep.high_sigma_ratio 0.05 \
+ --framework.dit4dit_video.tri_timestep.high_sigma_min 0.98 \
+ --framework.dit4dit_video.tri_timestep.feature_timestep 1.0 \
+ --framework.dit4dit_video.tri_timestep.action_time_distribution beta_action_head \
+ --framework.future_image_generation.enabled true \
+ --framework.future_image_generation.conditioning_mode auto \
+ --framework.future_image_generation.max_samples 1 \
+ --framework.future_image_generation.height 224 \
+ --framework.future_image_generation.width auto \
+ --framework.future_image_generation.num_frames 9 \
+ --framework.future_image_generation.num_inference_steps 1 \
+ --framework.future_image_generation.guidance_scale 1.0 \
+ --framework.future_image_generation.output_type pil \
+ --framework.future_image_generation.future_frame_index -1 \
+ --framework.future_image_generation.return_full_video true \
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
+ --datasets.vla_data.data_mix "${data_mix}" \
+ --datasets.vla_data.include_state true \
+ --datasets.vla_data.video_backend torchvision_av \
+ --datasets.vla_data.future_video_delta_indices "[2,4,6,8,10,12,14,16]" \
+ --datasets.vla_data.action_video_freq_ratio 2 \
+ --datasets.vla_data.per_device_batch_size 8 \
+ --trainer.freeze_modules "${freeze_module_list}" \
+ --trainer.max_train_steps 300000 \
+ --trainer.save_interval 50000 \
+ --trainer.logging_frequency 200 \
+ --trainer.eval_interval 200 \
+ --trainer.num_warmup_steps 5000 \
+ --trainer.learning_rate.base 1e-5 \
+ --trainer.learning_rate.backbone 1e-5 \
+ --trainer.learning_rate.action_model 1e-4 \
+ --trainer.scheduler_specific_kwargs.min_lr 5e-7 \
+ --trainer.optimizer.betas "[0.9,0.95]" \
+ --trainer.optimizer.weight_decay 1e-8 \
+ --trainer.pretrained_checkpoint ${pretrained_checkpoint} \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project joyRA_robocasa \
+ --wandb_entity curryyuan \
+ 2>&1 | tee -a "${output_dir}/train.log"
diff --git a/examples/Robocasa_tabletop/train_files/cosmos25_perceiver_pretrain_image.sh b/examples/Robocasa_tabletop/train_files/cosmos25_perceiver_pretrain_image.sh
new file mode 100644
index 0000000000000000000000000000000000000000..677e532f02231c9ed2c833d8ca7685c331c190d4
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files/cosmos25_perceiver_pretrain_image.sh
@@ -0,0 +1,123 @@
+#!/usr/bin/env zsh
+set -euo pipefail
+
+# Cosmos-Predict2.5 Perceiver training with eval-time future-image visualization.
+# Action training uses Cosmos hidden states + Perceiver; eval additionally runs
+# the Cosmos2.5 decoder/generation path and saves pred future images.
+
+if [ -d /sys/class/infiniband ]; then
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
+else
+ RDMA_DEVICES=""
+fi
+
+if [ -n "${RDMA_DEVICES}" ]; then
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
+ export NCCL_IB_HCA
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
+ export NCCL_IB_DISABLE=0
+ export NCCL_NET_GDR_LEVEL=2
+else
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
+ export NCCL_IB_DISABLE=1
+fi
+
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS || true
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+
+if [ -f /mnt/workspace/envs/conda3/bin/activate ]; then
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+fi
+
+NUM_GPUS_PER_NODE=${1:-8}
+
+Framework_name=CosmoPredict25PerceiverFutureImage
+base_wm=/mnt/workspace/users/yuanzhihao/code/starVLA/playground/Pretrained_models/Cosmos-Predict2.5-2B-Post-Trained
+cosmos_revision=${COSMOS_PREDICT25_REVISION-diffusers/base/post-trained}
+base_vlm=${base_wm}
+freeze_module_list=''
+DIT_TYPE="DiT-B"
+data_root_dir=/mnt/workspace1
+data_mix=sq_agi-beta_egodex-f_nvwa-f_robotwin_robocasa
+
+action_dim=32
+state_dim=64
+action_hidden_dim=1024
+cross_attention_dim=2048
+
+run_root_dir=./outputs/cosmopredict25_perceiver_future_image/pretrain
+run_id=sq_agi-beta_egodex-f_nvwa-f_robotwin_robocasa
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p "${output_dir}"
+export WANDB_MODE=offline
+export WANDB_DIR="${output_dir}/wandb"
+mkdir -p "${WANDB_DIR}"
+cp "$0" "${output_dir}/"
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
+ starVLA/training/train_starvla.py \
+ --config_yaml ./examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml \
+ --framework.name ${Framework_name} \
+ --framework.world_model.base_wm "${base_wm}" \
+ --framework.world_model.revision "${cosmos_revision}" \
+ --framework.world_model.extract_layers "[-1]" \
+ --framework.world_model.height 224 \
+ --framework.world_model.width auto \
+ --framework.world_model.conditional_frame_timestep 0.1 \
+ --framework.qwenvl.base_vlm "${base_vlm}" \
+ --framework.qwenvl.vl_hidden_dim 2048 \
+ --framework.action_model.action_model_type ${DIT_TYPE} \
+ --framework.action_model.action_dim ${action_dim} \
+ --framework.action_model.state_dim ${state_dim} \
+ --framework.action_model.action_hidden_dim ${action_hidden_dim} \
+ --framework.action_model.hidden_size ${action_hidden_dim} \
+ --framework.action_model.diffusion_model_cfg.cross_attention_dim ${cross_attention_dim} \
+ --framework.action_model.diffusion_model_cfg.output_dim ${action_hidden_dim} \
+ --framework.future_image_training.enabled true \
+ --framework.future_image_training.loss_weight 1.0 \
+ --framework.future_image_training.train_time_distribution logitnormal \
+ --framework.future_image_training.shift 5.0 \
+ --framework.future_image_generation.enabled true \
+ --framework.future_image_generation.conditioning_mode auto \
+ --framework.future_image_generation.max_samples 8 \
+ --framework.future_image_generation.height 224 \
+ --framework.future_image_generation.width auto \
+ --framework.future_image_generation.num_frames 9 \
+ --framework.future_image_generation.num_inference_steps 20 \
+ --framework.future_image_generation.guidance_scale 7.0 \
+ --framework.future_image_generation.output_type pil \
+ --framework.future_image_generation.future_frame_index -1 \
+ --framework.future_image_generation.num_latent_conditional_frames 1 \
+ --framework.future_image_generation.return_full_video false \
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
+ --datasets.vla_data.data_mix "${data_mix}" \
+ --datasets.vla_data.future_video_delta_indices "[16]" \
+ --datasets.vla_data.include_state true \
+ --datasets.vla_data.per_device_batch_size 8 \
+ --datasets.vla_data.video_backend torchvision_av \
+ --trainer.freeze_modules "${freeze_module_list}" \
+ --trainer.max_train_steps 300000 \
+ --trainer.save_interval 10000 \
+ --trainer.logging_frequency 200 \
+ --trainer.eval_interval 200 \
+ --trainer.num_warmup_steps 1000 \
+ --trainer.learning_rate.base 1e-5 \
+ --trainer.scheduler_specific_kwargs.min_lr 1.2e-6 \
+ --trainer.optimizer.betas "[0.9,0.999]" \
+ --trainer.optimizer.weight_decay 0.1 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project joyRA_robocasa \
+ --wandb_entity curryyuan \
+ 2>&1 | tee -a "${output_dir}/train.log"
diff --git a/examples/Robocasa_tabletop/train_files/cosmos25_perceiver_pretrain_video.sh b/examples/Robocasa_tabletop/train_files/cosmos25_perceiver_pretrain_video.sh
new file mode 100644
index 0000000000000000000000000000000000000000..f48955e309eb96b6e1f7359381c6f4ff8c46c5b2
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files/cosmos25_perceiver_pretrain_video.sh
@@ -0,0 +1,138 @@
+#!/usr/bin/env zsh
+set -euo pipefail
+
+# Cosmos-Predict2.5 Perceiver training with DiT4DiT-style video-action fusion.
+# Keeps the starVLA Perceiver action head, while training Cosmos video dynamics
+# with a tri-timestep scheme and using fixed-timestep Cosmos hidden states as
+# the action condition.
+
+if [ -d /sys/class/infiniband ]; then
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
+else
+ RDMA_DEVICES=""
+fi
+
+if [ -n "${RDMA_DEVICES}" ]; then
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
+ export NCCL_IB_HCA
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
+ export NCCL_IB_DISABLE=0
+ export NCCL_NET_GDR_LEVEL=2
+else
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
+ export NCCL_IB_DISABLE=1
+fi
+
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS || true
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+
+if [ -f /mnt/workspace/envs/conda3/bin/activate ]; then
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+fi
+
+NUM_GPUS_PER_NODE=${1:-8}
+
+Framework_name=CosmoPredict25PerceiverDiT4DiT
+base_wm=/mnt/workspace/users/yuanzhihao/code/starVLA/playground/Pretrained_models/Cosmos-Predict2.5-2B-Post-Trained
+cosmos_revision=${COSMOS_PREDICT25_REVISION-diffusers/base/post-trained}
+base_vlm=${base_wm}
+freeze_module_list=''
+DIT_TYPE="DiT-B"
+data_root_dir=/mnt/workspace1/
+data_mix=sq_agi-beta_robocasa
+
+action_dim=32
+state_dim=64
+action_hidden_dim=2560
+cross_attention_dim=2048
+
+run_root_dir=./outputs1/cosmopredict25_perceiver_dit4dit/pretrain
+run_id=sq_agi-beta_robocasa
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p "${output_dir}"
+export WANDB_MODE=offline
+export WANDB_DIR="${output_dir}/wandb"
+mkdir -p "${WANDB_DIR}"
+cp "$0" "${output_dir}/"
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29600} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
+ starVLA/training/train_starvla.py \
+ --config_yaml ./examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml \
+ --framework.name ${Framework_name} \
+ --framework.world_model.base_wm "${base_wm}" \
+ --framework.world_model.revision "${cosmos_revision}" \
+ --framework.world_model.attn_implementation flash_attention_2 \
+ --framework.world_model.extract_layers "[17]" \
+ --framework.world_model.height 224 \
+ --framework.world_model.width 224 \
+ --framework.world_model.conditional_frame_timestep 0.0001 \
+ --framework.qwenvl.base_vlm "${base_vlm}" \
+ --framework.qwenvl.vl_hidden_dim 2048 \
+ --framework.action_model.action_model_type ${DIT_TYPE} \
+ --framework.action_model.action_dim ${action_dim} \
+ --framework.action_model.state_dim ${state_dim} \
+ --framework.action_model.action_hidden_dim ${action_hidden_dim} \
+ --framework.action_model.hidden_size ${action_hidden_dim} \
+ --framework.action_model.diffusion_model_cfg.cross_attention_dim ${cross_attention_dim} \
+ --framework.action_model.diffusion_model_cfg.output_dim ${action_hidden_dim} \
+ --framework.action_model.num_inference_timesteps 4 \
+ --framework.dit4dit_video.enabled true \
+ --framework.dit4dit_video.training joint \
+ --framework.dit4dit_video.future_loss_type flow_matching \
+ --framework.dit4dit_video.future_loss_weight 1.0 \
+ --framework.dit4dit_video.future_num_inference_steps 1 \
+ --framework.dit4dit_action_head.enabled true \
+ --framework.dit4dit_video.conditional_frame_timestep 0.0001 \
+ --framework.dit4dit_video.height 224 \
+ --framework.dit4dit_video.width auto \
+ --framework.dit4dit_video.tri_timestep.video_time_distribution logit_normal \
+ --framework.dit4dit_video.tri_timestep.high_sigma_ratio 0.05 \
+ --framework.dit4dit_video.tri_timestep.high_sigma_min 0.98 \
+ --framework.dit4dit_video.tri_timestep.feature_timestep 1.0 \
+ --framework.dit4dit_video.tri_timestep.action_time_distribution beta_action_head \
+ --framework.future_image_generation.enabled true \
+ --framework.future_image_generation.conditioning_mode auto \
+ --framework.future_image_generation.max_samples 1 \
+ --framework.future_image_generation.height 224 \
+ --framework.future_image_generation.width auto \
+ --framework.future_image_generation.num_frames 9 \
+ --framework.future_image_generation.num_inference_steps 1 \
+ --framework.future_image_generation.guidance_scale 1.0 \
+ --framework.future_image_generation.output_type pil \
+ --framework.future_image_generation.future_frame_index -1 \
+ --framework.future_image_generation.return_full_video true \
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
+ --datasets.vla_data.data_mix "${data_mix}" \
+ --datasets.vla_data.include_state true \
+ --datasets.vla_data.video_backend torchvision_av \
+ --datasets.vla_data.future_video_delta_indices "[2,4,6,8,10,12,14,16]" \
+ --datasets.vla_data.action_video_freq_ratio 2 \
+ --datasets.vla_data.per_device_batch_size 4 \
+ --trainer.freeze_modules "${freeze_module_list}" \
+ --trainer.max_train_steps 300000 \
+ --trainer.save_interval 50000 \
+ --trainer.logging_frequency 200 \
+ --trainer.eval_interval 200 \
+ --trainer.num_warmup_steps 5000 \
+ --trainer.learning_rate.base 1e-5 \
+ --trainer.learning_rate.backbone 1e-5 \
+ --trainer.learning_rate.action_model 1e-4 \
+ --trainer.scheduler_specific_kwargs.min_lr 5e-7 \
+ --trainer.optimizer.betas "[0.9,0.95]" \
+ --trainer.optimizer.weight_decay 1e-8 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project joyRA_robocasa \
+ --wandb_entity curryyuan \
+ 2>&1 | tee -a "${output_dir}/train.log"
diff --git a/examples/Robocasa_tabletop/train_files/download_gr00t_ft_data.py b/examples/Robocasa_tabletop/train_files/download_gr00t_ft_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..9b88f578e462de8f2549291a90381cc2b8792872
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files/download_gr00t_ft_data.py
@@ -0,0 +1,124 @@
+from huggingface_hub import list_repo_files, hf_hub_download
+from concurrent.futures import ThreadPoolExecutor, as_completed
+import os
+import time
+import random
+
+
+REPO_ID = "nvidia/PhysicalAI-Robotics-GR00T-X-Embodiment-Sim"
+REPO_TYPE = "dataset"
+
+LOCAL_DIR = "./playground/Datasets/nvidia/PhysicalAI-Robotics-GR00T-X-Embodiment-Sim"
+
+FOLDERS = [
+ "gr1_unified.PnPBottleToCabinetClose_GR1ArmsAndWaistFourierHands_1000",
+ "gr1_unified.PnPCanToDrawerClose_GR1ArmsAndWaistFourierHands_1000",
+ "gr1_unified.PnPCupToDrawerClose_GR1ArmsAndWaistFourierHands_1000",
+ "gr1_unified.PnPMilkToMicrowaveClose_GR1ArmsAndWaistFourierHands_1000",
+ "gr1_unified.PnPPotatoToMicrowaveClose_GR1ArmsAndWaistFourierHands_1000",
+ "gr1_unified.PnPWineToCabinetClose_GR1ArmsAndWaistFourierHands_1000",
+ "gr1_unified.PosttrainPnPNovelFromCuttingboardToBasketSplitA_GR1ArmsAndWaistFourierHands_1000",
+ "gr1_unified.PosttrainPnPNovelFromCuttingboardToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_1000",
+ "gr1_unified.PosttrainPnPNovelFromCuttingboardToPanSplitA_GR1ArmsAndWaistFourierHands_1000",
+ "gr1_unified.PosttrainPnPNovelFromCuttingboardToPotSplitA_GR1ArmsAndWaistFourierHands_1000",
+ "gr1_unified.PosttrainPnPNovelFromCuttingboardToTieredbasketSplitA_GR1ArmsAndWaistFourierHands_1000",
+ "gr1_unified.PosttrainPnPNovelFromPlacematToBasketSplitA_GR1ArmsAndWaistFourierHands_1000",
+ "gr1_unified.PosttrainPnPNovelFromPlacematToBowlSplitA_GR1ArmsAndWaistFourierHands_1000",
+ "gr1_unified.PosttrainPnPNovelFromPlacematToPlateSplitA_GR1ArmsAndWaistFourierHands_1000",
+ "gr1_unified.PosttrainPnPNovelFromPlacematToTieredshelfSplitA_GR1ArmsAndWaistFourierHands_1000",
+ "gr1_unified.PosttrainPnPNovelFromPlateToBowlSplitA_GR1ArmsAndWaistFourierHands_1000",
+ "gr1_unified.PosttrainPnPNovelFromPlateToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_1000",
+ "gr1_unified.PosttrainPnPNovelFromPlateToPanSplitA_GR1ArmsAndWaistFourierHands_1000",
+ "gr1_unified.PosttrainPnPNovelFromPlateToPlateSplitA_GR1ArmsAndWaistFourierHands_1000",
+ "gr1_unified.PosttrainPnPNovelFromTrayToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_1000",
+ "gr1_unified.PosttrainPnPNovelFromTrayToPlateSplitA_GR1ArmsAndWaistFourierHands_1000",
+ "gr1_unified.PosttrainPnPNovelFromTrayToPotSplitA_GR1ArmsAndWaistFourierHands_1000",
+ "gr1_unified.PosttrainPnPNovelFromTrayToTieredbasketSplitA_GR1ArmsAndWaistFourierHands_1000",
+ "gr1_unified.PosttrainPnPNovelFromTrayToTieredshelfSplitA_GR1ArmsAndWaistFourierHands_1000",
+]
+
+
+def download_with_retry(
+ filename: str,
+ max_retries: int = 50,
+) -> bool:
+ """
+ Download a single file from Hugging Face Hub with retry logic.
+
+ Args:
+ filename: Path of the file in the repository.
+ max_retries: Maximum number of retry attempts.
+
+ Returns:
+ True if download succeeds, False otherwise.
+ """
+ for attempt in range(1, max_retries + 1):
+ try:
+ hf_hub_download(
+ repo_id=REPO_ID,
+ repo_type=REPO_TYPE,
+ filename=filename,
+ local_dir=LOCAL_DIR,
+ local_dir_use_symlinks=False,
+ )
+ return True
+ except Exception as exc:
+ wait_time = random.uniform(1.0, 5.0) * attempt / 10.0
+ print(
+ f"[{attempt}/{max_retries}] "
+ f"Download failed: {filename} ({exc}); "
+ f"retrying in {wait_time:.1f}s"
+ )
+ time.sleep(wait_time)
+
+ print(f"Giving up after {max_retries} retries: {filename}")
+ return False
+
+
+def main() -> None:
+ print("Listing all files in the repository...")
+ all_files = list_repo_files(repo_id=REPO_ID, repo_type=REPO_TYPE)
+
+ target_files = [
+ f
+ for f in all_files
+ if any(f.startswith(folder + "/") for folder in FOLDERS)
+ ]
+
+ print(f"Found {len(target_files)} matching files to download.\n")
+
+ max_workers = 32
+ print(f"Starting parallel download with {max_workers} workers...\n")
+
+ failed_files: list[str] = []
+
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
+ futures = {
+ executor.submit(download_with_retry, filename): filename
+ for filename in target_files
+ }
+
+ for idx, future in enumerate(as_completed(futures), start=1):
+ filename = futures[future]
+ try:
+ success = future.result()
+ if success:
+ print(f"[{idx}/{len(target_files)}] Downloaded: {filename}")
+ else:
+ failed_files.append(filename)
+ except Exception as exc:
+ print(f"Unexpected error for {filename}: {exc}")
+ failed_files.append(filename)
+
+ print("\nAll download attempts finished.")
+
+ if failed_files:
+ print(f"{len(failed_files)} files failed to download:")
+ for filename in failed_files:
+ print(f" - {filename}")
+ else:
+ print("All files downloaded successfully.")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/Robocasa_tabletop/train_files/joyra05.sh b/examples/Robocasa_tabletop/train_files/joyra05.sh
new file mode 100644
index 0000000000000000000000000000000000000000..7aa1ffec7e5710b1a01dfa60e2ad08b2dcf9e73e
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files/joyra05.sh
@@ -0,0 +1,99 @@
+#!/usr/bin/env zsh
+set -euo pipefail
+
+# Cosmos-Predict2.5 Perceiver training with eval-time future-image visualization.
+# Action training uses Cosmos hidden states + Perceiver; eval additionally runs
+# the Cosmos2.5 decoder/generation path and saves pred future images.
+
+if [ -d /sys/class/infiniband ]; then
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
+else
+ RDMA_DEVICES=""
+fi
+
+if [ -n "${RDMA_DEVICES}" ]; then
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
+ export NCCL_IB_HCA
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
+ export NCCL_IB_DISABLE=0
+ export NCCL_NET_GDR_LEVEL=2
+else
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
+ export NCCL_IB_DISABLE=1
+fi
+
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS || true
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+
+cd /mnt/workspace/users/maxiangkai/projects/WM4A
+if [ -f /mnt/workspace/envs/conda3/bin/activate ]; then
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+fi
+
+NUM_GPUS_PER_NODE=${1:-8} # mytest
+
+Framework_name=QwenWanPerceiver
+base_vlm=/mnt/workspace/users/maxiangkai/models/Qwen3-VL-4B-Instruct
+base_wm=/mnt/workspace/users/maxiangkai/models/Wan2.2-TI2V-5B-Diffusers
+transformer_path=/mnt/workspace/users/maxiangkai/models/Motus_Wan2_2_5B_pretrain
+pretrained_checkpoint=/mnt/workspace/users/chidafeng/main_results/joyra05/pretrain/0529_joyra05_data_0530_QwenWanPerceiver_15wsteps_bs16/final_model/pytorch_model.pt
+config_yaml=/mnt/workspace/users/maxiangkai/projects/WM4A/examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml
+DIT_TYPE="DiT-B"
+data_root_dir=/mnt/workspace/datasets/
+data_mix=robocasa_teleop_ee
+
+run_root_dir=/mnt/workspace/users/maxiangkai/projects/WM4A/outputs/joyra05
+run_id=robocasa
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p "${output_dir}"
+export WANDB_MODE=offline
+export WANDB_DIR="${output_dir}/wandb"
+mkdir -p "${WANDB_DIR}"
+cp "$0" "${output_dir}/"
+cp ${config_yaml} ${output_dir}
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
+ starVLA/training/train_starvla.py \
+ --config_yaml ${config_yaml} \
+ --framework.name ${Framework_name} \
+ --framework.qwenvl.base_vlm "${base_vlm}" \
+ --framework.qwenvl.vl_hidden_dim 2048 \
+ --framework.world_model.base_wm ${base_wm} \
+ --framework.world_model.transformer_path ${transformer_path} \
+ --framework.world_model.extract_layers "[-1]" \
+ --framework.action_model.hidden_size 1024 \
+ --framework.action_model.diffusion_model_cfg.output_dim 1024 \
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
+ --datasets.vla_data.data_mix "${data_mix}" \
+ --datasets.vla_data.include_state true \
+ --datasets.vla_data.per_device_batch_size 8 \
+ --datasets.vla_data.num_workers 8 \
+ --datasets.vla_data.prefetch_factor 2 \
+ --datasets.vla_data.pin_memory true \
+ --datasets.vla_data.persistent_workers true \
+ --trainer.pretrained_checkpoint ${pretrained_checkpoint} \
+ --trainer.max_train_steps 300000 \
+ --trainer.save_interval 50000 \
+ --trainer.logging_frequency 500 \
+ --trainer.eval_interval 500 \
+ --trainer.num_warmup_steps 1000 \
+ --trainer.learning_rate.base 1e-5 \
+ --trainer.scheduler_specific_kwargs.min_lr 1.2e-6 \
+ --trainer.optimizer.betas "[0.9,0.999]" \
+ --trainer.optimizer.weight_decay 0.1 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project joyRA_robocasa_mxk \
+ --wandb_entity mxk \
+ 2>&1 | tee -a "${output_dir}/train.log"
diff --git a/examples/Robocasa_tabletop/train_files/joyra05mask.sh b/examples/Robocasa_tabletop/train_files/joyra05mask.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e2e0921d9c519fec8d620f194c51638fb9f214fe
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files/joyra05mask.sh
@@ -0,0 +1,123 @@
+#!/usr/bin/env zsh
+set -euo pipefail
+
+# Cosmos-Predict2.5 Perceiver training with eval-time future-image visualization.
+# Action training uses Cosmos hidden states + Perceiver; eval additionally runs
+# the Cosmos2.5 decoder/generation path and saves pred future images.
+
+if [ -d /sys/class/infiniband ]; then
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
+else
+ RDMA_DEVICES=""
+fi
+
+if [ -n "${RDMA_DEVICES}" ]; then
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
+ export NCCL_IB_HCA
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
+ export NCCL_IB_DISABLE=0
+ export NCCL_NET_GDR_LEVEL=2
+else
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
+ export NCCL_IB_DISABLE=1
+fi
+
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS || true
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+
+cd /mnt/workspace/users/maxiangkai/projects/WM4A
+if [ -f /mnt/workspace/envs/conda3/bin/activate ]; then
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+fi
+
+NUM_GPUS_PER_NODE=${1:-8} # mytest
+
+Framework_name=QwenWanPerceiverMask
+base_vlm=/mnt/workspace/users/maxiangkai/models/Qwen3-VL-4B-Instruct
+base_wm=/mnt/workspace/users/maxiangkai/models/Wan2.2-TI2V-5B-Diffusers
+transformer_path=/mnt/workspace/users/maxiangkai/models/Motus_Wan2_2_5B_pretrain
+pretrained_checkpoint=/mnt/workspace/users/chidafeng/main_results/joyra05/pretrain/0529_joyra05_data_0530_QwenWanPerceiver_15wsteps_bs16/final_model/pytorch_model.pt
+config_yaml=/mnt/workspace/users/maxiangkai/projects/WM4A/examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml
+DIT_TYPE="DiT-B"
+data_root_dir=/mnt/workspace/datasets/
+data_mix=robocasa_teleop_ee
+
+run_root_dir=/mnt/workspace/users/maxiangkai/projects/WM4A/outputs/joyra05mask
+run_id=robocasa # mytest
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p "${output_dir}"
+export WANDB_MODE=offline
+export WANDB_DIR="${output_dir}/wandb"
+mkdir -p "${WANDB_DIR}"
+cp "$0" "${output_dir}/"
+cp ${config_yaml} ${output_dir}
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
+ starVLA/training/train_starvla_zero2.py \
+ --config_yaml ${config_yaml} \
+ --framework.name ${Framework_name} \
+ --framework.qwenvl.base_vlm "${base_vlm}" \
+ --framework.qwenvl.vl_hidden_dim 2048 \
+ --framework.qwenvl.is_frozen false \
+ --framework.world_model.base_wm ${base_wm} \
+ --framework.world_model.transformer_path ${transformer_path} \
+ --framework.world_model.extract_layers "[-1]" \
+ --framework.action_model.hidden_size 1024 \
+ --framework.action_model.diffusion_model_cfg.output_dim 1024 \
+ --framework.future_image_training.enabled true \
+ --framework.future_image_training.loss_weight 1.0 \
+ --framework.future_image_training.train_time_distribution logitnormal \
+ --framework.future_image_training.shift 5.0 \
+ --framework.future_image_training.change_mask_enabled true \
+ --framework.future_image_training.change_mask_top_ratio 0.25 \
+ --framework.future_image_training.change_mask_static_weight 0.05 \
+ --framework.future_image_training.change_mask_soft_loss true \
+ --framework.future_image_training.masked_denoising false \
+ --framework.future_image_training.condition_static_regions false \
+ --framework.future_image_generation.enabled true \
+ --framework.future_image_generation.conditioning_mode auto \
+ --framework.future_image_generation.max_samples 8 \
+ --framework.future_image_generation.height 224 \
+ --framework.future_image_generation.width 224 \
+ --framework.future_image_generation.num_frames 9 \
+ --framework.future_image_generation.num_inference_steps 20 \
+ --framework.future_image_generation.guidance_scale 7.0 \
+ --framework.future_image_generation.output_type pil \
+ --framework.future_image_generation.future_frame_index -1 \
+ --framework.future_image_generation.num_latent_conditional_frames 1 \
+ --framework.future_image_generation.return_full_video false \
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
+ --datasets.vla_data.data_mix "${data_mix}" \
+ --datasets.vla_data.future_video_delta_indices "[16]" \
+ --datasets.vla_data.include_state true \
+ --datasets.vla_data.per_device_batch_size 4 \
+ --datasets.vla_data.num_workers 8 \
+ --datasets.vla_data.prefetch_factor 2 \
+ --datasets.vla_data.pin_memory true \
+ --datasets.vla_data.persistent_workers true \
+ --trainer.pretrained_checkpoint ${pretrained_checkpoint} \
+ --trainer.max_train_steps 300000 \
+ --trainer.save_interval 50000 \
+ --trainer.logging_frequency 500 \
+ --trainer.eval_interval 500 \
+ --trainer.num_warmup_steps 1000 \
+ --trainer.learning_rate.base 1e-5 \
+ --trainer.scheduler_specific_kwargs.min_lr 1.2e-6 \
+ --trainer.optimizer.betas "[0.9,0.999]" \
+ --trainer.optimizer.weight_decay 0.1 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project joyRA_robocasa_mxk \
+ --wandb_entity mxk \
+ 2>&1 | tee -a "${output_dir}/train.log"
diff --git a/examples/Robocasa_tabletop/train_files/joyra05mask_frozen_vlm.sh b/examples/Robocasa_tabletop/train_files/joyra05mask_frozen_vlm.sh
new file mode 100644
index 0000000000000000000000000000000000000000..f55fadd26fdcd6d700934ff78bf5c25ab83c7242
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files/joyra05mask_frozen_vlm.sh
@@ -0,0 +1,123 @@
+#!/usr/bin/env zsh
+set -euo pipefail
+
+# Cosmos-Predict2.5 Perceiver training with eval-time future-image visualization.
+# Action training uses Cosmos hidden states + Perceiver; eval additionally runs
+# the Cosmos2.5 decoder/generation path and saves pred future images.
+
+if [ -d /sys/class/infiniband ]; then
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
+else
+ RDMA_DEVICES=""
+fi
+
+if [ -n "${RDMA_DEVICES}" ]; then
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
+ export NCCL_IB_HCA
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
+ export NCCL_IB_DISABLE=0
+ export NCCL_NET_GDR_LEVEL=2
+else
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
+ export NCCL_IB_DISABLE=1
+fi
+
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS || true
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+
+cd /mnt/workspace/users/maxiangkai/projects/WM4A
+if [ -f /mnt/workspace/envs/conda3/bin/activate ]; then
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+fi
+
+NUM_GPUS_PER_NODE=${1:-8} # mytest
+
+Framework_name=QwenWanPerceiverMask
+base_vlm=/mnt/workspace/users/maxiangkai/models/Qwen3-VL-4B-Instruct
+base_wm=/mnt/workspace/users/maxiangkai/models/Wan2.2-TI2V-5B-Diffusers
+transformer_path=/mnt/workspace/users/maxiangkai/models/Motus_Wan2_2_5B_pretrain
+pretrained_checkpoint=/mnt/workspace/users/chidafeng/main_results/joyra05/pretrain/0529_joyra05_data_0530_QwenWanPerceiver_15wsteps_bs16/final_model/pytorch_model.pt
+config_yaml=/mnt/workspace/users/maxiangkai/projects/WM4A/examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml
+DIT_TYPE="DiT-B"
+data_root_dir=/mnt/workspace/datasets/
+data_mix=robocasa_teleop_ee
+
+run_root_dir=/mnt/workspace/users/maxiangkai/projects/WM4A/outputs/joyra05mask_frozen_vlm
+run_id=robocasa # mytest
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p "${output_dir}"
+export WANDB_MODE=offline
+export WANDB_DIR="${output_dir}/wandb"
+mkdir -p "${WANDB_DIR}"
+cp "$0" "${output_dir}/"
+cp ${config_yaml} ${output_dir}
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
+ starVLA/training/train_starvla_zero2.py \
+ --config_yaml ${config_yaml} \
+ --framework.name ${Framework_name} \
+ --framework.qwenvl.base_vlm "${base_vlm}" \
+ --framework.qwenvl.vl_hidden_dim 2048 \
+ --framework.qwenvl.is_frozen true \
+ --framework.world_model.base_wm ${base_wm} \
+ --framework.world_model.transformer_path ${transformer_path} \
+ --framework.world_model.extract_layers "[-1]" \
+ --framework.action_model.hidden_size 1024 \
+ --framework.action_model.diffusion_model_cfg.output_dim 1024 \
+ --framework.future_image_training.enabled true \
+ --framework.future_image_training.loss_weight 1.0 \
+ --framework.future_image_training.train_time_distribution logitnormal \
+ --framework.future_image_training.shift 5.0 \
+ --framework.future_image_training.change_mask_enabled true \
+ --framework.future_image_training.change_mask_top_ratio 0.25 \
+ --framework.future_image_training.change_mask_static_weight 0.05 \
+ --framework.future_image_training.change_mask_soft_loss true \
+ --framework.future_image_training.masked_denoising false \
+ --framework.future_image_training.condition_static_regions false \
+ --framework.future_image_generation.enabled true \
+ --framework.future_image_generation.conditioning_mode auto \
+ --framework.future_image_generation.max_samples 8 \
+ --framework.future_image_generation.height 224 \
+ --framework.future_image_generation.width 224 \
+ --framework.future_image_generation.num_frames 9 \
+ --framework.future_image_generation.num_inference_steps 20 \
+ --framework.future_image_generation.guidance_scale 7.0 \
+ --framework.future_image_generation.output_type pil \
+ --framework.future_image_generation.future_frame_index -1 \
+ --framework.future_image_generation.num_latent_conditional_frames 1 \
+ --framework.future_image_generation.return_full_video false \
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
+ --datasets.vla_data.data_mix "${data_mix}" \
+ --datasets.vla_data.future_video_delta_indices "[16]" \
+ --datasets.vla_data.include_state true \
+ --datasets.vla_data.per_device_batch_size 4 \
+ --datasets.vla_data.num_workers 8 \
+ --datasets.vla_data.prefetch_factor 2 \
+ --datasets.vla_data.pin_memory true \
+ --datasets.vla_data.persistent_workers true \
+ --trainer.pretrained_checkpoint ${pretrained_checkpoint} \
+ --trainer.max_train_steps 300000 \
+ --trainer.save_interval 50000 \
+ --trainer.logging_frequency 500 \
+ --trainer.eval_interval 500 \
+ --trainer.num_warmup_steps 1000 \
+ --trainer.learning_rate.base 1e-5 \
+ --trainer.scheduler_specific_kwargs.min_lr 1.2e-6 \
+ --trainer.optimizer.betas "[0.9,0.999]" \
+ --trainer.optimizer.weight_decay 0.1 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project joyRA_robocasa_mxk \
+ --wandb_entity mxk \
+ 2>&1 | tee -a "${output_dir}/train.log"
diff --git a/examples/Robocasa_tabletop/train_files/run_robocasa.sh b/examples/Robocasa_tabletop/train_files/run_robocasa.sh
new file mode 100644
index 0000000000000000000000000000000000000000..969b63d4d44323d0e64f569030c408da545f44c8
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files/run_robocasa.sh
@@ -0,0 +1,104 @@
+RDMA_DEVICES=$(ls /sys/class/infiniband)
+if [ -z "$RDMA_DEVICES" ]; then
+ log "ERROR: No active RDMA devices found. Exiting script." >&2
+ exit 1
+fi
+
+# 设置RDMA设备列表 (逗号分隔)
+NCCL_IB_HCA=$(echo "$RDMA_DEVICES" | tr '\n' ',' | sed 's/,$//')
+export NCCL_IB_HCA
+echo "Detected RDMA devices: $NCCL_IB_HCA"
+
+# 获取GID_INDEX
+NCCL_IB_GID_INDEX=""
+output=$(show_gids | grep v2)
+# 遍历每一行
+while IFS= read -r line; do
+ ipv4=$(echo "$line" | awk '{print $5}')
+ # 检查IPv4地址是否有值(不是空字符串且不是全0地址)
+ if [[ -n "$ipv4" && "$ipv4" != "0000:0000:0000:0000:0000:ffff:0000:0000" && "$ipv4" =~ [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+ ]]; then
+ NCCL_IB_GID_INDEX=$(echo "$line" | awk '{print $3}')
+ # 找到第一个匹配项后立即退出循环
+ break
+ fi
+done <<<"$output"
+
+export NCCL_SOCKET_IFNAME="eth0"
+
+# 处理分布式训练需要使用到的相关环境变量
+export NCCL_IB_HCA=${NCCL_IB_HCA}
+export NCCL_IB_GID_INDEX=${NCCL_IB_GID_INDEX}
+export NCCL_NET_GDR_LEVEL=2
+# export NCCL_DEBUG_SUBSYS=ALL
+# 加速
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS
+export NCCL_IB_DISABLE=0
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME}
+
+# used for check save when communication
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000 # timeout set to 1 hour (unit: seconds)
+
+# ==== 多节点配置 ====
+# 总节点数(根据实际情况修改)
+NUM_NODES=${PET_NNODES}
+# 当前节点索引(0-based,每个节点启动时需指定不同值)
+NODE_RANK=${PET_NODE_RANK}
+# 主节点IP地址(确保所有节点可访问)
+MASTER_ADDR=${PET_MASTER_ADDR} # 替换为实际主节点IP
+# 主节点端口(保持与代码中一致)
+MASTER_PORT=${PET_MASTER_PORT}
+NUM_GPUS_PER_NODE=8
+
+cd /mnt/workspace/users/yuanzhihao/code/starVLA
+source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+
+Framework_name=QwenPerceiver
+base_vlm=./playground/Pretrained_models/Qwen3-VL-4B-Instruct
+freeze_module_list='' # just for fast debug, sota is under fully FT, i.g., freeze_module_list=""
+DIT_TYPE="DiT-B"
+data_root_dir=/mnt/workspace/datasets/robocasa_24tasks_datasets/pick_and_place_lerobot_task24_sampled_300
+data_mix=fourier_gr1_unified_1000
+
+
+run_root_dir=./outputs
+run_id=robocasa_300_id
+
+export WANDB_MODE=offline
+export WANDB_DIR=../../
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p ${output_dir}
+# mv this script to the output dir
+cp $0 ${output_dir}/
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE:-8} \
+ starVLA/training/train_starvla.py \
+ --config_yaml ./examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml \
+ --framework.name ${Framework_name} \
+ --framework.qwenvl.base_vlm ${base_vlm} \
+ --framework.action_model.action_model_type ${DIT_TYPE} \
+ --datasets.vla_data.data_root_dir ${data_root_dir} \
+ --datasets.vla_data.data_mix ${data_mix} \
+ --datasets.vla_data.per_device_batch_size 8 \
+ --trainer.freeze_modules ${freeze_module_list} \
+ --trainer.max_train_steps 100000 \
+ --trainer.save_interval 50000 \
+ --trainer.logging_frequency 50 \
+ --trainer.eval_interval 100 \
+ --trainer.learning_rate.base 3e-5 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project starVLA_robocasa \
+ --wandb_entity curryyuan \
+ 2>&1 | tee -a "${output_dir}/train.log"
+ # --is_debug True
+
+
diff --git a/examples/Robocasa_tabletop/train_files/run_yzh.sh b/examples/Robocasa_tabletop/train_files/run_yzh.sh
new file mode 100644
index 0000000000000000000000000000000000000000..ea565aed208fed664b76e14e7ba821180ac591a7
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files/run_yzh.sh
@@ -0,0 +1,114 @@
+RDMA_DEVICES=$(ls /sys/class/infiniband)
+if [ -z "$RDMA_DEVICES" ]; then
+ log "ERROR: No active RDMA devices found. Exiting script." >&2
+ exit 1
+fi
+
+# 设置RDMA设备列表 (逗号分隔)
+NCCL_IB_HCA=$(echo "$RDMA_DEVICES" | tr '\n' ',' | sed 's/,$//')
+export NCCL_IB_HCA
+echo "Detected RDMA devices: $NCCL_IB_HCA"
+
+# 获取GID_INDEX
+NCCL_IB_GID_INDEX=""
+output=$(show_gids | grep v2)
+# 遍历每一行
+while IFS= read -r line; do
+ ipv4=$(echo "$line" | awk '{print $5}')
+ # 检查IPv4地址是否有值(不是空字符串且不是全0地址)
+ if [[ -n "$ipv4" && "$ipv4" != "0000:0000:0000:0000:0000:ffff:0000:0000" && "$ipv4" =~ [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+ ]]; then
+ NCCL_IB_GID_INDEX=$(echo "$line" | awk '{print $3}')
+ # 找到第一个匹配项后立即退出循环
+ break
+ fi
+done <<<"$output"
+
+export NCCL_SOCKET_IFNAME="eth0"
+
+# 处理分布式训练需要使用到的相关环境变量
+export NCCL_IB_HCA=${NCCL_IB_HCA}
+export NCCL_IB_GID_INDEX=${NCCL_IB_GID_INDEX}
+export NCCL_NET_GDR_LEVEL=2
+# export NCCL_DEBUG_SUBSYS=ALL
+# 加速
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS
+export NCCL_IB_DISABLE=0
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME}
+
+# used for check save when communication
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000 # timeout set to 1 hour (unit: seconds)
+
+# ==== 多节点配置 ====
+# 总节点数(根据实际情况修改)
+NUM_NODES=${PET_NNODES}
+# 当前节点索引(0-based,每个节点启动时需指定不同值)
+NODE_RANK=${PET_NODE_RANK}
+# 主节点IP地址(确保所有节点可访问)
+MASTER_ADDR=${PET_MASTER_ADDR} # 替换为实际主节点IP
+# 主节点端口(保持与代码中一致)
+MASTER_PORT=${PET_MASTER_PORT}
+NUM_GPUS_PER_NODE=8
+
+source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+
+Framework_name=QwenPerceiver
+base_vlm=/mnt/workspace/users/yuanzhihao/code/starVLA/playground/Pretrained_models/Qwen3-VL-4B-Instruct
+freeze_module_list='' # just for fast debug, sota is under fully FT, i.g., freeze_module_list=""
+DIT_TYPE="DiT-B"
+data_root_dir=/mnt/workspace/datasets/
+data_mix=robocasa_merge
+pretrained_checkpoint="/mnt/workspace/users/yuanzhihao/code/starVLA/outputs/cotrain_sq_agi-beta_egodex-f/checkpoints/steps_100000_pytorch_model.pt"
+action_dim=32
+state_dim=64
+output_dim=2560
+
+run_root_dir=./outputs
+run_id=post_robocasa_pre_cotrain_sq_agi-beta_egodex-f
+
+export WANDB_MODE=offline
+export WANDB_DIR=../../
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p ${output_dir}
+# mv this script to the output dir
+cp $0 ${output_dir}/
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE:-8} \
+ starVLA/training/train_starvla.py \
+ --config_yaml ./examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml \
+ --framework.name ${Framework_name} \
+ --framework.qwenvl.base_vlm ${base_vlm} \
+ --framework.action_model.action_model_type ${DIT_TYPE} \
+ --datasets.vla_data.data_root_dir ${data_root_dir} \
+ --datasets.vla_data.data_mix ${data_mix} \
+ --datasets.vla_data.per_device_batch_size 16 \
+ --trainer.freeze_modules ${freeze_module_list} \
+ --trainer.max_train_steps 300000 \
+ --trainer.save_interval 50000 \
+ --trainer.logging_frequency 100 \
+ --trainer.eval_interval 100 \
+ --trainer.learning_rate.base 1e-4 \
+ --trainer.pretrained_checkpoint ${pretrained_checkpoint} \
+ --framework.action_model.action_dim ${action_dim} \
+ --framework.action_model.state_dim ${state_dim} \
+ --framework.action_model.hidden_size ${output_dim} \
+ --framework.action_model.diffusion_model_cfg.output_dim ${output_dim} \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project joyRA_robocasa \
+ --wandb_entity curryyuan \
+ 2>&1 | tee -a "${output_dir}/train.log"
+ # --is_debug True
+ #
+
+
+
+
diff --git a/examples/Robocasa_tabletop/train_files/run_yzh_cosmos25_perceiver.sh b/examples/Robocasa_tabletop/train_files/run_yzh_cosmos25_perceiver.sh
new file mode 100644
index 0000000000000000000000000000000000000000..49761d861bb98fa60f3dfcacc602f614eaeb81b8
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files/run_yzh_cosmos25_perceiver.sh
@@ -0,0 +1,132 @@
+#!/usr/bin/env zsh
+set -euo pipefail
+
+# Cosmos-Predict2.5 Perceiver training with eval-time future-image visualization.
+# Action training uses Cosmos hidden states + Perceiver; eval additionally runs
+# the Cosmos2.5 decoder/generation path and saves pred future images.
+
+if [ -d /sys/class/infiniband ]; then
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
+else
+ RDMA_DEVICES=""
+fi
+
+if [ -n "${RDMA_DEVICES}" ]; then
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
+ export NCCL_IB_HCA
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
+ export NCCL_IB_DISABLE=0
+ export NCCL_NET_GDR_LEVEL=2
+else
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
+ export NCCL_IB_DISABLE=1
+fi
+
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS || true
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+
+if [ -f /mnt/workspace/envs/conda3/bin/activate ]; then
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+fi
+
+NUM_GPUS_PER_NODE=${1:-1} # mytest
+
+Framework_name=CosmoPredict25PerceiverVJEPA2AC
+base_wm=/mnt/workspace/users/maxiangkai/models/Cosmos-Predict2.5-2B-Post-Trained
+cosmos_revision=${COSMOS_PREDICT25_REVISION-diffusers/base/post-trained}
+base_vlm=${base_wm}
+freeze_module_list=''
+DIT_TYPE="DiT-B"
+data_root_dir=/mnt/workspace/datasets/
+data_mix=robocasa_teleop_ee
+
+action_dim=32
+state_dim=64
+action_hidden_dim=1024
+cross_attention_dim=2048
+
+run_root_dir=/mnt/workspace/users/maxiangkai/projects/WM4A/outputs/cosmopredict25_test
+run_id=robocasa
+
+export PYTHONPATH="${PYTHONPATH}:/mnt/workspace/users/maxiangkai/projects/WM4A"
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p "${output_dir}"
+export WANDB_MODE=offline
+export WANDB_DIR="${output_dir}/wandb"
+mkdir -p "${WANDB_DIR}"
+cp "$0" "${output_dir}/"
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
+ /mnt/workspace/users/maxiangkai/projects/WM4A/starVLA/training/train_starvla.py \
+ --config_yaml /mnt/workspace/users/maxiangkai/projects/WM4A/examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr2.yaml \
+ --framework.name ${Framework_name} \
+ --framework.world_model.base_wm "${base_wm}" \
+ --framework.world_model.revision "${cosmos_revision}" \
+ --framework.world_model.extract_layers "[-1]" \
+ --framework.world_model.height 224 \
+ --framework.world_model.width 224 \
+ --framework.world_model.conditional_frame_timestep 0.1 \
+ --framework.qwenvl.base_vlm "${base_vlm}" \
+ --framework.qwenvl.vl_hidden_dim 2048 \
+ --framework.action_model.action_model_type ${DIT_TYPE} \
+ --framework.action_model.action_dim ${action_dim} \
+ --framework.action_model.state_dim ${state_dim} \
+ --framework.action_model.action_hidden_dim ${action_hidden_dim} \
+ --framework.action_model.hidden_size ${action_hidden_dim} \
+ --framework.action_model.diffusion_model_cfg.cross_attention_dim ${cross_attention_dim} \
+ --framework.action_model.diffusion_model_cfg.output_dim ${action_hidden_dim} \
+ --framework.vjepa2_ac.repo_dir /mnt/workspace/users/maxiangkai/projects/WM4A/starVLA/facebookresearch_vjepa2_main \
+ --framework.vjepa2_ac.pretrained /mnt/workspace/users/maxiangkai/models/VJEPA2-AC/vjepa2-ac-vitg.pt \
+ --framework.future_latent_training.enabled true \
+ --framework.future_latent_training.loss_weight 0.02 \
+ --framework.future_latent_training.train_time_distribution logitnormal \
+ --framework.future_latent_training.shift 5.0 \
+ --framework.future_image_training.enabled true \
+ --framework.future_image_training.loss_weight 1.0 \
+ --framework.future_image_training.train_time_distribution logitnormal \
+ --framework.future_image_training.shift 5.0 \
+ --framework.future_image_generation.enabled true \
+ --framework.future_image_generation.conditioning_mode auto \
+ --framework.future_image_generation.max_samples 1 \
+ --framework.future_image_generation.height 224 \
+ --framework.future_image_generation.width 224 \
+ --framework.future_image_generation.num_frames 93 \
+ --framework.future_image_generation.num_inference_steps 20 \
+ --framework.future_image_generation.guidance_scale 7.0 \
+ --framework.future_image_generation.output_type pil \
+ --framework.future_image_generation.future_frame_index -1 \
+ --framework.future_image_generation.return_full_video false \
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
+ --datasets.vla_data.data_mix "${data_mix}" \
+ --datasets.vla_data.include_state true \
+ --datasets.vla_data.per_device_batch_size 16 \
+ --trainer.freeze_modules "${freeze_module_list}" \
+ --trainer.max_train_steps 200000 \
+ --trainer.save_interval 20000 \
+ --trainer.logging_frequency 500 \
+ --trainer.eval_interval 500 \
+ --trainer.num_warmup_steps 2000 \
+ --trainer.learning_rate.base 1e-5 \
+ --trainer.learning_rate.action_model 5e-5 \
+ --trainer.learning_rate.vjepa_predictor 5e-5 \
+ --trainer.learning_rate.state_projector 5e-5 \
+ --trainer.learning_rate.action_projector 5e-5 \
+ --trainer.scheduler_specific_kwargs.min_lr 2e-7 \
+ --trainer.optimizer.betas "[0.9,0.999]" \
+ --trainer.optimizer.weight_decay 0.1 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project joyRA_robocasa_mxk \
+ --wandb_entity mxk \
+ 2>&1 | tee -a "${output_dir}/train.log"
diff --git a/examples/Robocasa_tabletop/train_files/run_yzh_cosmos25_perceiver_dino.sh b/examples/Robocasa_tabletop/train_files/run_yzh_cosmos25_perceiver_dino.sh
new file mode 100644
index 0000000000000000000000000000000000000000..4234042afe7b988b44dd04f2440bb9767b118db3
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files/run_yzh_cosmos25_perceiver_dino.sh
@@ -0,0 +1,133 @@
+#!/usr/bin/env zsh
+set -euo pipefail
+
+# Cosmos-Predict2.5 Perceiver + DINOv3 training with eval-time future-image visualization.
+# Action training uses Cosmos hidden states + Perceiver; eval additionally runs
+# the Cosmos2.5 decoder/generation path and saves pred future images.
+# DINOv3 encoder is frozen, DINO predictor is kaiming-initialized from scratch.
+
+if [ -d /sys/class/infiniband ]; then
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
+else
+ RDMA_DEVICES=""
+fi
+
+if [ -n "${RDMA_DEVICES}" ]; then
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
+ export NCCL_IB_HCA
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
+ export NCCL_IB_DISABLE=0
+ export NCCL_NET_GDR_LEVEL=2
+else
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
+ export NCCL_IB_DISABLE=1
+fi
+
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS || true
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+
+if [ -f /mnt/workspace/envs/conda3/bin/activate ]; then
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+fi
+
+NUM_GPUS_PER_NODE=${1:-8} # mytest
+
+Framework_name=CosmoPredict25PerceiverDINO
+base_wm=/mnt/workspace/users/maxiangkai/models/Cosmos-Predict2.5-2B-Post-Trained
+cosmos_revision=${COSMOS_PREDICT25_REVISION-diffusers/base/post-trained}
+base_vlm=${base_wm}
+freeze_module_list=''
+DIT_TYPE="DiT-B"
+data_root_dir=/mnt/workspace/datasets/
+data_mix=robocasa_teleop_ee
+
+action_dim=32
+state_dim=64
+action_hidden_dim=1024
+cross_attention_dim=2048
+
+run_root_dir=/mnt/workspace/users/maxiangkai/projects/WM4A/outputs/cosmopredict25_dino1.0
+run_id=robocasa
+
+export PYTHONPATH="${PYTHONPATH}:/mnt/workspace/users/maxiangkai/projects/WM4A:/mnt/workspace/users/maxiangkai/projects/WM4A/starVLA/facebookresearch_vjepa2_main"
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p "${output_dir}"
+export WANDB_MODE=offline
+export WANDB_DIR="${output_dir}/wandb"
+mkdir -p "${WANDB_DIR}"
+cp "$0" "${output_dir}/"
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
+ /mnt/workspace/users/maxiangkai/projects/WM4A/starVLA/training/train_starvla.py \
+ --config_yaml /mnt/workspace/users/maxiangkai/projects/WM4A/examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr2.yaml \
+ --framework.name ${Framework_name} \
+ --framework.world_model.base_wm "${base_wm}" \
+ --framework.world_model.revision "${cosmos_revision}" \
+ --framework.world_model.extract_layers "[-1]" \
+ --framework.world_model.height 224 \
+ --framework.world_model.width 224 \
+ --framework.world_model.conditional_frame_timestep 0.1 \
+ --framework.qwenvl.base_vlm "${base_vlm}" \
+ --framework.qwenvl.vl_hidden_dim 2048 \
+ --framework.action_model.action_model_type ${DIT_TYPE} \
+ --framework.action_model.action_dim ${action_dim} \
+ --framework.action_model.state_dim ${state_dim} \
+ --framework.action_model.action_hidden_dim ${action_hidden_dim} \
+ --framework.action_model.hidden_size ${action_hidden_dim} \
+ --framework.action_model.diffusion_model_cfg.cross_attention_dim ${cross_attention_dim} \
+ --framework.action_model.diffusion_model_cfg.output_dim ${action_hidden_dim} \
+ --framework.dinov3.repo_dir /mnt/workspace/users/maxiangkai/projects/WM4A/starVLA/dinov3 \
+ --framework.dinov3.pretrained /mnt/workspace/users/maxiangkai/models/dinov3-vith16plus-pretrain-lvd1689m \
+ --framework.future_latent_training.enabled true \
+ --framework.future_latent_training.loss_weight 1.0 \
+ --framework.future_latent_training.train_time_distribution logitnormal \
+ --framework.future_latent_training.shift 5.0 \
+ --framework.future_image_training.enabled false \
+ --framework.future_image_training.loss_weight 1.0 \
+ --framework.future_image_training.train_time_distribution logitnormal \
+ --framework.future_image_training.shift 5.0 \
+ --framework.future_image_generation.enabled false \
+ --framework.future_image_generation.conditioning_mode auto \
+ --framework.future_image_generation.max_samples 1 \
+ --framework.future_image_generation.height 224 \
+ --framework.future_image_generation.width 224 \
+ --framework.future_image_generation.num_frames 93 \
+ --framework.future_image_generation.num_inference_steps 20 \
+ --framework.future_image_generation.guidance_scale 7.0 \
+ --framework.future_image_generation.output_type pil \
+ --framework.future_image_generation.future_frame_index -1 \
+ --framework.future_image_generation.return_full_video false \
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
+ --datasets.vla_data.data_mix "${data_mix}" \
+ --datasets.vla_data.include_state true \
+ --datasets.vla_data.per_device_batch_size 32 \
+ --trainer.freeze_modules "${freeze_module_list}" \
+ --trainer.max_train_steps 100000 \
+ --trainer.save_interval 5000 \
+ --trainer.logging_frequency 200 \
+ --trainer.eval_interval 200 \
+ --trainer.num_warmup_steps 1000 \
+ --trainer.learning_rate.base 1e-5 \
+ --trainer.learning_rate.action_model 5e-5 \
+ --trainer.learning_rate.dino_predictor 5e-5 \
+ --trainer.learning_rate.state_projector 5e-5 \
+ --trainer.learning_rate.action_projector 5e-5 \
+ --trainer.scheduler_specific_kwargs.min_lr 5e-7 \
+ --trainer.optimizer.betas "[0.9,0.999]" \
+ --trainer.optimizer.weight_decay 0.1 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project joyRA_robocasa_mxk \
+ --wandb_entity mxk \
+ 2>&1 | tee -a "${output_dir}/train.log"
\ No newline at end of file
diff --git a/examples/Robocasa_tabletop/train_files/run_yzh_cosmos25_perceiver_dino_resume.sh b/examples/Robocasa_tabletop/train_files/run_yzh_cosmos25_perceiver_dino_resume.sh
new file mode 100644
index 0000000000000000000000000000000000000000..d97f3325b8aa492103a0301816a8d7c6f71ff04f
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files/run_yzh_cosmos25_perceiver_dino_resume.sh
@@ -0,0 +1,146 @@
+#!/usr/bin/env zsh
+set -euo pipefail
+
+# Cosmos-Predict2.5 Perceiver + DINOv3 resume training with eval-time future-image visualization.
+# Action training uses Cosmos hidden states + Perceiver; eval additionally runs
+# the Cosmos2.5 decoder/generation path and saves pred future images.
+# DINOv3 encoder is frozen, DINO predictor is kaiming-initialized from scratch.
+#
+# This script resumes training from a specific checkpoint with adjusted parameters:
+# - Loads 10000-step checkpoint from the original training run
+# - Sets max_train_steps to 100000
+# - Reduces future_latent_training.loss_weight from 0.05 to 0.005
+# - Outputs to a timestamped directory (robocasa_dino_MM-DD-HH-MM)
+
+if [ -d /sys/class/infiniband ]; then
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
+else
+ RDMA_DEVICES=""
+fi
+
+if [ -n "${RDMA_DEVICES}" ]; then
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
+ export NCCL_IB_HCA
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
+ export NCCL_IB_DISABLE=0
+ export NCCL_NET_GDR_LEVEL=2
+else
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
+ export NCCL_IB_DISABLE=1
+fi
+
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS || true
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+
+if [ -f /mnt/workspace/envs/conda3/bin/activate ]; then
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+fi
+
+NUM_GPUS_PER_NODE=${1:-8} # mytest
+
+Framework_name=CosmoPredict25PerceiverDINO
+base_wm=/mnt/workspace/users/maxiangkai/models/Cosmos-Predict2.5-2B-Post-Trained
+cosmos_revision=${COSMOS_PREDICT25_REVISION-diffusers/base/post-trained}
+base_vlm=${base_wm}
+freeze_module_list=''
+DIT_TYPE="DiT-B"
+data_root_dir=/mnt/workspace/datasets/
+data_mix=robocasa_teleop_ee
+
+action_dim=32
+state_dim=64
+action_hidden_dim=1024
+cross_attention_dim=2048
+
+# Resume checkpoint from the original training run
+resume_checkpoint=/mnt/workspace/users/maxiangkai/projects/WM4A/outputs/cosmopredict25_dino/robocasa_dino/checkpoints/steps_10000_pytorch_model.pt
+
+run_root_dir=/mnt/workspace/users/maxiangkai/projects/WM4A/outputs/cosmopredict25_dino
+# Timestamp in Shanghai time: MM-DD-HH-MM
+timestamp=$(TZ='Asia/Shanghai' date +%m-%d-%H-%M)
+run_id=robocasa_dino_${timestamp}
+
+export PYTHONPATH="${PYTHONPATH}:/mnt/workspace/users/maxiangkai/projects/WM4A:/mnt/workspace/users/maxiangkai/projects/WM4A/starVLA/facebookresearch_vjepa2_main"
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p "${output_dir}"
+export WANDB_MODE=offline
+export WANDB_DIR="${output_dir}/wandb"
+mkdir -p "${WANDB_DIR}"
+cp "$0" "${output_dir}/"
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-38500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
+ /mnt/workspace/users/maxiangkai/projects/WM4A/starVLA/training/train_starvla.py \
+ --config_yaml /mnt/workspace/users/maxiangkai/projects/WM4A/examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr2.yaml \
+ --framework.name ${Framework_name} \
+ --framework.world_model.base_wm "${base_wm}" \
+ --framework.world_model.revision "${cosmos_revision}" \
+ --framework.world_model.extract_layers "[-1]" \
+ --framework.world_model.height 224 \
+ --framework.world_model.width 224 \
+ --framework.world_model.conditional_frame_timestep 0.1 \
+ --framework.qwenvl.base_vlm "${base_vlm}" \
+ --framework.qwenvl.vl_hidden_dim 2048 \
+ --framework.action_model.action_model_type ${DIT_TYPE} \
+ --framework.action_model.action_dim ${action_dim} \
+ --framework.action_model.state_dim ${state_dim} \
+ --framework.action_model.action_hidden_dim ${action_hidden_dim} \
+ --framework.action_model.hidden_size ${action_hidden_dim} \
+ --framework.action_model.diffusion_model_cfg.cross_attention_dim ${cross_attention_dim} \
+ --framework.action_model.diffusion_model_cfg.output_dim ${action_hidden_dim} \
+ --framework.dinov3.repo_dir /mnt/workspace/users/maxiangkai/projects/WM4A/starVLA/dinov3 \
+ --framework.dinov3.pretrained /mnt/workspace/users/maxiangkai/models/dinov3-vith16plus-pretrain-lvd1689m \
+ --framework.future_latent_training.enabled true \
+ --framework.future_latent_training.loss_weight 0.1 \
+ --framework.future_latent_training.train_time_distribution logitnormal \
+ --framework.future_latent_training.shift 5.0 \
+ --framework.future_image_training.enabled false \
+ --framework.future_image_training.loss_weight 1.0 \
+ --framework.future_image_training.train_time_distribution logitnormal \
+ --framework.future_image_training.shift 5.0 \
+ --framework.future_image_generation.enabled false \
+ --framework.future_image_generation.conditioning_mode auto \
+ --framework.future_image_generation.max_samples 1 \
+ --framework.future_image_generation.height 224 \
+ --framework.future_image_generation.width 224 \
+ --framework.future_image_generation.num_frames 93 \
+ --framework.future_image_generation.num_inference_steps 20 \
+ --framework.future_image_generation.guidance_scale 7.0 \
+ --framework.future_image_generation.output_type pil \
+ --framework.future_image_generation.future_frame_index -1 \
+ --framework.future_image_generation.return_full_video false \
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
+ --datasets.vla_data.data_mix "${data_mix}" \
+ --datasets.vla_data.include_state true \
+ --datasets.vla_data.per_device_batch_size 32 \
+ --trainer.freeze_modules "${freeze_module_list}" \
+ --trainer.is_resume true \
+ --trainer.pretrained_checkpoint "${resume_checkpoint}" \
+ --trainer.max_train_steps 100000 \
+ --trainer.save_interval 5000 \
+ --trainer.logging_frequency 200 \
+ --trainer.eval_interval 200 \
+ --trainer.num_warmup_steps 1000 \
+ --trainer.learning_rate.base 1e-5 \
+ --trainer.learning_rate.action_model 2e-5 \
+ --trainer.learning_rate.dino_predictor 2e-5 \
+ --trainer.learning_rate.state_projector 2e-5 \
+ --trainer.learning_rate.action_projector 2e-5 \
+ --trainer.scheduler_specific_kwargs.min_lr 2e-7 \
+ --trainer.optimizer.betas "[0.9,0.999]" \
+ --trainer.optimizer.weight_decay 0.1 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project joyRA_robocasa_mxk \
+ --wandb_entity mxk \
+ 2>&1 | tee -a "${output_dir}/train.log"
\ No newline at end of file
diff --git a/examples/Robocasa_tabletop/train_files/run_yzh_cosmos25_perceiver_future_image.sh b/examples/Robocasa_tabletop/train_files/run_yzh_cosmos25_perceiver_future_image.sh
new file mode 100644
index 0000000000000000000000000000000000000000..05e9ccf413938c3dafd1a9572dd7a16b88d60a63
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files/run_yzh_cosmos25_perceiver_future_image.sh
@@ -0,0 +1,120 @@
+#!/usr/bin/env zsh
+set -euo pipefail
+
+# Cosmos-Predict2.5 Perceiver training with eval-time future-image visualization.
+# Action training uses Cosmos hidden states + Perceiver; eval additionally runs
+# the Cosmos2.5 decoder/generation path and saves pred future images.
+
+if [ -d /sys/class/infiniband ]; then
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
+else
+ RDMA_DEVICES=""
+fi
+
+if [ -n "${RDMA_DEVICES}" ]; then
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
+ export NCCL_IB_HCA
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
+ export NCCL_IB_DISABLE=0
+ export NCCL_NET_GDR_LEVEL=2
+else
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
+ export NCCL_IB_DISABLE=1
+fi
+
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS || true
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+
+if [ -f /mnt/workspace/envs/conda3/bin/activate ]; then
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+fi
+
+NUM_GPUS_PER_NODE=${1:-1} # mytest
+
+Framework_name=CosmoPredict25PerceiverFutureImage
+base_wm=/mnt/workspace/users/yuanzhihao/code/starVLA/playground/Pretrained_models/Cosmos-Predict2.5-2B-Post-Trained
+cosmos_revision=${COSMOS_PREDICT25_REVISION-diffusers/base/post-trained}
+base_vlm=${base_wm}
+freeze_module_list=''
+DIT_TYPE="DiT-B"
+data_root_dir=/mnt/workspace/datasets/
+data_mix=robocasa_teleop_ee
+
+action_dim=32
+state_dim=64
+action_hidden_dim=1024
+cross_attention_dim=2048
+
+run_root_dir=./outputs/cosmopredict25_perceiver_future_image
+run_id=robocasa
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p "${output_dir}"
+export WANDB_MODE=offline
+export WANDB_DIR="${output_dir}/wandb"
+mkdir -p "${WANDB_DIR}"
+cp "$0" "${output_dir}/"
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
+ starVLA/training/train_starvla.py \
+ --config_yaml ./examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml \
+ --framework.name ${Framework_name} \
+ --framework.world_model.base_wm "${base_wm}" \
+ --framework.world_model.revision "${cosmos_revision}" \
+ --framework.world_model.extract_layers "[-1]" \
+ --framework.world_model.height 224 \
+ --framework.world_model.width 224 \
+ --framework.world_model.conditional_frame_timestep 0.1 \
+ --framework.qwenvl.base_vlm "${base_vlm}" \
+ --framework.qwenvl.vl_hidden_dim 2048 \
+ --framework.action_model.action_model_type ${DIT_TYPE} \
+ --framework.action_model.action_dim ${action_dim} \
+ --framework.action_model.state_dim ${state_dim} \
+ --framework.action_model.action_hidden_dim ${action_hidden_dim} \
+ --framework.action_model.hidden_size ${action_hidden_dim} \
+ --framework.action_model.diffusion_model_cfg.cross_attention_dim ${cross_attention_dim} \
+ --framework.action_model.diffusion_model_cfg.output_dim ${action_hidden_dim} \
+ --framework.future_image_training.enabled true \
+ --framework.future_image_training.loss_weight 1.0 \
+ --framework.future_image_training.train_time_distribution logitnormal \
+ --framework.future_image_training.shift 5.0 \
+ --framework.future_image_generation.enabled true \
+ --framework.future_image_generation.conditioning_mode auto \
+ --framework.future_image_generation.max_samples 1 \
+ --framework.future_image_generation.height 224 \
+ --framework.future_image_generation.width 224 \
+ --framework.future_image_generation.num_frames 93 \
+ --framework.future_image_generation.num_inference_steps 20 \
+ --framework.future_image_generation.guidance_scale 7.0 \
+ --framework.future_image_generation.output_type pil \
+ --framework.future_image_generation.future_frame_index -1 \
+ --framework.future_image_generation.return_full_video false \
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
+ --datasets.vla_data.data_mix "${data_mix}" \
+ --datasets.vla_data.include_state true \
+ --datasets.vla_data.per_device_batch_size 8 \
+ --trainer.freeze_modules "${freeze_module_list}" \
+ --trainer.max_train_steps 300000 \
+ --trainer.save_interval 10000 \
+ --trainer.logging_frequency 200 \
+ --trainer.eval_interval 200 \
+ --trainer.num_warmup_steps 1000 \
+ --trainer.learning_rate.base 1e-5 \
+ --trainer.scheduler_specific_kwargs.min_lr 1.2e-6 \
+ --trainer.optimizer.betas "[0.9,0.999]" \
+ --trainer.optimizer.weight_decay 0.1 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project joyRA_robocasa_mxk \
+ --wandb_entity mxk \
+ 2>&1 | tee -a "${output_dir}/train.log"
diff --git a/examples/Robocasa_tabletop/train_files/run_yzh_cosmos25_perceiver_vjepa2_ac.sh b/examples/Robocasa_tabletop/train_files/run_yzh_cosmos25_perceiver_vjepa2_ac.sh
new file mode 100644
index 0000000000000000000000000000000000000000..2482495336a4e57b3251ac467b9a46cd5baf0078
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files/run_yzh_cosmos25_perceiver_vjepa2_ac.sh
@@ -0,0 +1,137 @@
+#!/usr/bin/env zsh
+set -euo pipefail
+
+# Cosmos-Predict2.5 Perceiver training with eval-time future-image visualization.
+# Action training uses Cosmos hidden states + Perceiver; eval additionally runs
+# the Cosmos2.5 decoder/generation path and saves pred future images.
+
+if [ -d /sys/class/infiniband ]; then
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
+else
+ RDMA_DEVICES=""
+fi
+
+if [ -n "${RDMA_DEVICES}" ]; then
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
+ export NCCL_IB_HCA
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
+ export NCCL_IB_DISABLE=0
+ export NCCL_NET_GDR_LEVEL=2
+else
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
+ export NCCL_IB_DISABLE=1
+fi
+
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS || true
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+
+cd /mnt/workspace/users/maxiangkai/projects/WM4A
+if [ -f /mnt/workspace/envs/conda3/bin/activate ]; then
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+fi
+
+NUM_GPUS_PER_NODE=${1:-8} # mytest
+
+Framework_name=CosmoPredict25PerceiverVJEPA2AC
+base_wm=/mnt/workspace/users/maxiangkai/models/Cosmos-Predict2.5-2B-Post-Trained
+cosmos_revision=${COSMOS_PREDICT25_REVISION-diffusers/base/post-trained}
+base_vlm=${base_wm}
+freeze_module_list=''
+config_yaml=/mnt/workspace/users/maxiangkai/projects/WM4A/examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml
+DIT_TYPE="DiT-B"
+data_root_dir=/mnt/workspace/datasets/
+data_mix=robocasa_teleop_ee
+
+action_dim=32
+state_dim=64
+action_hidden_dim=1024
+cross_attention_dim=2048
+
+run_root_dir=/mnt/workspace/users/maxiangkai/projects/WM4A/outputs/cosmopredict25_vjepa_ImageLatent
+run_id=robocasa_testest
+
+export PYTHONPATH="${PYTHONPATH}:/mnt/workspace/users/maxiangkai/projects/WM4A"
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p "${output_dir}"
+export WANDB_MODE=offline
+export WANDB_DIR="${output_dir}/wandb"
+mkdir -p "${WANDB_DIR}"
+cp "$0" "${output_dir}/"
+cp ${config_yaml} ${output_dir}
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
+ starVLA/training/train_starvla_zero2.py \
+ --config_yaml examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr2.yaml \
+ --framework.name ${Framework_name} \
+ --framework.world_model.base_wm "${base_wm}" \
+ --framework.world_model.revision "${cosmos_revision}" \
+ --framework.world_model.extract_layers "[-1]" \
+ --framework.world_model.height 224 \
+ --framework.world_model.width 224 \
+ --framework.world_model.conditional_frame_timestep 0.1 \
+ --framework.qwenvl.base_vlm "${base_vlm}" \
+ --framework.qwenvl.vl_hidden_dim 2048 \
+ --framework.action_model.action_model_type ${DIT_TYPE} \
+ --framework.action_model.action_dim ${action_dim} \
+ --framework.action_model.state_dim ${state_dim} \
+ --framework.action_model.action_hidden_dim ${action_hidden_dim} \
+ --framework.action_model.hidden_size ${action_hidden_dim} \
+ --framework.action_model.diffusion_model_cfg.cross_attention_dim ${cross_attention_dim} \
+ --framework.action_model.diffusion_model_cfg.output_dim ${action_hidden_dim} \
+ --framework.action_model.num_target_vision_tokens 64 \
+ --framework.vjepa2_ac.repo_dir /mnt/workspace/users/maxiangkai/projects/WM4A/starVLA/facebookresearch_vjepa2_main \
+ --framework.vjepa2_ac.pretrained /mnt/workspace/users/maxiangkai/models/VJEPA2-AC/vjepa2-ac-vitg.pt \
+ --framework.future_latent_training.enabled true \
+ --framework.future_latent_training.loss_weight 0.1 \
+ --framework.future_latent_training.train_time_distribution logitnormal \
+ --framework.future_latent_training.shift 5.0 \
+ --framework.future_image_training.enabled true \
+ --framework.future_image_training.loss_weight 1.0 \
+ --framework.future_image_training.train_time_distribution logitnormal \
+ --framework.future_image_training.shift 5.0 \
+ --framework.future_image_generation.enabled true \
+ --framework.future_image_generation.conditioning_mode auto \
+ --framework.future_image_generation.max_samples 1 \
+ --framework.future_image_generation.height 224 \
+ --framework.future_image_generation.width 224 \
+ --framework.future_image_generation.num_frames 93 \
+ --framework.future_image_generation.num_inference_steps 20 \
+ --framework.future_image_generation.guidance_scale 7.0 \
+ --framework.future_image_generation.output_type pil \
+ --framework.future_image_generation.future_frame_index -1 \
+ --framework.future_image_generation.return_full_video false \
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
+ --datasets.vla_data.data_mix "${data_mix}" \
+ --datasets.vla_data.include_state true \
+ --datasets.vla_data.per_device_batch_size 12 \
+ --datasets.vla_data.video_backend decord \
+ --trainer.freeze_modules "${freeze_module_list}" \
+ --trainer.max_train_steps 200000 \
+ --trainer.save_interval 20000 \
+ --trainer.logging_frequency 500 \
+ --trainer.eval_interval 500 \
+ --trainer.num_warmup_steps 2000 \
+ --trainer.learning_rate.base 1e-5 \
+ --trainer.learning_rate.action_model 1.5e-5 \
+ --trainer.learning_rate.vjepa_predictor 1.5e-5 \
+ --trainer.learning_rate.state_projector 1.5e-5 \
+ --trainer.learning_rate.action_projector 1.5e-5 \
+ --trainer.scheduler_specific_kwargs.min_lr 1.5e-7 \
+ --trainer.optimizer.betas "[0.9,0.999]" \
+ --trainer.optimizer.weight_decay 0.1 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project joyRA_robocasa_mxk \
+ --wandb_entity mxk \
+ 2>&1 | tee -a "${output_dir}/train.log"
diff --git a/examples/Robocasa_tabletop/train_files/run_yzh_cosmos25_perceiver_vjepa2_ac_resume.sh b/examples/Robocasa_tabletop/train_files/run_yzh_cosmos25_perceiver_vjepa2_ac_resume.sh
new file mode 100644
index 0000000000000000000000000000000000000000..1b93eeaf206ef087f8f43a7e49870f8d06809273
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files/run_yzh_cosmos25_perceiver_vjepa2_ac_resume.sh
@@ -0,0 +1,146 @@
+#!/usr/bin/env zsh
+set -euo pipefail
+
+# Cosmos-Predict2.5 Perceiver training with eval-time future-image visualization.
+# Action training uses Cosmos hidden states + Perceiver; eval additionally runs
+# the Cosmos2.5 decoder/generation path and saves pred future images.
+#
+# This script resumes training from a specific checkpoint with adjusted parameters:
+# - Loads 25000-step checkpoint from the original training run
+# - Sets max_train_steps to 50000 (so LR decays from ~0.984e-4 to min_lr 1.2e-6)
+# - Reduces future_latent_training.loss_weight from 0.1 to 0.05
+# - Outputs to a timestamped directory (robocasa_MM-DD-HH-MM)
+
+if [ -d /sys/class/infiniband ]; then
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
+else
+ RDMA_DEVICES=""
+fi
+
+if [ -n "${RDMA_DEVICES}" ]; then
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
+ export NCCL_IB_HCA
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
+ export NCCL_IB_DISABLE=0
+ export NCCL_NET_GDR_LEVEL=2
+else
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
+ export NCCL_IB_DISABLE=1
+fi
+
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS || true
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+
+if [ -f /mnt/workspace/envs/conda3/bin/activate ]; then
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+fi
+
+NUM_GPUS_PER_NODE=${1:-2} # mytest
+
+Framework_name=CosmoPredict25PerceiverVJEPA2AC
+base_wm=/mnt/workspace/users/maxiangkai/models/Cosmos-Predict2.5-2B-Post-Trained
+cosmos_revision=${COSMOS_PREDICT25_REVISION-diffusers/base/post-trained}
+base_vlm=${base_wm}
+freeze_module_list=''
+DIT_TYPE="DiT-B"
+data_root_dir=/mnt/workspace/datasets/
+data_mix=robocasa_teleop_ee
+
+action_dim=32
+state_dim=64
+action_hidden_dim=1024
+cross_attention_dim=2048
+
+run_root_dir=/mnt/workspace/users/maxiangkai/projects/WM4A/outputs/cosmopredict25_vjepa_ImageLatent
+timestamp=$(TZ='Asia/Shanghai' date +%m-%d-%H-%M)
+run_id=robocasa_${timestamp}
+resume_checkpoint=/mnt/workspace/users/maxiangkai/projects/WM4A/outputs/cosmopredict25_vjepa_ImageLatent/robocasa_06-26-16-51/checkpoints/steps_180000_pytorch_model.pt
+# resume_checkpoint=/mnt/workspace/users/maxiangkai/projects/WM4A/outputs/cosmopredict25_vjepa_ImageLatent/robocasa_06-28-13-10/checkpoints/steps_280000_pytorch_model.pt
+
+export PYTHONPATH="${PYTHONPATH}:/mnt/workspace/users/maxiangkai/projects/WM4A"
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p "${output_dir}"
+export WANDB_MODE=offline
+export WANDB_DIR="${output_dir}/wandb"
+mkdir -p "${WANDB_DIR}"
+cp "$0" "${output_dir}/"
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-38500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
+ /mnt/workspace/users/maxiangkai/projects/WM4A/starVLA/training/train_starvla_zero2.py \
+ --config_yaml /mnt/workspace/users/maxiangkai/projects/WM4A/examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr2.yaml \
+ --framework.name ${Framework_name} \
+ --framework.world_model.base_wm "${base_wm}" \
+ --framework.world_model.revision "${cosmos_revision}" \
+ --framework.world_model.extract_layers "[-1]" \
+ --framework.world_model.height 224 \
+ --framework.world_model.width 224 \
+ --framework.world_model.conditional_frame_timestep 0.1 \
+ --framework.qwenvl.base_vlm "${base_vlm}" \
+ --framework.qwenvl.vl_hidden_dim 2048 \
+ --framework.action_model.action_model_type ${DIT_TYPE} \
+ --framework.action_model.action_dim ${action_dim} \
+ --framework.action_model.state_dim ${state_dim} \
+ --framework.action_model.action_hidden_dim ${action_hidden_dim} \
+ --framework.action_model.hidden_size ${action_hidden_dim} \
+ --framework.action_model.diffusion_model_cfg.cross_attention_dim ${cross_attention_dim} \
+ --framework.action_model.diffusion_model_cfg.output_dim ${action_hidden_dim} \
+ --framework.vjepa2_ac.repo_dir /mnt/workspace/users/maxiangkai/projects/WM4A/starVLA/facebookresearch_vjepa2_main \
+ --framework.vjepa2_ac.pretrained /mnt/workspace/users/maxiangkai/models/VJEPA2-AC/vjepa2-ac-vitg.pt \
+ --framework.future_latent_training.enabled true \
+ --framework.future_latent_training.loss_weight 0.1 \
+ --framework.future_latent_training.train_time_distribution logitnormal \
+ --framework.future_latent_training.shift 5.0 \
+ --framework.future_image_training.enabled true \
+ --framework.future_image_training.loss_weight 1.0 \
+ --framework.future_image_training.train_time_distribution logitnormal \
+ --framework.future_image_training.shift 5.0 \
+ --framework.future_image_generation.enabled true \
+ --framework.future_image_generation.conditioning_mode auto \
+ --framework.future_image_generation.max_samples 8 \
+ --framework.future_image_generation.height 224 \
+ --framework.future_image_generation.width 224 \
+ --framework.future_image_generation.num_frames 9 \
+ --framework.future_image_generation.num_inference_steps 20 \
+ --framework.future_image_generation.guidance_scale 5.0 \
+ --framework.future_image_generation.output_type pil \
+ --framework.future_image_generation.future_frame_index -1 \
+ --framework.future_image_generation.num_latent_conditional_frames 1 \
+ --framework.future_image_generation.return_full_video false \
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
+ --datasets.vla_data.data_mix "${data_mix}" \
+ --datasets.vla_data.include_state true \
+ --datasets.vla_data.per_device_batch_size 8 \
+ --datasets.vla_data.video_backend decord \
+ --trainer.freeze_modules "${freeze_module_list}" \
+ --trainer.is_resume true \
+ --trainer.pretrained_checkpoint "${resume_checkpoint}" \
+ --trainer.max_train_steps 300000 \
+ --trainer.save_interval 20000 \
+ --trainer.logging_frequency 1 \
+ --trainer.eval_interval 5 \
+ --trainer.num_warmup_steps 2000 \
+ --trainer.learning_rate.base 1e-5 \
+ --trainer.learning_rate.action_model 1.5e-5 \
+ --trainer.learning_rate.vjepa_predictor 1.5e-5 \
+ --trainer.learning_rate.state_projector 1.5e-5 \
+ --trainer.learning_rate.action_projector 1.5e-5 \
+ --trainer.scheduler_specific_kwargs.min_lr 1e-7 \
+ --trainer.optimizer.betas "[0.9,0.999]" \
+ --trainer.optimizer.weight_decay 0.1 \
+ --trainer.gradient_accumulation_steps 24 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project joyRA_robocasa_mxk \
+ --wandb_entity mxk \
+ 2>&1 | tee -a "${output_dir}/train.log"
\ No newline at end of file
diff --git a/examples/Robocasa_tabletop/train_files/run_yzh_cosmos25_perceiver_vjepa2_ac_resume_back.sh b/examples/Robocasa_tabletop/train_files/run_yzh_cosmos25_perceiver_vjepa2_ac_resume_back.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b6f3baf0d58351d3fb52f8daa38cadcb7747e7e2
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files/run_yzh_cosmos25_perceiver_vjepa2_ac_resume_back.sh
@@ -0,0 +1,38 @@
+#!/bin/bash
+
+EVAL_SCRIPT="$(cd "$(dirname "$0")" && pwd)/run_yzh_cosmos25_perceiver_vjepa2_ac_resume.sh"
+LOG_FILE="/mnt/workspace/users/maxiangkai/projects/WM4A/outputs/cosmopredict25_vjepa_ImageLatent/train_back_$(date +%Y%m%d_%H%M%S).log"
+mkdir -p "$(dirname "${LOG_FILE}")"
+
+if [ ! -f "${EVAL_SCRIPT}" ]; then
+ echo "ERROR: cannot find ${EVAL_SCRIPT}" >&2; exit 1
+fi
+
+nohup setsid bash "${EVAL_SCRIPT}" "$@" >"${LOG_FILE}" 2>&1 &
+EVAL_PID=$!
+disown "${EVAL_PID}" 2>/dev/null || true
+sleep 1
+
+ABS_LOG_FILE="$(cd "$(dirname "${LOG_FILE}")" && pwd)/$(basename "${LOG_FILE}")"
+
+cat </dev/null; echo ""; echo "Detached from log. Eval PID=${EVAL_PID} still running."; echo " Re-attach: tail -F ${ABS_LOG_FILE}"; exit 0' INT
+wait "${TAIL_PID}"
\ No newline at end of file
diff --git a/examples/Robocasa_tabletop/train_files/run_yzh_cosmos25_policy_fm.sh b/examples/Robocasa_tabletop/train_files/run_yzh_cosmos25_policy_fm.sh
new file mode 100644
index 0000000000000000000000000000000000000000..49de3977fda0f15c0e1d162b0c5b1583c36373c9
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files/run_yzh_cosmos25_policy_fm.sh
@@ -0,0 +1,99 @@
+#!/usr/bin/env zsh
+set -euo pipefail
+
+# Cosmos-Predict2.5 Policy training, aligned with the official RF/FM recipe:
+# action/future latent frames are trained as velocity targets.
+
+if [ -d /sys/class/infiniband ]; then
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
+else
+ RDMA_DEVICES=""
+fi
+
+if [ -n "${RDMA_DEVICES}" ]; then
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
+ export NCCL_IB_HCA
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
+ export NCCL_IB_DISABLE=0
+ export NCCL_NET_GDR_LEVEL=2
+else
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
+ export NCCL_IB_DISABLE=1
+fi
+
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS || true
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+
+if [ -f /mnt/workspace/envs/conda3/bin/activate ]; then
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+fi
+
+NUM_GPUS_PER_NODE=${1:-8}
+
+Framework_name=CosmoPredict25Policy
+base_wm=/mnt/workspace/users/yuanzhihao/code/starVLA/playground/Pretrained_models/Cosmos-Predict2.5-2B-Pre-Trained
+base_vlm=${base_wm}
+freeze_module_list=backbone.vae,backbone.text_encoder
+data_root_dir=/mnt/workspace/datasets/
+data_mix=robocasa_teleop_ee
+
+action_dim=32
+state_dim=64
+
+run_root_dir=./outputs/cosmopredict25_policy_fm
+run_id=robocasa_teleop_ee_primary_only_rf_slots5_steps5
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p "${output_dir}"
+export WANDB_MODE=offline
+export WANDB_DIR="${output_dir}/wandb"
+mkdir -p "${WANDB_DIR}"
+cp "$0" "${output_dir}/"
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
+ starVLA/training/train_starvla.py \
+ --config_yaml ./examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml \
+ --framework.name ${Framework_name} \
+ --framework.world_model.base_wm "${base_wm}" \
+ --framework.world_model.height 224 \
+ --framework.world_model.width 224 \
+ --framework.world_model.text_max_length 128 \
+ --framework.world_model.conditional_frame_timestep 0.0 \
+ --framework.qwenvl.base_vlm "${base_vlm}" \
+ --framework.action_model.action_dim ${action_dim} \
+ --framework.action_model.state_dim ${state_dim} \
+ --framework.policy.train_time_distribution logitnormal \
+ --framework.policy.train_time_weight uniform \
+ --framework.policy.shift 5.0 \
+ --framework.policy.action_loss_weight 16.0 \
+ --framework.policy.future_image_loss_weight 1.0 \
+ --framework.policy.num_inference_steps 5 \
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
+ --datasets.vla_data.data_mix "${data_mix}" \
+ --datasets.vla_data.include_state true \
+ --datasets.vla_data.per_device_batch_size 8 \
+ --trainer.freeze_modules "${freeze_module_list}" \
+ --trainer.max_train_steps 300000 \
+ --trainer.save_interval 10000 \
+ --trainer.logging_frequency 200 \
+ --trainer.eval_interval 200 \
+ --trainer.num_warmup_steps 1000 \
+ --trainer.learning_rate.base 2e-5 \
+ --trainer.scheduler_specific_kwargs.min_lr 1.2e-6 \
+ --trainer.optimizer.betas "[0.9,0.999]" \
+ --trainer.optimizer.weight_decay 0.1 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project joyRA_robocasa \
+ --wandb_entity curryyuan \
+ 2>&1 | tee -a "${output_dir}/train.log"
diff --git a/examples/Robocasa_tabletop/train_files/run_yzh_cosmos25_policy_native.sh b/examples/Robocasa_tabletop/train_files/run_yzh_cosmos25_policy_native.sh
new file mode 100644
index 0000000000000000000000000000000000000000..bf79ace5ff87da716fd0f207dd35424055e8bcbe
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files/run_yzh_cosmos25_policy_native.sh
@@ -0,0 +1,105 @@
+#!/usr/bin/env zsh
+set -euo pipefail
+
+# Native Cosmos-Predict2.5 Policy training.
+# This uses NVIDIA's cosmos-predict2.5 policy model directly instead of the
+# diffusers Cosmos2_5_PredictBasePipeline wrapper.
+
+if [ -d /sys/class/infiniband ]; then
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
+else
+ RDMA_DEVICES=""
+fi
+
+if [ -n "${RDMA_DEVICES}" ]; then
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
+ export NCCL_IB_HCA
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
+ export NCCL_IB_DISABLE=0
+ export NCCL_NET_GDR_LEVEL=2
+else
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
+ export NCCL_IB_DISABLE=1
+fi
+
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS || true
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+
+if [ -f /mnt/workspace/envs/conda3/bin/activate ]; then
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+fi
+
+NUM_GPUS_PER_NODE=${1:-8}
+MASTER_PORT=${2:-12341}
+reason1_ckpt=${3:-}
+
+Framework_name=CosmoPredict25PolicyNative
+native_repo_path=/mnt/workspace/users/yuanzhihao/code/cosmos-predict2.5
+native_ckpt=/mnt/workspace1/users/chidafeng/models/Cosmos-Predict2.5-2B
+
+data_root_dir=/mnt/workspace/datasets/
+data_mix=robocasa_teleop_ee
+
+action_dim=32
+state_dim=64
+
+run_root_dir=./outputs/cosmopredict25_policy_native
+run_id=robocasa_teleop_ee_native_policy
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p "${output_dir}"
+export WANDB_MODE=offline
+export WANDB_DIR="${output_dir}/wandb"
+mkdir -p "${WANDB_DIR}"
+cp "$0" "${output_dir}/"
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${MASTER_PORT} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
+ starVLA/training/train_starvla.py \
+ --config_yaml ./examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml \
+ --framework.name ${Framework_name} \
+ --framework.world_model.base_wm "${native_ckpt}" \
+ --framework.qwenvl.base_vlm "${native_ckpt}" \
+ --framework.action_model.action_dim ${action_dim} \
+ --framework.action_model.state_dim ${state_dim} \
+ --framework.action_model.future_action_window_size 15 \
+ --framework.action_model.action_horizon 16 \
+ --framework.policy.native_repo_path "${native_repo_path}" \
+ --framework.policy.checkpoint_path "${native_ckpt}" \
+ --framework.policy.experiment cosmos_predict2p5_2b_480p_robocasa_50_demos_per_task_no_s3 \
+ --framework.policy.use_online_text_encoder true \
+ --framework.policy.text_encoder_ckpt_path "${reason1_ckpt}" \
+ --framework.policy.height 224 \
+ --framework.policy.width 224 \
+ --framework.policy.shift 5.0 \
+ --framework.policy.num_inference_steps 5 \
+ --framework.policy.mask_policy_loss true \
+ --framework.policy.action_loss_multiplier 16 \
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
+ --datasets.vla_data.data_mix "${data_mix}" \
+ --datasets.vla_data.include_state true \
+ --datasets.vla_data.per_device_batch_size 8 \
+ --trainer.freeze_modules "" \
+ --trainer.max_train_steps 300000 \
+ --trainer.save_interval 10000 \
+ --trainer.logging_frequency 200 \
+ --trainer.eval_interval 200 \
+ --trainer.num_warmup_steps 1000 \
+ --trainer.learning_rate.base 2e-4 \
+ --trainer.scheduler_specific_kwargs.min_lr 1.2e-5 \
+ --trainer.optimizer.betas "[0.9,0.999]" \
+ --trainer.optimizer.weight_decay 0.1 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project joyRA_robocasa \
+ --wandb_entity curryyuan \
+ 2>&1 | tee -a "${output_dir}/train.log"
diff --git a/examples/Robocasa_tabletop/train_files/run_yzh_cosmos_policy.sh b/examples/Robocasa_tabletop/train_files/run_yzh_cosmos_policy.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b602bdc28bbeaaf80482f1a36309cbfa7cfa3b59
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files/run_yzh_cosmos_policy.sh
@@ -0,0 +1,92 @@
+#!/usr/bin/env zsh
+set -euo pipefail
+
+# Cosmos2 Policy-style training script: action chunk is injected as a Cosmos latent frame.
+
+if [ -d /sys/class/infiniband ]; then
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
+else
+ RDMA_DEVICES=""
+fi
+
+if [ -n "${RDMA_DEVICES}" ]; then
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
+ export NCCL_IB_HCA
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
+ export NCCL_IB_DISABLE=0
+ export NCCL_NET_GDR_LEVEL=2
+else
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
+ export NCCL_IB_DISABLE=1
+fi
+
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS || true
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+
+if [ -f /mnt/workspace/envs/conda3/bin/activate ]; then
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+fi
+
+NUM_GPUS_PER_NODE=8
+
+Framework_name=CosmoPredict25Policy
+# base_wm=/mnt/workspace1/users/chidafeng/models/Cosmos-Predict2-2B-Video2World
+base_wm=/mnt/workspace/users/yuanzhihao/code/starVLA/playground/Pretrained_models/Cosmos-Predict2.5-2B-Post-Trained
+base_vlm=${base_wm}
+freeze_module_list=backbone.vae,backbone.text_encoder
+data_root_dir=/mnt/workspace/datasets/
+data_mix=robocasa_teleop_ee
+
+action_dim=32
+state_dim=64
+
+run_root_dir=./outputs/cosmopredict25_policy_1
+run_id=robocasa_teleop_ee
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p "${output_dir}"
+export WANDB_MODE=offline
+export WANDB_DIR="${output_dir}/wandb"
+mkdir -p "${WANDB_DIR}"
+cp "$0" "${output_dir}/"
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
+ starVLA/training/train_starvla.py \
+ --config_yaml ./examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml \
+ --framework.name ${Framework_name} \
+ --framework.world_model.base_wm "${base_wm}" \
+ --framework.world_model.height 224 \
+ --framework.world_model.width 224 \
+ --framework.world_model.text_max_length 128 \
+ --framework.qwenvl.base_vlm "${base_vlm}" \
+ --framework.action_model.action_dim ${action_dim} \
+ --framework.action_model.state_dim ${state_dim} \
+ --framework.policy.prediction_type x0 \
+ --framework.policy.min_timestep 0.02 \
+ --framework.policy.max_timestep 1.0 \
+ --framework.policy.noise_offset 0.02 \
+ --framework.policy.future_image_loss_weight 1.0 \
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
+ --datasets.vla_data.data_mix "${data_mix}" \
+ --datasets.vla_data.per_device_batch_size 16 \
+ --trainer.freeze_modules "${freeze_module_list}" \
+ --trainer.max_train_steps 300000 \
+ --trainer.save_interval 50000 \
+ --trainer.logging_frequency 200 \
+ --trainer.eval_interval 200 \
+ --trainer.learning_rate.base 1e-5 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project joyRA_robocasa \
+ --wandb_entity curryyuan \
+ 2>&1 | tee -a "${output_dir}/train.log"
diff --git a/examples/Robocasa_tabletop/train_files/run_yzh_cosmos_policy_edm.sh b/examples/Robocasa_tabletop/train_files/run_yzh_cosmos_policy_edm.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b2d40d37e1345ed763dd0819b28603c38a979dc1
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files/run_yzh_cosmos_policy_edm.sh
@@ -0,0 +1,103 @@
+#!/usr/bin/env zsh
+set -euo pipefail
+
+# Cosmos2 EDM Policy training script:
+# action/future-image latent frames are trained with a sigma-space denoising objective.
+
+if [ -d /sys/class/infiniband ]; then
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
+else
+ RDMA_DEVICES=""
+fi
+
+if [ -n "${RDMA_DEVICES}" ]; then
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
+ export NCCL_IB_HCA
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
+ export NCCL_IB_DISABLE=0
+ export NCCL_NET_GDR_LEVEL=2
+else
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
+ export NCCL_IB_DISABLE=1
+fi
+
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS || true
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+
+if [ -f /mnt/workspace/envs/conda3/bin/activate ]; then
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+fi
+
+NUM_GPUS_PER_NODE=8
+
+Framework_name=CosmoPredict2PolicyEDM
+base_wm=/mnt/workspace1/users/chidafeng/models/Cosmos-Predict2-2B-Video2World
+base_vlm=${base_wm}
+freeze_module_list=backbone.vae,backbone.text_encoder
+data_root_dir=/mnt/workspace/datasets/
+data_mix=robocasa_teleop_ee
+
+action_dim=32
+state_dim=64
+
+run_root_dir=./outputs/cosmopredict2_policy_edm
+run_id=robocasa_teleop_ee
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p "${output_dir}"
+export WANDB_MODE=offline
+export WANDB_DIR="${output_dir}/wandb"
+mkdir -p "${WANDB_DIR}"
+cp "$0" "${output_dir}/"
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
+ starVLA/training/train_starvla.py \
+ --config_yaml ./examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml \
+ --framework.name ${Framework_name} \
+ --framework.world_model.base_wm "${base_wm}" \
+ --framework.world_model.height 224 \
+ --framework.world_model.width 224 \
+ --framework.world_model.text_max_length 128 \
+ --framework.qwenvl.base_vlm "${base_vlm}" \
+ --framework.action_model.action_dim ${action_dim} \
+ --framework.action_model.state_dim ${state_dim} \
+ --framework.policy.sigma_data 1.0 \
+ --framework.policy.sigma_min 0.0002 \
+ --framework.policy.sigma_max 80.0 \
+ --framework.policy.sigma_p_mean -1.2 \
+ --framework.policy.sigma_p_std 1.2 \
+ --framework.policy.hybrid_sigma_distribution true \
+ --framework.policy.hybrid_sigma_lognormal_prob 0.7 \
+ --framework.policy.uniform_lower 1.0 \
+ --framework.policy.uniform_upper 85.0 \
+ --framework.policy.rho 7.0 \
+ --framework.policy.loss_weighting edm \
+ --framework.policy.max_loss_weight 100.0 \
+ --framework.policy.num_inference_steps 5 \
+ --framework.policy.sampler 2ab \
+ --framework.policy.preconditioning true \
+ --framework.policy.future_image_loss_weight 1.0 \
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
+ --datasets.vla_data.data_mix "${data_mix}" \
+ --datasets.vla_data.per_device_batch_size 16 \
+ --trainer.freeze_modules "${freeze_module_list}" \
+ --trainer.max_train_steps 300000 \
+ --trainer.save_interval 50000 \
+ --trainer.logging_frequency 200 \
+ --trainer.eval_interval 200 \
+ --trainer.learning_rate.base 1e-5 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project joyRA_wm \
+ --wandb_entity curryyuan \
+ 2>&1 | tee -a "${output_dir}/train.log"
diff --git a/examples/Robocasa_tabletop/train_files/run_yzh_dit4dit_perceiver_future_image.sh b/examples/Robocasa_tabletop/train_files/run_yzh_dit4dit_perceiver_future_image.sh
new file mode 100644
index 0000000000000000000000000000000000000000..ed7beaca8eb9dee6011938c884fe3977dede65b8
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files/run_yzh_dit4dit_perceiver_future_image.sh
@@ -0,0 +1,137 @@
+#!/usr/bin/env zsh
+set -euo pipefail
+
+# Cosmos-Predict2.5 Perceiver training with DiT4DiT-style video-action fusion.
+# Keeps the starVLA Perceiver action head, while training Cosmos video dynamics
+# with a tri-timestep scheme and using fixed-timestep Cosmos hidden states as
+# the action condition.
+
+if [ -d /sys/class/infiniband ]; then
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
+else
+ RDMA_DEVICES=""
+fi
+
+if [ -n "${RDMA_DEVICES}" ]; then
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
+ export NCCL_IB_HCA
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
+ export NCCL_IB_DISABLE=0
+ export NCCL_NET_GDR_LEVEL=2
+else
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
+ export NCCL_IB_DISABLE=1
+fi
+
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS || true
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+
+if [ -f /mnt/workspace/envs/conda3/bin/activate ]; then
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+fi
+
+NUM_GPUS_PER_NODE=${1:-8}
+
+Framework_name=CosmoPredict25PerceiverDiT4DiT
+base_wm=/mnt/workspace/users/yuanzhihao/code/starVLA/playground/Pretrained_models/Cosmos-Predict2.5-2B-Post-Trained
+cosmos_revision=${COSMOS_PREDICT25_REVISION-diffusers/base/post-trained}
+base_vlm=${base_wm}
+freeze_module_list=''
+DIT_TYPE="DiT-B"
+data_root_dir=/mnt/workspace/datasets/
+data_mix=robocasa_teleop_ee
+
+action_dim=32
+state_dim=64
+action_hidden_dim=2560
+cross_attention_dim=2048
+
+run_root_dir=./outputs1/cosmopredict25_perceiver_dit4dit
+run_id=robocasa_teleop_ee_new_head_goal_image
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p "${output_dir}"
+export WANDB_MODE=offline
+export WANDB_DIR="${output_dir}/wandb"
+mkdir -p "${WANDB_DIR}"
+cp "$0" "${output_dir}/"
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
+ starVLA/training/train_starvla.py \
+ --config_yaml ./examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml \
+ --framework.name ${Framework_name} \
+ --framework.world_model.base_wm "${base_wm}" \
+ --framework.world_model.revision "${cosmos_revision}" \
+ --framework.world_model.attn_implementation flash_attention_2 \
+ --framework.world_model.extract_layers "[17]" \
+ --framework.world_model.height 224 \
+ --framework.world_model.width 224 \
+ --framework.world_model.conditional_frame_timestep 0.0001 \
+ --framework.qwenvl.base_vlm "${base_vlm}" \
+ --framework.qwenvl.vl_hidden_dim 2048 \
+ --framework.action_model.action_model_type ${DIT_TYPE} \
+ --framework.action_model.action_dim ${action_dim} \
+ --framework.action_model.state_dim ${state_dim} \
+ --framework.action_model.action_hidden_dim ${action_hidden_dim} \
+ --framework.action_model.hidden_size ${action_hidden_dim} \
+ --framework.action_model.diffusion_model_cfg.cross_attention_dim ${cross_attention_dim} \
+ --framework.action_model.diffusion_model_cfg.output_dim ${action_hidden_dim} \
+ --framework.action_model.num_inference_timesteps 4 \
+ --framework.dit4dit_action_head.enabled true \
+ --framework.dit4dit_video.enabled true \
+ --framework.dit4dit_video.training joint \
+ --framework.dit4dit_video.future_loss_type flow_matching \
+ --framework.dit4dit_video.future_loss_weight 1.0 \
+ --framework.dit4dit_video.future_num_inference_steps 1 \
+ --framework.dit4dit_video.conditional_frame_timestep 0.0001 \
+ --framework.dit4dit_video.height 224 \
+ --framework.dit4dit_video.width auto \
+ --framework.dit4dit_video.tri_timestep.video_time_distribution logit_normal \
+ --framework.dit4dit_video.tri_timestep.high_sigma_ratio 0.05 \
+ --framework.dit4dit_video.tri_timestep.high_sigma_min 0.98 \
+ --framework.dit4dit_video.tri_timestep.feature_timestep 1.0 \
+ --framework.dit4dit_video.tri_timestep.action_time_distribution beta_action_head \
+ --framework.future_image_generation.enabled true \
+ --framework.future_image_generation.conditioning_mode auto \
+ --framework.future_image_generation.max_samples 1 \
+ --framework.future_image_generation.height 224 \
+ --framework.future_image_generation.width auto \
+ --framework.future_image_generation.num_frames 5 \
+ --framework.future_image_generation.num_inference_steps 1 \
+ --framework.future_image_generation.guidance_scale 1.0 \
+ --framework.future_image_generation.output_type pil \
+ --framework.future_image_generation.future_frame_index -1 \
+ --framework.future_image_generation.return_full_video false \
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
+ --datasets.vla_data.data_mix "${data_mix}" \
+ --datasets.vla_data.include_state true \
+ --datasets.vla_data.future_video_delta_indices "[17]" \
+ --datasets.vla_data.action_video_freq_ratio 2 \
+ --datasets.vla_data.per_device_batch_size 8 \
+ --trainer.freeze_modules "${freeze_module_list}" \
+ --trainer.max_train_steps 300000 \
+ --trainer.save_interval 50000 \
+ --trainer.logging_frequency 200 \
+ --trainer.eval_interval 200 \
+ --trainer.num_warmup_steps 5000 \
+ --trainer.learning_rate.base 1e-5 \
+ --trainer.learning_rate.backbone 1e-5 \
+ --trainer.learning_rate.action_model 1e-4 \
+ --trainer.scheduler_specific_kwargs.min_lr 5e-7 \
+ --trainer.optimizer.betas "[0.9,0.95]" \
+ --trainer.optimizer.weight_decay 1e-8 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project joyRA_robocasa \
+ --wandb_entity curryyuan \
+ 2>&1 | tee -a "${output_dir}/train.log"
diff --git a/examples/Robocasa_tabletop/train_files/run_yzh_dreamzero_policy_fm.sh b/examples/Robocasa_tabletop/train_files/run_yzh_dreamzero_policy_fm.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b7d1f1197fff8cea3b183972b0db534f8f4eae9a
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files/run_yzh_dreamzero_policy_fm.sh
@@ -0,0 +1,112 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+# DreamZero Wan2.2 policy training through the starVLA trainer.
+#
+# This is a starVLA-native model file that uses the local Wan2.2 diffusers
+# backbone and does not require the official DreamZero/Groot training stack.
+
+if [ -d /sys/class/infiniband ]; then
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
+else
+ RDMA_DEVICES=""
+fi
+
+if [ -n "${RDMA_DEVICES}" ]; then
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
+ export NCCL_IB_HCA
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
+ export NCCL_IB_DISABLE=0
+ export NCCL_NET_GDR_LEVEL=2
+else
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
+ export NCCL_IB_DISABLE=1
+fi
+
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS || true
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+export TOKENIZERS_PARALLELISM=false
+
+if [ -f /mnt/workspace/envs/conda3/bin/activate ] && [ "${SKIP_CONDA_ACTIVATE:-0}" != "1" ]; then
+ source /mnt/workspace/envs/conda3/bin/activate "${STARVLA_CONDA_ENV:-starVLA_1}" || true
+fi
+
+NUM_GPUS_PER_NODE=${1:-8}
+
+Framework_name=DreamZero
+base_wm=${BASE_WM:-/mnt/workspace1/users/chidafeng/models/Wan2.2-TI2V-5B-Diffusers}
+base_vlm=${base_wm}
+freeze_module_list=${FREEZE_MODULES:-backbone.vae,backbone.text_encoder}
+data_root_dir=${DATA_ROOT_DIR:-/mnt/workspace/datasets/}
+data_mix=${DATA_MIX:-robocasa_teleop_ee}
+wm_height=${WM_HEIGHT:-224}
+wm_width=${WM_WIDTH:-224}
+
+action_dim=${ACTION_DIM:-32}
+state_dim=${STATE_DIM:-64}
+future_action_window_size=${FUTURE_ACTION_WINDOW_SIZE:-15}
+action_horizon=${ACTION_HORIZON:-16}
+
+run_root_dir=${RUN_ROOT_DIR:-./outputs/dreamzero_policy_fm}
+run_id=${RUN_ID:-robocasa_teleop_ee_dreamzero_wan22_fm}
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p "${output_dir}"
+export WANDB_MODE=${WANDB_MODE:-offline}
+export WANDB_DIR="${output_dir}/wandb"
+mkdir -p "${WANDB_DIR}"
+cp "$0" "${output_dir}/"
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
+ starVLA/training/train_starvla.py \
+ --config_yaml ./examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml \
+ --framework.name ${Framework_name} \
+ --framework.world_model.base_wm "${base_wm}" \
+ --framework.world_model.extract_layers "[-1]" \
+ --framework.world_model.height ${wm_height} \
+ --framework.world_model.width ${wm_width} \
+ --framework.qwenvl.base_vlm "${base_vlm}" \
+ --framework.action_model.action_dim ${action_dim} \
+ --framework.action_model.state_dim ${state_dim} \
+ --framework.action_model.future_action_window_size ${future_action_window_size} \
+ --framework.action_model.action_horizon ${action_horizon} \
+ --framework.action_model.past_action_window_size 0 \
+ --framework.policy.train_time_distribution logitnormal \
+ --framework.policy.shift 5.0 \
+ --framework.policy.action_loss_weight 1.0 \
+ --framework.policy.future_image_loss_weight ${FUTURE_IMAGE_LOSS_WEIGHT:-1.0} \
+ --framework.policy.num_inference_steps 5 \
+ --framework.policy.timestep_scale 1000.0 \
+ --framework.policy.autoregressive true \
+ --framework.policy.latent_clip_value ${LATENT_CLIP_VALUE:-30.0} \
+ --framework.policy.prediction_clip_value ${PREDICTION_CLIP_VALUE:-30.0} \
+ --framework.policy.decode_future_images true \
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
+ --datasets.vla_data.data_mix "${data_mix}" \
+ --datasets.vla_data.include_state true \
+ --datasets.vla_data.per_device_batch_size ${PER_DEVICE_BATCH_SIZE:-1} \
+ --trainer.freeze_modules "${freeze_module_list}" \
+ --trainer.max_train_steps ${MAX_TRAIN_STEPS:-300000} \
+ --trainer.save_interval ${SAVE_INTERVAL:-10000} \
+ --trainer.logging_frequency ${LOGGING_FREQUENCY:-200} \
+ --trainer.eval_interval ${EVAL_INTERVAL:-200} \
+ --trainer.num_warmup_steps ${NUM_WARMUP_STEPS:-1000} \
+ --trainer.learning_rate.base ${LEARNING_RATE:-1e-6} \
+ --trainer.scheduler_specific_kwargs.min_lr ${MIN_LR:-1e-7} \
+ --trainer.optimizer.betas "[0.9,0.999]" \
+ --trainer.optimizer.weight_decay ${WEIGHT_DECAY:-0.1} \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project ${WANDB_PROJECT:-joyRA_robocasa_dreamzero} \
+ --wandb_entity ${WANDB_ENTITY:-curryyuan} \
+ 2>&1 | tee -a "${output_dir}/train.log"
diff --git a/examples/Robocasa_tabletop/train_files/run_yzh_wm.sh b/examples/Robocasa_tabletop/train_files/run_yzh_wm.sh
new file mode 100644
index 0000000000000000000000000000000000000000..69cb69f4ba7a497eee6eab8c95ea5ad61f3c837c
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files/run_yzh_wm.sh
@@ -0,0 +1,110 @@
+#!/usr/bin/env zsh
+set -euo pipefail
+
+# Cosmos Predict2.5 Perceiver training script based on run_yzh.sh.
+
+if [ -d /sys/class/infiniband ]; then
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
+else
+ RDMA_DEVICES=""
+fi
+
+if [ -n "${RDMA_DEVICES}" ]; then
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
+ export NCCL_IB_HCA
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
+
+ if command -v show_gids >/dev/null 2>&1; then
+ NCCL_IB_GID_INDEX=""
+ output=$(show_gids | grep v2 || true)
+ while IFS= read -r line; do
+ ipv4=$(echo "${line}" | awk '{print $5}')
+ if [[ -n "${ipv4}" && "${ipv4}" != "0000:0000:0000:0000:0000:ffff:0000:0000" && "${ipv4}" =~ [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+ ]]; then
+ NCCL_IB_GID_INDEX=$(echo "${line}" | awk '{print $3}')
+ break
+ fi
+ done <<<"${output}"
+ export NCCL_IB_GID_INDEX
+ fi
+
+ export NCCL_IB_DISABLE=0
+ export NCCL_NET_GDR_LEVEL=2
+else
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
+ export NCCL_IB_DISABLE=1
+fi
+
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS || true
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+
+if [ -f /mnt/workspace/envs/conda3/bin/activate ]; then
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+fi
+
+NUM_GPUS_PER_NODE=${1:-8}
+
+Framework_name=CosmoPredict25Perceiver
+base_wm=/mnt/workspace/users/yuanzhihao/code/starVLA/playground/Pretrained_models/Cosmos-Predict2.5-2B-Post-Trained
+cosmos_revision=${COSMOS_PREDICT25_REVISION-diffusers/base/post-trained}
+base_vlm=${base_wm}
+freeze_module_list=''
+DIT_TYPE="DiT-B"
+data_root_dir=/mnt/workspace/datasets/
+data_mix=robocasa_teleop_ee
+
+action_dim=32
+state_dim=64
+action_hidden_dim=1024
+cross_attention_dim=2048
+
+run_root_dir=./outputs
+run_id=cosmopredict25_perceiver_robocasa_teleop_ee
+
+export WANDB_MODE=offline
+export WANDB_DIR=../../
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p "${output_dir}"
+cp "$0" "${output_dir}/"
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
+ starVLA/training/train_starvla.py \
+ --config_yaml ./examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml \
+ --framework.name ${Framework_name} \
+ --framework.world_model.base_wm "${base_wm}" \
+ --framework.world_model.revision "${cosmos_revision}" \
+ --framework.world_model.extract_layers "[-1]" \
+ --framework.world_model.height 224 \
+ --framework.world_model.width 224 \
+ --framework.qwenvl.base_vlm "${base_vlm}" \
+ --framework.qwenvl.vl_hidden_dim 2048 \
+ --framework.action_model.action_model_type ${DIT_TYPE} \
+ --framework.action_model.action_dim ${action_dim} \
+ --framework.action_model.state_dim ${state_dim} \
+ --framework.action_model.action_hidden_dim ${action_hidden_dim} \
+ --framework.action_model.hidden_size ${action_hidden_dim} \
+ --framework.action_model.diffusion_model_cfg.cross_attention_dim ${cross_attention_dim} \
+ --framework.action_model.diffusion_model_cfg.output_dim ${action_hidden_dim} \
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
+ --datasets.vla_data.data_mix "${data_mix}" \
+ --datasets.vla_data.per_device_batch_size 16 \
+ --trainer.freeze_modules "${freeze_module_list}" \
+ --trainer.max_train_steps 300000 \
+ --trainer.save_interval 10000 \
+ --trainer.logging_frequency 200 \
+ --trainer.eval_interval 200 \
+ --trainer.learning_rate.base 1e-5 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project joyRA_robocasa \
+ --wandb_entity curryyuan \
+ 2>&1 | tee -a "${output_dir}/train.log"
diff --git a/examples/Robocasa_tabletop/train_files/run_zhanka.sh b/examples/Robocasa_tabletop/train_files/run_zhanka.sh
new file mode 100644
index 0000000000000000000000000000000000000000..4a5a3f260cbf04bbb5c48fde90d12cf35707fbb7
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files/run_zhanka.sh
@@ -0,0 +1,99 @@
+#!/usr/bin/env zsh
+set -euo pipefail
+
+# Cosmos-Predict2.5 Policy training, aligned with the official RF/FM recipe:
+# action/future latent frames are trained as velocity targets.
+
+if [ -d /sys/class/infiniband ]; then
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
+else
+ RDMA_DEVICES=""
+fi
+
+if [ -n "${RDMA_DEVICES}" ]; then
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
+ export NCCL_IB_HCA
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
+ export NCCL_IB_DISABLE=0
+ export NCCL_NET_GDR_LEVEL=2
+else
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
+ export NCCL_IB_DISABLE=1
+fi
+
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS || true
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+
+if [ -f /mnt/workspace/envs/conda3/bin/activate ]; then
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+fi
+
+NUM_GPUS_PER_NODE=${1:-8}
+
+Framework_name=CosmoPredict25Policy
+base_wm=/mnt/workspace/users/yuanzhihao/code/starVLA/playground/Pretrained_models/Cosmos-Predict2.5-2B-Post-Trained
+base_vlm=${base_wm}
+freeze_module_list=backbone.vae,backbone.text_encoder
+data_root_dir=/mnt/workspace/datasets/
+data_mix=robocasa_teleop_ee
+
+action_dim=32
+state_dim=64
+
+run_root_dir=./outputs/cosmopredict25_policy_fm
+run_id=robocasa_teleop_ee_official_rf_state_steps5_2gpu
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p "${output_dir}"
+export WANDB_MODE=offline
+export WANDB_DIR="${output_dir}/wandb"
+mkdir -p "${WANDB_DIR}"
+cp "$0" "${output_dir}/"
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
+ starVLA/training/train_starvla.py \
+ --config_yaml ./examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml \
+ --framework.name ${Framework_name} \
+ --framework.world_model.base_wm "${base_wm}" \
+ --framework.world_model.height 224 \
+ --framework.world_model.width 224 \
+ --framework.world_model.text_max_length 128 \
+ --framework.world_model.conditional_frame_timestep 0.0 \
+ --framework.qwenvl.base_vlm "${base_vlm}" \
+ --framework.action_model.action_dim ${action_dim} \
+ --framework.action_model.state_dim ${state_dim} \
+ --framework.policy.train_time_distribution logitnormal \
+ --framework.policy.train_time_weight uniform \
+ --framework.policy.shift 5.0 \
+ --framework.policy.action_loss_weight 16.0 \
+ --framework.policy.future_image_loss_weight 1.0 \
+ --framework.policy.num_inference_steps 5 \
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
+ --datasets.vla_data.data_mix "${data_mix}" \
+ --datasets.vla_data.include_state true \
+ --datasets.vla_data.per_device_batch_size 8 \
+ --trainer.freeze_modules "${freeze_module_list}" \
+ --trainer.max_train_steps 300000 \
+ --trainer.save_interval 50000 \
+ --trainer.logging_frequency 200 \
+ --trainer.eval_interval 200 \
+ --trainer.num_warmup_steps 1000 \
+ --trainer.learning_rate.base 2e-4 \
+ --trainer.scheduler_specific_kwargs.min_lr 1.2e-5 \
+ --trainer.optimizer.betas "[0.9,0.999]" \
+ --trainer.optimizer.weight_decay 0.1 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project joyRA_robocasa \
+ --wandb_entity curryyuan \
+ 2>&1 | tee -a "${output_dir}/train.log"
diff --git a/examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml b/examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..9fb7aeec6fd33328fa3fc87aedba974ec81564a2
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml
@@ -0,0 +1,114 @@
+run_id: qwenact
+run_root_dir: results/Checkpoints
+seed: 42
+trackers: [jsonl, wandb]
+wandb_entity: your_wandb_entity
+wandb_project: starvla
+is_debug: false
+
+framework:
+ name: '' # override in bash
+ qwenvl:
+ base_vlm: ./playground/Pretrained_models/Qwen3-VL-4B-Instruct
+ attn_implementation: flash_attention_2
+ vl_hidden_dim: 2048
+ dino:
+ dino_backbone: dinov2_vits14
+
+ action_model:
+ action_model_type: DiT-B
+ hidden_size: 2560 # 和 DiT 最后的 projection 对应,用于 ActionDecoder
+ add_pos_embed: True
+ max_seq_len: 1024
+ action_dim: 32
+ state_dim: 64
+ future_action_window_size: 15
+ action_horizon: 16
+ past_action_window_size: 0
+ repeated_diffusion_steps: 8
+ noise_beta_alpha: 1.5
+ noise_beta_beta: 1.0
+ noise_s: 0.999
+ num_timestep_buckets: 1000
+ num_inference_timesteps: 20
+ num_target_vision_tokens: 32
+ max_num_embodiments: 32
+ use_category_specific: false
+ diffusion_model_cfg: # DiT Transformers 的参数
+ cross_attention_dim: 2048 # VLM 的 dim
+ dropout: 0.2
+ final_dropout: true
+ interleave_self_attention: true
+ norm_type: "ada_norm"
+ num_layers: 16
+ output_dim: 2560
+ positional_embeddings: null
+
+datasets:
+ vlm_data:
+ dataset_py: vlm_datasets
+ dataformat: llava_json
+ dataset_use: asv2_conversation_en,asv2_detailed_description_en,asv2_region_captioning_en,coco_internvl_longcap_en,coco_karpathy_train_567_en,coco_negative_gpt4o_en,coco_poetry_zh,coco_rem_en_zh,cocorem_exist_yorn_en,cocotextv2_en,cocotextv2_gpt4o_en,okvqa_en,refcoco_grounding_aug_en,refcoco_grounding_en,tallyqa_coco_en,toloka_grounding_aug_en,vqav2_en,vsr_en
+ eval_dataset: aokvqa_cauldron_llava_format
+ data_flatten: false
+ base_interval: 2
+ max_pixels: 50176
+ min_pixels: 784
+ model_max_length: 2048
+ model_type: qwen2.5vl
+ per_device_batch_size: 4
+
+ vla_data:
+ dataset_py: lerobot_datasets
+ data_root_dir: /mnt/workspace/datasets
+ data_mix: fourier_gr1_unified_1000 # bridge_rt_1
+ action_type: delta_ee
+ CoT_prompt: "Your task is {instruction}. To identify the key objects for your task. Locate their bounding boxes in [x1,y1,x2,y2] format."
+ CoT_answer: bbox
+ default_image_resolution: [3, 224, 224]
+ per_device_batch_size: 16
+ load_all_data_for_training: true
+ obs: ["image_0"]
+ image_size: [224,224]
+ delete_pause_frame: false
+ video_backend: decord
+
+trainer:
+ epochs: 100
+ max_train_steps: 100000
+ num_warmup_steps: 5000
+ save_interval: 5000
+ eval_interval: 100
+ learning_rate:
+ base: 1e-05
+ qwen_vl_interface: 1.0e-05
+ action_model: 1.0e-04
+ lr_scheduler_type: cosine_with_min_lr
+ scheduler_specific_kwargs:
+ min_lr: 5.0e-07
+ freeze_modules: ''
+ loss_scale:
+ vla: 1.0
+ vlm: 0.1
+ # pretrained_checkpoint: ./results/Checkpoints/1_need/0601_qwenact_fixqwen_32gpus_lr_1e-3_qformer_36_37/steps_100000/pytorch_model.pt
+ # reload_modules: 'action_model,layer_qformer' # warning: this may cause model to not converge
+ repeated_diffusion_steps: 4
+ max_grad_norm: 1.0
+ warmup_ratio: 0.1
+ weight_decay: 0.0
+ logging_frequency: 10
+ gradient_clipping: 1.0
+ gradient_accumulation_steps: 1
+
+ optimizer:
+ name: AdamW
+ betas: [0.9, 0.95]
+ eps: 1.0e-08
+ weight_decay: 1.0e-08
+
+ # parameters to be determined
+ is_resume: false
+ resume_epoch: null
+ resume_step: null
+ enable_gradient_checkpointing: true
+ enable_mixed_precision_training: true
diff --git a/examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr2.yaml b/examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr2.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..523d6c1924941a754bd79a1b51651c0bacd4475c
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr2.yaml
@@ -0,0 +1,116 @@
+run_id: qwenact
+run_root_dir: results/Checkpoints
+seed: 42
+trackers: [jsonl, wandb]
+wandb_entity: your_wandb_entity
+wandb_project: starvla
+is_debug: false
+
+framework:
+ name: '' # override in bash
+ qwenvl:
+ base_vlm: ./playground/Pretrained_models/Qwen3-VL-4B-Instruct
+ attn_implementation: flash_attention_2
+ vl_hidden_dim: 2048
+ dino:
+ dino_backbone: dinov2_vits14
+
+ action_model:
+ action_model_type: DiT-B
+ hidden_size: 2560 # 和 DiT 最后的 projection 对应,用于 ActionDecoder
+ add_pos_embed: True
+ max_seq_len: 1024
+ action_dim: 32
+ state_dim: 64
+ future_action_window_size: 15
+ action_horizon: 16
+ past_action_window_size: 0
+ repeated_diffusion_steps: 8
+ noise_beta_alpha: 1.5
+ noise_beta_beta: 1.0
+ noise_s: 0.999
+ num_timestep_buckets: 1000
+ num_inference_timesteps: 20
+ num_target_vision_tokens: 64
+ max_num_embodiments: 32
+ use_category_specific: false
+ diffusion_model_cfg: # DiT Transformers 的参数
+ cross_attention_dim: 2048 # VLM 的 dim
+ dropout: 0.2
+ final_dropout: true
+ interleave_self_attention: true
+ norm_type: "ada_norm"
+ num_layers: 16
+ output_dim: 2560
+ positional_embeddings: null
+
+
+
+datasets:
+ vlm_data:
+ dataset_py: vlm_datasets
+ dataformat: llava_json
+ dataset_use: asv2_conversation_en,asv2_detailed_description_en,asv2_region_captioning_en,coco_internvl_longcap_en,coco_karpathy_train_567_en,coco_negative_gpt4o_en,coco_poetry_zh,coco_rem_en_zh,cocorem_exist_yorn_en,cocotextv2_en,cocotextv2_gpt4o_en,okvqa_en,refcoco_grounding_aug_en,refcoco_grounding_en,tallyqa_coco_en,toloka_grounding_aug_en,vqav2_en,vsr_en
+ eval_dataset: aokvqa_cauldron_llava_format
+ data_flatten: false
+ base_interval: 2
+ max_pixels: 50176
+ min_pixels: 784
+ model_max_length: 2048
+ model_type: qwen2.5vl
+ per_device_batch_size: 4
+
+ vla_data:
+ dataset_py: lerobot_datasets
+ data_root_dir: /mnt/workspace/datasets
+ data_mix: fourier_gr1_unified_1000 # bridge_rt_1
+ action_type: delta_ee
+ CoT_prompt: "Your task is {instruction}. To identify the key objects for your task. Locate their bounding boxes in [x1,y1,x2,y2] format."
+ CoT_answer: bbox
+ default_image_resolution: [3, 224, 224]
+ per_device_batch_size: 16
+ load_all_data_for_training: true
+ obs: ["image_0"]
+ image_size: [224,224]
+ delete_pause_frame: false
+ video_backend: decord
+
+trainer:
+ epochs: 100
+ max_train_steps: 100000
+ num_warmup_steps: 5000
+ save_interval: 5000
+ eval_interval: 100
+ learning_rate:
+ base: 1e-05
+ qwen_vl_interface: 1.0e-05
+ action_model: 1.0e-04
+ lr_scheduler_type: cosine_with_min_lr
+ scheduler_specific_kwargs:
+ min_lr: 5.0e-07
+ freeze_modules: ''
+ loss_scale:
+ vla: 1.0
+ vlm: 0.1
+ # pretrained_checkpoint: ./results/Checkpoints/1_need/0601_qwenact_fixqwen_32gpus_lr_1e-3_qformer_36_37/steps_100000/pytorch_model.pt
+ # reload_modules: 'action_model,layer_qformer' # warning: this may cause model to not converge
+ repeated_diffusion_steps: 4
+ max_grad_norm: 1.0
+ warmup_ratio: 0.1
+ weight_decay: 0.0
+ logging_frequency: 10
+ gradient_clipping: 1.0
+ gradient_accumulation_steps: 1
+
+ optimizer:
+ name: AdamW
+ betas: [0.9, 0.95]
+ eps: 1.0e-08
+ weight_decay: 1.0e-08
+
+ # parameters to be determined
+ is_resume: false
+ resume_epoch: null
+ resume_step: null
+ enable_gradient_checkpointing: true
+ enable_mixed_precision_training: true
diff --git a/examples/Robocasa_tabletop/train_files/submit_robocasa_training.sh b/examples/Robocasa_tabletop/train_files/submit_robocasa_training.sh
new file mode 100644
index 0000000000000000000000000000000000000000..cdb0de61c7f261a0c269f89f6b6ea0211d3e667f
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files/submit_robocasa_training.sh
@@ -0,0 +1,104 @@
+#!/bin/bash
+#SBATCH --job-name=test_RoCaPI # name
+#SBATCH -p si
+#SBATCH -N 4 # nodes
+#SBATCH --ntasks-per-node=1 # crucial - only 1 task per dist per node!
+#SBATCH --cpus-per-task=128 # number of cores per tasks
+#SBATCH --gres=gpu:8 # number of gpus
+#SBATCH --output=/mnt/petrelfs/yejinhui/Projects/starVLA/results/logs/%x-%j.out # output file name
+#SBATCH --error=/mnt/petrelfs/yejinhui/Projects/starVLA/results/logs/%x-%j.err
+#SBATCH --exclude=SH-IDCA1404-10-140-54-13
+
+# 6955707 si RoCaPI reserved yejinhui normal R 9:14 4 gpu:32 SH-IDCA1404-10-140-54-[13,88-89,107]
+
+# source ~/.bashrc # 确保 conda 命令可用
+# source ~/.zshrc
+# source ~/envs4jinhui.sh
+# proxy_on
+
+# conda activate llavavla310 # 替换为你的环境名
+
+# export task_id=31_32_33
+
+export NCCL_TIMEOUT=10000 # timeout set to 1 hour (unit: seconds)
+export NCCL_SOCKET_TIMEOUT_MS=360000
+
+
+export NCCL_SOCKET_IFNAME=bond0
+# export NCCL_IB_HCA=mlx5_2,mlx5_3,mlx5_4,mlx5_5
+export NCCL_IB_HCA=mlx5_2,mlx5_3
+
+export GPUS_PER_NODE=8
+export MASTER_ADDR=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1)
+export MASTER_PORT=$((RANDOM % 101 + 20000))
+
+
+cd /mnt/petrelfs/yejinhui/Projects/starVLA
+export PYTHONPATH="$PWD/starVLA/model/openvla:$PYTHONPATH"
+
+# conda activate llavavla310
+proxy_on
+
+#
+
+# === Please modify the following paths according to your environment ===
+###########################################################################################
+
+export Framework_name=QwenPI_v2
+export base_vlm=./playground/Pretrained_models/Qwen2.5-VL-3B-Instruct # must be a local path, due to simpler will run in other where
+export base_vlm=./playground/Pretrained_models/Qwen3-VL-4B-Instruct-Action
+export freeze_module_list=""
+export action_input_dim=2560
+export DIT_TYPE="DiT-B"
+export config_yaml=./examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml
+export data_mix=fourier_gr1_unified_1000
+export include_state=True
+export run_root_dir=./results/Checkpoints
+export run_id=debug_1224_${data_mix}_${Framework_name}_nostate_qwen3
+# === End of environment variable configuration ===
+###########################################################################################
+
+
+unset DEBUG
+
+export TOTAL_GPUS=$((GPUS_PER_NODE * SLURM_NNODES))
+export global_batch_size=$((TOTAL_GPUS * vla_per_device_batch_size)) # 512 is the default global batch size, you can change it if needed
+echo "Total GPUs: $TOTAL_GPUS"
+
+
+# export WANDB_MODE=disabled
+
+export output_dir=${run_root_dir}/${run_id}
+mkdir -p ${output_dir}
+# mv this script to the output dir
+cp $0 ${output_dir}/
+
+ # --datasets.vla_data.include_state ${include_state} \
+
+srun --jobid $SLURM_JOBID bash -c 'accelerate launch \
+ --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \
+ --main_process_ip $MASTER_ADDR \
+ --main_process_port $MASTER_PORT \
+ --machine_rank $SLURM_PROCID \
+ --num_machines $SLURM_NNODES \
+ --num_processes=${TOTAL_GPUS} \
+ starVLA/training/train_starvla.py \
+ --config_yaml ${config_yaml} \
+ --framework.name ${Framework_name} \
+ --framework.action_model.action_model_type ${DIT_TYPE} \
+ --framework.qwenvl.base_vlm ${base_vlm} \
+ --datasets.vla_data.per_device_batch_size 8 \
+ --trainer.freeze_modules ${freeze_module_list} \
+ --datasets.vla_data.data_mix ${data_mix} \
+ --trainer.max_train_steps 200000 \
+ --trainer.save_interval 10000 \
+ --trainer.eval_interval 100 \
+ --trainer.num_warmup_steps 5000 \
+ --trainer.logging_frequency 50 \
+ --trainer.learning_rate.base 3e-5 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project StarVLA_Robocasa \
+ --wandb_entity jinhuiye \
+ --trainer.is_resume True '
+
diff --git a/examples/Robocasa_tabletop/train_files/train_setting7.sh b/examples/Robocasa_tabletop/train_files/train_setting7.sh
new file mode 100644
index 0000000000000000000000000000000000000000..8f5726cde6567d5e79f3d33ba8b73b5a4273bc5e
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files/train_setting7.sh
@@ -0,0 +1,116 @@
+RDMA_DEVICES=$(ls /sys/class/infiniband)
+if [ -z "$RDMA_DEVICES" ]; then
+ log "ERROR: No active RDMA devices found. Exiting script." >&2
+ exit 1
+fi
+
+# 设置RDMA设备列表 (逗号分隔)
+NCCL_IB_HCA=$(echo "$RDMA_DEVICES" | tr '\n' ',' | sed 's/,$//')
+export NCCL_IB_HCA
+echo "Detected RDMA devices: $NCCL_IB_HCA"
+
+# 获取GID_INDEX
+NCCL_IB_GID_INDEX=""
+output=$(show_gids | grep v2)
+# 遍历每一行
+while IFS= read -r line; do
+ ipv4=$(echo "$line" | awk '{print $5}')
+ # 检查IPv4地址是否有值(不是空字符串且不是全0地址)
+ if [[ -n "$ipv4" && "$ipv4" != "0000:0000:0000:0000:0000:ffff:0000:0000" && "$ipv4" =~ [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+ ]]; then
+ NCCL_IB_GID_INDEX=$(echo "$line" | awk '{print $3}')
+ # 找到第一个匹配项后立即退出循环
+ break
+ fi
+done <<<"$output"
+
+export NCCL_SOCKET_IFNAME="eth0"
+
+# 处理分布式训练需要使用到的相关环境变量
+export NCCL_IB_HCA=${NCCL_IB_HCA}
+export NCCL_IB_GID_INDEX=${NCCL_IB_GID_INDEX}
+export NCCL_NET_GDR_LEVEL=2
+# export NCCL_DEBUG_SUBSYS=ALL
+# 加速
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS
+export NCCL_IB_DISABLE=0
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME}
+
+# used for check save when communication
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000 # timeout set to 1 hour (unit: seconds)
+
+# ==== 多节点配置 ====
+# 总节点数(根据实际情况修改)
+NUM_NODES=${PET_NNODES}
+# 当前节点索引(0-based,每个节点启动时需指定不同值)
+NODE_RANK=${PET_NODE_RANK}
+# 主节点IP地址(确保所有节点可访问)
+MASTER_ADDR=${PET_MASTER_ADDR} # 替换为实际主节点IP
+# 主节点端口(保持与代码中一致)
+MASTER_PORT=${PET_MASTER_PORT}
+NUM_GPUS_PER_NODE=2
+
+source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+
+cd /mnt/workspace/users/liao/proj/JoyRA
+
+Framework_name=QwenPerceiver
+base_vlm=/mnt/workspace/users/chidafeng/models/Qwen3-VL-4B-Instruct-Action
+freeze_module_list='' # just for fast debug, sota is under fully FT, i.g., freeze_module_list=""
+DIT_TYPE="DiT-B"
+data_root_dir=/mnt/workspace/datasets
+data_mix=robocasa_teleop_ee
+pretrained_checkpoint='/mnt/workspace/users/chidafeng/results/Checkpoints/VLM-cam_ref_cos_gal-VLA-ego_dex_suqian_agibot_agi-4nodes-mn1-vla-pretrain-vlm-mn6-QwenPerceiver/final_model/pytorch_model.pt'
+action_dim=32
+state_dim=64
+output_dim=1024
+
+
+run_root_dir=/mnt/workspace/users/liao/training_outputs/train_robocasa_teleop_ee
+run_id=train_robocasa_teleop_ee
+
+export WANDB_MODE=offline
+export WANDB_DIR=../../
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p ${output_dir}
+# mv this script to the output dir
+cp $0 ${output_dir}/
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE:-8} \
+ starVLA/training/train_starvla.py \
+ --config_yaml ./examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml \
+ --framework.name ${Framework_name} \
+ --framework.qwenvl.base_vlm ${base_vlm} \
+ --framework.action_model.action_model_type ${DIT_TYPE} \
+ --datasets.vla_data.data_root_dir ${data_root_dir} \
+ --datasets.vla_data.data_mix ${data_mix} \
+ --datasets.vla_data.per_device_batch_size 16 \
+ --trainer.freeze_modules ${freeze_module_list} \
+ --trainer.max_train_steps 200000 \
+ --trainer.save_interval 20000 \
+ --trainer.logging_frequency 100 \
+ --trainer.eval_interval 100 \
+ --trainer.learning_rate.base 3e-5 \
+ --trainer.pretrained_checkpoint ${pretrained_checkpoint} \
+ --framework.action_model.action_dim ${action_dim} \
+ --framework.action_model.state_dim ${state_dim} \
+ --framework.action_model.hidden_size ${output_dim} \
+ --framework.action_model.diffusion_model_cfg.output_dim ${output_dim} \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project starVLA_robocasa \
+ --wandb_entity rammusleo \
+ 2>&1 | tee -a "${output_dir}/train.log"
+ # --is_debug True
+ # --trainer.pretrained_checkpoint outputs/pretrain_sq_joint/checkpoints/steps_100000_pytorch_model.pt \
+
+
+
diff --git a/examples/Robocasa_tabletop/train_files_new/back.sh b/examples/Robocasa_tabletop/train_files_new/back.sh
new file mode 100644
index 0000000000000000000000000000000000000000..9b6505c84de2a70ce77cef6f9613ff7bd5b4747e
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files_new/back.sh
@@ -0,0 +1,38 @@
+#!/bin/bash
+
+EVAL_SCRIPT="$(cd "$(dirname "$0")" && pwd)/run_yzh_cosmos25_perceiver_vjepa2_ac.sh"
+LOG_FILE="/mnt/workspace/users/maxiangkai/projects/WM4A/examples/Robocasa_tabletop/train_files_new/train_back_$(date +%Y%m%d_%H%M%S).log"
+mkdir -p "$(dirname "${LOG_FILE}")"
+
+if [ ! -f "${EVAL_SCRIPT}" ]; then
+ echo "ERROR: cannot find ${EVAL_SCRIPT}" >&2; exit 1
+fi
+
+nohup setsid bash "${EVAL_SCRIPT}" "$@" >"${LOG_FILE}" 2>&1 &
+EVAL_PID=$!
+disown "${EVAL_PID}" 2>/dev/null || true
+sleep 1
+
+ABS_LOG_FILE="$(cd "$(dirname "${LOG_FILE}")" && pwd)/$(basename "${LOG_FILE}")"
+
+cat </dev/null; echo ""; echo "Detached from log. Eval PID=${EVAL_PID} still running."; echo " Re-attach: tail -F ${ABS_LOG_FILE}"; exit 0' INT
+wait "${TAIL_PID}"
\ No newline at end of file
diff --git a/examples/Robocasa_tabletop/train_files_new/run_yzh_cosmos25_perceiver_vjepa2_ac.sh b/examples/Robocasa_tabletop/train_files_new/run_yzh_cosmos25_perceiver_vjepa2_ac.sh
new file mode 100644
index 0000000000000000000000000000000000000000..79d4bf38d9fc8f60d7420fb6ca6465e84e77597b
--- /dev/null
+++ b/examples/Robocasa_tabletop/train_files_new/run_yzh_cosmos25_perceiver_vjepa2_ac.sh
@@ -0,0 +1,137 @@
+#!/usr/bin/env zsh
+set -euo pipefail
+
+# Cosmos-Predict2.5 Perceiver training with eval-time future-image visualization.
+# Action training uses Cosmos hidden states + Perceiver; eval additionally runs
+# the Cosmos2.5 decoder/generation path and saves pred future images.
+
+if [ -d /sys/class/infiniband ]; then
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
+else
+ RDMA_DEVICES=""
+fi
+
+if [ -n "${RDMA_DEVICES}" ]; then
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
+ export NCCL_IB_HCA
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
+ export NCCL_IB_DISABLE=0
+ export NCCL_NET_GDR_LEVEL=2
+else
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
+ export NCCL_IB_DISABLE=1
+fi
+
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS || true
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+
+cd /mnt/workspace/users/maxiangkai/projects/WM4A
+if [ -f /mnt/workspace/envs/conda3/bin/activate ]; then
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+fi
+
+NUM_GPUS_PER_NODE=${1:-8} # mytest
+
+Framework_name=CosmoPredict25PerceiverVJEPA2AC
+base_wm=/mnt/workspace/users/maxiangkai/models/Cosmos-Predict2.5-2B-Post-Trained
+cosmos_revision=${COSMOS_PREDICT25_REVISION-diffusers/base/post-trained}
+base_vlm=${base_wm}
+freeze_module_list=''
+config_yaml=/mnt/workspace/users/maxiangkai/projects/WM4A/examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml
+DIT_TYPE="DiT-B"
+data_root_dir=/mnt/workspace/datasets/
+data_mix=robocasa_teleop_ee
+
+action_dim=32
+state_dim=64
+action_hidden_dim=1024
+cross_attention_dim=2048
+
+run_root_dir=/mnt/workspace/users/maxiangkai/projects/WM4A/outputs/cosmopredict25_vjepa_ImageLatent_0730
+run_id=robocasa
+
+export PYTHONPATH="${PYTHONPATH}:/mnt/workspace/users/maxiangkai/projects/WM4A"
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p "${output_dir}"
+export WANDB_MODE=offline
+export WANDB_DIR="${output_dir}/wandb"
+mkdir -p "${WANDB_DIR}"
+cp "$0" "${output_dir}/"
+cp ${config_yaml} ${output_dir}
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
+ starVLA/training/train_starvla_zero2.py \
+ --config_yaml examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr2.yaml \
+ --framework.name ${Framework_name} \
+ --framework.world_model.base_wm "${base_wm}" \
+ --framework.world_model.revision "${cosmos_revision}" \
+ --framework.world_model.extract_layers "[-1]" \
+ --framework.world_model.height 224 \
+ --framework.world_model.width 224 \
+ --framework.world_model.conditional_frame_timestep 0.1 \
+ --framework.qwenvl.base_vlm "${base_vlm}" \
+ --framework.qwenvl.vl_hidden_dim 2048 \
+ --framework.action_model.action_model_type ${DIT_TYPE} \
+ --framework.action_model.action_dim ${action_dim} \
+ --framework.action_model.state_dim ${state_dim} \
+ --framework.action_model.action_hidden_dim ${action_hidden_dim} \
+ --framework.action_model.hidden_size ${action_hidden_dim} \
+ --framework.action_model.diffusion_model_cfg.cross_attention_dim ${cross_attention_dim} \
+ --framework.action_model.diffusion_model_cfg.output_dim ${action_hidden_dim} \
+ --framework.action_model.num_target_vision_tokens 64 \
+ --framework.vjepa2_ac.repo_dir /mnt/workspace/users/maxiangkai/projects/WM4A/starVLA/facebookresearch_vjepa2_main \
+ --framework.vjepa2_ac.pretrained /mnt/workspace/users/maxiangkai/models/VJEPA2-AC/vjepa2-ac-vitg.pt \
+ --framework.future_latent_training.enabled true \
+ --framework.future_latent_training.loss_weight 0.1 \
+ --framework.future_latent_training.train_time_distribution logitnormal \
+ --framework.future_latent_training.shift 5.0 \
+ --framework.future_image_training.enabled true \
+ --framework.future_image_training.loss_weight 1.0 \
+ --framework.future_image_training.train_time_distribution logitnormal \
+ --framework.future_image_training.shift 5.0 \
+ --framework.future_image_generation.enabled true \
+ --framework.future_image_generation.conditioning_mode auto \
+ --framework.future_image_generation.max_samples 1 \
+ --framework.future_image_generation.height 224 \
+ --framework.future_image_generation.width 224 \
+ --framework.future_image_generation.num_frames 93 \
+ --framework.future_image_generation.num_inference_steps 20 \
+ --framework.future_image_generation.guidance_scale 7.0 \
+ --framework.future_image_generation.output_type pil \
+ --framework.future_image_generation.future_frame_index -1 \
+ --framework.future_image_generation.return_full_video false \
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
+ --datasets.vla_data.data_mix "${data_mix}" \
+ --datasets.vla_data.include_state true \
+ --datasets.vla_data.per_device_batch_size 14 \
+ --datasets.vla_data.video_backend decord \
+ --trainer.freeze_modules "${freeze_module_list}" \
+ --trainer.max_train_steps 400000 \
+ --trainer.save_interval 10000 \
+ --trainer.logging_frequency 500 \
+ --trainer.eval_interval 500 \
+ --trainer.num_warmup_steps 2000 \
+ --trainer.learning_rate.base 1e-5 \
+ --trainer.learning_rate.action_model 5e-5 \
+ --trainer.learning_rate.vjepa_predictor 5e-5 \
+ --trainer.learning_rate.state_projector 5e-5 \
+ --trainer.learning_rate.action_projector 5e-5 \
+ --trainer.scheduler_specific_kwargs.min_lr 2e-7 \
+ --trainer.optimizer.betas "[0.9,0.999]" \
+ --trainer.optimizer.weight_decay 0.1 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project joyRA_robocasa_mxk \
+ --wandb_entity mxk \
+ 2>&1 | tee -a "${output_dir}/train.log"
diff --git a/examples/Robotwin/README.md b/examples/Robotwin/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..958c7f83e725c52f1a7433256183f8d6efd5681e
--- /dev/null
+++ b/examples/Robotwin/README.md
@@ -0,0 +1,170 @@
+# 🚀 RoboTwin 2.0 Evaluation
+
+This document provides instructions for reproducing our **experimental results** with [RoboTwin2.0](https://github.com/RoboTwin-Platform/RoboTwin).
+The evaluation process consists of two main parts:
+
+1. Setting up the `robotwin` environment and dependencies.
+2. Running the evaluation by launching services in both `starVLA` and `robotwin` environments.
+
+We have verified that this workflow runs successfully on **NVIDIA 4090** GPUs.
+
+# Results
+
+
+
+RoboTwin 2.0 Benchmark Results over 48 Tasks
+
+
+| Task Name | RDT Easy | RDT Hard | Pi0 Easy | Pi0 Hard | ACT Easy | ACT Hard | DP Easy | DP Hard | DP3 Easy | DP3 Hard | Qwen3OFT Easy |
+|:---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
+| Adjust Bottle | 81 | 75 | 90 | 56 | 97 | 23 | 97 | 0 | 99 | 3 | 96 |
+| Beat Block Hammer | 77 | 37 | 43 | 21 | 56 | 3 | 42 | 0 | 72 | 8 | 58 |
+| Blocks Ranking RGB | 3 | 0 | 19 | 5 | 1 | 0 | 0 | 0 | 3 | 0 | 45 |
+| Blocks Ranking Size | 0 | 0 | 7 | 1 | 0 | 0 | 1 | 0 | 2 | 0 | 27 |
+| Click Alarmclock | 61 | 12 | 63 | 11 | 32 | 4 | 61 | 5 | 77 | 14 | 91 |
+| Click Bell | 80 | 9 | 44 | 3 | 58 | 3 | 54 | 0 | 90 | 0 | 94 |
+| Dump Bin Bigbin | 64 | 32 | 83 | 24 | 68 | 1 | 49 | 0 | 85 | 53 | 68 |
+| Grab Roller | 74 | 43 | 96 | 80 | 94 | 25 | 98 | 0 | 98 | 2 | 93 |
+| Handover Block | 45 | 14 | 45 | 8 | 42 | 0 | 10 | 0 | 70 | 0 | 0 |
+| Handover Mic | 90 | 31 | 98 | 13 | 85 | 0 | 53 | 0 | 100 | 3 | 39 |
+| Hanging Mug | 23 | 16 | 11 | 3 | 7 | 0 | 8 | 0 | 17 | 1 | 15 |
+| Lift Pot | 72 | 9 | 84 | 36 | 88 | 0 | 39 | 0 | 97 | 0 | 0 |
+| Move Can Pot | 25 | 12 | 58 | 21 | 22 | 4 | 39 | 0 | 70 | 6 | 50 |
+| Move Pillbottle Pad | 8 | 0 | 21 | 1 | 0 | 0 | 1 | 0 | 41 | 0 | 54 |
+| Move Playingcard Away | 43 | 11 | 53 | 22 | 36 | 0 | 47 | 0 | 68 | 3 | 69 |
+| Move Stapler Pad | 2 | 0 | 0 | 2 | 0 | 0 | 1 | 0 | 12 | 0 | 12 |
+| Open Laptop | 59 | 32 | 85 | 46 | 56 | 0 | 49 | 0 | 82 | 7 | 31 |
+| Open Microwave | 37 | 20 | 80 | 50 | 86 | 0 | 5 | 0 | 61 | 22 | -- |
+| Pick Diverse Bottles | 2 | 0 | 27 | 6 | 7 | 0 | 6 | 0 | 52 | 1 | 30 |
+| Pick Dual Bottles | 42 | 13 | 57 | 12 | 31 | 0 | 24 | 0 | 60 | 1 | 43 |
+| Place A2B Left | 3 | 1 | 31 | 1 | 1 | 0 | 2 | 0 | 46 | 2 | 20 |
+| Place A2B Right | 1 | 1 | 27 | 6 | 0 | 0 | 13 | 0 | 49 | 0 | 22 |
+| Place Bread Basket | 10 | 2 | 17 | 4 | 6 | 0 | 14 | 0 | 26 | 1 | 52 |
+| Place Bread Skillet | 5 | 1 | 23 | 1 | 7 | 0 | 11 | 0 | 19 | 0 | 56 |
+| Place Burger Fries | 50 | 27 | 80 | 4 | 49 | 0 | 72 | 0 | 72 | 18 | 96 |
+| Place Can Basket | 19 | 6 | 41 | 5 | 1 | 0 | 18 | 0 | 67 | 2 | 63 |
+| Place Cans Plasticbox | 6 | 5 | 34 | 2 | 16 | 0 | 40 | 0 | 48 | 3 | 81 |
+| Place Container Plate | 78 | 17 | 88 | 45 | 72 | 1 | 41 | 0 | 86 | 1 | 99 |
+| Place Dual Shoes | 4 | 4 | 15 | 0 | 9 | 0 | 8 | 0 | 13 | 0 | 28 |
+| Place Empty Cup | 56 | 7 | 37 | 11 | 61 | 0 | 37 | 0 | 65 | 1 | 72 |
+| Place Fan | 12 | 2 | 20 | 10 | 1 | 0 | 3 | 0 | 36 | 1 | 28 |
+| Place Mouse Pad | 1 | 0 | 7 | 1 | 0 | 0 | 0 | 0 | 4 | 1 | 9 |
+| Place Object Basket | 33 | 17 | 16 | 2 | 15 | 0 | 15 | 0 | 65 | 0 | 40 |
+| Place Object Scale | 1 | 0 | 10 | 0 | 0 | 0 | 1 | 0 | 15 | 0 | 19 |
+| Place Object Stand | 15 | 5 | 36 | 11 | 1 | 0 | 22 | 0 | 60 | 0 | 48 |
+| Place Phone Stand | 15 | 6 | 35 | 7 | 2 | 0 | 13 | 0 | 44 | 2 | 24 |
+| Place Shoe | 35 | 7 | 28 | 6 | 5 | 0 | 23 | 0 | 58 | 2 | 63 |
+| Press Stapler | 41 | 24 | 62 | 29 | 31 | 6 | 6 | 0 | 69 | 3 | 60 |
+| Put Bottles Dustbin | 21 | 4 | 54 | 13 | 27 | 1 | 22 | 0 | 60 | 21 | -- |
+| Put Object Cabinet | 33 | 18 | 68 | 18 | 15 | 0 | 42 | 0 | 72 | 1 | 35 |
+| Rotate QRcode | 50 | 5 | 68 | 15 | 1 | 0 | 13 | 0 | 74 | 1 | 50 |
+| Scan Object | 4 | 1 | 18 | 1 | 2 | 0 | 9 | 0 | 31 | 1 | 13 |
+| Shake Bottle Horizontally | 84 | 51 | 99 | 51 | 63 | 4 | 59 | 18 | 100 | 25 | 98 |
+| Shake Bottle | 74 | 45 | 97 | 60 | 74 | 10 | 65 | 8 | 98 | 19 | 98 |
+| Stack Blocks Three | 2 | 0 | 17 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 41 |
+| Stack Blocks Two | 21 | 2 | 42 | 1 | 25 | 0 | 7 | 0 | 24 | 0 | 83 |
+| Stack Bowls Three | 51 | 17 | 66 | 24 | 48 | 0 | 63 | 0 | 57 | 5 | 62 |
+| Stack Bowls Two | 76 | 30 | 91 | 41 | 82 | 0 | 61 | 0 | 83 | 6 | 90 |
+| Stamp Seal | 1 | 0 | 3 | 4 | 2 | 0 | 2 | 0 | 18 | 0 | 27 |
+| Turn Switch | 35 | 15 | 27 | 23 | 5 | 2 | 36 | 1 | 46 | 8 | 26 |
+| **Average** | **34.50** | **13.72** | **46.42** | **16.34** | **29.74** | **1.74** | **28.04** | **0.64** | **55.24** | **4.96** | **50.38** |
+
+*Note: All 50 tasks are trained within a single model, using 50 demonstrations per task (50×50 total demonstrations). Checkpoints can be downloaded at [Qwen3-VL-OFT-Robotwin2](https://huggingface.co/StarVLA/Qwen3-VL-OFT-Robotwin2)*.
+
+
+
+
+# Evaluation
+
+## 📦 1. Environment Setup
+
+To set up the environment, please first follow the [official RoboTwin installation guide](https://robotwin-platform.github.io/doc/usage/robotwin-install.html) to install the base `robotwin` environment.
+
+than pip install additional requirements
+
+```bash
+pip install -r examples/Robotwin/eval_files/requirements.txt
+```
+
+and edit `ROBOTWIN_PATH` in `examples/Robotwin/eval_files/eval.sh`.
+
+## 🚀 2. Evaluation Workflow
+
+### Step 1. Start the server (starVLA environment)
+
+In the first terminal, activate the `starVLA` conda environment and run:
+
+```bash
+python examples/Robotwin/eval_files/run_policy_server.sh
+```
+
+Edit your checkpoint path in `examples/Robotwin/eval_files/deploy_policy.yml` and `examples/Robotwin/eval_files/run_policy_server.sh`.
+
+---
+
+### Step 2. Start the simulation (robotwin environment)
+
+In the second terminal, activate the `robotwin` conda environment and run:
+
+```bash
+conda activate robotwin
+cd examples/Robotwin/eval_files
+bash eval.sh task_name demo_clean my_test_v1 0 0
+```
+
+all tasks in RoboTwin 2.0 include:
+
+```txt
+adjust_bottle
+beat_block_hammer
+blocks_ranking_rgb
+blocks_ranking_size
+click_alarmclock
+click_bell
+dump_bin_bigbin
+grab_roller
+handover_block
+handover_mic
+hanging_mug
+lift_pot
+move_can_pot
+move_pillbottle_pad
+move_playingcard_away
+move_stapler_pad
+open_laptop
+open_microwave
+pick_diverse_bottles
+pick_dual_bottles
+place_a2b_left
+place_a2b_right
+place_bread_basket
+place_bread_skillet
+place_burger_fries
+place_can_basket
+place_cans_plasticbox
+place_container_plate
+place_dual_shoes
+place_empty_cup
+place_fan
+place_mouse_pad
+place_object_basket
+place_object_scale
+place_object_stand
+place_phone_stand
+place_shoe
+press_stapler
+put_bottles_dustbin
+put_object_cabinet
+rotate_qrcode
+scan_object
+shake_bottle_horizontally
+shake_bottle
+stack_blocks_three
+stack_blocks_two
+stack_bowls_three
+stack_bowls_two
+stamp_seal
+turn_switch
+```
+
+and all modes include `demo_clean` and `demo_randomized`.
diff --git a/examples/Robotwin/eval_files/deploy_policy.yml b/examples/Robotwin/eval_files/deploy_policy.yml
new file mode 100644
index 0000000000000000000000000000000000000000..2485935a84a66a5fe94dcaef7887a0c5d7a369d6
--- /dev/null
+++ b/examples/Robotwin/eval_files/deploy_policy.yml
@@ -0,0 +1,12 @@
+policy_name: starVLA
+task_name: null
+task_config: null
+ckpt_setting: null
+seed: null
+instruction_type: unseen
+
+# StarVLA Client Parameters
+host: "127.0.0.1"
+port: 5694
+policy_ckpt_path: "/mnt/data/gaoning/code_repos/starVLA/results/Checkpoints/robotwin2/QwenPI-noState/checkpoints/steps_60000_pytorch_model.pt"
+unnorm_key: "robotwin"
diff --git a/examples/Robotwin/eval_files/eval.sh b/examples/Robotwin/eval_files/eval.sh
new file mode 100644
index 0000000000000000000000000000000000000000..fc5cfd821ee7ef7935d97bda04541171e1d8fe25
--- /dev/null
+++ b/examples/Robotwin/eval_files/eval.sh
@@ -0,0 +1,34 @@
+#!/bin/bash
+
+ROBOTWIN_PATH=/mnt/data/gaoning/code_repos/RoboTwin
+
+policy_name="model2robotwin_interface"
+task_name=${1}
+task_config=${2}
+ckpt_setting=${3:-starvla_demo}
+seed=${4:-0}
+gpu_id=${5:-0} # default is 0
+
+export CUDA_VISIBLE_DEVICES=${gpu_id}
+echo -e "\033[33mgpu id (to use): ${gpu_id}\033[0m"
+
+EVAL_FILES_PATH=$(pwd)
+STARVLA_PATH=$EVAL_FILES_PATH/../../..
+DEPLOY_POLICY_PATH=$EVAL_FILES_PATH/deploy_policy.yml
+
+export PYTHONPATH=$ROBOTWIN_PATH:$PYTHONPATH
+export PYTHONPATH=$STARVLA_PATH:$PYTHONPATH
+export PYTHONPATH=$EVAL_FILES_PATH:$PYTHONPATH
+
+cd $ROBOTWIN_PATH
+
+echo "PYTHONPATH: $PYTHONPATH"
+
+PYTHONWARNINGS=ignore::UserWarning \
+python script/eval_policy.py --config $DEPLOY_POLICY_PATH \
+ --overrides \
+ --task_name ${task_name} \
+ --task_config ${task_config} \
+ --ckpt_setting ${ckpt_setting} \
+ --seed ${seed} \
+ --policy_name ${policy_name}
diff --git a/examples/Robotwin/eval_files/model2robotwin_interface.py b/examples/Robotwin/eval_files/model2robotwin_interface.py
new file mode 100644
index 0000000000000000000000000000000000000000..6f2a124f4a07e0083d5eac4bcaf81b806f360771
--- /dev/null
+++ b/examples/Robotwin/eval_files/model2robotwin_interface.py
@@ -0,0 +1,235 @@
+import collections
+import logging
+import math
+import time
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Dict, Optional, Sequence
+from collections import deque
+
+import numpy as np
+import cv2 as cv
+import json_numpy
+
+
+from deployment.model_server.tools.websocket_policy_client import WebsocketClientPolicy
+from starVLA.model.tools import read_mode_config
+
+try:
+ from examples.SimplerEnv.eval_files.adaptive_ensemble import AdaptiveEnsembler
+except ImportError:
+ AdaptiveEnsembler = None
+
+
+class ModelClient:
+ def __init__(
+ self,
+ policy_ckpt_path,
+ unnorm_key: Optional[str] = None,
+ policy_setup: str = "robotwin",
+ horizon: int = 0,
+ action_ensemble=False,
+ action_ensemble_horizon: Optional[int] = 3,
+ image_size: list[int] = [224, 224],
+ use_ddim: bool = True,
+ num_ddim_steps: int = 10,
+ adaptive_ensemble_alpha=0.1,
+ host="127.0.0.1",
+ port=5694,
+ ) -> None:
+
+ self.client = WebsocketClientPolicy(host, port)
+ self.policy_setup = policy_setup
+ self.unnorm_key = unnorm_key
+
+ print(f"*** policy_setup: {policy_setup}, unnorm_key: {unnorm_key} ***")
+ self.use_ddim = use_ddim
+ self.num_ddim_steps = num_ddim_steps
+ self.image_size = image_size
+ self.horizon = horizon
+ self.action_ensemble = action_ensemble and (AdaptiveEnsembler is not None)
+ self.adaptive_ensemble_alpha = adaptive_ensemble_alpha
+ self.action_ensemble_horizon = action_ensemble_horizon
+
+ self.task_description = None
+ self.image_history = deque(maxlen=self.horizon)
+ if self.action_ensemble:
+ self.action_ensembler = AdaptiveEnsembler(self.action_ensemble_horizon, self.adaptive_ensemble_alpha)
+ else:
+ self.action_ensembler = None
+ self.num_image_history = 0
+
+ self.action_norm_stats = self.get_action_stats(self.unnorm_key, policy_ckpt_path=policy_ckpt_path)
+ self.action_chunk_size = self.get_action_chunk_size(policy_ckpt_path=policy_ckpt_path)
+ self.state_norm_stats = self.get_state_stats(self.unnorm_key, policy_ckpt_path=policy_ckpt_path)
+ self.raw_actions = None
+
+ def reset(self, task_description: str) -> None:
+ self.task_description = task_description
+ self.image_history.clear()
+ if self.action_ensemble:
+ self.action_ensembler.reset()
+ self.num_image_history = 0
+ self.raw_actions = None
+
+ def step(
+ self,
+ example: dict,
+ step: int = 0,
+ ) -> np.ndarray:
+ state = example.get("state", None)
+ # if state is not None:
+ # state = self.normalize_state(state, self.state_norm_stats)
+ # state = state[[0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 6, 13]]
+ # example["state"] = state.reshape(1, -1)
+
+ task_description = example.get("lang", None)
+ images = example["image"]
+
+ if example is not None:
+ if task_description != self.task_description:
+ self.reset(task_description)
+
+ images = [self._resize_image(image) for image in images]
+ example["image"] = images
+ vla_input = {
+ "examples": [example],
+ "do_sample": False,
+ "use_ddim": self.use_ddim,
+ "num_ddim_steps": self.num_ddim_steps,
+ }
+
+ action_chunk_size = self.action_chunk_size
+
+ if step % action_chunk_size == 0 or self.raw_actions is None:
+ response = self.client.predict_action(vla_input)
+ try:
+ normalized_actions = response["data"]["normalized_actions"] # B, chunk, D
+ except KeyError:
+ print(f"Response data: {response}")
+ raise KeyError(f"Key 'normalized_actions' not found in response data: {response['data'].keys()}")
+
+ normalized_actions = normalized_actions[0]
+ self.raw_actions = self.unnormalize_actions(
+ normalized_actions=normalized_actions, action_norm_stats=self.action_norm_stats
+ )
+
+ action_idx = step % action_chunk_size
+ if action_idx >= len(self.raw_actions):
+ pass
+
+ current_action = self.raw_actions[action_idx]
+ current_action = current_action[[0, 1, 2, 3, 4, 5, 12, 6, 7, 8, 9, 10, 11, 13]]
+ return current_action
+
+ @staticmethod
+ def normalize_state(state: dict[str, np.ndarray], state_norm_stats: Dict[str, np.ndarray]) -> dict[str, np.ndarray]:
+ """
+ Normalize the state
+ """
+ mask = [True, True, True, True, True, True, True, True, True, True, True, True, False, False]
+ mask = np.array(mask, dtype=bool)
+ state_high, state_low = np.array(state_norm_stats["max"]), np.array(state_norm_stats["min"])
+ normalized_state = np.where(
+ mask,
+ (state - state_low) / (state_high - state_low) * 2 - 1,
+ state,
+ )
+ normalized_state = np.where(~mask, (normalized_state > 0.5).astype(normalized_state.dtype), normalized_state)
+ return normalized_state
+
+ @staticmethod
+ def unnormalize_actions(normalized_actions: np.ndarray, action_norm_stats: Dict[str, np.ndarray]) -> np.ndarray:
+ mask = action_norm_stats.get("mask", np.ones_like(action_norm_stats["min"], dtype=bool))
+ action_high, action_low = np.array(action_norm_stats["max"]), np.array(action_norm_stats["min"])
+ normalized_actions = np.clip(normalized_actions, -1, 1)
+
+ actions = np.where(
+ mask,
+ 0.5 * (normalized_actions + 1) * (action_high - action_low) + action_low,
+ normalized_actions,
+ )
+
+ return actions
+
+ @staticmethod
+ def get_action_stats(unnorm_key: str, policy_ckpt_path) -> dict:
+ policy_ckpt_path = Path(policy_ckpt_path)
+ model_config, norm_stats = read_mode_config(policy_ckpt_path)
+ unnorm_key = ModelClient._check_unnorm_key(norm_stats, unnorm_key)
+ return norm_stats[unnorm_key]["action"]
+
+ @staticmethod
+ def get_state_stats(unnorm_key: str, policy_ckpt_path) -> dict:
+ policy_ckpt_path = Path(policy_ckpt_path)
+ model_config, norm_stats = read_mode_config(policy_ckpt_path)
+ unnorm_key = ModelClient._check_unnorm_key(norm_stats, unnorm_key)
+ return norm_stats[unnorm_key]["state"]
+
+ @staticmethod
+ def get_action_chunk_size(policy_ckpt_path):
+ model_config, _ = read_mode_config(policy_ckpt_path)
+ return model_config["framework"]["action_model"]["future_action_window_size"] + 1
+
+ def _resize_image(self, image: np.ndarray) -> np.ndarray:
+ image = cv.resize(image, tuple(self.image_size), interpolation=cv.INTER_AREA)
+ return image
+
+ @staticmethod
+ def _check_unnorm_key(norm_stats, unnorm_key):
+ if unnorm_key is None:
+ if len(norm_stats) == 1:
+ unnorm_key = next(iter(norm_stats.keys()))
+ else:
+ unnorm_key = next(iter(norm_stats.keys()))
+
+ if unnorm_key not in norm_stats:
+ unnorm_key = next(iter(norm_stats.keys()))
+
+ return unnorm_key
+
+
+def get_model(usr_args):
+ policy_ckpt_path = usr_args.get("policy_ckpt_path")
+ host = usr_args.get("host", "127.0.0.1")
+ port = usr_args.get("port", 5694)
+ unnorm_key = usr_args.get("unnorm_key", None)
+
+ if policy_ckpt_path is None:
+ raise ValueError("policy_ckpt_path must be provided in config")
+
+ return ModelClient(
+ policy_ckpt_path=policy_ckpt_path,
+ host=host,
+ port=port,
+ unnorm_key=unnorm_key,
+ )
+
+
+def reset_model(model):
+ model.reset(task_description="")
+
+
+def eval(TASK_ENV, model, observation):
+ # Get instruction
+ instruction = TASK_ENV.get_instruction()
+
+ # Prepare images
+ head_img = observation["observation"]["head_camera"]["rgb"]
+ left_img = observation["observation"]["left_camera"]["rgb"]
+ right_img = observation["observation"]["right_camera"]["rgb"]
+
+ # Order: [head, left, right] to match training order
+ images = [head_img, left_img, right_img]
+
+ state = observation["joint_action"]["vector"]
+ example = {
+ "lang": str(instruction),
+ "image": images,
+ # "state": state,
+ }
+
+ action = model.step(example, step=TASK_ENV.take_action_cnt)
+
+ # Execute action
+ TASK_ENV.take_action(action)
diff --git a/examples/Robotwin/eval_files/requirements.txt b/examples/Robotwin/eval_files/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..a15aea9caf9e1acdc89990adbfb5fc6e9a6aa9fc
--- /dev/null
+++ b/examples/Robotwin/eval_files/requirements.txt
@@ -0,0 +1,6 @@
+accelerate==1.5.2
+json_numpy==2.1.1
+websockets==15.0.1
+msgpack==1.1.2
+rich==14.2.0
+omegaconf==2.3.0
\ No newline at end of file
diff --git a/examples/Robotwin/eval_files/run_policy_server.sh b/examples/Robotwin/eval_files/run_policy_server.sh
new file mode 100644
index 0000000000000000000000000000000000000000..722f5b931089f45515111ec2e86302c523a2a723
--- /dev/null
+++ b/examples/Robotwin/eval_files/run_policy_server.sh
@@ -0,0 +1,15 @@
+#!/bin/bash
+export PYTHONPATH=$(pwd):${PYTHONPATH} # let LIBERO find the websocket tools from main repo
+export star_vla_python=/root/miniconda3/envs/starvla/bin/python
+your_ckpt=results/Checkpoints/robotwin2/QwenPI-noState/checkpoints/steps_60000_pytorch_model.pt
+gpu_id=0
+port=5694
+################# star Policy Server ######################
+
+# export DEBUG=true
+CUDA_VISIBLE_DEVICES=$gpu_id ${star_vla_python} deployment/model_server/server_policy.py \
+ --ckpt_path ${your_ckpt} \
+ --port ${port} \
+ --use_bf16
+
+# #################################
diff --git a/examples/Robotwin/train_files/joyra05.sh b/examples/Robotwin/train_files/joyra05.sh
new file mode 100644
index 0000000000000000000000000000000000000000..706fbae66a02a3b1167d91cd6b17c18e3944e1ac
--- /dev/null
+++ b/examples/Robotwin/train_files/joyra05.sh
@@ -0,0 +1,99 @@
+#!/usr/bin/env zsh
+set -euo pipefail
+
+# Cosmos-Predict2.5 Perceiver training with eval-time future-image visualization.
+# Action training uses Cosmos hidden states + Perceiver; eval additionally runs
+# the Cosmos2.5 decoder/generation path and saves pred future images.
+
+if [ -d /sys/class/infiniband ]; then
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
+else
+ RDMA_DEVICES=""
+fi
+
+if [ -n "${RDMA_DEVICES}" ]; then
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
+ export NCCL_IB_HCA
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
+ export NCCL_IB_DISABLE=0
+ export NCCL_NET_GDR_LEVEL=2
+else
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
+ export NCCL_IB_DISABLE=1
+fi
+
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS || true
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+
+cd /mnt/workspace/users/maxiangkai/projects/WM4A
+if [ -f /mnt/workspace/envs/conda3/bin/activate ]; then
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+fi
+
+NUM_GPUS_PER_NODE=${1:-8} # mytest
+
+Framework_name=QwenWanPerceiver
+base_vlm=/mnt/workspace/users/maxiangkai/models/Qwen3-VL-4B-Instruct
+base_wm=/mnt/workspace/users/maxiangkai/models/Wan2.2-TI2V-5B-Diffusers
+transformer_path=/mnt/workspace/users/maxiangkai/models/Motus_Wan2_2_5B_pretrain
+pretrained_checkpoint=/mnt/workspace/users/chidafeng/main_results/joyra05/pretrain/0529_joyra05_data_0530_QwenWanPerceiver_15wsteps_bs16/final_model/pytorch_model.pt
+config_yaml=/mnt/workspace/users/maxiangkai/projects/WM4A/examples/Robotwin/train_files/starvla_cotrain_robotwin.yaml
+DIT_TYPE="DiT-B"
+data_root_dir=/mnt/workspace/datasets/
+data_mix=robotwin_ee
+
+run_root_dir=/mnt/workspace/users/maxiangkai/projects/WM4A/outputs/joyra05
+run_id=robotwin
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p "${output_dir}"
+export WANDB_MODE=offline
+export WANDB_DIR="${output_dir}/wandb"
+mkdir -p "${WANDB_DIR}"
+cp "$0" "${output_dir}/"
+cp ${config_yaml} ${output_dir}
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
+ starVLA/training/train_starvla.py \
+ --config_yaml ${config_yaml} \
+ --framework.name ${Framework_name} \
+ --framework.qwenvl.base_vlm "${base_vlm}" \
+ --framework.qwenvl.vl_hidden_dim 2048 \
+ --framework.world_model.base_wm ${base_wm} \
+ --framework.world_model.transformer_path ${transformer_path} \
+ --framework.world_model.extract_layers "[-1]" \
+ --framework.action_model.hidden_size 1024 \
+ --framework.action_model.diffusion_model_cfg.output_dim 1024 \
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
+ --datasets.vla_data.data_mix "${data_mix}" \
+ --datasets.vla_data.include_state true \
+ --datasets.vla_data.per_device_batch_size 8 \
+ --datasets.vla_data.num_workers 8 \
+ --datasets.vla_data.prefetch_factor 2 \
+ --datasets.vla_data.pin_memory true \
+ --datasets.vla_data.persistent_workers true \
+ --trainer.pretrained_checkpoint ${pretrained_checkpoint} \
+ --trainer.max_train_steps 300000 \
+ --trainer.save_interval 50000 \
+ --trainer.logging_frequency 500 \
+ --trainer.eval_interval 500 \
+ --trainer.num_warmup_steps 1000 \
+ --trainer.learning_rate.base 1e-5 \
+ --trainer.scheduler_specific_kwargs.min_lr 1.2e-6 \
+ --trainer.optimizer.betas "[0.9,0.999]" \
+ --trainer.optimizer.weight_decay 0.1 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project joyRA_robotwin_mxk \
+ --wandb_entity mxk \
+ 2>&1 | tee -a "${output_dir}/train.log"
diff --git a/examples/Robotwin/train_files/joyra05mask.sh b/examples/Robotwin/train_files/joyra05mask.sh
new file mode 100644
index 0000000000000000000000000000000000000000..dc0bc154b0808e57cc6fec8528fb10f296d0b6da
--- /dev/null
+++ b/examples/Robotwin/train_files/joyra05mask.sh
@@ -0,0 +1,123 @@
+#!/usr/bin/env zsh
+set -euo pipefail
+
+# Cosmos-Predict2.5 Perceiver training with eval-time future-image visualization.
+# Action training uses Cosmos hidden states + Perceiver; eval additionally runs
+# the Cosmos2.5 decoder/generation path and saves pred future images.
+
+if [ -d /sys/class/infiniband ]; then
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
+else
+ RDMA_DEVICES=""
+fi
+
+if [ -n "${RDMA_DEVICES}" ]; then
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
+ export NCCL_IB_HCA
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
+ export NCCL_IB_DISABLE=0
+ export NCCL_NET_GDR_LEVEL=2
+else
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
+ export NCCL_IB_DISABLE=1
+fi
+
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS || true
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+
+cd /mnt/workspace/users/maxiangkai/projects/WM4A
+if [ -f /mnt/workspace/envs/conda3/bin/activate ]; then
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+fi
+
+NUM_GPUS_PER_NODE=${1:-8} # mytest
+
+Framework_name=QwenWanPerceiverMask
+base_vlm=/mnt/workspace/users/maxiangkai/models/Qwen3-VL-4B-Instruct
+base_wm=/mnt/workspace/users/xiangzhiyuan/FastWAM/converted/step_115000_Wan2.2-TI2V-5B-Diffusers
+transformer_path=/mnt/workspace/users/maxiangkai/models/Motus_Wan2_2_5B_pretrain
+pretrained_checkpoint=/mnt/workspace/users/chidafeng/main_results/joyra05/pretrain/0529_joyra05_data_0530_QwenWanPerceiver_15wsteps_bs16/final_model/pytorch_model.pt
+config_yaml=/mnt/workspace/users/maxiangkai/projects/WM4A/examples/Robotwin/train_files/starvla_cotrain_robotwin.yaml
+DIT_TYPE="DiT-B"
+data_root_dir=/mnt/workspace/datasets/
+data_mix=robotwin_ee
+
+run_root_dir=/mnt/workspace/users/maxiangkai/projects/WM4A/outputs/joyra05mask
+run_id=robotwin # mytest
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p "${output_dir}"
+export WANDB_MODE=offline
+export WANDB_DIR="${output_dir}/wandb"
+mkdir -p "${WANDB_DIR}"
+cp "$0" "${output_dir}/"
+cp ${config_yaml} ${output_dir}
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
+ starVLA/training/train_starvla_zero2.py \
+ --config_yaml ${config_yaml} \
+ --framework.name ${Framework_name} \
+ --framework.qwenvl.base_vlm "${base_vlm}" \
+ --framework.qwenvl.vl_hidden_dim 2048 \
+ --framework.qwenvl.is_frozen false \
+ --framework.world_model.base_wm ${base_wm} \
+ --framework.world_model.transformer_path ${transformer_path} \
+ --framework.world_model.extract_layers "[-1]" \
+ --framework.action_model.hidden_size 1024 \
+ --framework.action_model.diffusion_model_cfg.output_dim 1024 \
+ --framework.future_image_training.enabled true \
+ --framework.future_image_training.loss_weight 1.0 \
+ --framework.future_image_training.train_time_distribution logitnormal \
+ --framework.future_image_training.shift 5.0 \
+ --framework.future_image_training.change_mask_enabled true \
+ --framework.future_image_training.change_mask_top_ratio 0.25 \
+ --framework.future_image_training.change_mask_static_weight 0.05 \
+ --framework.future_image_training.change_mask_soft_loss true \
+ --framework.future_image_training.masked_denoising false \
+ --framework.future_image_training.condition_static_regions false \
+ --framework.future_image_generation.enabled true \
+ --framework.future_image_generation.conditioning_mode auto \
+ --framework.future_image_generation.max_samples 8 \
+ --framework.future_image_generation.height 224 \
+ --framework.future_image_generation.width 224 \
+ --framework.future_image_generation.num_frames 9 \
+ --framework.future_image_generation.num_inference_steps 20 \
+ --framework.future_image_generation.guidance_scale 7.0 \
+ --framework.future_image_generation.output_type pil \
+ --framework.future_image_generation.future_frame_index -1 \
+ --framework.future_image_generation.num_latent_conditional_frames 1 \
+ --framework.future_image_generation.return_full_video false \
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
+ --datasets.vla_data.data_mix "${data_mix}" \
+ --datasets.vla_data.future_video_delta_indices "[16]" \
+ --datasets.vla_data.include_state true \
+ --datasets.vla_data.per_device_batch_size 2 \
+ --datasets.vla_data.num_workers 8 \
+ --datasets.vla_data.prefetch_factor 2 \
+ --datasets.vla_data.pin_memory true \
+ --datasets.vla_data.persistent_workers true \
+ --trainer.pretrained_checkpoint ${pretrained_checkpoint} \
+ --trainer.max_train_steps 300000 \
+ --trainer.save_interval 50000 \
+ --trainer.logging_frequency 500 \
+ --trainer.eval_interval 500 \
+ --trainer.num_warmup_steps 1000 \
+ --trainer.learning_rate.base 1e-5 \
+ --trainer.scheduler_specific_kwargs.min_lr 1.2e-6 \
+ --trainer.optimizer.betas "[0.9,0.999]" \
+ --trainer.optimizer.weight_decay 0.1 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project joyRA_robotwin_mxk \
+ --wandb_entity mxk \
+ 2>&1 | tee -a "${output_dir}/train.log"
diff --git a/examples/Robotwin/train_files/joyra05mask_frozen_vlm.sh b/examples/Robotwin/train_files/joyra05mask_frozen_vlm.sh
new file mode 100644
index 0000000000000000000000000000000000000000..f4792323cd245fe2eae2be4366b85112de6ea0be
--- /dev/null
+++ b/examples/Robotwin/train_files/joyra05mask_frozen_vlm.sh
@@ -0,0 +1,123 @@
+#!/usr/bin/env zsh
+set -euo pipefail
+
+# Cosmos-Predict2.5 Perceiver training with eval-time future-image visualization.
+# Action training uses Cosmos hidden states + Perceiver; eval additionally runs
+# the Cosmos2.5 decoder/generation path and saves pred future images.
+
+if [ -d /sys/class/infiniband ]; then
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
+else
+ RDMA_DEVICES=""
+fi
+
+if [ -n "${RDMA_DEVICES}" ]; then
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
+ export NCCL_IB_HCA
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
+ export NCCL_IB_DISABLE=0
+ export NCCL_NET_GDR_LEVEL=2
+else
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
+ export NCCL_IB_DISABLE=1
+fi
+
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS || true
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+
+cd /mnt/workspace/users/maxiangkai/projects/WM4A
+if [ -f /mnt/workspace/envs/conda3/bin/activate ]; then
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+fi
+
+NUM_GPUS_PER_NODE=${1:-8} # mytest
+
+Framework_name=QwenWanPerceiverMask
+base_vlm=/mnt/workspace/users/maxiangkai/models/Qwen3-VL-4B-Instruct
+base_wm=/mnt/workspace/users/xiangzhiyuan/FastWAM/converted/step_115000_Wan2.2-TI2V-5B-Diffusers
+transformer_path=/mnt/workspace/users/maxiangkai/models/Motus_Wan2_2_5B_pretrain
+pretrained_checkpoint=/mnt/workspace/users/chidafeng/main_results/joyra05/pretrain/0529_joyra05_data_0530_QwenWanPerceiver_15wsteps_bs16/final_model/pytorch_model.pt
+config_yaml=/mnt/workspace/users/maxiangkai/projects/WM4A/examples/Robotwin/train_files/starvla_cotrain_robotwin.yaml
+DIT_TYPE="DiT-B"
+data_root_dir=/mnt/workspace/datasets/
+data_mix=robotwin_ee
+
+run_root_dir=/mnt/workspace/users/maxiangkai/projects/WM4A/outputs/joyra05mask_frozen_vlm
+run_id=robotwin # mytest
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p "${output_dir}"
+export WANDB_MODE=offline
+export WANDB_DIR="${output_dir}/wandb"
+mkdir -p "${WANDB_DIR}"
+cp "$0" "${output_dir}/"
+cp ${config_yaml} ${output_dir}
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
+ starVLA/training/train_starvla_zero2.py \
+ --config_yaml ${config_yaml} \
+ --framework.name ${Framework_name} \
+ --framework.qwenvl.base_vlm "${base_vlm}" \
+ --framework.qwenvl.vl_hidden_dim 2048 \
+ --framework.qwenvl.is_frozen true \
+ --framework.world_model.base_wm ${base_wm} \
+ --framework.world_model.transformer_path ${transformer_path} \
+ --framework.world_model.extract_layers "[-1]" \
+ --framework.action_model.hidden_size 1024 \
+ --framework.action_model.diffusion_model_cfg.output_dim 1024 \
+ --framework.future_image_training.enabled true \
+ --framework.future_image_training.loss_weight 1.0 \
+ --framework.future_image_training.train_time_distribution logitnormal \
+ --framework.future_image_training.shift 5.0 \
+ --framework.future_image_training.change_mask_enabled true \
+ --framework.future_image_training.change_mask_top_ratio 0.25 \
+ --framework.future_image_training.change_mask_static_weight 0.05 \
+ --framework.future_image_training.change_mask_soft_loss true \
+ --framework.future_image_training.masked_denoising false \
+ --framework.future_image_training.condition_static_regions false \
+ --framework.future_image_generation.enabled true \
+ --framework.future_image_generation.conditioning_mode auto \
+ --framework.future_image_generation.max_samples 8 \
+ --framework.future_image_generation.height 224 \
+ --framework.future_image_generation.width 224 \
+ --framework.future_image_generation.num_frames 9 \
+ --framework.future_image_generation.num_inference_steps 20 \
+ --framework.future_image_generation.guidance_scale 7.0 \
+ --framework.future_image_generation.output_type pil \
+ --framework.future_image_generation.future_frame_index -1 \
+ --framework.future_image_generation.num_latent_conditional_frames 1 \
+ --framework.future_image_generation.return_full_video false \
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
+ --datasets.vla_data.data_mix "${data_mix}" \
+ --datasets.vla_data.future_video_delta_indices "[16]" \
+ --datasets.vla_data.include_state true \
+ --datasets.vla_data.per_device_batch_size 2 \
+ --datasets.vla_data.num_workers 8 \
+ --datasets.vla_data.prefetch_factor 2 \
+ --datasets.vla_data.pin_memory true \
+ --datasets.vla_data.persistent_workers true \
+ --trainer.pretrained_checkpoint ${pretrained_checkpoint} \
+ --trainer.max_train_steps 300000 \
+ --trainer.save_interval 50000 \
+ --trainer.logging_frequency 500 \
+ --trainer.eval_interval 500 \
+ --trainer.num_warmup_steps 1000 \
+ --trainer.learning_rate.base 1e-5 \
+ --trainer.scheduler_specific_kwargs.min_lr 1.2e-6 \
+ --trainer.optimizer.betas "[0.9,0.999]" \
+ --trainer.optimizer.weight_decay 0.1 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project joyRA_robotwin_mxk \
+ --wandb_entity mxk \
+ 2>&1 | tee -a "${output_dir}/train.log"
diff --git a/examples/Robotwin/train_files/modality.json b/examples/Robotwin/train_files/modality.json
new file mode 100644
index 0000000000000000000000000000000000000000..9071f047b467536460cf18fb15d375fbdabeb722
--- /dev/null
+++ b/examples/Robotwin/train_files/modality.json
@@ -0,0 +1,62 @@
+{
+ "action": {
+ "left_joints": {
+ "start": 0,
+ "end": 6,
+ "original_key": "action"
+ },
+ "left_gripper": {
+ "start": 6,
+ "end": 7,
+ "original_key": "action"
+ },
+ "right_joints": {
+ "start": 7,
+ "end": 13,
+ "original_key": "action"
+ },
+ "right_gripper": {
+ "start": 13,
+ "end": 14,
+ "original_key": "action"
+ }
+ },
+ "state": {
+ "left_joints": {
+ "start": 0,
+ "end": 6,
+ "original_key": "observation.state"
+ },
+ "left_gripper": {
+ "start": 6,
+ "end": 7,
+ "original_key": "observation.state"
+ },
+ "right_joints": {
+ "start": 7,
+ "end": 13,
+ "original_key": "observation.state"
+ },
+ "right_gripper": {
+ "start": 13,
+ "end": 14,
+ "original_key": "observation.state"
+ }
+ },
+ "video": {
+ "cam_high": {
+ "original_key": "observation.images.cam_high"
+ },
+ "cam_left_wrist": {
+ "original_key": "observation.images.cam_left_wrist"
+ },
+ "cam_right_wrist": {
+ "original_key": "observation.images.cam_right_wrist"
+ }
+ },
+ "annotation": {
+ "human.action.task_description": {
+ "original_key": "task_index"
+ }
+ }
+}
\ No newline at end of file
diff --git a/examples/Robotwin/train_files/run_robotwin_train.sh b/examples/Robotwin/train_files/run_robotwin_train.sh
new file mode 100644
index 0000000000000000000000000000000000000000..0800af9c244a827ec4498e35371504a93e260792
--- /dev/null
+++ b/examples/Robotwin/train_files/run_robotwin_train.sh
@@ -0,0 +1,70 @@
+
+
+export NCCL_SOCKET_IFNAME=bond0
+export NCCL_IB_HCA=mlx5_2,mlx5_3
+
+# used for check save when communication
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000 # timeout set to 1 hour (unit: seconds)
+
+###########################################################################################
+# === Please modify the following paths according to your environment ===
+Framework_name=QwenFast
+freeze_module_list=''
+base_vlm=playground/Pretrained_models/Qwen3-VL-4B-Instruct-Action
+config_yaml=./examples/Robotwin/train_files/starvla_cotrain_robotwin.yaml
+run_root_dir=./results/Checkpoints
+data_mix=robotwin
+run_id=1218_${data_mix}_qwen3Fast_debug
+# === End of environment variable configuration ===
+###########################################################################################
+
+
+export WANDB_MODE=disabled
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p ${output_dir}
+# mv this script to the output dir
+cp $0 ${output_dir}/
+
+
+accelerate launch \
+ --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \
+ --num_processes 8 \
+ starVLA/training/train_starvla.py \
+ --config_yaml ${config_yaml} \
+ --framework.name ${Framework_name} \
+ --framework.qwenvl.base_vlm ${base_vlm} \
+ --datasets.vla_data.per_device_batch_size 8 \
+ --datasets.vla_data.data_mix ${data_mix} \
+ --trainer.freeze_modules ${freeze_module_list} \
+ --trainer.max_train_steps 100000 \
+ --trainer.save_interval 10000 \
+ --trainer.logging_frequency 100 \
+ --trainer.eval_interval 1000 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project starVLA_Robotwin \
+ --wandb_entity jinhuiye \
+ # --is_debug True
+
+
+
+##### Multi-Server Multi-GPU training script #####
+ # accelerate launch \
+ # --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \
+ # --main_process_ip $MASTER_ADDR \
+ # --main_process_port $MASTER_PORT \
+ # --machine_rank $SLURM_PROCID \
+ # --num_machines $SLURM_NNODES \
+ # --num_processes=${TOTAL_GPUS} \
+ # starVLA/training/train_starvla.py \
+ # --config_yaml ${config_yaml} \
+ # --framework.name ${Framework_name} \
+ # --framework.qwenvl.base_vlm ${base_vlm} \
+ # --run_root_dir ${run_root_dir} \
+ # --run_id ${run_id} \
+ # --wandb_project your_project \
+ # --wandb_entity your_name
+##### Multi-Server Multi-GPU training script #####
diff --git a/examples/Robotwin/train_files/run_yzh.sh b/examples/Robotwin/train_files/run_yzh.sh
new file mode 100644
index 0000000000000000000000000000000000000000..cdc7d0cde714add488f4ea8311251c156bda827d
--- /dev/null
+++ b/examples/Robotwin/train_files/run_yzh.sh
@@ -0,0 +1,104 @@
+#!/usr/bin/env bash
+
+RDMA_DEVICES=$(ls /sys/class/infiniband)
+if [ -z "$RDMA_DEVICES" ]; then
+ echo "ERROR: No active RDMA devices found. Exiting script." >&2
+ exit 1
+fi
+
+# 设置RDMA设备列表 (逗号分隔)
+NCCL_IB_HCA=$(echo "$RDMA_DEVICES" | tr '\n' ',' | sed 's/,$//')
+export NCCL_IB_HCA
+echo "Detected RDMA devices: $NCCL_IB_HCA"
+
+# 获取GID_INDEX
+NCCL_IB_GID_INDEX=""
+output=$(show_gids | grep v2)
+while IFS= read -r line; do
+ ipv4=$(echo "$line" | awk '{print $5}')
+ if [[ -n "$ipv4" && "$ipv4" != "0000:0000:0000:0000:0000:ffff:0000:0000" && "$ipv4" =~ [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+ ]]; then
+ NCCL_IB_GID_INDEX=$(echo "$line" | awk '{print $3}')
+ break
+ fi
+done <<<"$output"
+
+export NCCL_SOCKET_IFNAME="eth0"
+export NCCL_IB_HCA=${NCCL_IB_HCA}
+export NCCL_IB_GID_INDEX=${NCCL_IB_GID_INDEX}
+export NCCL_NET_GDR_LEVEL=2
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS
+export NCCL_IB_DISABLE=0
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME}
+
+# used for check save when communication
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+
+# ==== 多节点配置 ====
+NUM_NODES=${PET_NNODES}
+NODE_RANK=${PET_NODE_RANK}
+MASTER_ADDR=${PET_MASTER_ADDR}
+MASTER_PORT=${PET_MASTER_PORT}
+NUM_GPUS_PER_NODE=${NUM_GPUS_PER_NODE:-8}
+
+source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+
+Framework_name=QwenPerceiver
+base_vlm=/mnt/workspace/users/yuanzhihao/code/starVLA/playground/Pretrained_models/Qwen3-VL-4B-Instruct
+freeze_module_list=''
+DIT_TYPE="DiT-B"
+config_yaml=./examples/Robotwin/train_files/starvla_cotrain_robotwin.yaml
+data_root_dir=/mnt/workspace/datasets/
+data_mix=robotwin
+pretrained_checkpoint=${PRETRAINED_CHECKPOINT:-"/mnt/workspace/users/yuanzhihao/code/starVLA/outputs/cotrain_sq_agi-beta_egodex-f/checkpoints/steps_50000_pytorch_model.pt"}
+action_dim=32
+state_dim=64
+output_dim=2560
+action_horizon=50
+future_action_window_size=49
+
+run_root_dir=./outputs
+run_id=post_robotwin_pre_cotrain_sq_agi-beta_egodex-f
+
+export WANDB_MODE=offline
+export WANDB_DIR=../../
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p ${output_dir}
+cp "$0" ${output_dir}/
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE:-8} \
+ starVLA/training/train_starvla.py \
+ --config_yaml ${config_yaml} \
+ --framework.name ${Framework_name} \
+ --framework.qwenvl.base_vlm ${base_vlm} \
+ --framework.action_model.action_model_type ${DIT_TYPE} \
+ --datasets.vla_data.data_root_dir ${data_root_dir} \
+ --datasets.vla_data.data_mix ${data_mix} \
+ --datasets.vla_data.per_device_batch_size 8 \
+ --trainer.freeze_modules ${freeze_module_list} \
+ --trainer.max_train_steps 300000 \
+ --trainer.save_interval 50000 \
+ --trainer.logging_frequency 100 \
+ --trainer.eval_interval 100 \
+ --trainer.learning_rate.base 1e-4 \
+ --trainer.pretrained_checkpoint ${pretrained_checkpoint} \
+ --framework.action_model.action_dim ${action_dim} \
+ --framework.action_model.state_dim ${state_dim} \
+ --framework.action_model.hidden_size ${output_dim} \
+ --framework.action_model.diffusion_model_cfg.output_dim ${output_dim} \
+ --framework.action_model.action_horizon ${action_horizon} \
+ --framework.action_model.future_action_window_size ${future_action_window_size} \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project starVLA_Robotwin \
+ --wandb_entity curryyuan \
+ 2>&1 | tee -a "${output_dir}/train.log"
+ # --is_debug True
diff --git a/examples/Robotwin/train_files/starvla_cotrain_robotwin.yaml b/examples/Robotwin/train_files/starvla_cotrain_robotwin.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..e16182ef5190516b4e9478e08876406ff8dbe1bc
--- /dev/null
+++ b/examples/Robotwin/train_files/starvla_cotrain_robotwin.yaml
@@ -0,0 +1,111 @@
+run_id: qwenact
+run_root_dir: results/Checkpoints
+seed: 42
+trackers: [jsonl, wandb]
+wandb_entity: your_wandb_entity
+wandb_project: starvla
+is_debug: false
+
+framework:
+ name: '' # override in bash
+ qwenvl:
+ base_vlm: ./playground/Pretrained_models/Qwen3-VL-4B-Instruct
+ attn_implementation: flash_attention_2
+ vl_hidden_dim: 2048
+ dino:
+ dino_backbone: dinov2_vits14
+
+ action_model:
+ action_model_type: DiT-B
+ hidden_size: 2560 # 和 DiT 最后的 projection 对应,用于 ActionDecoder
+ add_pos_embed: True
+ max_seq_len: 1024
+ action_dim: 32
+ state_dim: 64
+ future_action_window_size: 49
+ action_horizon: 50
+ past_action_window_size: 0
+ repeated_diffusion_steps: 8
+ noise_beta_alpha: 1.5
+ noise_beta_beta: 1.0
+ noise_s: 0.999
+ num_timestep_buckets: 1000
+ num_inference_timesteps: 20
+ num_target_vision_tokens: 32
+ max_num_embodiments: 32
+ use_category_specific: false
+ diffusion_model_cfg: # DiT Transformers 的参数
+ cross_attention_dim: 2048 # VLM 的 dim
+ dropout: 0.2
+ final_dropout: true
+ interleave_self_attention: true
+ norm_type: "ada_norm"
+ num_layers: 16
+ output_dim: 2560
+ positional_embeddings: null
+
+datasets:
+ vlm_data:
+ dataset_py: vlm_datasets
+ dataformat: llava_json
+ dataset_use: asv2_conversation_en,asv2_detailed_description_en,asv2_region_captioning_en,coco_internvl_longcap_en,coco_karpathy_train_567_en,coco_negative_gpt4o_en,coco_poetry_zh,coco_rem_en_zh,cocorem_exist_yorn_en,cocotextv2_en,cocotextv2_gpt4o_en,okvqa_en,refcoco_grounding_aug_en,refcoco_grounding_en,tallyqa_coco_en,toloka_grounding_aug_en,vqav2_en,vsr_en
+ eval_dataset: aokvqa_cauldron_llava_format
+ data_flatten: false
+ base_interval: 2
+ max_pixels: 50176
+ min_pixels: 784
+ model_max_length: 2048
+ model_type: qwen2.5vl
+ per_device_batch_size: 4
+
+ vla_data:
+ dataset_py: lerobot_datasets
+ data_root_dir: playground/Datasets/RoboTwin
+ data_mix: robotwin # bridge_rt_1
+ action_type: delta_ee
+ default_image_resolution: [3, 224, 224]
+ per_device_batch_size: 16
+ load_all_data_for_training: true
+ obs: ["image_0"]
+ image_size: [224,224]
+ delete_pause_frame: false
+
+trainer:
+ epochs: 100
+ max_train_steps: 100000
+ num_warmup_steps: 5000
+ save_interval: 5000
+ eval_interval: 100
+ learning_rate:
+ base: 1e-05
+ qwen_vl_interface: 1.0e-05
+ action_model: 1.0e-04
+ lr_scheduler_type: cosine_with_min_lr
+ scheduler_specific_kwargs:
+ min_lr: 5.0e-07
+ freeze_modules: ''
+ loss_scale:
+ vla: 1.0
+ vlm: 0.1
+ # pretrained_checkpoint: ./results/Checkpoints/1_need/0601_qwenact_fixqwen_32gpus_lr_1e-3_qformer_36_37/steps_100000/pytorch_model.pt
+ # reload_modules: 'action_model,layer_qformer' # warning: this may cause model to not converge
+ repeated_diffusion_steps: 4
+ max_grad_norm: 1.0
+ warmup_ratio: 0.1
+ weight_decay: 0.0
+ logging_frequency: 10
+ gradient_clipping: 1.0
+ gradient_accumulation_steps: 1
+
+ optimizer:
+ name: AdamW
+ betas: [0.9, 0.95]
+ eps: 1.0e-08
+ weight_decay: 1.0e-08
+
+ # parameters to be determined
+ is_resume: false
+ resume_epoch: null
+ resume_step: null
+ enable_gradient_checkpointing: true
+ enable_mixed_precision_training: true
diff --git a/examples/Robotwin/train_files/starvla_train_arx.yaml b/examples/Robotwin/train_files/starvla_train_arx.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..25bc2ad5b346f4af3f72680b984b6744d067c0a6
--- /dev/null
+++ b/examples/Robotwin/train_files/starvla_train_arx.yaml
@@ -0,0 +1,110 @@
+run_id: qwenact
+run_root_dir: results/Checkpoints
+seed: 42
+trackers: [jsonl, wandb]
+wandb_entity: your_wandb_entity
+wandb_project: llavavla
+is_debug: false
+
+framework:
+ name: QwenOFT
+ qwenvl:
+ base_vlm: ./playground/Pretrained_models/Qwen2.5-VL-3B-Instruct
+ attn_implementation: flash_attention_2
+ vl_hidden_dim: 2048
+ dino:
+ dino_backbone: dinov2_vits14
+
+ action_model:
+ action_model_type: DiT-B
+ hidden_size: 1024 # 和 DiT 最后的 projection 对应,用于 ActionDecoder
+ add_pos_embed: True
+ max_seq_len: 1024
+ action_dim: 14
+ state_dim: 14
+ future_action_window_size: 15
+ action_horizon: 16
+ past_action_window_size: 0
+ repeated_diffusion_steps: 8
+ noise_beta_alpha: 1.5
+ noise_beta_beta: 1.0
+ noise_s: 0.999
+ num_timestep_buckets: 1000
+ num_inference_timesteps: 4
+ num_target_vision_tokens: 32
+ diffusion_model_cfg: # DiT Transformers 的参数
+ cross_attention_dim: 2048 # VLM 的 dim
+ dropout: 0.2
+ final_dropout: true
+ interleave_self_attention: true
+ norm_type: "ada_norm"
+ num_layers: 16
+ output_dim: 1024
+ positional_embeddings: null
+
+
+
+datasets:
+ vlm_data:
+ dataset_py: vlm_datasets
+ dataformat: llava_json
+ dataset_use: asv2_conversation_en,asv2_detailed_description_en,asv2_region_captioning_en,coco_internvl_longcap_en,coco_karpathy_train_567_en,coco_negative_gpt4o_en,coco_poetry_zh,coco_rem_en_zh,cocorem_exist_yorn_en,cocotextv2_en,cocotextv2_gpt4o_en,okvqa_en,refcoco_grounding_aug_en,refcoco_grounding_en,tallyqa_coco_en,toloka_grounding_aug_en,vqav2_en,vsr_en
+ eval_dataset: aokvqa_cauldron_llava_format
+ data_flatten: false
+ base_interval: 2
+ max_pixels: 50176
+ min_pixels: 784
+ model_max_length: 2048
+ model_type: qwen2.5vl
+ per_device_batch_size: 4
+
+ vla_data:
+ dataset_py: lerobot_datasets
+ data_root_dir: playground/Datasets/arx-x5
+ data_mix: arx_x5 # bridge_rt_1
+ action_type: abs_qpos
+ default_image_resolution: [3, 224, 224]
+ per_device_batch_size: 16
+ load_all_data_for_training: true
+ obs: ["image_0"]
+ image_size: [224,224]
+
+trainer:
+ epochs: 100
+ max_train_steps: 100000
+ num_warmup_steps: 5000
+ save_interval: 5000
+ eval_interval: 100
+ learning_rate:
+ base: 1e-05
+ qwen_vl_interface: 1.0e-05
+ action_model: 1.0e-04
+ lr_scheduler_type: cosine_with_min_lr
+ scheduler_specific_kwargs:
+ min_lr: 5.0e-07
+ freeze_modules: ''
+ loss_scale:
+ vla: 1.0
+ vlm: 0.1
+ # pretrained_checkpoint: ./results/Checkpoints/1_need/0601_qwenact_fixqwen_32gpus_lr_1e-3_qformer_36_37/steps_100000/pytorch_model.pt
+ # reload_modules: 'action_model,layer_qformer' # warning: this may cause model to not converge
+ repeated_diffusion_steps: 4
+ max_grad_norm: 1.0
+ warmup_ratio: 0.1
+ weight_decay: 0.0
+ logging_frequency: 10
+ gradient_clipping: 1.0
+ gradient_accumulation_steps: 1
+
+ optimizer:
+ name: AdamW
+ betas: [0.9, 0.95]
+ eps: 1.0e-08
+ weight_decay: 1.0e-08
+
+ # parameters to be determined
+ is_resume: false
+ resume_epoch: null
+ resume_step: null
+ enable_gradient_checkpointing: true
+ enable_mixed_precision_training: true
diff --git a/examples/Robotwin_ee/eval_files/.ipynb_checkpoints/model2robotwin_interface_mxk-checkpoint.py b/examples/Robotwin_ee/eval_files/.ipynb_checkpoints/model2robotwin_interface_mxk-checkpoint.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f3d375736f72f727cb877122b2cd9757c90cd36
--- /dev/null
+++ b/examples/Robotwin_ee/eval_files/.ipynb_checkpoints/model2robotwin_interface_mxk-checkpoint.py
@@ -0,0 +1,1034 @@
+import collections
+import logging
+import math
+import time
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Dict, Optional, Sequence
+from collections import deque
+
+import numpy as np
+import cv2 as cv
+import json_numpy
+
+import matplotlib
+matplotlib.use("Agg")
+import matplotlib.pyplot as plt
+
+
+from deployment_robotwin.model_server.tools.websocket_policy_client import WebsocketClientPolicy
+from starVLA.model.tools import read_mode_config
+
+try:
+ from examples.SimplerEnv.eval_files.adaptive_ensemble import AdaptiveEnsembler
+except ImportError:
+ AdaptiveEnsembler = None
+
+from robotwin_aloha_transform_kdl import AlohaRetargeter, RobotwinRetargetConfig
+
+# Embodiment tag string to projector index mapping (from embodiment_tags.py)
+EMBODIMENT_TAG_MAPPING = {
+ "new_embodiment": 31,
+ "oxe_droid": 17,
+ "oxe_bridge": 18,
+ "oxe_rt1": 19,
+ "agibot_genie1": 26,
+ "gr1": 24,
+ "franka": 25,
+ "my_robotwin": 27,
+}
+
+
+class ModelClient:
+ def __init__(
+ self,
+ policy_ckpt_path,
+ unnorm_key: Optional[str] = None,
+ embodiment_tag: Optional[str] = None,
+ use_ee_pose: Optional[bool] = True,
+ policy_setup: str = "robotwin",
+ horizon: int = 0,
+ action_ensemble=False,
+ action_ensemble_horizon: Optional[int] = 3,
+ image_size: list[int] = [224, 224],
+ use_ddim: bool = True,
+ num_ddim_steps: int = 10,
+ adaptive_ensemble_alpha=0.1,
+ host="127.0.0.1",
+ port=5694,
+ debug_save_head_images: bool = False,
+ use_fixed_test_data: bool = False,
+ fixed_test_data_dir: str = "../Camera/test_1",
+ fixed_test_frame_idx: int = 119,
+ ) -> None:
+ print("######## WM4A-MODE(2/3): StarVLA/examples/Robotwin_ee/eval_files/model2robotwin_interface_mxk.py")
+ self.is_train_in_WM4A = True
+ if self.is_train_in_WM4A:
+ self.policy_ckpt_path = policy_ckpt_path
+ print("######## WM4A-MODE(3/3): The EVAL with the WM4A's mode")
+ else:
+ print("######## JoyRA-MODE(1/1): The EVAL with the JoyRA's mode")
+
+ print("######## Whether to use 'state' as the input is determined by the function 'eval(TASK_ENV, model, observation)' in the file 'model2robotwin_interface_mxk.py'.")
+ print("######## The 'use_ee_pose' value is a T/F (True/False) and is determined by hard-coding the input parameters of the ModelClient.")
+ print(f"######### The Setting 'self.use_ee_pose' is {use_ee_pose}")
+
+ self.client = WebsocketClientPolicy(host, port)
+ self.policy_setup = policy_setup
+ self.unnorm_key = unnorm_key
+ # 将embodiment_tag字符串转换为对应的index
+ self.embodiment_tag = EMBODIMENT_TAG_MAPPING.get(embodiment_tag, embodiment_tag)
+ self.use_ee_pose = use_ee_pose
+ if self.use_ee_pose:
+ robotwin_config = RobotwinRetargetConfig()
+ self.retargeter = AlohaRetargeter(urdf_path=Path(robotwin_config.urdf_path))
+ print(f"*** enable ee pose action space ***")
+ print(f"*** policy_setup: {policy_setup}, unnorm_key: {unnorm_key} ***")
+ self.use_ddim = use_ddim
+ self.num_ddim_steps = num_ddim_steps
+ self.image_size = image_size
+ self.horizon = horizon
+ self.action_ensemble = action_ensemble and (AdaptiveEnsembler is not None)
+ self.adaptive_ensemble_alpha = adaptive_ensemble_alpha
+ self.action_ensemble_horizon = action_ensemble_horizon
+ self.debug_save_head_images = debug_save_head_images
+ self.use_fixed_test_data = use_fixed_test_data
+ self.fixed_test_data_dir = fixed_test_data_dir
+ self.fixed_test_frame_idx = fixed_test_frame_idx
+
+ # Load fixed test data if enabled
+ self.fixed_head_img = None
+ self.fixed_left_img = None
+ self.fixed_right_img = None
+ self.fixed_state = None
+
+ if self.use_fixed_test_data:
+ self._load_fixed_test_data()
+
+ self.task_description = None
+ self.image_history = deque(maxlen=self.horizon)
+ if self.action_ensemble:
+ self.action_ensembler = AdaptiveEnsembler(self.action_ensemble_horizon, self.adaptive_ensemble_alpha)
+ else:
+ self.action_ensembler = None
+ self.num_image_history = 0
+
+ self.action_norm_stats = self.get_action_stats(self.unnorm_key, policy_ckpt_path=policy_ckpt_path)
+ self.action_chunk_size = self.get_action_chunk_size(policy_ckpt_path=policy_ckpt_path)
+ # self.action_chunk_size = 10
+ self.state_norm_stats = self.get_state_stats(self.unnorm_key, policy_ckpt_path=policy_ckpt_path)
+ self.raw_actions = None
+ self.left_arm_joint_angles = None
+ self.right_arm_joint_angles = None
+ self.left_arm_actions_history = []
+ self.right_arm_actions_history = []
+ self.left_arm_ee_pose_history = [] # 保存左臂的ee_pose (pos + axis)
+ self.right_arm_ee_pose_history = [] # 保存右臂的ee_pose (pos + axis)
+ self.left_gripper_history = [] # 保存左臂夹爪动作
+ self.right_gripper_history = [] # 保存右臂夹爪动作
+ self.camera_images_history = {
+ "head": [],
+ "left": [],
+ "right": []
+ } # 用于保存所有相机的图片用于debug
+ self.state_history = [] # 用于保存原始state用于debug
+ self.normalized_action_chunks = [] # 用于开环测试,收集每次模型生成的原始normalized_actions (50, 32)
+ self._action_plot_save_dir = None # episode结束时保存action图的目录
+ self._action_plot_episode_num = None # episode编号
+ self._future_concat_frames = [] # 每次推理的当前帧+未来帧拼接图
+ self._future_concat_save_dir = None
+ self._future_concat_episode_num = None
+
+ def _load_fixed_test_data(self) -> None:
+ """
+ 加载固定的测试数据(图像和state)
+ """
+ test_data_dir = Path(self.fixed_test_data_dir)
+
+ # Load fixed images
+ head_img_path = test_data_dir / "head" / f"frame_{self.fixed_test_frame_idx:06d}.png"
+ left_img_path = test_data_dir / "left" / f"frame_{self.fixed_test_frame_idx:06d}.png"
+ right_img_path = test_data_dir / "right" / f"frame_{self.fixed_test_frame_idx:06d}.png"
+
+ if head_img_path.exists():
+ self.fixed_head_img = cv.imread(str(head_img_path))
+ self.fixed_head_img = cv.cvtColor(self.fixed_head_img, cv.COLOR_BGR2RGB)
+ print(f"Loaded fixed head image from {head_img_path}, shape: {self.fixed_head_img.shape}")
+ else:
+ print(f"Warning: Fixed head image not found at {head_img_path}")
+
+ if left_img_path.exists():
+ self.fixed_left_img = cv.imread(str(left_img_path))
+ self.fixed_left_img = cv.cvtColor(self.fixed_left_img, cv.COLOR_BGR2RGB)
+ print(f"Loaded fixed left image from {left_img_path}, shape: {self.fixed_left_img.shape}")
+ else:
+ print(f"Warning: Fixed left image not found at {left_img_path}")
+
+ if right_img_path.exists():
+ self.fixed_right_img = cv.imread(str(right_img_path))
+ self.fixed_right_img = cv.cvtColor(self.fixed_right_img, cv.COLOR_BGR2RGB)
+ print(f"Loaded fixed right image from {right_img_path}, shape: {self.fixed_right_img.shape}")
+ else:
+ print(f"Warning: Fixed right image not found at {right_img_path}")
+
+ # Load fixed state
+ state_path = test_data_dir / "state" / "state_history.npz"
+ if state_path.exists():
+ state_data = np.load(str(state_path))
+ state_history = state_data['state']
+ if self.fixed_test_frame_idx < len(state_history):
+ self.fixed_state = state_history[self.fixed_test_frame_idx].copy()
+ print(f"Loaded fixed state at index {self.fixed_test_frame_idx}, shape: {self.fixed_state.shape}")
+ else:
+ print(f"Warning: Fixed test frame index {self.fixed_test_frame_idx} out of range (state length: {len(state_history)})")
+ self.fixed_state = state_history[0].copy()
+ print(f"Using first state instead, shape: {self.fixed_state.shape}")
+ else:
+ print(f"Warning: Fixed state not found at {state_path}")
+
+ def reset(self, task_description: str) -> None:
+ self.task_description = task_description
+ self.image_history.clear()
+ if self.action_ensemble:
+ self.action_ensembler.reset()
+ if self.use_ee_pose:
+ self.retargeter.reset_ik_cache()
+ self.num_image_history = 0
+ self.raw_actions = None
+ self.left_arm_joint_angles = None
+ self.right_arm_joint_angles = None
+ self.left_arm_actions_history = []
+ self.right_arm_actions_history = []
+ self.left_arm_ee_pose_history = []
+ self.right_arm_ee_pose_history = []
+ self.left_gripper_history = []
+ self.right_gripper_history = []
+ self.camera_images_history = {
+ "head": [],
+ "left": [],
+ "right": []
+ }
+ self.state_history = []
+ self.normalized_action_chunks = [] # 重置开环测试收集
+ self._action_plot_save_dir = None
+ self._action_plot_episode_num = None
+ self._future_concat_frames = []
+ self._future_concat_save_dir = None
+ self._future_concat_episode_num = None
+
+ def step(self, example: dict, step: int = 0) -> np.ndarray:
+ state = example.get("state", None)
+ if state is not None:
+ # 保存原始state用于debug
+ if self.debug_save_head_images:
+ self.state_history.append(state.copy())
+ if self.use_ee_pose:
+ # 最初从client获取的state是14维向量:[left_arm,left_gripper,right_arm,right_gripper]
+ # 这里首先将其转换为:[left_arm,right_arm,left_gripper,right_gripper]
+ original_state = np.array(state[[0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 6, 13]])
+
+ # 随后将从Robotwin环境中获取的原始state转换为ee-pose-state,
+ # 似乎只需要对left_arm和right_arm做转换,保持left_gripper,right_gripper不变,同时需要保存原始的left_arm,right_arm
+ self.left_arm_joint_angles = original_state[0:6]
+ self.right_arm_joint_angles = original_state[6:12]
+ (left_pos, left_axis), (right_pos, right_axis), (left_q, right_q) = self.retargeter.process_frame_kinematics_axisangle(state)
+ # 将 left_pos, left_axis, right_pos, right_axis 与 original_state 的最后两维度拼成新的 state
+ # new_state = np.concatenate([left_pos, left_axis, right_pos, right_axis, original_state[-2:].reshape(1, -1)], axis=1)
+ # state_keys = [
+ # "state.left_arm",
+ # "state.left_gripper",
+ # "state.right_arm",
+ # "state.right_gripper",
+ # ] order of state
+
+ # JoyRA模型输入的state为:[left_arm,left_gripper,right_arm,right_gripper,0*50],共64维,前14维是有效的,
+ # print('### input-state')
+ new_state = np.concatenate([left_pos, left_axis, original_state[-2].reshape(1, -1), right_pos, right_axis, original_state[-1].reshape(1, -1)], axis=1)
+ # print(new_state.shape) # (1, 14)
+
+ # JoyRA格式的state对齐到WM4A格式
+ # WM4A模型输入的state为:[left_arm,right_arm,left_gripper,right_gripper,0*50],共64维,前14维是有效的,
+ # print(self.is_train_in_WM4A) # True
+ if self.is_train_in_WM4A:
+ left_arm = new_state[:, 0:6]
+ left_gripper = new_state[:, 6:7]
+ right_arm = new_state[:, 7:13]
+ right_gripper = new_state[:, 13:14]
+ new_state = np.concatenate([left_arm, right_arm, left_gripper, right_gripper], axis=1)
+ # print(new_state.shape) # (1, 14)
+
+ # print(self.unnorm_key) # robotwin
+ # print(self.policy_ckpt_path) # /mnt/workspace1/users/chidafeng/results/Checkpoints/robotwin_clean_random_reversed-QwenFastWanPerceiver-mn-train-motus-fast-chunk50/checkpoints/steps_260000_pytorch_model.pt
+ # print(len(self.action_norm_stats["min"])) # 14
+ # print(len(self.action_norm_stats["max"])) # 14
+ new_state = self.normalize_state(new_state, self.state_norm_stats)
+ # print(new_state.shape) # (1, 14)
+
+ # 将14维的state padding到64维
+ current_state_dim = new_state.shape[1]
+ target_dim = 64
+ if current_state_dim < target_dim:
+ padding = np.zeros((1, target_dim - current_state_dim), dtype=new_state.dtype)
+ new_state = np.concatenate([new_state, padding], axis=1)
+
+ example["state"] = new_state.reshape(1, -1)
+
+ else:
+ state = self.normalize_state(state, self.state_norm_stats)
+ state = state[[0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 6, 13]]
+ example["state"] = state.reshape(1, -1)
+ else:
+ print('######## state is NONE')
+
+ task_description = example.get("lang", None)
+ if example is not None:
+ if task_description != self.task_description:
+ self.reset(task_description)
+
+ images = example["image"]
+ # images = [self._center_crop_image(image, crop_ratio=0.95) for image in images]
+ # images = [self._resize_image_pad(image) for image in images]
+ concat_img = self._concat_view_images(images, view_size=tuple(self.image_size))
+ images = [np.array(concat_img)]
+ example["image"] = images
+ # add embodiment_tag to example
+ example["embodiment_tag"] = self.embodiment_tag
+ vla_input = {
+ "examples": [example],
+ "do_sample": False,
+ "use_ddim": self.use_ddim,
+ "num_ddim_steps": self.num_ddim_steps,
+ "future_image_generation": {
+ "enabled": True,
+ "num_frames": 9, # 生成 9 帧未来图像
+ "return_full_video": False, # 如果为 True,data 中会包含所有帧;如果为 False,通常只返回最后一帧或指定索引帧
+ "future_frame_index": -1, # -1 通常代表最后一帧
+ "height": 224,
+ "width": "auto",
+ "num_inference_steps": 1, # 如果模型支持,可以单独设置未来帧生成的步数
+ }
+ }
+
+ action_chunk_size = self.action_chunk_size
+
+ if step % action_chunk_size == 0 or self.raw_actions is None:
+ # print("Calling model to predict action")
+ max_retries = 3
+ retry_sleep_s = 0.3
+ normalized_actions = None
+ last_error_message = ""
+
+ for attempt in range(max_retries):
+ # ************** 模型前向传播
+ response = self.client.predict_action(vla_input)
+ data = response.get("data") if isinstance(response, dict) else None
+ normalized_actions = data.get("normalized_actions") if isinstance(data, dict) else None
+
+ if normalized_actions is not None:
+ # 收集完整的原始 normalized_actions 用于开环测试绘图
+ self.normalized_action_chunks.append(normalized_actions.copy())
+ # 收集每次推理的"当前帧+未来帧"拼接图,用于episode结束时合成视频
+ self._append_future_concat_frame(data, images[0])
+ break
+
+ status = response.get("status") if isinstance(response, dict) else None
+ error_obj = response.get("error") if isinstance(response, dict) else None
+ error_message = ""
+ if isinstance(error_obj, dict):
+ error_message = str(error_obj.get("message", ""))
+ elif error_obj is not None:
+ error_message = str(error_obj)
+ last_error_message = (
+ f"status={status}, error={error_message or 'missing data.normalized_actions'}"
+ )
+ print(
+ f"Policy response missing normalized_actions "
+ f"(attempt {attempt + 1}/{max_retries}): {last_error_message}"
+ )
+ if attempt < max_retries - 1:
+ time.sleep(retry_sleep_s)
+
+ if normalized_actions is None:
+ raise RuntimeError(
+ "Policy inference response is invalid after retries: "
+ f"{last_error_message}"
+ )
+
+ # WM4A模型输出的action为:[left_arm,right_arm,left_gripper,right_gripper,0*18],共32维,前14维是有效的,
+ # JoyRA模型输出的action为:[left_arm,left_gripper,right_arm,right_gripper,0*18],共32维,前14维是有效的,
+ # print('### output-action')
+ # print(normalized_actions.shape) # (1, 50, 32)
+ normalized_actions = normalized_actions[0]
+ # print(normalized_actions.shape) # (50, 32)
+ normalized_actions = normalized_actions[:, :14]
+ # print(normalized_actions.shape) # (50, 14)
+
+ # print(self.unnorm_key) # robotwin
+ # print(self.policy_ckpt_path) # /mnt/workspace1/users/chidafeng/results/Checkpoints/robotwin_clean_random_reversed-QwenFastWanPerceiver-mn-train-motus-fast-chunk50/checkpoints/steps_260000_pytorch_model.pt
+ # print(len(self.action_norm_stats["min"])) # 14
+ # print(len(self.action_norm_stats["max"])) # 14
+ self.raw_actions = self.unnormalize_actions(
+ normalized_actions=normalized_actions, action_norm_stats=self.action_norm_stats
+ )
+ # print(self.raw_actions.shape) # (50, 14)
+
+ # 将WM4A模型输出的格式对齐到JoyRA格式,因为这套Robotwin测试代码是适配oyRA的
+ # print(self.is_train_in_WM4A) # True
+ if self.is_train_in_WM4A:
+ # print('self.is_train_in_WM4A is TRUE')
+ left_arm = self.raw_actions[:, 0:6]
+ right_arm = self.raw_actions[:, 6:12]
+ left_gripper = self.raw_actions[:, 12:13]
+ right_gripper = self.raw_actions[:, 13:14]
+ self.raw_actions = np.concatenate([left_arm, left_gripper, right_arm, right_gripper], axis=1)
+ # print(self.raw_actions.shape) # (50, 14)
+
+ action_idx = step % action_chunk_size
+ if action_idx >= len(self.raw_actions):
+ pass
+
+ # action_keys = [
+ # "action.left_arm",
+ # "action.left_gripper",
+ # "action.right_arm",
+ # "action.right_gripper",
+ # ] order of action output from model
+
+ current_action = self.raw_actions[action_idx]
+ if self.use_ee_pose:
+ left_hand_pos = current_action[0:3] # 左手位置向量
+ left_hand_axis = current_action[3:6] # 左手旋转向量
+ left_hand_q = current_action[6] # 左手夹爪
+ right_hand_pos = current_action[7:10] # 右手位置向量
+ right_hand_axis = current_action[10:13] # 右手旋转向量
+ right_hand_q = current_action[13] # 右手夹爪
+
+ q_left_arm, q_right_arm = self.retargeter.inverse_kinematics_from_camera_axisangle(
+ left_hand_pos, left_hand_axis, right_hand_pos, right_hand_axis, q_init_left=self.left_arm_joint_angles, q_init_right=self.right_arm_joint_angles
+ )
+ # 记录左右臂的所有动作(关节角度形式)
+ self.left_arm_actions_history.append(q_left_arm.reshape(-1).copy())
+ self.right_arm_actions_history.append(q_right_arm.reshape(-1).copy())
+ # 记录左右臂的ee_pose形式(pos + axis)
+ self.left_arm_ee_pose_history.append(np.concatenate([left_hand_pos, left_hand_axis]).copy())
+ self.right_arm_ee_pose_history.append(np.concatenate([right_hand_pos, right_hand_axis]).copy())
+ # 记录夹爪动作
+ self.left_gripper_history.append(left_hand_q.copy())
+ self.right_gripper_history.append(right_hand_q.copy())
+
+ current_action = np.concatenate([q_left_arm, q_right_arm, left_hand_q.reshape(1, -1), right_hand_q.reshape(1, -1)], axis=1)
+ current_action = current_action.reshape(-1)
+
+ current_action = current_action[[0, 1, 2, 3, 4, 5, 12, 6, 7, 8, 9, 10, 11, 13]]
+ # 最终交给client的current_action是14维向量:[left_arm,left_gripper,right_arm,right_gripper]
+ return current_action
+
+ @staticmethod
+ def normalize_state(state: dict[str, np.ndarray], state_norm_stats: Dict[str, np.ndarray]) -> dict[str, np.ndarray]:
+ """
+ Normalize the state
+ """
+ mask = [True, True, True, True, True, True, True, True, True, True, True, True, True, True]
+ mask = np.array(mask, dtype=bool)
+ state_high, state_low = np.array(state_norm_stats["max"]), np.array(state_norm_stats["min"])
+ normalized_state = np.where(
+ mask,
+ (state - state_low) / (state_high - state_low) * 2 - 1,
+ state,
+ )
+ normalized_state = np.where(~mask, (normalized_state > 0.5).astype(normalized_state.dtype), normalized_state)
+ return normalized_state
+
+ @staticmethod
+ def unnormalize_actions(normalized_actions: np.ndarray, action_norm_stats: Dict[str, np.ndarray]) -> np.ndarray:
+ # mask = action_norm_stats.get("mask", np.ones_like(action_norm_stats["min"], dtype=bool))
+ mask = [True, True, True, True, True, True, True, True, True, True, True, True, True, True]
+ mask = np.array(mask, dtype=bool)
+ action_high, action_low = np.array(action_norm_stats["max"]), np.array(action_norm_stats["min"])
+ normalized_actions = np.clip(normalized_actions, -1, 1)
+
+ actions = np.where(
+ mask,
+ 0.5 * (normalized_actions + 1) * (action_high - action_low) + action_low,
+ normalized_actions,
+ )
+
+ return actions
+
+ @staticmethod
+ def get_action_stats(unnorm_key: str, policy_ckpt_path) -> dict:
+ policy_ckpt_path = Path(policy_ckpt_path)
+ model_config, norm_stats = read_mode_config(policy_ckpt_path)
+ unnorm_key = ModelClient._check_unnorm_key(norm_stats, unnorm_key)
+ return norm_stats[unnorm_key]["action"]
+
+ @staticmethod
+ def get_state_stats(unnorm_key: str, policy_ckpt_path) -> dict:
+ policy_ckpt_path = Path(policy_ckpt_path)
+ model_config, norm_stats = read_mode_config(policy_ckpt_path)
+ unnorm_key = ModelClient._check_unnorm_key(norm_stats, unnorm_key)
+ return norm_stats[unnorm_key]["state"]
+
+ @staticmethod
+ def get_action_chunk_size(policy_ckpt_path):
+ model_config, _ = read_mode_config(policy_ckpt_path)
+ return model_config["framework"]["action_model"]["future_action_window_size"] + 1
+
+ def _resize_image(self, image: np.ndarray) -> np.ndarray:
+ image = cv.resize(image, tuple(self.image_size), interpolation=cv.INTER_LINEAR)
+ return image
+
+ def _resize_image_pad(
+ self,
+ image: np.ndarray,
+ target_size: int | None = None,
+ fill_value: float = 0.0,
+ interpolation: int = cv.INTER_LINEAR,
+ ) -> np.ndarray:
+ """
+ Resize image keeping aspect ratio, then center pad to target square size.
+
+ This matches the behavior of VideoResizePad in video.py:
+ 1. Scale the longest edge to target size
+ 2. Center pad the rest to make it square
+
+ Args:
+ image: Input image of shape (H, W, C) or (H, W)
+ target_size: Target size for both height and width. If None, uses self.image_size[0]
+ fill_value: The value to fill the padding (0.0 for black, 1.0 for white)
+ interpolation: OpenCV interpolation mode (e.g., cv.INTER_LINEAR)
+
+ Returns:
+ Resized and padded image of shape (target_size, target_size, C) or (target_size, target_size)
+ """
+ if target_size is None:
+ target_size = self.image_size[0]
+
+ h, w = image.shape[:2]
+
+ # Calculate scaling factor (scale longest edge to target size)
+ scale = target_size / max(h, w)
+ new_h = int(h * scale)
+ new_w = int(w * scale)
+
+ # Resize image
+ resized = cv.resize(image, (new_w, new_h), interpolation=interpolation)
+
+ # Calculate padding (center the image)
+ pad_h = target_size - new_h
+ pad_w = target_size - new_w
+ pad_top = pad_h // 2
+ pad_bottom = pad_h - pad_top
+ pad_left = pad_w // 2
+ pad_right = pad_w - pad_left
+
+ # Convert fill_value to uint8 range if needed
+ if resized.dtype == np.uint8:
+ fill_color = int(fill_value * 255)
+ else:
+ fill_color = fill_value
+
+ # Handle grayscale vs color images
+ if len(image.shape) == 2:
+ # Grayscale image
+ padded = cv.copyMakeBorder(
+ resized,
+ pad_top,
+ pad_bottom,
+ pad_left,
+ pad_right,
+ cv.BORDER_CONSTANT,
+ value=fill_color,
+ )
+ else:
+ # Color image - need to provide fill value for each channel
+ if isinstance(fill_color, int):
+ fill_color = (fill_color, fill_color, fill_color)
+ padded = cv.copyMakeBorder(
+ resized,
+ pad_top,
+ pad_bottom,
+ pad_left,
+ pad_right,
+ cv.BORDER_CONSTANT,
+ value=fill_color,
+ )
+
+ return padded
+
+ @staticmethod
+ def _center_crop_image(image: np.ndarray, crop_size: tuple[int, int] | None = None, crop_ratio: float = 1.0) -> np.ndarray:
+ """
+ 对图像进行中心裁剪
+
+ Args:
+ image: 输入图像,形状为 (H, W, C) 或 (H, W)
+ crop_size: 裁剪后的目标尺寸 (height, width),如果为 None 则使用 crop_ratio
+ crop_ratio: 裁剪比例,从中心和四周裁剪的比例 (0.0-1.0),仅在 crop_size 为 None 时使用
+
+ Returns:
+ 裁剪后的图像
+ """
+ h, w = image.shape[:2]
+
+ if crop_size is not None:
+ crop_h, crop_w = crop_size
+ else:
+ # 使用比例裁剪
+ if not (0.0 < crop_ratio <= 1.0):
+ raise ValueError(f"crop_ratio must be between 0.0 and 1.0, got {crop_ratio}")
+ crop_h = int(h * crop_ratio)
+ crop_w = int(w * crop_ratio)
+
+ # 计算裁剪区域的起始坐标(中心点)
+ start_y = (h - crop_h) // 2
+ start_x = (w - crop_w) // 2
+ end_y = start_y + crop_h
+ end_x = start_x + crop_w
+
+ # 确保裁剪区域不超出图像边界
+ if crop_h > h or crop_w > w:
+ raise ValueError(f"crop_size ({crop_w}x{crop_h}) larger than image size ({w}x{h})")
+
+ # 中心裁剪
+ cropped_image = image[start_y:end_y, start_x:end_x]
+
+ return cropped_image
+
+ @staticmethod
+ def _as_rgb_pil(image) -> "Image.Image":
+ """将各种格式的图像转换为 RGB PIL Image。"""
+ from PIL import Image as PILImage
+ import torch
+ if isinstance(image, PILImage.Image):
+ return image.convert("RGB")
+ if isinstance(image, torch.Tensor):
+ image = image.detach().cpu().numpy()
+ arr = np.asarray(image)
+ if arr.ndim == 3 and arr.shape[0] in (1, 3, 4) and arr.shape[-1] not in (1, 3, 4):
+ arr = np.moveaxis(arr, 0, -1)
+ if arr.ndim == 2:
+ arr = np.repeat(arr[..., None], 3, axis=-1)
+ if arr.ndim != 3:
+ raise ValueError(f"Expected image with 2 or 3 dims, got shape {arr.shape}")
+ if arr.shape[-1] == 4:
+ arr = arr[..., :3]
+ if arr.shape[-1] == 1:
+ arr = np.repeat(arr, 3, axis=-1)
+ if arr.dtype != np.uint8:
+ if arr.size and np.nanmax(arr) <= 1.0 and np.nanmin(arr) >= 0.0:
+ arr = arr * 255.0
+ elif arr.size and np.nanmin(arr) < 0.0:
+ arr = (arr + 1.0) * 127.5
+ arr = np.clip(arr, 0, 255).astype(np.uint8)
+ return PILImage.fromarray(arr).convert("RGB")
+
+ @staticmethod
+ def _resize_with_pad_pil(image, size=(224, 224)) -> "Image.Image":
+ """等比例缩放并中心填充到指定尺寸(PIL版本)。"""
+ from PIL import Image as PILImage
+ image = ModelClient._as_rgb_pil(image)
+ width, height = size
+ scale = min(width / image.width, height / image.height)
+ resized_size = (
+ max(1, int(round(image.width * scale))),
+ max(1, int(round(image.height * scale))),
+ )
+ resized = image.resize(resized_size, PILImage.BICUBIC)
+ canvas = PILImage.new("RGB", size, 0)
+ paste_xy = ((width - resized.width) // 2, (height - resized.height) // 2)
+ canvas.paste(resized, paste_xy)
+ return canvas
+
+ @staticmethod
+ def _concat_view_images(images, view_size=(224, 224), gap=0) -> "Image.Image":
+ """Match training's three-view layout: main view on top, wrist views below."""
+ from PIL import Image as PILImage
+ images = [ModelClient._as_rgb_pil(image) for image in images]
+ if not images:
+ raise ValueError("No camera images provided")
+
+ if len(images) == 3:
+ view_width, _view_height = view_size
+ bottom_width = int(view_width)
+ bottom_height = max(1, int(round(bottom_width * 9 / 16)))
+ canvas_width = bottom_width * 2 + int(gap)
+ main_height = max(1, int(round(canvas_width * 9 / 16)))
+ canvas_height = main_height + int(gap) + bottom_height
+ canvas = PILImage.new("RGB", (canvas_width, canvas_height), 0)
+
+ canvas.paste(ModelClient._resize_with_pad_pil(images[0], (canvas_width, main_height)), (0, 0))
+ bottom_y = main_height + int(gap)
+ canvas.paste(ModelClient._resize_with_pad_pil(images[1], (bottom_width, bottom_height)), (0, bottom_y))
+ canvas.paste(
+ ModelClient._resize_with_pad_pil(images[2], (bottom_width, bottom_height)),
+ (bottom_width + int(gap), bottom_y),
+ )
+ return canvas
+
+ # 非3张图时水平拼接
+ resized = [ModelClient._resize_with_pad_pil(image, view_size) for image in images]
+ panorama = PILImage.new("RGB", (sum(image.width for image in resized), max(image.height for image in resized)), 0)
+ x_offset = 0
+ for image in resized:
+ panorama.paste(image, (x_offset, 0))
+ x_offset += image.width
+ return panorama
+
+ def _open_loop(self, save_dir: str, episode_num: int) -> None:
+ """开环测试可视化:拼接所有模型生成action并保存14维长图。"""
+ if not self.normalized_action_chunks:
+ print("No normalized action chunks collected, skipping open-loop plot")
+ return
+
+ # 每次推理返回 shape (1, 50, 32),拼接为 (50*K, 32)
+ try:
+ chunk_list = [np.asarray(chunk)[0] for chunk in self.normalized_action_chunks]
+ all_actions = np.concatenate(chunk_list, axis=0)
+ except Exception as exc:
+ print(f"Warning: failed to concat normalized action chunks: {exc}")
+ return
+
+ if all_actions.ndim != 2 or all_actions.shape[1] < 14:
+ print(f"Warning: invalid open-loop action shape {all_actions.shape}, expect (?, >=14)")
+ return
+
+ actions_14 = all_actions[:, :14]
+ total_steps = actions_14.shape[0]
+ chunk_size = chunk_list[0].shape[0] if chunk_list else 50
+
+ dim_names = [
+ "left_arm_j0", "left_arm_j1", "left_arm_j2",
+ "left_arm_j3", "left_arm_j4", "left_arm_j5",
+ "left_gripper",
+ "right_arm_j0", "right_arm_j1", "right_arm_j2",
+ "right_arm_j3", "right_arm_j4", "right_arm_j5",
+ "right_gripper",
+ ]
+
+ fig, axes = plt.subplots(14, 1, figsize=(22, 2.5 * 14), sharex=True)
+ axes = np.atleast_1d(axes)
+
+ for dim_idx in range(14):
+ ax = axes[dim_idx]
+ ax.plot(actions_14[:, dim_idx], linewidth=0.8, color="steelblue")
+
+ # 标记每个chunk边界,便于观察step()累积后的段落
+ for k in range(1, len(chunk_list)):
+ boundary = k * chunk_size
+ if boundary < total_steps:
+ ax.axvline(x=boundary, color="gray", linestyle="--", linewidth=0.5, alpha=0.6)
+
+ ax.set_ylabel(dim_names[dim_idx], fontsize=9, rotation=0, labelpad=80)
+ ax.yaxis.set_ticks_position("right")
+ ax.grid(True, alpha=0.3)
+ if total_steps > 0:
+ ax.set_xlim(0, total_steps - 1)
+
+ axes[-1].set_xlabel("Step", fontsize=10)
+ fig.suptitle(
+ f"Open-loop Normalized Actions (total_steps={total_steps}, chunks={len(chunk_list)})",
+ fontsize=12,
+ )
+ fig.tight_layout(rect=[0, 0, 1, 0.97])
+
+ save_dir = Path(save_dir)
+ save_dir.mkdir(parents=True, exist_ok=True)
+ save_path = save_dir / f"episode{episode_num}_action_openloop.png"
+ fig.savefig(str(save_path), dpi=150, bbox_inches="tight")
+ plt.close(fig)
+ print(f"Open-loop action plot saved to {save_path}")
+
+ # 兼容旧调用
+ def _save_action_plot(self, save_dir: str, episode_num: int) -> None:
+ self._open_loop(save_dir, episode_num)
+
+ @staticmethod
+ def _as_uint8_rgb(image) -> np.ndarray:
+ image = np.asarray(image)
+ if image.ndim == 2:
+ image = np.repeat(image[..., None], 3, axis=-1)
+ if image.ndim == 3 and image.shape[0] in (1, 3, 4) and image.shape[-1] not in (1, 3, 4):
+ image = np.moveaxis(image, 0, -1)
+ if image.ndim != 3:
+ raise ValueError(f"Expected image with 2 or 3 dims, got shape {image.shape}")
+ if image.shape[-1] == 4:
+ image = image[..., :3]
+ if image.shape[-1] == 1:
+ image = np.repeat(image, 3, axis=-1)
+ if image.dtype != np.uint8:
+ if image.size and np.nanmax(image) <= 1.0 and np.nanmin(image) >= 0.0:
+ image = image * 255.0
+ elif image.size and np.nanmin(image) < 0.0:
+ image = (image + 1.0) * 127.5
+ image = np.clip(image, 0, 255).astype(np.uint8)
+ return image
+
+ @classmethod
+ def _extract_last_future_frame(cls, pred_future_images) -> Optional[np.ndarray]:
+ if pred_future_images is None:
+ return None
+ arr = np.asarray(pred_future_images)
+ if arr.size == 0:
+ return None
+ if arr.ndim == 5:
+ return cls._as_uint8_rgb(arr[0, -1])
+ if arr.ndim == 4:
+ if arr.shape[-1] in (1, 3, 4) or arr.shape[1] in (1, 3, 4):
+ return cls._as_uint8_rgb(arr[0])
+ return cls._as_uint8_rgb(arr[-1])
+ if arr.ndim == 3:
+ return cls._as_uint8_rgb(arr)
+ return None
+
+ def _append_future_concat_frame(self, response_data: dict, current_input_image: np.ndarray) -> None:
+ if not isinstance(response_data, dict):
+ return
+ future_image = self._extract_last_future_frame(response_data.get("pred_future_images"))
+ if future_image is None:
+ return
+
+ try:
+ obs_image = self._as_uint8_rgb(current_input_image)
+ future_image = cv.resize(
+ future_image,
+ (obs_image.shape[1], obs_image.shape[0]),
+ interpolation=cv.INTER_AREA,
+ )
+ if obs_image.shape[1] >= obs_image.shape[0]:
+ concat_frame = np.concatenate([obs_image, future_image], axis=0)
+ else:
+ concat_frame = np.concatenate([obs_image, future_image], axis=1)
+ self._future_concat_frames.append(concat_frame)
+ except Exception as exc:
+ print(f"Warning: failed to append future concat frame: {exc}")
+
+ def _save_future_concat_video(self, save_dir: str, episode_num: int, fps: int = 1) -> None:
+ if not self._future_concat_frames:
+ print("No future concat frames collected, skipping future concat video")
+ return
+
+ save_dir = Path(save_dir)
+ save_dir.mkdir(parents=True, exist_ok=True)
+ save_path = save_dir / f"episode{episode_num}_future_concat.mp4"
+
+ first_frame = self._future_concat_frames[0]
+ h, w = int(first_frame.shape[0]), int(first_frame.shape[1])
+ writer = cv.VideoWriter(str(save_path), cv.VideoWriter_fourcc(*"mp4v"), float(fps), (w, h))
+ if not writer.isOpened():
+ print(f"Warning: failed to open video writer for {save_path}")
+ return
+
+ try:
+ for frame in self._future_concat_frames:
+ if frame.shape[0] != h or frame.shape[1] != w:
+ frame = cv.resize(frame, (w, h), interpolation=cv.INTER_AREA)
+ writer.write(cv.cvtColor(frame, cv.COLOR_RGB2BGR))
+ finally:
+ writer.release()
+
+ print(f"Future concat video saved to {save_path}")
+
+ @staticmethod
+ def _check_unnorm_key(norm_stats, unnorm_key):
+ if unnorm_key is None:
+ if len(norm_stats) == 1:
+ unnorm_key = next(iter(norm_stats.keys()))
+ else:
+ unnorm_key = next(iter(norm_stats.keys()))
+
+ if unnorm_key not in norm_stats:
+ unnorm_key = next(iter(norm_stats.keys()))
+
+ return unnorm_key
+
+ def save_actions_history(self, output_path: str) -> None:
+ """
+ 保存左右臂的动作历史到文件(同时保存关节角度和ee_pose形式)
+
+ :param output_path: 输出文件路径,支持 .npy 或 .npz 格式
+ """
+ output_path = Path(output_path)
+
+ # 将夹爪动作拼接在ee_pose后面
+ left_arm_ee_pose_with_gripper = np.array([
+ np.concatenate([ee_pose, [gripper]])
+ for ee_pose, gripper in zip(self.left_arm_ee_pose_history, self.left_gripper_history)
+ ])
+ right_arm_ee_pose_with_gripper = np.array([
+ np.concatenate([ee_pose, [gripper]])
+ for ee_pose, gripper in zip(self.right_arm_ee_pose_history, self.right_gripper_history)
+ ])
+
+ if output_path.suffix == '.npz':
+ np.savez(
+ output_path,
+ # 关节角度形式
+ left_arm_actions=np.array(self.left_arm_actions_history),
+ right_arm_actions=np.array(self.right_arm_actions_history),
+ # 夹爪动作
+ left_gripper=np.array(self.left_gripper_history),
+ right_gripper=np.array(self.right_gripper_history),
+ # ee_pose形式 with gripper (pos + axis + gripper)
+ left_arm_ee_pose=left_arm_ee_pose_with_gripper,
+ right_arm_ee_pose=right_arm_ee_pose_with_gripper
+ )
+ print(f"Actions history (joint angles & ee_pose & gripper) saved to {output_path}")
+ else:
+ # 默认保存为 .npz 格式
+ output_path = output_path.with_suffix('.npz')
+ np.savez(
+ output_path,
+ # 关节角度形式
+ left_arm_actions=np.array(self.left_arm_actions_history),
+ right_arm_actions=np.array(self.right_arm_actions_history),
+ # 夹爪动作
+ left_gripper=np.array(self.left_gripper_history),
+ right_gripper=np.array(self.right_gripper_history),
+ # ee_pose形式 with gripper (pos + axis + gripper)
+ left_arm_ee_pose=left_arm_ee_pose_with_gripper,
+ right_arm_ee_pose=right_arm_ee_pose_with_gripper
+ )
+ print(f"Actions history (joint angles & ee_pose & gripper) saved to {output_path}")
+
+ def save_camera_images(self, output_dir: str, test_num: int) -> None:
+ """
+ 将保存的所有相机图片保存到对应的子文件夹中,同时保存state数据
+
+ :param output_dir: 输出目录的总路径,每个相机会有单独的子文件夹
+ :param test_num: 测试编号,用于命名子文件夹
+ """
+ output_dir = Path(output_dir)
+ test_dir = output_dir / f"test_{test_num}"
+ test_dir.mkdir(parents=True, exist_ok=True)
+
+ for camera_name, images in self.camera_images_history.items():
+ if len(images) == 0:
+ print(f"No {camera_name} images to save, skipping")
+ continue
+
+ camera_dir = test_dir / camera_name
+ camera_dir.mkdir(parents=True, exist_ok=True)
+
+ for i, img in enumerate(images):
+ # 确保图像是uint8类型
+ if img.dtype != np.uint8:
+ img = (img * 255).astype(np.uint8)
+ # 确保是BGR格式用于保存
+ if len(img.shape) == 2:
+ img = cv.cvtColor(img, cv.COLOR_GRAY2BGR)
+ elif img.shape[2] == 3:
+ img = cv.cvtColor(img, cv.COLOR_RGB2BGR)
+
+ img_path = camera_dir / f"frame_{i:06d}.png"
+ cv.imwrite(str(img_path), img)
+
+ print(f"{camera_name.capitalize()} images saved to {camera_dir} ({len(images)} frames)")
+
+ # 保存state数据
+ if len(self.state_history) > 0:
+ state_dir = test_dir / "state"
+ state_dir.mkdir(parents=True, exist_ok=True)
+
+ state_array = np.array(self.state_history)
+ state_path = state_dir / "state_history.npz"
+ np.savez(str(state_path), state=state_array)
+ print(f"State data saved to {state_path} ({len(self.state_history)} frames)")
+ else:
+ print(f"No state data to save, skipping")
+
+ print(f"All camera images and state saved to {test_dir}")
+
+
+def get_model(usr_args):
+ policy_ckpt_path = usr_args.get("policy_ckpt_path")
+ host = usr_args.get("host", "127.0.0.1")
+ port = usr_args.get("port", 5694)
+ unnorm_key = usr_args.get("unnorm_key", None)
+ embodiment_tag = usr_args.get("embodiment_tag", None)
+ debug_save_head_images = usr_args.get("debug_save_head_images", False)
+ use_fixed_test_data = usr_args.get("use_fixed_test_data", False)
+ fixed_test_data_dir = usr_args.get("fixed_test_data_dir", "../Camera/test_1")
+ fixed_test_frame_idx = usr_args.get("fixed_test_frame_idx", 119)
+ if policy_ckpt_path is None:
+ raise ValueError("policy_ckpt_path must be provided in config")
+
+ return ModelClient(
+ policy_ckpt_path=policy_ckpt_path,
+ host=host,
+ port=port,
+ unnorm_key=unnorm_key,
+ embodiment_tag=embodiment_tag,
+ debug_save_head_images=debug_save_head_images,
+ use_fixed_test_data=use_fixed_test_data,
+ fixed_test_data_dir=fixed_test_data_dir,
+ fixed_test_frame_idx=fixed_test_frame_idx,
+ )
+
+
+def reset_model(model: ModelClient):
+ # episode结束时保存action长图
+ if model._action_plot_save_dir is not None:
+ model._open_loop(model._action_plot_save_dir, model._action_plot_episode_num)
+
+ # episode结束时保存“当前帧+未来帧”拼接视频
+ if model._future_concat_save_dir is not None:
+ model._save_future_concat_video(model._future_concat_save_dir, model._future_concat_episode_num)
+
+ model.reset(task_description="")
+
+
+def eval(TASK_ENV, model, observation):
+ # Get instruction
+ instruction = TASK_ENV.get_instruction()
+
+ # Prepare images
+ if model.use_fixed_test_data:
+ # 使用固定的测试图像
+ head_img = model.fixed_head_img
+ left_img = model.fixed_left_img
+ right_img = model.fixed_right_img
+ state = model.fixed_state.copy()
+ print(f"[USING FIXED TEST DATA] Frame idx: {model.fixed_test_frame_idx}")
+ else:
+ # 使用真实观察到的图像和state
+ head_img = observation["observation"]["head_camera"]["rgb"]
+ left_img = observation["observation"]["left_camera"]["rgb"]
+ right_img = observation["observation"]["right_camera"]["rgb"]
+ state = observation["joint_action"]["vector"]
+
+ # Debug: save all camera images
+ if model.debug_save_head_images and not model.use_fixed_test_data:
+ # 只有在使用真实数据时才保存
+ model.camera_images_history["head"].append(head_img.copy())
+ model.camera_images_history["left"].append(left_img.copy())
+ model.camera_images_history["right"].append(right_img.copy())
+
+ # Order: [head, left, right] to match training order
+ images = [head_img, left_img, right_img]
+ # images = [head_img]
+
+ example = {
+ "lang": str(instruction),
+ "image": images,
+ "state": state,
+ }
+
+ action = model.step(example, step=TASK_ENV.take_action_cnt)
+
+ # Execute action
+ TASK_ENV.take_action(action)
+
+ # episode结束时保存action长图与future拼接视频(与episode视频同轮次)
+ # 此处不再每步保存,而是在reset_model中统一保存
+ # 三个产物(action开环图、仿真录制视频、当前帧+预测帧concat视频)统一保存到
+ # 同一个 eval_video_path 目录下(该目录已包含 task_name 维度),通过文件名区分:
+ # - episode{N}.mp4 仿真录制视频(由RoboTwin框架保存)
+ # - episode{N}_action_openloop.png action开环测试图
+ # - episode{N}_future_concat.mp4 当前帧+预测帧concat视频
+ if hasattr(TASK_ENV, 'eval_video_path') and TASK_ENV.eval_video_path is not None:
+ model._action_plot_save_dir = TASK_ENV.eval_video_path
+ model._action_plot_episode_num = TASK_ENV.test_num
+
+ model._future_concat_save_dir = TASK_ENV.eval_video_path
+ model._future_concat_episode_num = TASK_ENV.test_num
diff --git a/examples/Robotwin_ee/eval_files/.ipynb_checkpoints/run_parallel_eval_mxk-checkpoint.sh b/examples/Robotwin_ee/eval_files/.ipynb_checkpoints/run_parallel_eval_mxk-checkpoint.sh
new file mode 100644
index 0000000000000000000000000000000000000000..6adad377c5c291a0654c66eccb4af1a662715c37
--- /dev/null
+++ b/examples/Robotwin_ee/eval_files/.ipynb_checkpoints/run_parallel_eval_mxk-checkpoint.sh
@@ -0,0 +1,203 @@
+#!/bin/bash
+# Copyright 2025 starVLA community. All rights reserved.
+# Licensed under the MIT License, Version 1.0 (the "License");
+# One-click script: Start server on GPU 0, run 50 tasks dynamically on GPUs 1-7
+
+# source /mnt/workspace/envs/conda3/bin/activate robot_njn
+# bash /mnt/workspace/users/hukejun/JoyRA/StarVLA/scripts/setup_kdl/set_kdl.sh
+# bash /mnt/workspace/users/hukejun/JoyRA/StarVLA/scripts/setup_kdl/set_pykdl.sh
+
+set -e
+
+#####################################################################
+# ======================= Configuration ============================
+#####################################################################
+# export LD_LIBRARY_PATH=/tmp/nvidia-gl-extract/usr/lib/x86_64-linux-gnu:$LD_LIBRARY_PATH
+export VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/nvidia_icd.json
+export CUROBO_TORCH_COMPILE=1
+
+# -------------------- Path Settings --------------------
+STARVLA_PATH=/mnt/workspace/users/maxiangkai/projects/WM4A
+ROBOTWIN_PATH=/mnt/workspace/users/maxiangkai/projects/WM4A/RoboTwin
+STAR_VLA_PYTHON=/mnt/workspace/envs/conda3/envs/starVLA_1/bin/python
+ROBOTWIN_PYTHON=/mnt/workspace/envs/conda3/envs/robot_njn/bin/python
+
+# -------------------- Model Settings --------------------
+
+# wm4a
+CKPT_SETTING="robotwin_wan22_masked_future_image"
+CKPT_PATH=/mnt/workspace/users/yuanzhihao/code/starVLA/outputs/wan22_perceiver_masked_future_image/posttrain/robotwin_wan22_masked_future_image/checkpoints/steps_200000_pytorch_model.pt
+
+# joyra05
+# CKPT_SETTING="robotwin_clean_random_reversed-QwenFastWanPerceiver-mn-train-motus-fast-chunk50"
+# CKPT_PATH=/mnt/workspace/users/maxiangkai/models/${CKPT_SETTING}/checkpoints/steps_260000_pytorch_model.pt
+
+WAN_PATH=/mnt/workspace/users/maxiangkai/models/Wan2.2-TI2V-5B-Diffusers
+FAST_TOKENIZER_PATH=/mnt/workspace/users/maxiangkai/models/physical-intelligence-fast
+export FAST_TOKENIZER_PATH
+USE_BF16=true
+
+# -------------------- Server Settings --------------------
+SERVER_BASE_PORT=5693 # Per-GPU server ports: base + (gpu_id - EVAL_GPU_START_ID)
+SEED=42
+
+# -------------------- Eval Settings --------------------
+TASK_CONFIG="demo_clean"
+EVAL_SEED=0
+NUM_EVAL_GPUS=2 # Number of GPUs used for eval
+EVAL_GPU_START_ID=0 # Set 0 to include GPU0 as eval client
+SLOTS_PER_GPU=8 # Keep 1 for per-GPU single-task strategy
+NUM_TRAJ_WORKERS=8 # Keep 1 so each task is bound to one GPU
+TEST_NUM_PER_TASK=100 # Total trajectories per task
+
+# -------------------- Timing Settings --------------------
+SERVER_STARTUP_WAIT=240
+
+# -------------------- Output Settings --------------------
+# 增加运行时间戳(并行评估避免日志目录冲突)
+timestamp=$(date +%Y%m%d_%H%M%S)
+LOG_DIR="/mnt/workspace/users/maxiangkai/projects/JoyRA_robotwin/${CKPT_SETTING}-${TASK_CONFIG}-26wsteps-ds4"
+mkdir -p ${LOG_DIR}
+
+#####################################################################
+# ======================= Helper Functions =========================
+#####################################################################
+
+RED='\033[0;31m'
+GREEN='\033[0;32m'
+YELLOW='\033[0;33m'
+BLUE='\033[0;34m'
+NC='\033[0m'
+
+log_info() { echo -e "${GREEN}[INFO]${NC} $1"; }
+log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
+log_error() { echo -e "${RED}[ERROR]${NC} $1"; }
+log_step() { echo -e "${BLUE}[STEP]${NC} $1"; }
+
+cleanup() {
+ log_warn "Cleaning up..."
+ for pid in "${SERVER_PIDS[@]}"; do
+ if [ ! -z "$pid" ]; then
+ log_info "Stopping policy server (PID: $pid)..."
+ kill "$pid" 2>/dev/null || true
+ wait "$pid" 2>/dev/null || true
+ fi
+ done
+ log_info "Cleanup complete."
+}
+
+trap cleanup EXIT INT TERM
+
+#####################################################################
+# ======================= Main Script ==============================
+#####################################################################
+
+log_step "========== StarVLA 50-Task Dynamic Evaluation =========="
+log_info "Eval GPU range: ${EVAL_GPU_START_ID}-$((EVAL_GPU_START_ID + NUM_EVAL_GPUS - 1))"
+log_info "Slots per GPU: ${SLOTS_PER_GPU}"
+log_info "Trajectory workers per task: ${NUM_TRAJ_WORKERS}"
+log_info "Trajectories per task: ${TEST_NUM_PER_TASK}"
+log_info "Total Tasks: 50"
+log_info "Checkpoint: ${CKPT_PATH}"
+log_info "Server Base Port: ${SERVER_BASE_PORT}"
+log_info "Log Directory: ${LOG_DIR}"
+log_info "Server Python: ${STAR_VLA_PYTHON}"
+log_info "Eval Python: ${ROBOTWIN_PYTHON}"
+echo ""
+
+# -------------------- Step 1: Start Per-GPU Policy Servers --------------------
+log_step "Step 1: Starting policy servers (one per eval GPU)..."
+
+cd ${STARVLA_PATH}
+export PYTHONPATH=$(pwd):${PYTHONPATH}
+
+BF16_FLAG=""
+if [ "$USE_BF16" = true ]; then
+ BF16_FLAG="--use_bf16"
+fi
+
+SERVER_PIDS=()
+SERVER_PORTS=()
+SERVER_PORTS_ARG=""
+
+for ((idx=0; idx/dev/null; then
+ log_error "Policy server failed to start (PID: ${pid}, port: ${port})!"
+ exit 1
+ fi
+done
+log_info "All policy servers are running."
+log_info "Server mapping: ${SERVER_PORTS_ARG}"
+echo ""
+
+# -------------------- Step 2: Run Dynamic Task Scheduler --------------------
+log_step "Step 2: Running Dynamic Task Scheduler (50 tasks)..."
+
+set +e # Don't exit on error, capture exit code
+
+${STAR_VLA_PYTHON} ${STARVLA_PATH}/examples/Robotwin_ee/eval_files/dynamic_task_scheduler_50_mxk.py \
+ --mode run \
+ --num_gpus ${NUM_EVAL_GPUS} \
+ --gpu_start_id ${EVAL_GPU_START_ID} \
+ --slots_per_gpu ${SLOTS_PER_GPU} \
+ --num_traj_workers ${NUM_TRAJ_WORKERS} \
+ --test_num ${TEST_NUM_PER_TASK} \
+ --ckpt_path ${CKPT_PATH} \
+ --server_port ${SERVER_BASE_PORT} \
+ --server_ports "${SERVER_PORTS_ARG}" \
+ --task_config ${TASK_CONFIG} \
+ --ckpt_setting ${CKPT_SETTING} \
+ --eval_seed ${EVAL_SEED} \
+ --log_dir ${LOG_DIR} \
+ --starvla_path ${STARVLA_PATH} \
+ --robotwin_path ${ROBOTWIN_PATH} \
+ --python_path ${ROBOTWIN_PYTHON} \
+ --resource_log_interval 300
+# CPU监测
+# --resource_log_interval 30 间隔多少s打印
+# --disable_resource_monitor 不打印CPU监测
+SCHEDULER_EXIT_CODE=$?
+
+set -e
+
+echo ""
+
+# -------------------- Step 3: Summary --------------------
+log_step "Step 3: Evaluation Complete"
+
+if [ "$SCHEDULER_EXIT_CODE" -eq 0 ]; then
+ log_info "All 50 tasks completed successfully!"
+else
+ log_error "Some tasks failed. Check logs in: ${LOG_DIR}"
+fi
+
+exit $SCHEDULER_EXIT_CODE
diff --git a/examples/Robotwin_ee/eval_files/.ipynb_checkpoints/run_parallel_eval_mxk_back-checkpoint.sh b/examples/Robotwin_ee/eval_files/.ipynb_checkpoints/run_parallel_eval_mxk_back-checkpoint.sh
new file mode 100644
index 0000000000000000000000000000000000000000..aa40971019a48b8aa10de104de92776f10dc96d4
--- /dev/null
+++ b/examples/Robotwin_ee/eval_files/.ipynb_checkpoints/run_parallel_eval_mxk_back-checkpoint.sh
@@ -0,0 +1,38 @@
+#!/bin/bash
+
+EVAL_SCRIPT="$(cd "$(dirname "$0")" && pwd)/run_parallel_eval_mxk.sh"
+LOG_FILE="/mnt/workspace/users/maxiangkai/projects/WM4A/examples/Robotwin_ee/eval_files/eval_back_$(date +%Y%m%d_%H%M%S).log"
+mkdir -p "$(dirname "${LOG_FILE}")"
+
+if [ ! -f "${EVAL_SCRIPT}" ]; then
+ echo "ERROR: cannot find ${EVAL_SCRIPT}" >&2; exit 1
+fi
+
+nohup setsid bash "${EVAL_SCRIPT}" "$@" >"${LOG_FILE}" 2>&1 &
+EVAL_PID=$!
+disown "${EVAL_PID}" 2>/dev/null || true
+sleep 1
+
+ABS_LOG_FILE="$(cd "$(dirname "${LOG_FILE}")" && pwd)/$(basename "${LOG_FILE}")"
+
+cat </dev/null; echo ""; echo "Detached from log. Eval PID=${EVAL_PID} still running."; echo " Re-attach: tail -F ${ABS_LOG_FILE}"; exit 0' INT
+wait "${TAIL_PID}"
\ No newline at end of file
diff --git a/examples/Robotwin_ee/eval_files/arx5_description_isaac.urdf b/examples/Robotwin_ee/eval_files/arx5_description_isaac.urdf
new file mode 100644
index 0000000000000000000000000000000000000000..54bfdb6259701cd9f2abf8d8274675ee2218367b
--- /dev/null
+++ b/examples/Robotwin_ee/eval_files/arx5_description_isaac.urdf
@@ -0,0 +1,1675 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/examples/Robotwin_ee/eval_files/deploy_policy.yml b/examples/Robotwin_ee/eval_files/deploy_policy.yml
new file mode 100644
index 0000000000000000000000000000000000000000..995fade1d41b80a7512f597836018bab46453809
--- /dev/null
+++ b/examples/Robotwin_ee/eval_files/deploy_policy.yml
@@ -0,0 +1,13 @@
+policy_name: starVLA
+task_name: beat_block_hammer
+task_config: demo_clean
+ckpt_setting: null
+seed: null
+instruction_type: unseen
+
+# StarVLA Client Parameters
+host: "127.0.0.1"
+port: 5693
+policy_ckpt_path: "/mnt/workspace/users/hukejun/JoyRA/StarVLA/outputs/robotwin_ee_clean_random/final_model/pytorch_model.pt"
+unnorm_key: "robotwin"
+embodiment_tag: "my_robotwin"
\ No newline at end of file
diff --git a/examples/Robotwin_ee/eval_files/dynamic_task_scheduler_50_mxk.py b/examples/Robotwin_ee/eval_files/dynamic_task_scheduler_50_mxk.py
new file mode 100644
index 0000000000000000000000000000000000000000..57b5a86acf9d43203211e9408cc387be0332de24
--- /dev/null
+++ b/examples/Robotwin_ee/eval_files/dynamic_task_scheduler_50_mxk.py
@@ -0,0 +1,830 @@
+# Copyright 2025 starVLA community. All rights reserved.
+# Copyright 2025 starVLA community. All rights reserved.
+# Licensed under the MIT License, Version 1.0 (the "License");
+# Implemented by StarVLA community in 2025.
+
+"""
+Dynamic task scheduler for parallel evaluation of all 50 robotwin tasks.
+Maintains a task queue and assigns tasks to GPUs as they become available.
+"""
+
+import argparse
+import os
+import re
+import subprocess
+import sys
+import threading
+import time
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Dict, List, Optional, Tuple
+
+# All 50 robotwin tasks from mixtures.py
+EVAL_TASKS = [
+ "adjust_bottle",
+ "beat_block_hammer",
+ "blocks_ranking_rgb",
+ "blocks_ranking_size",
+ "click_alarmclock",
+ "click_bell",
+ "dump_bin_bigbin",
+ "grab_roller",
+ "handover_block",
+ "handover_mic",
+ "hanging_mug",
+ "lift_pot",
+ "move_can_pot",
+ "move_pillbottle_pad",
+ "move_playingcard_away",
+ "move_stapler_pad",
+ "open_laptop",
+ "open_microwave",
+ "pick_diverse_bottles",
+ "pick_dual_bottles",
+ "place_a2b_left",
+ "place_a2b_right",
+ "place_bread_basket",
+ "place_bread_skillet",
+ "place_burger_fries",
+ "place_can_basket",
+ "place_cans_plasticbox",
+ "place_container_plate",
+ "place_dual_shoes",
+ "place_empty_cup",
+ "place_fan",
+ "place_mouse_pad",
+ "place_object_basket",
+ "place_object_scale",
+ "place_object_stand",
+ "place_phone_stand",
+ "place_shoe",
+ "press_stapler",
+ "put_bottles_dustbin",
+ "put_object_cabinet",
+ "rotate_qrcode",
+ "scan_object",
+ "shake_bottle",
+ "shake_bottle_horizontally",
+ "stack_blocks_three",
+ "stack_blocks_two",
+ "stack_bowls_three",
+ "stack_bowls_two",
+ "stamp_seal",
+ "turn_switch",
+]
+
+
+@dataclass
+class EvalConfig:
+ """Configuration for evaluation."""
+
+ ckpt_path: str = "/mnt/workspace/users/hukejun/JoyRA/StarVLA/outputs/robotwin_ee_clean_random/final_model/pytorch_model.pt"
+ server_port: int = 5693
+ server_port_map: Optional[Dict[int, int]] = None
+ task_config: str = "demo_clean"
+ ckpt_setting: str = "nopre_550_step4"
+ eval_seed: int = 0
+ starvla_path: str = ""
+ robotwin_path: str = ""
+ python_path: str = "python"
+ log_dir: str = ""
+ eval_save_root: str = "/mnt/workspace/users/maxiangkai/projects/JoyRA_robotwin"
+ eval_timestamp: str = ""
+ test_num: int = 100
+ num_traj_workers: int = 1
+ slots_per_gpu: int = 1
+ gpu_start_id: int = 1
+ resource_log_interval_s: int = 150 # Check every 5 seconds for peak detection
+ enable_resource_monitor: bool = True
+
+
+@dataclass
+class EvalJob:
+ """One sharded evaluation job for a task."""
+
+ task_name: str
+ worker_id: int
+ num_workers: int
+ start_seed: int
+ test_num: int
+
+ @property
+ def job_name(self) -> str:
+ return f"{self.task_name}#w{self.worker_id}"
+
+
+def strip_ansi_codes(text: str) -> str:
+ """Remove ANSI color codes from text."""
+ ansi_escape = re.compile(r"\x1b\[[0-9;]*m")
+ return ansi_escape.sub("", text)
+
+
+def get_default_paths() -> Tuple[str, str]:
+ """Infer default paths from this file location and workspace layout."""
+ current_file = Path(__file__).resolve()
+ # .../JoyRA_v1_paral_pass_bak/examples/Robotwin_ee/eval_files/dynamic_task_scheduler_50.py
+ # -> STARVLA root is parents[3]
+ starvla_root = current_file.parents[3]
+ sibling_robotwin = starvla_root.parent / "RoboTwin"
+ if sibling_robotwin.exists():
+ return str(starvla_root), str(sibling_robotwin)
+ # Fallback to legacy in-tree layout
+ return str(starvla_root), str(starvla_root / "RoboTwin")
+
+
+def split_test_num(total_test_num: int, num_workers: int) -> List[int]:
+ """Split test_num into near-equal shards."""
+ base = total_test_num // num_workers
+ rem = total_test_num % num_workers
+ return [base + (1 if i < rem else 0) for i in range(num_workers)]
+
+
+def format_seconds(seconds: float) -> str:
+ """Format seconds to HH:MM:SS."""
+ seconds = max(0, int(seconds))
+ h = seconds // 3600
+ m = (seconds % 3600) // 60
+ s = seconds % 60
+ return f"{h:02d}:{m:02d}:{s:02d}"
+
+
+def render_progress_bar(completed: int, total: int, width: int = 30) -> str:
+ """Render ASCII progress bar."""
+ if total <= 0:
+ total = 1
+ ratio = completed / total
+ filled = int(width * ratio)
+ return f"[{'#' * filled}{'-' * (width - filled)}] {completed}/{total} ({ratio * 100:.1f}%)"
+
+
+class SystemResourceMonitor:
+ """Lightweight system monitor based on /proc (no external dependency)."""
+
+ def __init__(self) -> None:
+ self._prev_total: Optional[int] = None
+ self._prev_idle: Optional[int] = None
+
+ def _read_cpu_times(self) -> Optional[Tuple[int, int]]:
+ try:
+ with open("/proc/stat", "r", encoding="utf-8") as f:
+ first = f.readline().strip().split()
+ if len(first) < 5 or first[0] != "cpu":
+ return None
+ values = [int(x) for x in first[1:]]
+ idle = values[3] + (values[4] if len(values) > 4 else 0) # idle + iowait
+ total = sum(values)
+ return total, idle
+ except Exception:
+ return None
+
+ def _read_memory(self) -> Optional[Tuple[int, int]]:
+ mem_total_kb = None
+ mem_available_kb = None
+ try:
+ with open("/proc/meminfo", "r", encoding="utf-8") as f:
+ for line in f:
+ if line.startswith("MemTotal:"):
+ mem_total_kb = int(line.split()[1])
+ elif line.startswith("MemAvailable:"):
+ mem_available_kb = int(line.split()[1])
+ if mem_total_kb is not None and mem_available_kb is not None:
+ break
+ except Exception:
+ return None
+
+ if mem_total_kb is None or mem_available_kb is None:
+ return None
+ used_kb = max(0, mem_total_kb - mem_available_kb)
+ return used_kb, mem_total_kb
+
+ def sample(self) -> str:
+ cpu_usage_str = "N/A"
+ cpu_times = self._read_cpu_times()
+ if cpu_times is not None:
+ total, idle = cpu_times
+ if self._prev_total is not None and self._prev_idle is not None:
+ delta_total = total - self._prev_total
+ delta_idle = idle - self._prev_idle
+ if delta_total > 0:
+ cpu_usage = 100.0 * (1.0 - (delta_idle / delta_total))
+ cpu_usage_str = f"{cpu_usage:.1f}%"
+ self._prev_total = total
+ self._prev_idle = idle
+
+ mem_str = "N/A"
+ memory = self._read_memory()
+ if memory is not None:
+ used_kb, total_kb = memory
+ used_gb = used_kb / (1024 * 1024)
+ total_gb = total_kb / (1024 * 1024)
+ pct = (used_kb / total_kb * 100.0) if total_kb > 0 else 0.0
+ mem_str = f"{used_gb:.1f}/{total_gb:.1f} GiB ({pct:.1f}%)"
+
+ load_str = "N/A"
+ runnable_str = "N/A"
+ try:
+ l1, l5, l15 = os.getloadavg()
+ cpu_count = os.cpu_count() or 1
+ load_str = f"{l1:.2f}/{l5:.2f}/{l15:.2f} (l1/core={l1 / cpu_count:.2f})"
+ with open("/proc/loadavg", "r", encoding="utf-8") as f:
+ fields = f.read().strip().split()
+ if len(fields) >= 4 and "/" in fields[3]:
+ runnable_str = fields[3]
+ except Exception:
+ pass
+
+ return (
+ f"[RESOURCE] CPU: {cpu_usage_str} | Load: {load_str} | "
+ f"RAM: {mem_str} | Runnable/Total: {runnable_str}"
+ )
+
+
+def parse_final_result_from_log(log_file: str) -> Optional[Tuple[int, int]]:
+ """Parse FINAL_RESULT line from log and return (success, total)."""
+ if not os.path.exists(log_file):
+ return None
+
+ final_pattern = re.compile(r"FINAL_RESULT .*success=(\d+)\s+total=(\d+)")
+ success = None
+ total = None
+
+ with open(log_file, "r", encoding="utf-8", errors="ignore") as f:
+ for line in f:
+ m = final_pattern.search(line)
+ if m:
+ success = int(m.group(1))
+ total = int(m.group(2))
+
+ if success is None or total is None:
+ return None
+ return success, total
+
+
+def build_jobs(tasks: List[str], config: EvalConfig) -> List[EvalJob]:
+ """
+ Create sharded jobs for all tasks with expanded seed ranges.
+
+ To handle unstable seeds that get skipped, we allocate 2x seeds per worker.
+ Example: 100 trajectories with 4 workers:
+ Worker 0: seeds 0-49 (need 25 trajectories)
+ Worker 1: seeds 50-99 (need 25 trajectories)
+ Worker 2: seeds 100-149 (need 25 trajectories)
+ Worker 3: seeds 150-199 (need 25 trajectories)
+
+ This ensures no overlap even if up to 50% of seeds are unstable.
+ """
+ jobs: List[EvalJob] = []
+ per_worker_counts = split_test_num(config.test_num, config.num_traj_workers)
+ base_seed = 100000 * (1 + config.eval_seed)
+
+ # Expanded seed range: allocate 4x seeds per worker to avoid overlap
+ seed_range_per_trajectory = 4 # 4x buffer for unstable seeds
+
+ for task_name in tasks:
+ seed_offset = 0
+ for worker_id, shard_test_num in enumerate(per_worker_counts):
+ if shard_test_num <= 0:
+ continue
+ jobs.append(
+ EvalJob(
+ task_name=task_name,
+ worker_id=worker_id,
+ num_workers=config.num_traj_workers,
+ start_seed=base_seed + seed_offset,
+ test_num=shard_test_num,
+ )
+ )
+ # Allocate expanded seed range (2x the actual test_num)
+ seed_offset += shard_test_num * seed_range_per_trajectory
+ return jobs
+
+
+def parse_server_ports(server_ports_str: str) -> Dict[int, int]:
+ """
+ Parse gpu->port mapping string.
+ Format example: "0:5693,1:5694"
+ """
+ mapping: Dict[int, int] = {}
+ if not server_ports_str:
+ return mapping
+
+ for item in server_ports_str.split(","):
+ pair = item.strip()
+ if not pair:
+ continue
+ if ":" not in pair:
+ raise ValueError(
+ f"Invalid server port mapping '{pair}', expected format gpu_id:port"
+ )
+ gpu_str, port_str = pair.split(":", 1)
+ gpu_id = int(gpu_str.strip())
+ port = int(port_str.strip())
+ mapping[gpu_id] = port
+ return mapping
+
+
+def run_dynamic_scheduler(
+ tasks: List[str],
+ num_gpus: int,
+ config: EvalConfig,
+) -> Tuple[Dict[str, Dict[str, int]], float]:
+ """
+ Run dynamic task scheduler.
+
+ Args:
+ tasks: List of task names to evaluate
+ num_gpus: Number of GPUs to use (1 to num_gpus)
+ config: Evaluation configuration
+
+ Returns:
+ Tuple of (task stats dict, total elapsed seconds)
+ """
+ import queue
+
+ gpu_ids = list(range(config.gpu_start_id, config.gpu_start_id + num_gpus))
+ jobs = build_jobs(tasks, config)
+ server_port_map = config.server_port_map or {}
+
+ # Create job queue
+ task_queue = queue.Queue()
+ for job in jobs:
+ task_queue.put(job)
+
+ # Track shard and task results
+ results: Dict[str, Dict[str, int]] = {
+ task: {
+ "success": 0,
+ "total": 0,
+ "done_shards": 0,
+ "failed_shards": 0,
+ }
+ for task in tasks
+ }
+
+ # Track task-level timing for summary
+ task_start_times: Dict[str, float] = {} # task_name -> first shard start time
+ task_completed: Dict[str, bool] = {task: False for task in tasks} # Track completion
+
+ completed = 0
+ total = len(jobs)
+ start_time = time.time()
+ last_progress_print = 0.0
+ last_resource_print = 0.0
+
+ # Track running processes per slot (gpu_id, slot_id)
+ running_processes: Dict[Tuple[int, int], subprocess.Popen] = {}
+ running_jobs: Dict[Tuple[int, int], EvalJob] = {}
+ running_logs: Dict[Tuple[int, int], str] = {}
+ running_start_ts: Dict[Tuple[int, int], float] = {}
+
+ scheduler_log_file = os.path.join(config.log_dir, "scheduler_progress.log")
+ with open(scheduler_log_file, "w", encoding="utf-8") as f:
+ f.write("")
+
+ def log_line(message: str = "") -> None:
+ print(message)
+ with open(scheduler_log_file, "a", encoding="utf-8") as f:
+ f.write(message + "\n")
+
+ log_line(f"\n{'='*60}")
+ log_line("Dynamic Task Scheduler - 50 Tasks")
+ log_line(f"{'='*60}")
+ log_line(f"Total tasks: {len(tasks)}")
+ log_line(f"Total shard jobs: {total}")
+ log_line(f"GPU IDs: {gpu_ids}")
+ if server_port_map:
+ log_line(f"Server port map: {server_port_map}")
+ else:
+ log_line(f"Server port: {config.server_port} (shared)")
+ log_line(f"Slots per GPU: {config.slots_per_gpu}")
+ log_line(f"Trajectory workers per task: {config.num_traj_workers}")
+ log_line(f"Each task test_num: {config.test_num}")
+ log_line(
+ f"Resource monitor: {config.enable_resource_monitor}, "
+ f"interval={config.resource_log_interval_s}s"
+ )
+ log_line(f"Scheduler progress log: {scheduler_log_file}")
+ log_line(f"{'='*60}\n")
+
+ resource_monitor = SystemResourceMonitor()
+
+ # Function to stream output and strip ANSI codes
+ def stream_to_log(process, log_f):
+ """Read process output, strip ANSI codes, and write to log file."""
+ for line in process.stdout:
+ clean_line = strip_ansi_codes(line)
+ log_f.write(clean_line)
+ log_f.flush()
+ log_f.close()
+
+ # Function to start a job on a specific GPU slot
+ def start_job_on_slot(gpu_id: int, slot_id: int, job: EvalJob):
+ log_file = os.path.join(
+ config.log_dir,
+ f"eval_gpu{gpu_id}_s{slot_id}_{job.task_name}_w{job.worker_id}.log",
+ )
+ eval_files_path = os.path.join(config.starvla_path, "examples/Robotwin_ee/eval_files")
+ deploy_policy_path = os.path.join(eval_files_path, "deploy_policy.yml")
+
+ env = os.environ.copy()
+ env["PYTHONPATH"] = (
+ f"{config.robotwin_path}:{config.starvla_path}:{eval_files_path}"
+ f":{env.get('PYTHONPATH', '')}"
+ )
+ env["PYTHONWARNINGS"] = "ignore::UserWarning"
+ # env["LD_LIBRARY_PATH"] = (
+ # f"/tmp/nvidia-gl-extract/usr/lib/x86_64-linux-gnu:{env.get('LD_LIBRARY_PATH', '')}"
+ # )
+ env["VK_ICD_FILENAMES"] = "/usr/share/vulkan/icd.d/nvidia_icd.json"
+ env["CUROBO_TORCH_COMPILE"] = "1"
+ env["CUDA_VISIBLE_DEVICES"] = str(gpu_id)
+ env ["PYTHONUNBUFFERED"] = "1"
+
+ server_port = server_port_map.get(gpu_id, config.server_port)
+ cmd = [
+ config.python_path,
+ os.path.join(config.robotwin_path, "script/eval_policy.py"),
+ "--config",
+ deploy_policy_path,
+ "--overrides",
+ "--port",
+ str(server_port),
+ "--policy_ckpt_path",
+ config.ckpt_path,
+ "--task_name",
+ job.task_name,
+ "--task_config",
+ config.task_config,
+ "--ckpt_setting",
+ config.ckpt_setting,
+ "--seed",
+ str(config.eval_seed),
+ "--test_num",
+ str(job.test_num),
+ "--start_seed",
+ str(job.start_seed),
+ "--worker_id",
+ str(job.worker_id),
+ "--num_workers",
+ str(job.num_workers),
+ "--policy_name",
+ "model2robotwin_interface_mxk",
+ "--eval_save_root",
+ config.eval_save_root,
+ "--eval_timestamp",
+ config.eval_timestamp,
+ ]
+
+ log_line(
+ f"[GPU {gpu_id}|SLOT {slot_id}] Starting: {job.job_name} "
+ f"(seed={job.start_seed}, test_num={job.test_num}, port={server_port})"
+ )
+
+ log_f = open(log_file, "w")
+ process = subprocess.Popen(
+ cmd,
+ env=env,
+ cwd=config.robotwin_path,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ text=True,
+ )
+ # Start thread to stream output with ANSI stripping
+ thread = threading.Thread(target=stream_to_log, args=(process, log_f))
+ thread.daemon = True
+ thread.start()
+ return process, thread, log_file
+
+ def pop_next_job() -> Optional[EvalJob]:
+ try:
+ job = task_queue.get_nowait()
+ # Record task start time on first shard
+ if job.task_name not in task_start_times:
+ task_start_times[job.task_name] = time.time()
+ return job
+ except queue.Empty:
+ return None
+
+ # Initialize slots
+ for gpu_id in gpu_ids:
+ for slot_id in range(config.slots_per_gpu):
+ job = pop_next_job()
+ if job is None:
+ break
+ process, thread, log_file = start_job_on_slot(gpu_id, slot_id, job)
+ slot_key = (gpu_id, slot_id)
+ running_processes[slot_key] = process
+ running_jobs[slot_key] = job
+ running_logs[slot_key] = log_file
+ running_start_ts[slot_key] = time.time()
+ running_processes[slot_key].log_thread = thread
+
+ # Main loop: monitor jobs and refill free slots
+ while completed < total:
+ for slot_key in list(running_processes.keys()):
+ process = running_processes[slot_key]
+ ret = process.poll()
+
+ if ret is not None: # Process finished
+ gpu_id, slot_id = slot_key
+ job = running_jobs[slot_key]
+ task_name = job.task_name
+ exit_code = ret
+
+ # Wait for log thread to finish
+ if hasattr(process, "log_thread"):
+ process.log_thread.join()
+
+ elapsed_job = time.time() - running_start_ts[slot_key]
+ status = "SUCCESS" if exit_code == 0 else f"FAILED (exit code: {exit_code})"
+ log_line(
+ f"[GPU {gpu_id}|SLOT {slot_id}] {status}: {job.job_name} "
+ f"(elapsed={format_seconds(elapsed_job)})"
+ )
+
+ shard_result = parse_final_result_from_log(running_logs[slot_key])
+ if shard_result is not None:
+ shard_success, shard_total = shard_result
+ else:
+ shard_success = 0
+ shard_total = job.test_num
+
+ results[task_name]["success"] += shard_success
+ results[task_name]["total"] += shard_total
+ results[task_name]["done_shards"] += 1
+ if exit_code != 0:
+ results[task_name]["failed_shards"] += 1
+ completed += 1
+
+ # Check if task is fully completed (all shards done)
+ task_total_shards = sum(1 for j in jobs if j.task_name == task_name)
+ if results[task_name]["done_shards"] == task_total_shards and not task_completed[task_name]:
+ task_completed[task_name] = True
+ task_elapsed = time.time() - task_start_times[task_name]
+ task_success = results[task_name]["success"]
+ task_total = results[task_name]["total"]
+ task_rate = (task_success / task_total * 100) if task_total > 0 else 0.0
+
+ log_line("")
+ log_line(f"{'='*60}")
+ log_line(f"✓ TASK COMPLETED: {task_name}")
+ log_line(f"{'='*60}")
+ log_line(f" Total Time: {format_seconds(task_elapsed)}")
+ log_line(f" Success Rate: {task_success}/{task_total} ({task_rate:.1f}%)")
+ log_line(f" Shards: {results[task_name]['done_shards']} completed, "
+ f"{results[task_name]['failed_shards']} failed")
+ log_line(f"{'='*60}")
+ log_line("")
+
+ elapsed = time.time() - start_time
+ eta = (elapsed / completed) * (total - completed) if completed > 0 else 0
+ log_line(
+ f" Progress: {render_progress_bar(completed, total)} | "
+ f"Elapsed: {format_seconds(elapsed)} | ETA: {format_seconds(eta)}"
+ )
+
+ # Remove finished slot from tracking
+ del running_processes[slot_key]
+ del running_jobs[slot_key]
+ del running_logs[slot_key]
+ del running_start_ts[slot_key]
+
+ # Assign next job to this free slot
+ new_job = pop_next_job()
+ if new_job is not None:
+ process, thread, log_file = start_job_on_slot(gpu_id, slot_id, new_job)
+ running_processes[slot_key] = process
+ running_jobs[slot_key] = new_job
+ running_logs[slot_key] = log_file
+ running_start_ts[slot_key] = time.time()
+ running_processes[slot_key].log_thread = thread
+
+ now = time.time()
+ if now - last_progress_print >= 300.0:
+ elapsed = now - start_time
+ eta = (elapsed / completed) * (total - completed) if completed > 0 else 0
+ log_line(
+ f"[HEARTBEAT] {render_progress_bar(completed, total)} | "
+ f"Elapsed: {format_seconds(elapsed)} | ETA: {format_seconds(eta)} | "
+ f"Running slots: {len(running_processes)}"
+ )
+ last_progress_print = now
+
+ if config.enable_resource_monitor and now - last_resource_print >= config.resource_log_interval_s:
+ log_line(resource_monitor.sample())
+ last_resource_print = now
+
+ time.sleep(0.5) # Poll interval
+
+ return results, (time.time() - start_time)
+
+
+def main():
+ default_starvla_path, default_robotwin_path = get_default_paths()
+ parser = argparse.ArgumentParser(
+ description="Dynamic task scheduler for 50 robotwin tasks"
+ )
+ parser.add_argument(
+ "--mode",
+ type=str,
+ default="run",
+ choices=["run", "list"],
+ help="Mode: run (execute tasks), list (just list tasks)",
+ )
+ parser.add_argument(
+ "--num_gpus",
+ type=int,
+ default=7,
+ help="Number of GPUs used for evaluation",
+ )
+ parser.add_argument(
+ "--gpu_start_id",
+ type=int,
+ default=1,
+ help="First GPU ID for evaluation (set 0 to include GPU0)",
+ )
+ parser.add_argument(
+ "--slots_per_gpu",
+ type=int,
+ default=1,
+ help="Concurrent eval processes per GPU",
+ )
+ parser.add_argument(
+ "--num_traj_workers",
+ type=int,
+ default=1,
+ help="How many shards to split each task into",
+ )
+ parser.add_argument(
+ "--test_num",
+ type=int,
+ default=100,
+ help="Total trajectories per task",
+ )
+ parser.add_argument(
+ "--ckpt_path",
+ type=str,
+ default="/mnt/workspace/users/hukejun/JoyRA/StarVLA/outputs/robotwin_ee_clean_random/final_model/pytorch_model.pt",
+ help="Path to model checkpoint",
+ )
+ parser.add_argument(
+ "--server_port",
+ type=int,
+ default=5693,
+ help="Port for policy server",
+ )
+ parser.add_argument(
+ "--server_ports",
+ type=str,
+ default="",
+ help="Optional GPU-specific server ports, e.g. '0:5693,1:5694'",
+ )
+ parser.add_argument(
+ "--task_config",
+ type=str,
+ default="demo_clean",
+ help="Task configuration",
+ )
+ parser.add_argument(
+ "--ckpt_setting",
+ type=str,
+ default="nopre_550_step4",
+ help="Checkpoint setting",
+ )
+ parser.add_argument(
+ "--eval_seed",
+ type=int,
+ default=0,
+ help="Base evaluation seed",
+ )
+ parser.add_argument(
+ "--log_dir",
+ type=str,
+ default="",
+ help="Directory for log files",
+ )
+ parser.add_argument(
+ "--eval_save_root",
+ type=str,
+ default="/mnt/workspace/users/maxiangkai/projects/JoyRA_robotwin",
+ help="Root directory for saving eval videos/images",
+ )
+ parser.add_argument(
+ "--eval_timestamp",
+ type=str,
+ default="",
+ help="Unified run timestamp (shared by log/video dirs)",
+ )
+ parser.add_argument(
+ "--starvla_path",
+ type=str,
+ default=default_starvla_path,
+ help="Path to StarVLA project root",
+ )
+ parser.add_argument(
+ "--robotwin_path",
+ type=str,
+ default=default_robotwin_path,
+ help="Path to RoboTwin project root",
+ )
+ parser.add_argument(
+ "--python_path",
+ type=str,
+ default=sys.executable,
+ help="Python executable used to launch eval workers",
+ )
+ parser.add_argument(
+ "--resource_log_interval",
+ type=int,
+ default=5,
+ help="System resource log interval in seconds (default: 5 for peak detection)",
+ )
+ parser.add_argument(
+ "--disable_resource_monitor",
+ action="store_true",
+ help="Disable CPU/RAM resource logging",
+ )
+
+ args = parser.parse_args()
+
+ if args.mode == "list":
+ print("Tasks to evaluate (50 total):")
+ for i, task in enumerate(EVAL_TASKS, 1):
+ print(f" {i:2d}. {task}")
+ return
+
+ # Setup log directory
+ if not args.log_dir:
+ args.log_dir = os.path.join(
+ os.path.dirname(os.path.abspath(__file__)),
+ "eval_logs_50tasks",
+ )
+ os.makedirs(args.log_dir, exist_ok=True)
+
+ config = EvalConfig(
+ ckpt_path=args.ckpt_path,
+ server_port=args.server_port,
+ server_port_map=parse_server_ports(args.server_ports),
+ task_config=args.task_config,
+ ckpt_setting=args.ckpt_setting,
+ eval_seed=args.eval_seed,
+ starvla_path=os.path.abspath(args.starvla_path),
+ robotwin_path=os.path.abspath(args.robotwin_path),
+ python_path=args.python_path,
+ log_dir=args.log_dir,
+ eval_save_root=args.eval_save_root,
+ eval_timestamp=args.eval_timestamp,
+ test_num=args.test_num,
+ num_traj_workers=max(1, args.num_traj_workers),
+ slots_per_gpu=max(1, args.slots_per_gpu),
+ gpu_start_id=args.gpu_start_id,
+ resource_log_interval_s=max(1, args.resource_log_interval),
+ enable_resource_monitor=not args.disable_resource_monitor,
+ )
+
+ # Run scheduler
+ print("######## WM4A-MODE(1/3): StarVLA/examples/Robotwin_ee/eval_files/dynamic_task_scheduler_50_mxk.py")
+ results, elapsed_total = run_dynamic_scheduler(EVAL_TASKS, args.num_gpus, config)
+
+ # Print summary
+ print(f"\n{'='*60}")
+ print("Evaluation Summary")
+ print(f"{'='*60}")
+
+ failed_tasks = []
+ success_trajs = 0
+ all_trajs = 0
+ for task_name, stat in results.items():
+ total = max(1, stat["total"])
+ rate = stat["success"] / total * 100
+ print(
+ f"{task_name:<28} | "
+ f"success {stat['success']:>3d}/{stat['total']:<3d} "
+ f"({rate:>5.1f}%) | "
+ f"shards {stat['done_shards']}/{config.num_traj_workers} | "
+ f"failed_shards={stat['failed_shards']}"
+ )
+ if stat["failed_shards"] > 0:
+ failed_tasks.append(task_name)
+ success_trajs += stat['success']
+ all_trajs += stat['total']
+
+ success_count = len(results) - len(failed_tasks)
+ fail_count = len(failed_tasks)
+ print(f"\nTask Success: {success_count}/{len(results)}")
+ print(f"Success Rate: {success_trajs}/{all_trajs}")
+ print(f"Task Failed: {fail_count}/{len(results)}")
+ print(f"Total elapsed: {format_seconds(elapsed_total)}")
+
+ if fail_count > 0:
+ print("\nFailed tasks:")
+ for task in failed_tasks:
+ print(f" - {task}")
+
+ print(f"{'='*60}")
+
+ sys.exit(0 if fail_count == 0 else 1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/Robotwin_ee/eval_files/model2robotwin_interface_mxk.py b/examples/Robotwin_ee/eval_files/model2robotwin_interface_mxk.py
new file mode 100644
index 0000000000000000000000000000000000000000..41f43d31e960d93f01cdfa0458e3e5f575121650
--- /dev/null
+++ b/examples/Robotwin_ee/eval_files/model2robotwin_interface_mxk.py
@@ -0,0 +1,1103 @@
+import collections
+import logging
+import math
+import time
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Dict, Optional, Sequence
+from collections import deque
+
+import numpy as np
+import cv2 as cv
+import json_numpy
+
+import matplotlib
+matplotlib.use("Agg")
+import matplotlib.pyplot as plt
+
+
+from deployment_robotwin.model_server.tools.websocket_policy_client import WebsocketClientPolicy
+from starVLA.model.tools import read_mode_config
+
+try:
+ from examples.SimplerEnv.eval_files.adaptive_ensemble import AdaptiveEnsembler
+except ImportError:
+ AdaptiveEnsembler = None
+
+from robotwin_aloha_transform_kdl import AlohaRetargeter, RobotwinRetargetConfig
+
+# Embodiment tag string to projector index mapping (from embodiment_tags.py)
+EMBODIMENT_TAG_MAPPING = {
+ "new_embodiment": 31,
+ "oxe_droid": 17,
+ "oxe_bridge": 18,
+ "oxe_rt1": 19,
+ "agibot_genie1": 26,
+ "gr1": 24,
+ "franka": 25,
+ "my_robotwin": 27,
+}
+
+
+class ModelClient:
+ def __init__(
+ self,
+ policy_ckpt_path,
+ unnorm_key: Optional[str] = None,
+ embodiment_tag: Optional[str] = None,
+ use_ee_pose: Optional[bool] = True,
+ policy_setup: str = "robotwin",
+ horizon: int = 0,
+ action_ensemble=False,
+ action_ensemble_horizon: Optional[int] = 3,
+ image_size: list[int] = [224, 224],
+ use_ddim: bool = True,
+ num_ddim_steps: int = 10,
+ adaptive_ensemble_alpha=0.1,
+ host="127.0.0.1",
+ port=5694,
+ debug_save_head_images: bool = False,
+ use_fixed_test_data: bool = False,
+ fixed_test_data_dir: str = "../Camera/test_1",
+ fixed_test_frame_idx: int = 119,
+ ) -> None:
+ print("######## WM4A-MODE(2/3): StarVLA/examples/Robotwin_ee/eval_files/model2robotwin_interface_mxk.py")
+ self.is_train_in_WM4A = True
+ if self.is_train_in_WM4A:
+ self.policy_ckpt_path = policy_ckpt_path
+ print("######## WM4A-MODE(3/3): The EVAL with the WM4A's mode")
+ else:
+ print("######## JoyRA-MODE(1/1): The EVAL with the JoyRA's mode")
+
+ print("######## Whether to use 'state' as the input is determined by the function 'eval(TASK_ENV, model, observation)' in the file 'model2robotwin_interface_mxk.py'.")
+ print("######## The 'use_ee_pose' value is a T/F (True/False) and is determined by hard-coding the input parameters of the ModelClient.")
+ print(f"######### The Setting 'self.use_ee_pose' is {use_ee_pose}")
+
+ self.client = WebsocketClientPolicy(host, port)
+ self.policy_setup = policy_setup
+ self.unnorm_key = unnorm_key
+ # 将embodiment_tag字符串转换为对应的index
+ self.embodiment_tag = EMBODIMENT_TAG_MAPPING.get(embodiment_tag, embodiment_tag)
+ self.use_ee_pose = use_ee_pose
+ if self.use_ee_pose:
+ robotwin_config = RobotwinRetargetConfig()
+ self.retargeter = AlohaRetargeter(urdf_path=Path(robotwin_config.urdf_path))
+ print(f"*** enable ee pose action space ***")
+ print(f"*** policy_setup: {policy_setup}, unnorm_key: {unnorm_key} ***")
+ self.use_ddim = use_ddim
+ self.num_ddim_steps = num_ddim_steps
+ self.image_size = image_size
+ self.horizon = horizon
+ self.action_ensemble = action_ensemble and (AdaptiveEnsembler is not None)
+ self.adaptive_ensemble_alpha = adaptive_ensemble_alpha
+ self.action_ensemble_horizon = action_ensemble_horizon
+ self.debug_save_head_images = debug_save_head_images
+ self.use_fixed_test_data = use_fixed_test_data
+ self.fixed_test_data_dir = fixed_test_data_dir
+ self.fixed_test_frame_idx = fixed_test_frame_idx
+
+ # Load fixed test data if enabled
+ self.fixed_head_img = None
+ self.fixed_left_img = None
+ self.fixed_right_img = None
+ self.fixed_state = None
+
+ if self.use_fixed_test_data:
+ self._load_fixed_test_data()
+
+ self.task_description = None
+ self.image_history = deque(maxlen=self.horizon)
+ if self.action_ensemble:
+ self.action_ensembler = AdaptiveEnsembler(self.action_ensemble_horizon, self.adaptive_ensemble_alpha)
+ else:
+ self.action_ensembler = None
+ self.num_image_history = 0
+
+ self.action_norm_stats = self.get_action_stats(self.unnorm_key, policy_ckpt_path=policy_ckpt_path)
+ self.action_chunk_size = self.get_action_chunk_size(policy_ckpt_path=policy_ckpt_path)
+ # self.action_chunk_size = 10
+ self.state_norm_stats = self.get_state_stats(self.unnorm_key, policy_ckpt_path=policy_ckpt_path)
+ self.raw_actions = None
+ self.left_arm_joint_angles = None
+ self.right_arm_joint_angles = None
+ self.left_arm_actions_history = []
+ self.right_arm_actions_history = []
+ self.left_arm_ee_pose_history = [] # 保存左臂的ee_pose (pos + axis)
+ self.right_arm_ee_pose_history = [] # 保存右臂的ee_pose (pos + axis)
+ self.left_gripper_history = [] # 保存左臂夹爪动作
+ self.right_gripper_history = [] # 保存右臂夹爪动作
+ self.camera_images_history = {
+ "head": [],
+ "left": [],
+ "right": []
+ } # 用于保存所有相机的图片用于debug
+ self.state_history = [] # 用于保存原始state用于debug
+ self.normalized_action_chunks = [] # 用于开环测试,收集每次模型生成的原始normalized_actions (50, 32)
+ self._action_plot_save_dir = None # episode结束时保存action图的目录
+ self._action_plot_episode_num = None # episode编号
+ self._future_concat_frames = [] # 每次推理的当前帧+未来帧拼接图
+ self._future_concat_save_dir = None
+ self._future_concat_episode_num = None
+
+ def _load_fixed_test_data(self) -> None:
+ """
+ 加载固定的测试数据(图像和state)
+ """
+ test_data_dir = Path(self.fixed_test_data_dir)
+
+ # Load fixed images
+ head_img_path = test_data_dir / "head" / f"frame_{self.fixed_test_frame_idx:06d}.png"
+ left_img_path = test_data_dir / "left" / f"frame_{self.fixed_test_frame_idx:06d}.png"
+ right_img_path = test_data_dir / "right" / f"frame_{self.fixed_test_frame_idx:06d}.png"
+
+ if head_img_path.exists():
+ self.fixed_head_img = cv.imread(str(head_img_path))
+ self.fixed_head_img = cv.cvtColor(self.fixed_head_img, cv.COLOR_BGR2RGB)
+ print(f"Loaded fixed head image from {head_img_path}, shape: {self.fixed_head_img.shape}")
+ else:
+ print(f"Warning: Fixed head image not found at {head_img_path}")
+
+ if left_img_path.exists():
+ self.fixed_left_img = cv.imread(str(left_img_path))
+ self.fixed_left_img = cv.cvtColor(self.fixed_left_img, cv.COLOR_BGR2RGB)
+ print(f"Loaded fixed left image from {left_img_path}, shape: {self.fixed_left_img.shape}")
+ else:
+ print(f"Warning: Fixed left image not found at {left_img_path}")
+
+ if right_img_path.exists():
+ self.fixed_right_img = cv.imread(str(right_img_path))
+ self.fixed_right_img = cv.cvtColor(self.fixed_right_img, cv.COLOR_BGR2RGB)
+ print(f"Loaded fixed right image from {right_img_path}, shape: {self.fixed_right_img.shape}")
+ else:
+ print(f"Warning: Fixed right image not found at {right_img_path}")
+
+ # Load fixed state
+ state_path = test_data_dir / "state" / "state_history.npz"
+ if state_path.exists():
+ state_data = np.load(str(state_path))
+ state_history = state_data['state']
+ if self.fixed_test_frame_idx < len(state_history):
+ self.fixed_state = state_history[self.fixed_test_frame_idx].copy()
+ print(f"Loaded fixed state at index {self.fixed_test_frame_idx}, shape: {self.fixed_state.shape}")
+ else:
+ print(f"Warning: Fixed test frame index {self.fixed_test_frame_idx} out of range (state length: {len(state_history)})")
+ self.fixed_state = state_history[0].copy()
+ print(f"Using first state instead, shape: {self.fixed_state.shape}")
+ else:
+ print(f"Warning: Fixed state not found at {state_path}")
+
+ def reset(self, task_description: str) -> None:
+ self.task_description = task_description
+ self.image_history.clear()
+ if self.action_ensemble:
+ self.action_ensembler.reset()
+ if self.use_ee_pose:
+ self.retargeter.reset_ik_cache()
+ self.num_image_history = 0
+ self.raw_actions = None
+ self.left_arm_joint_angles = None
+ self.right_arm_joint_angles = None
+ self.left_arm_actions_history = []
+ self.right_arm_actions_history = []
+ self.left_arm_ee_pose_history = []
+ self.right_arm_ee_pose_history = []
+ self.left_gripper_history = []
+ self.right_gripper_history = []
+ self.camera_images_history = {
+ "head": [],
+ "left": [],
+ "right": []
+ }
+ self.state_history = []
+ self.normalized_action_chunks = [] # 重置开环测试收集
+ self._action_plot_save_dir = None
+ self._action_plot_episode_num = None
+ self._future_concat_frames = []
+ self._future_concat_save_dir = None
+ self._future_concat_episode_num = None
+
+ def step(self, example: dict, step: int = 0) -> np.ndarray:
+ state = example.get("state", None)
+ if state is not None:
+ # 保存原始state用于debug
+ if self.debug_save_head_images:
+ self.state_history.append(state.copy())
+ if self.use_ee_pose:
+ # 最初从client获取的state是14维向量:[left_arm,left_gripper,right_arm,right_gripper]
+ # 这里首先将其转换为:[left_arm,right_arm,left_gripper,right_gripper]
+ original_state = np.array(state[[0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 6, 13]])
+
+ # 随后将从Robotwin环境中获取的原始state转换为ee-pose-state,
+ # 似乎只需要对left_arm和right_arm做转换,保持left_gripper,right_gripper不变,同时需要保存原始的left_arm,right_arm
+ self.left_arm_joint_angles = original_state[0:6]
+ self.right_arm_joint_angles = original_state[6:12]
+ (left_pos, left_axis), (right_pos, right_axis), (left_q, right_q) = self.retargeter.process_frame_kinematics_axisangle(state)
+ # 将 left_pos, left_axis, right_pos, right_axis 与 original_state 的最后两维度拼成新的 state
+ # new_state = np.concatenate([left_pos, left_axis, right_pos, right_axis, original_state[-2:].reshape(1, -1)], axis=1)
+ # state_keys = [
+ # "state.left_arm",
+ # "state.left_gripper",
+ # "state.right_arm",
+ # "state.right_gripper",
+ # ] order of state
+
+ # JoyRA模型输入的state为:[left_arm,left_gripper,right_arm,right_gripper,0*50],共64维,前14维是有效的,
+ # print('### input-state')
+ new_state = np.concatenate([left_pos, left_axis, original_state[-2].reshape(1, -1), right_pos, right_axis, original_state[-1].reshape(1, -1)], axis=1)
+ # print(new_state.shape) # (1, 14)
+
+ # JoyRA格式的state对齐到WM4A格式
+ # WM4A模型输入的state为:[left_arm,right_arm,left_gripper,right_gripper,0*50],共64维,前14维是有效的,
+ # print(self.is_train_in_WM4A) # True
+ if self.is_train_in_WM4A:
+ left_arm = new_state[:, 0:6]
+ left_gripper = new_state[:, 6:7]
+ right_arm = new_state[:, 7:13]
+ right_gripper = new_state[:, 13:14]
+ new_state = np.concatenate([left_arm, right_arm, left_gripper, right_gripper], axis=1)
+ # print(new_state.shape) # (1, 14)
+
+ # print(self.unnorm_key) # robotwin
+ # print(self.policy_ckpt_path) # /mnt/workspace1/users/chidafeng/results/Checkpoints/robotwin_clean_random_reversed-QwenFastWanPerceiver-mn-train-motus-fast-chunk50/checkpoints/steps_260000_pytorch_model.pt
+ # print(len(self.action_norm_stats["min"])) # 14
+ # print(len(self.action_norm_stats["max"])) # 14
+ new_state = self.normalize_state(new_state, self.state_norm_stats)
+ # print(new_state.shape) # (1, 14)
+
+ # 将14维的state padding到64维
+ current_state_dim = new_state.shape[1]
+ target_dim = 64
+ if current_state_dim < target_dim:
+ padding = np.zeros((1, target_dim - current_state_dim), dtype=new_state.dtype)
+ new_state = np.concatenate([new_state, padding], axis=1)
+
+ example["state"] = new_state.reshape(1, -1)
+
+ else:
+ state = self.normalize_state(state, self.state_norm_stats)
+ state = state[[0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 6, 13]]
+ example["state"] = state.reshape(1, -1)
+ else:
+ print('######## state is NONE')
+
+ task_description = example.get("lang", None)
+ if example is not None:
+ if task_description != self.task_description:
+ self.reset(task_description)
+
+ images = example["image"]
+ # images = [self._center_crop_image(image, crop_ratio=0.95) for image in images]
+ # images = [self._resize_image_pad(image) for image in images]
+ concat_img = self._concat_view_images(images)
+ images = [np.array(concat_img)]
+ example["image"] = images
+ # add embodiment_tag to example
+ example["embodiment_tag"] = self.embodiment_tag
+ vla_input = {
+ "examples": [example],
+ "do_sample": False,
+ "use_ddim": self.use_ddim,
+ "num_ddim_steps": self.num_ddim_steps,
+ "future_image_generation": {
+ "enabled": True,
+ "num_frames": 9, # 生成 9 帧未来图像
+ "return_full_video": False, # 如果为 True,data 中会包含所有帧;如果为 False,通常只返回最后一帧或指定索引帧
+ "future_frame_index": -1, # -1 通常代表最后一帧
+ "height": 224,
+ "width": 224,
+ "num_inference_steps": 1, # 如果模型支持,可以单独设置未来帧生成的步数
+ }
+ }
+
+ action_chunk_size = self.action_chunk_size
+
+ if step % action_chunk_size == 0 or self.raw_actions is None:
+ # print("Calling model to predict action")
+ max_retries = 3
+ retry_sleep_s = 0.3
+ normalized_actions = None
+ last_error_message = ""
+
+ for attempt in range(max_retries):
+ # ************** 模型前向传播
+ response = self.client.predict_action(vla_input)
+ data = response.get("data") if isinstance(response, dict) else None
+ normalized_actions = data.get("normalized_actions") if isinstance(data, dict) else None
+
+ if normalized_actions is not None:
+ # 收集完整的原始 normalized_actions 用于开环测试绘图
+ self.normalized_action_chunks.append(normalized_actions.copy())
+ # 收集每次推理的"当前帧+未来帧"拼接图,用于episode结束时合成视频
+ self._append_future_concat_frame(data, images[0])
+ break
+
+ status = response.get("status") if isinstance(response, dict) else None
+ error_obj = response.get("error") if isinstance(response, dict) else None
+ error_message = ""
+ if isinstance(error_obj, dict):
+ error_message = str(error_obj.get("message", ""))
+ elif error_obj is not None:
+ error_message = str(error_obj)
+ last_error_message = (
+ f"status={status}, error={error_message or 'missing data.normalized_actions'}"
+ )
+ print(
+ f"Policy response missing normalized_actions "
+ f"(attempt {attempt + 1}/{max_retries}): {last_error_message}"
+ )
+ if attempt < max_retries - 1:
+ time.sleep(retry_sleep_s)
+
+ if normalized_actions is None:
+ raise RuntimeError(
+ "Policy inference response is invalid after retries: "
+ f"{last_error_message}"
+ )
+
+ # WM4A模型输出的action为:[left_arm,right_arm,left_gripper,right_gripper,0*18],共32维,前14维是有效的,
+ # JoyRA模型输出的action为:[left_arm,left_gripper,right_arm,right_gripper,0*18],共32维,前14维是有效的,
+ # print('### output-action')
+ # print(normalized_actions.shape) # (1, 50, 32)
+ normalized_actions = normalized_actions[0]
+ # print(normalized_actions.shape) # (50, 32)
+ normalized_actions = normalized_actions[:, :14]
+ # print(normalized_actions.shape) # (50, 14)
+
+ # print(self.unnorm_key) # robotwin
+ # print(self.policy_ckpt_path) # /mnt/workspace1/users/chidafeng/results/Checkpoints/robotwin_clean_random_reversed-QwenFastWanPerceiver-mn-train-motus-fast-chunk50/checkpoints/steps_260000_pytorch_model.pt
+ # print(len(self.action_norm_stats["min"])) # 14
+ # print(len(self.action_norm_stats["max"])) # 14
+ self.raw_actions = self.unnormalize_actions(
+ normalized_actions=normalized_actions, action_norm_stats=self.action_norm_stats
+ )
+ # print(self.raw_actions.shape) # (50, 14)
+
+ # 将WM4A模型输出的格式对齐到JoyRA格式,因为这套Robotwin测试代码是适配oyRA的
+ # print(self.is_train_in_WM4A) # True
+ if self.is_train_in_WM4A:
+ # print('self.is_train_in_WM4A is TRUE')
+ left_arm = self.raw_actions[:, 0:6]
+ right_arm = self.raw_actions[:, 6:12]
+ left_gripper = self.raw_actions[:, 12:13]
+ right_gripper = self.raw_actions[:, 13:14]
+ self.raw_actions = np.concatenate([left_arm, left_gripper, right_arm, right_gripper], axis=1)
+ # print(self.raw_actions.shape) # (50, 14)
+
+ action_idx = step % action_chunk_size
+ if action_idx >= len(self.raw_actions):
+ pass
+
+ # action_keys = [
+ # "action.left_arm",
+ # "action.left_gripper",
+ # "action.right_arm",
+ # "action.right_gripper",
+ # ] order of action output from model
+
+ current_action = self.raw_actions[action_idx]
+ if self.use_ee_pose:
+ left_hand_pos = current_action[0:3] # 左手位置向量
+ left_hand_axis = current_action[3:6] # 左手旋转向量
+ left_hand_q = current_action[6] # 左手夹爪
+ right_hand_pos = current_action[7:10] # 右手位置向量
+ right_hand_axis = current_action[10:13] # 右手旋转向量
+ right_hand_q = current_action[13] # 右手夹爪
+
+ q_left_arm, q_right_arm = self.retargeter.inverse_kinematics_from_camera_axisangle(
+ left_hand_pos, left_hand_axis, right_hand_pos, right_hand_axis, q_init_left=self.left_arm_joint_angles, q_init_right=self.right_arm_joint_angles
+ )
+ # 记录左右臂的所有动作(关节角度形式)
+ self.left_arm_actions_history.append(q_left_arm.reshape(-1).copy())
+ self.right_arm_actions_history.append(q_right_arm.reshape(-1).copy())
+ # 记录左右臂的ee_pose形式(pos + axis)
+ self.left_arm_ee_pose_history.append(np.concatenate([left_hand_pos, left_hand_axis]).copy())
+ self.right_arm_ee_pose_history.append(np.concatenate([right_hand_pos, right_hand_axis]).copy())
+ # 记录夹爪动作
+ self.left_gripper_history.append(left_hand_q.copy())
+ self.right_gripper_history.append(right_hand_q.copy())
+
+ current_action = np.concatenate([q_left_arm, q_right_arm, left_hand_q.reshape(1, -1), right_hand_q.reshape(1, -1)], axis=1)
+ current_action = current_action.reshape(-1)
+
+ current_action = current_action[[0, 1, 2, 3, 4, 5, 12, 6, 7, 8, 9, 10, 11, 13]]
+ # 最终交给client的current_action是14维向量:[left_arm,left_gripper,right_arm,right_gripper]
+ return current_action
+
+ @staticmethod
+ def normalize_state(state: dict[str, np.ndarray], state_norm_stats: Dict[str, np.ndarray]) -> dict[str, np.ndarray]:
+ """
+ Normalize the state
+ """
+ mask = [True, True, True, True, True, True, True, True, True, True, True, True, True, True]
+ mask = np.array(mask, dtype=bool)
+ state_high, state_low = np.array(state_norm_stats["max"]), np.array(state_norm_stats["min"])
+ normalized_state = np.where(
+ mask,
+ (state - state_low) / (state_high - state_low) * 2 - 1,
+ state,
+ )
+ normalized_state = np.where(~mask, (normalized_state > 0.5).astype(normalized_state.dtype), normalized_state)
+ return normalized_state
+
+ @staticmethod
+ def unnormalize_actions(normalized_actions: np.ndarray, action_norm_stats: Dict[str, np.ndarray]) -> np.ndarray:
+ # mask = action_norm_stats.get("mask", np.ones_like(action_norm_stats["min"], dtype=bool))
+ mask = [True, True, True, True, True, True, True, True, True, True, True, True, True, True]
+ mask = np.array(mask, dtype=bool)
+ action_high, action_low = np.array(action_norm_stats["max"]), np.array(action_norm_stats["min"])
+ normalized_actions = np.clip(normalized_actions, -1, 1)
+
+ actions = np.where(
+ mask,
+ 0.5 * (normalized_actions + 1) * (action_high - action_low) + action_low,
+ normalized_actions,
+ )
+
+ return actions
+
+ @staticmethod
+ def get_action_stats(unnorm_key: str, policy_ckpt_path) -> dict:
+ policy_ckpt_path = Path(policy_ckpt_path)
+ model_config, norm_stats = read_mode_config(policy_ckpt_path)
+ unnorm_key = ModelClient._check_unnorm_key(norm_stats, unnorm_key)
+ return norm_stats[unnorm_key]["action"]
+
+ @staticmethod
+ def get_state_stats(unnorm_key: str, policy_ckpt_path) -> dict:
+ policy_ckpt_path = Path(policy_ckpt_path)
+ model_config, norm_stats = read_mode_config(policy_ckpt_path)
+ unnorm_key = ModelClient._check_unnorm_key(norm_stats, unnorm_key)
+ return norm_stats[unnorm_key]["state"]
+
+ @staticmethod
+ def get_action_chunk_size(policy_ckpt_path):
+ model_config, _ = read_mode_config(policy_ckpt_path)
+ return model_config["framework"]["action_model"]["future_action_window_size"] + 1
+
+ def _resize_image(self, image: np.ndarray) -> np.ndarray:
+ image = cv.resize(image, tuple(self.image_size), interpolation=cv.INTER_LINEAR)
+ return image
+
+ def _resize_image_pad(
+ self,
+ image: np.ndarray,
+ target_size: int | None = None,
+ fill_value: float = 0.0,
+ interpolation: int = cv.INTER_LINEAR,
+ ) -> np.ndarray:
+ """
+ Resize image keeping aspect ratio, then center pad to target square size.
+
+ This matches the behavior of VideoResizePad in video.py:
+ 1. Scale the longest edge to target size
+ 2. Center pad the rest to make it square
+
+ Args:
+ image: Input image of shape (H, W, C) or (H, W)
+ target_size: Target size for both height and width. If None, uses self.image_size[0]
+ fill_value: The value to fill the padding (0.0 for black, 1.0 for white)
+ interpolation: OpenCV interpolation mode (e.g., cv.INTER_LINEAR)
+
+ Returns:
+ Resized and padded image of shape (target_size, target_size, C) or (target_size, target_size)
+ """
+ if target_size is None:
+ target_size = self.image_size[0]
+
+ h, w = image.shape[:2]
+
+ # Calculate scaling factor (scale longest edge to target size)
+ scale = target_size / max(h, w)
+ new_h = int(h * scale)
+ new_w = int(w * scale)
+
+ # Resize image
+ resized = cv.resize(image, (new_w, new_h), interpolation=interpolation)
+
+ # Calculate padding (center the image)
+ pad_h = target_size - new_h
+ pad_w = target_size - new_w
+ pad_top = pad_h // 2
+ pad_bottom = pad_h - pad_top
+ pad_left = pad_w // 2
+ pad_right = pad_w - pad_left
+
+ # Convert fill_value to uint8 range if needed
+ if resized.dtype == np.uint8:
+ fill_color = int(fill_value * 255)
+ else:
+ fill_color = fill_value
+
+ # Handle grayscale vs color images
+ if len(image.shape) == 2:
+ # Grayscale image
+ padded = cv.copyMakeBorder(
+ resized,
+ pad_top,
+ pad_bottom,
+ pad_left,
+ pad_right,
+ cv.BORDER_CONSTANT,
+ value=fill_color,
+ )
+ else:
+ # Color image - need to provide fill value for each channel
+ if isinstance(fill_color, int):
+ fill_color = (fill_color, fill_color, fill_color)
+ padded = cv.copyMakeBorder(
+ resized,
+ pad_top,
+ pad_bottom,
+ pad_left,
+ pad_right,
+ cv.BORDER_CONSTANT,
+ value=fill_color,
+ )
+
+ return padded
+
+ @staticmethod
+ def _center_crop_image(image: np.ndarray, crop_size: tuple[int, int] | None = None, crop_ratio: float = 1.0) -> np.ndarray:
+ """
+ 对图像进行中心裁剪
+
+ Args:
+ image: 输入图像,形状为 (H, W, C) 或 (H, W)
+ crop_size: 裁剪后的目标尺寸 (height, width),如果为 None 则使用 crop_ratio
+ crop_ratio: 裁剪比例,从中心和四周裁剪的比例 (0.0-1.0),仅在 crop_size 为 None 时使用
+
+ Returns:
+ 裁剪后的图像
+ """
+ h, w = image.shape[:2]
+
+ if crop_size is not None:
+ crop_h, crop_w = crop_size
+ else:
+ # 使用比例裁剪
+ if not (0.0 < crop_ratio <= 1.0):
+ raise ValueError(f"crop_ratio must be between 0.0 and 1.0, got {crop_ratio}")
+ crop_h = int(h * crop_ratio)
+ crop_w = int(w * crop_ratio)
+
+ # 计算裁剪区域的起始坐标(中心点)
+ start_y = (h - crop_h) // 2
+ start_x = (w - crop_w) // 2
+ end_y = start_y + crop_h
+ end_x = start_x + crop_w
+
+ # 确保裁剪区域不超出图像边界
+ if crop_h > h or crop_w > w:
+ raise ValueError(f"crop_size ({crop_w}x{crop_h}) larger than image size ({w}x{h})")
+
+ # 中心裁剪
+ cropped_image = image[start_y:end_y, start_x:end_x]
+
+ return cropped_image
+
+ @staticmethod
+ def _as_rgb_pil(image) -> "Image.Image":
+ """将各种格式的图像转换为 RGB PIL Image。"""
+ from PIL import Image as PILImage
+ import torch
+ if isinstance(image, PILImage.Image):
+ return image.convert("RGB")
+ if isinstance(image, torch.Tensor):
+ image = image.detach().cpu().numpy()
+ arr = np.asarray(image)
+ if arr.ndim == 3 and arr.shape[0] in (1, 3, 4) and arr.shape[-1] not in (1, 3, 4):
+ arr = np.moveaxis(arr, 0, -1)
+ if arr.ndim == 2:
+ arr = np.repeat(arr[..., None], 3, axis=-1)
+ if arr.ndim != 3:
+ raise ValueError(f"Expected image with 2 or 3 dims, got shape {arr.shape}")
+ if arr.shape[-1] == 4:
+ arr = arr[..., :3]
+ if arr.shape[-1] == 1:
+ arr = np.repeat(arr, 3, axis=-1)
+ if arr.dtype != np.uint8:
+ if arr.size and np.nanmax(arr) <= 1.0 and np.nanmin(arr) >= 0.0:
+ arr = arr * 255.0
+ elif arr.size and np.nanmin(arr) < 0.0:
+ arr = (arr + 1.0) * 127.5
+ arr = np.clip(arr, 0, 255).astype(np.uint8)
+ return PILImage.fromarray(arr).convert("RGB")
+
+ @staticmethod
+ def _resize_with_pad_pil(image, size=(224, 224)) -> "Image.Image":
+ """等比例缩放并中心填充到指定尺寸(PIL版本)。"""
+ from PIL import Image as PILImage
+ image = ModelClient._as_rgb_pil(image)
+ width, height = size
+ scale = min(width / image.width, height / image.height)
+ resized_size = (
+ max(1, int(round(image.width * scale))),
+ max(1, int(round(image.height * scale))),
+ )
+ resized = image.resize(resized_size, PILImage.BICUBIC)
+ canvas = PILImage.new("RGB", size, 0)
+ paste_xy = ((width - resized.width) // 2, (height - resized.height) // 2)
+ canvas.paste(resized, paste_xy)
+ return canvas
+
+ @staticmethod
+ def _crop_black_borders(image, threshold=10, min_margin=5):
+ """Crop black borders from an image (common in wrist cameras).
+
+ Exact copy of LeRobotMixtureDataset._crop_black_borders in
+ starVLA/dataloader/gr00t_lerobot/datasets.py to ensure eval-time
+ view concatenation matches training.
+ """
+ arr = np.asarray(image, dtype=np.uint8)
+ if arr.ndim != 3:
+ return image
+ content_mask = arr.max(axis=2) > threshold
+ if not content_mask.any():
+ return image
+ ys, xs = np.where(content_mask)
+ x0, x1 = int(xs.min()), int(xs.max())
+ y0, y1 = int(ys.min()), int(ys.max())
+ margins = (x0, y0, arr.shape[1] - 1 - x1, arr.shape[0] - 1 - y1)
+ if max(margins) < min_margin:
+ return image
+ cropped = image.crop((x0, y0, x1 + 1, y1 + 1))
+ if cropped.size[0] <= 0 or cropped.size[1] <= 0:
+ return image
+ return cropped
+
+ @staticmethod
+ def _render_view(image, target_size):
+ """Crop black borders, resize to target_size preserving aspect ratio, center-paste.
+
+ Exact copy of LeRobotMixtureDataset._render_view in
+ starVLA/dataloader/gr00t_lerobot/datasets.py to ensure eval-time
+ view concatenation matches training.
+ """
+ from PIL import Image as PILImage
+ target_h, target_w = target_size
+ canvas = PILImage.new("RGB", (target_w, target_h), (0, 0, 0))
+ if image is None:
+ return canvas
+ image = ModelClient._as_rgb_pil(image)
+ image = ModelClient._crop_black_borders(image)
+ src_w, src_h = image.size
+ if src_w <= 0 or src_h <= 0:
+ return canvas
+ scale = min(target_w / src_w, target_h / src_h)
+ resized_w = max(1, int(round(src_w * scale)))
+ resized_h = max(1, int(round(src_h * scale)))
+ resized = image.resize((resized_w, resized_h), PILImage.BICUBIC)
+ x_offset = (target_w - resized_w) // 2
+ y_offset = (target_h - resized_h) // 2
+ canvas.paste(resized, (x_offset, y_offset))
+ return canvas
+
+ @staticmethod
+ def _concat_view_images(images, view_size=(224, 224), gap=0):
+ """Concatenate camera views into one frame — identical to training.
+
+ Exact copy of LeRobotMixtureDataset._concat_view_images in
+ starVLA/dataloader/gr00t_lerobot/datasets.py to ensure eval-time
+ view concatenation matches training.
+
+ Three-view layout with hardcoded sizes matching compose_ego_wrist:
+ - Canvas: [384, 320] (H x W)
+ - Ego (top): [256, 320]
+ - Left wrist (bottom-left): [128, 160]
+ - Right wrist (bottom-right): [128, 160]
+ Pipeline: crop black borders -> resize to fixed size -> paste.
+ """
+ from PIL import Image as PILImage
+ if not images:
+ raise ValueError("No camera images provided")
+
+ images = list(images)
+ for image_idx, image in enumerate(images):
+ images[image_idx] = ModelClient._as_rgb_pil(image)
+
+ if len(images) == 3:
+ # Hardcoded sizes: ego=[256,320], wrist=[128,160], canvas=[384,320]
+ ego_h, ego_w = 256, 320
+ wrist_h, wrist_w = 128, 160
+ canvas_h, canvas_w = 384, 320
+
+ canvas = PILImage.new("RGB", (canvas_w, canvas_h), (0, 0, 0))
+ # Top: ego view
+ canvas.paste(ModelClient._render_view(images[0], (ego_h, ego_w)), (0, 0))
+ # Bottom-left: left wrist
+ canvas.paste(ModelClient._render_view(images[1], (wrist_h, wrist_w)), (0, ego_h))
+ # Bottom-right: right wrist
+ canvas.paste(ModelClient._render_view(images[2], (wrist_h, wrist_w)), (wrist_w, ego_h))
+ return canvas
+
+ # 非3张图时水平拼接 (fallback)
+ resized = [ModelClient._resize_with_pad_pil(image, view_size) for image in images]
+ panorama = PILImage.new("RGB", (sum(image.width for image in resized), max(image.height for image in resized)), 0)
+ x_offset = 0
+ for image in resized:
+ panorama.paste(image, (x_offset, 0))
+ x_offset += image.width
+ return panorama
+
+ def _open_loop(self, save_dir: str, episode_num: int, result_suffix: Optional[str] = None) -> None:
+ """开环测试可视化:拼接所有模型生成action并保存14维长图。
+
+ result_suffix: 若提供(如 "SUCCESS" / "FAIL"),会追加到文件名末尾。
+ """
+ if not self.normalized_action_chunks:
+ print("No normalized action chunks collected, skipping open-loop plot")
+ return
+
+ # 每次推理返回 shape (1, 50, 32),拼接为 (50*K, 32)
+ try:
+ chunk_list = [np.asarray(chunk)[0] for chunk in self.normalized_action_chunks]
+ all_actions = np.concatenate(chunk_list, axis=0)
+ except Exception as exc:
+ print(f"Warning: failed to concat normalized action chunks: {exc}")
+ return
+
+ if all_actions.ndim != 2 or all_actions.shape[1] < 14:
+ print(f"Warning: invalid open-loop action shape {all_actions.shape}, expect (?, >=14)")
+ return
+
+ actions_14 = all_actions[:, :14]
+ total_steps = actions_14.shape[0]
+ chunk_size = chunk_list[0].shape[0] if chunk_list else 50
+
+ dim_names = [
+ "left_arm_j0", "left_arm_j1", "left_arm_j2",
+ "left_arm_j3", "left_arm_j4", "left_arm_j5",
+ "left_gripper",
+ "right_arm_j0", "right_arm_j1", "right_arm_j2",
+ "right_arm_j3", "right_arm_j4", "right_arm_j5",
+ "right_gripper",
+ ]
+
+ fig, axes = plt.subplots(14, 1, figsize=(22, 2.5 * 14), sharex=True)
+ axes = np.atleast_1d(axes)
+
+ for dim_idx in range(14):
+ ax = axes[dim_idx]
+ ax.plot(actions_14[:, dim_idx], linewidth=0.8, color="steelblue")
+
+ # 标记每个chunk边界,便于观察step()累积后的段落
+ for k in range(1, len(chunk_list)):
+ boundary = k * chunk_size
+ if boundary < total_steps:
+ ax.axvline(x=boundary, color="gray", linestyle="--", linewidth=0.5, alpha=0.6)
+
+ ax.set_ylabel(dim_names[dim_idx], fontsize=9, rotation=0, labelpad=80)
+ ax.yaxis.set_ticks_position("right")
+ ax.grid(True, alpha=0.3)
+ if total_steps > 0:
+ ax.set_xlim(0, total_steps - 1)
+
+ axes[-1].set_xlabel("Step", fontsize=10)
+ fig.suptitle(
+ f"Open-loop Normalized Actions (total_steps={total_steps}, chunks={len(chunk_list)})",
+ fontsize=12,
+ )
+ fig.tight_layout(rect=[0, 0, 1, 0.97])
+
+ save_dir = Path(save_dir)
+ save_dir.mkdir(parents=True, exist_ok=True)
+ suffix = f"_{result_suffix}" if result_suffix else ""
+ save_path = save_dir / f"episode{episode_num}_action_openloop{suffix}.png"
+ fig.savefig(str(save_path), dpi=150, bbox_inches="tight")
+ plt.close(fig)
+ print(f"Open-loop action plot saved to {save_path}")
+
+ # 兼容旧调用
+ def _save_action_plot(self, save_dir: str, episode_num: int) -> None:
+ self._open_loop(save_dir, episode_num)
+
+ @staticmethod
+ def _as_uint8_rgb(image) -> np.ndarray:
+ image = np.asarray(image)
+ if image.ndim == 2:
+ image = np.repeat(image[..., None], 3, axis=-1)
+ if image.ndim == 3 and image.shape[0] in (1, 3, 4) and image.shape[-1] not in (1, 3, 4):
+ image = np.moveaxis(image, 0, -1)
+ if image.ndim != 3:
+ raise ValueError(f"Expected image with 2 or 3 dims, got shape {image.shape}")
+ if image.shape[-1] == 4:
+ image = image[..., :3]
+ if image.shape[-1] == 1:
+ image = np.repeat(image, 3, axis=-1)
+ if image.dtype != np.uint8:
+ if image.size and np.nanmax(image) <= 1.0 and np.nanmin(image) >= 0.0:
+ image = image * 255.0
+ elif image.size and np.nanmin(image) < 0.0:
+ image = (image + 1.0) * 127.5
+ image = np.clip(image, 0, 255).astype(np.uint8)
+ return image
+
+ @classmethod
+ def _extract_last_future_frame(cls, pred_future_images) -> Optional[np.ndarray]:
+ if pred_future_images is None:
+ return None
+ arr = np.asarray(pred_future_images)
+ if arr.size == 0:
+ return None
+ if arr.ndim == 5:
+ return cls._as_uint8_rgb(arr[0, -1])
+ if arr.ndim == 4:
+ if arr.shape[-1] in (1, 3, 4) or arr.shape[1] in (1, 3, 4):
+ return cls._as_uint8_rgb(arr[0])
+ return cls._as_uint8_rgb(arr[-1])
+ if arr.ndim == 3:
+ return cls._as_uint8_rgb(arr)
+ return None
+
+ def _append_future_concat_frame(self, response_data: dict, current_input_image: np.ndarray) -> None:
+ if not isinstance(response_data, dict):
+ return
+ future_image = self._extract_last_future_frame(response_data.get("pred_future_images"))
+ if future_image is None:
+ return
+
+ try:
+ obs_image = self._as_uint8_rgb(current_input_image)
+ future_image = cv.resize(
+ future_image,
+ (obs_image.shape[1], obs_image.shape[0]),
+ interpolation=cv.INTER_AREA,
+ )
+ if obs_image.shape[1] >= obs_image.shape[0]:
+ concat_frame = np.concatenate([obs_image, future_image], axis=0)
+ else:
+ concat_frame = np.concatenate([obs_image, future_image], axis=1)
+ self._future_concat_frames.append(concat_frame)
+ except Exception as exc:
+ print(f"Warning: failed to append future concat frame: {exc}")
+
+ def _save_future_concat_video(self, save_dir: str, episode_num: int, fps: int = 1, result_suffix: Optional[str] = None) -> None:
+ if not self._future_concat_frames:
+ print("No future concat frames collected, skipping future concat video")
+ return
+
+ save_dir = Path(save_dir)
+ save_dir.mkdir(parents=True, exist_ok=True)
+ suffix = f"_{result_suffix}" if result_suffix else ""
+ save_path = save_dir / f"episode{episode_num}_future_concat{suffix}.mp4"
+
+ first_frame = self._future_concat_frames[0]
+ h, w = int(first_frame.shape[0]), int(first_frame.shape[1])
+ writer = cv.VideoWriter(str(save_path), cv.VideoWriter_fourcc(*"mp4v"), float(fps), (w, h))
+ if not writer.isOpened():
+ print(f"Warning: failed to open video writer for {save_path}")
+ return
+
+ try:
+ for frame in self._future_concat_frames:
+ if frame.shape[0] != h or frame.shape[1] != w:
+ frame = cv.resize(frame, (w, h), interpolation=cv.INTER_AREA)
+ writer.write(cv.cvtColor(frame, cv.COLOR_RGB2BGR))
+ finally:
+ writer.release()
+
+ print(f"Future concat video saved to {save_path}")
+
+ @staticmethod
+ def _check_unnorm_key(norm_stats, unnorm_key):
+ if unnorm_key is None:
+ if len(norm_stats) == 1:
+ unnorm_key = next(iter(norm_stats.keys()))
+ else:
+ unnorm_key = next(iter(norm_stats.keys()))
+
+ if unnorm_key not in norm_stats:
+ unnorm_key = next(iter(norm_stats.keys()))
+
+ return unnorm_key
+
+ def save_actions_history(self, output_path: str) -> None:
+ """
+ 保存左右臂的动作历史到文件(同时保存关节角度和ee_pose形式)
+
+ :param output_path: 输出文件路径,支持 .npy 或 .npz 格式
+ """
+ output_path = Path(output_path)
+
+ # 将夹爪动作拼接在ee_pose后面
+ left_arm_ee_pose_with_gripper = np.array([
+ np.concatenate([ee_pose, [gripper]])
+ for ee_pose, gripper in zip(self.left_arm_ee_pose_history, self.left_gripper_history)
+ ])
+ right_arm_ee_pose_with_gripper = np.array([
+ np.concatenate([ee_pose, [gripper]])
+ for ee_pose, gripper in zip(self.right_arm_ee_pose_history, self.right_gripper_history)
+ ])
+
+ if output_path.suffix == '.npz':
+ np.savez(
+ output_path,
+ # 关节角度形式
+ left_arm_actions=np.array(self.left_arm_actions_history),
+ right_arm_actions=np.array(self.right_arm_actions_history),
+ # 夹爪动作
+ left_gripper=np.array(self.left_gripper_history),
+ right_gripper=np.array(self.right_gripper_history),
+ # ee_pose形式 with gripper (pos + axis + gripper)
+ left_arm_ee_pose=left_arm_ee_pose_with_gripper,
+ right_arm_ee_pose=right_arm_ee_pose_with_gripper
+ )
+ print(f"Actions history (joint angles & ee_pose & gripper) saved to {output_path}")
+ else:
+ # 默认保存为 .npz 格式
+ output_path = output_path.with_suffix('.npz')
+ np.savez(
+ output_path,
+ # 关节角度形式
+ left_arm_actions=np.array(self.left_arm_actions_history),
+ right_arm_actions=np.array(self.right_arm_actions_history),
+ # 夹爪动作
+ left_gripper=np.array(self.left_gripper_history),
+ right_gripper=np.array(self.right_gripper_history),
+ # ee_pose形式 with gripper (pos + axis + gripper)
+ left_arm_ee_pose=left_arm_ee_pose_with_gripper,
+ right_arm_ee_pose=right_arm_ee_pose_with_gripper
+ )
+ print(f"Actions history (joint angles & ee_pose & gripper) saved to {output_path}")
+
+ def save_camera_images(self, output_dir: str, test_num: int) -> None:
+ """
+ 将保存的所有相机图片保存到对应的子文件夹中,同时保存state数据
+
+ :param output_dir: 输出目录的总路径,每个相机会有单独的子文件夹
+ :param test_num: 测试编号,用于命名子文件夹
+ """
+ output_dir = Path(output_dir)
+ test_dir = output_dir / f"test_{test_num}"
+ test_dir.mkdir(parents=True, exist_ok=True)
+
+ for camera_name, images in self.camera_images_history.items():
+ if len(images) == 0:
+ print(f"No {camera_name} images to save, skipping")
+ continue
+
+ camera_dir = test_dir / camera_name
+ camera_dir.mkdir(parents=True, exist_ok=True)
+
+ for i, img in enumerate(images):
+ # 确保图像是uint8类型
+ if img.dtype != np.uint8:
+ img = (img * 255).astype(np.uint8)
+ # 确保是BGR格式用于保存
+ if len(img.shape) == 2:
+ img = cv.cvtColor(img, cv.COLOR_GRAY2BGR)
+ elif img.shape[2] == 3:
+ img = cv.cvtColor(img, cv.COLOR_RGB2BGR)
+
+ img_path = camera_dir / f"frame_{i:06d}.png"
+ cv.imwrite(str(img_path), img)
+
+ print(f"{camera_name.capitalize()} images saved to {camera_dir} ({len(images)} frames)")
+
+ # 保存state数据
+ if len(self.state_history) > 0:
+ state_dir = test_dir / "state"
+ state_dir.mkdir(parents=True, exist_ok=True)
+
+ state_array = np.array(self.state_history)
+ state_path = state_dir / "state_history.npz"
+ np.savez(str(state_path), state=state_array)
+ print(f"State data saved to {state_path} ({len(self.state_history)} frames)")
+ else:
+ print(f"No state data to save, skipping")
+
+ print(f"All camera images and state saved to {test_dir}")
+
+
+def get_model(usr_args):
+ policy_ckpt_path = usr_args.get("policy_ckpt_path")
+ host = usr_args.get("host", "127.0.0.1")
+ port = usr_args.get("port", 5694)
+ unnorm_key = usr_args.get("unnorm_key", None)
+ embodiment_tag = usr_args.get("embodiment_tag", None)
+ debug_save_head_images = usr_args.get("debug_save_head_images", False)
+ use_fixed_test_data = usr_args.get("use_fixed_test_data", False)
+ fixed_test_data_dir = usr_args.get("fixed_test_data_dir", "../Camera/test_1")
+ fixed_test_frame_idx = usr_args.get("fixed_test_frame_idx", 119)
+ if policy_ckpt_path is None:
+ raise ValueError("policy_ckpt_path must be provided in config")
+
+ return ModelClient(
+ policy_ckpt_path=policy_ckpt_path,
+ host=host,
+ port=port,
+ unnorm_key=unnorm_key,
+ embodiment_tag=embodiment_tag,
+ debug_save_head_images=debug_save_head_images,
+ use_fixed_test_data=use_fixed_test_data,
+ fixed_test_data_dir=fixed_test_data_dir,
+ fixed_test_frame_idx=fixed_test_frame_idx,
+ )
+
+
+def reset_model(model: ModelClient):
+ # episode结束时保存action长图
+ if model._action_plot_save_dir is not None:
+ model._open_loop(model._action_plot_save_dir, model._action_plot_episode_num)
+
+ # episode结束时保存“当前帧+未来帧”拼接视频
+ if model._future_concat_save_dir is not None:
+ model._save_future_concat_video(model._future_concat_save_dir, model._future_concat_episode_num)
+
+ model.reset(task_description="")
+
+
+def eval(TASK_ENV, model, observation):
+ # Get instruction
+ instruction = TASK_ENV.get_instruction()
+
+ # Prepare images
+ if model.use_fixed_test_data:
+ # 使用固定的测试图像
+ head_img = model.fixed_head_img
+ left_img = model.fixed_left_img
+ right_img = model.fixed_right_img
+ state = model.fixed_state.copy()
+ print(f"[USING FIXED TEST DATA] Frame idx: {model.fixed_test_frame_idx}")
+ else:
+ # 使用真实观察到的图像和state
+ head_img = observation["observation"]["head_camera"]["rgb"]
+ left_img = observation["observation"]["left_camera"]["rgb"]
+ right_img = observation["observation"]["right_camera"]["rgb"]
+ state = observation["joint_action"]["vector"]
+
+ # Debug: save all camera images
+ if model.debug_save_head_images and not model.use_fixed_test_data:
+ # 只有在使用真实数据时才保存
+ model.camera_images_history["head"].append(head_img.copy())
+ model.camera_images_history["left"].append(left_img.copy())
+ model.camera_images_history["right"].append(right_img.copy())
+
+ # Order: [head, left, right] to match training order
+ images = [head_img, left_img, right_img]
+ # images = [head_img]
+
+ example = {
+ "lang": str(instruction),
+ "image": images,
+ "state": state,
+ }
+
+ action = model.step(example, step=TASK_ENV.take_action_cnt)
+
+ # Execute action
+ TASK_ENV.take_action(action)
+
+ # episode结束时保存action长图与future拼接视频(与episode视频同轮次)
+ # 此处不再每步保存,而是在reset_model中统一保存
+ # 三个产物(action开环图、仿真录制视频、当前帧+预测帧concat视频)统一保存到
+ # 同一个 eval_video_path 目录下(该目录已包含 task_name 维度),通过文件名区分:
+ # - episode{N}.mp4 仿真录制视频(由RoboTwin框架保存)
+ # - episode{N}_action_openloop.png action开环测试图
+ # - episode{N}_future_concat.mp4 当前帧+预测帧concat视频
+ if hasattr(TASK_ENV, 'eval_video_path') and TASK_ENV.eval_video_path is not None:
+ model._action_plot_save_dir = TASK_ENV.eval_video_path
+ model._action_plot_episode_num = TASK_ENV.test_num
+
+ model._future_concat_save_dir = TASK_ENV.eval_video_path
+ model._future_concat_episode_num = TASK_ENV.test_num
diff --git a/examples/Robotwin_ee/eval_files/robotwin_aloha_transform_kdl.py b/examples/Robotwin_ee/eval_files/robotwin_aloha_transform_kdl.py
new file mode 100644
index 0000000000000000000000000000000000000000..fabdc7f30b53672ce9fac2cecee6c568e8c6bd0e
--- /dev/null
+++ b/examples/Robotwin_ee/eval_files/robotwin_aloha_transform_kdl.py
@@ -0,0 +1,758 @@
+"""
+ALOHA-AGILEX 双臂机器人末端执行器投影可视化脚本(简化版)
+
+功能:
+1. 读取 ALOHA-AGILEX URDF,建立运动学链(基座 = footprint,末端 = fl_link6 / fr_link6)
+2. 从 LeRobot 数据集读取关节角度(parquet)
+3. 用 KDL 做 FK,得到末端在基座坐标系 (footprint) 下的 4x4 位姿矩阵
+4. 使用给定的 T_foot_cam(相机在 footprint 坐标系下的外参)转换到相机坐标系
+5. 使用相机内参将 3D 末端点投影到每一帧图像上并可视化
+
+相机外参使用固定矩阵(你给的 T_foot_cam):
+T_foot_cam = ^foot T_cam 满足:p_foot = T_foot_cam @ p_cam
+
+代码中会先求逆得到:
+T_base_to_camera = T_cam_foot = (T_foot_cam)^(-1)
+然后做:
+T_cam_ee = T_base_to_camera @ T_base_to_ee
+"""
+
+import argparse
+import cv2
+import numpy as np
+import pandas as pd
+from pathlib import Path
+from typing import Dict, List, Tuple, Optional
+from dataclasses import dataclass , field
+import subprocess
+import tempfile
+import os
+
+from urdf_parser_py.urdf import URDF
+from pykdl_utils.kdl_parser import kdl_tree_from_urdf_model
+from pykdl_utils.kdl_kinematics import KDLKinematics
+from scipy.spatial.transform import Rotation as R
+from tqdm import tqdm
+import PyKDL as kdl
+
+"""
+"kdl库的FK+IK求解"
+python /vla/users/lijiayi/code/robotwin_aloha_ee_projection_kdl2.py \
+ --verify_ik
+
+"""
+
+# ^foot T_cam: p_foot = T_foot_cam @ p_cam
+T_FOOT_CAM_DEFAULT = np.array(
+ [
+ [0.6, 0.0, 0.8, 0.2],
+ [0.0, 1.0, 0.0, 0.032],
+ [-0.8, 0.0, 0.6, 1.35],
+ [0.0, 0.0, 0.0, 1.0],
+ ],
+ dtype=np.float64,
+)
+
+# ALOHA 14-dim layout
+ALOHA_ACTION_LAYOUT = {
+ "left_arm": (0, 6),
+ "left_gripper": (6, 7),
+ "right_arm": (7, 13),
+ "right_gripper": (13, 14),
+}
+
+
+def slice_action_vector(action: np.ndarray) -> Dict[str, np.ndarray]:
+ action = np.asarray(action, dtype=np.float64)
+ if action.shape[-1] != 14:
+ raise ValueError(f"ALOHA action/state 最后一维必须是 14,当前 shape={action.shape}")
+ return {k: action[..., s:e] for k, (s, e) in ALOHA_ACTION_LAYOUT.items()}
+
+def _as_batch(x: np.ndarray) -> Tuple[np.ndarray, bool]:
+ x = np.asarray(x, dtype=np.float64)
+ if x.ndim == 1:
+ return x[None, :], True
+ return x, False
+
+
+@dataclass
+class RobotwinRetargetConfig:
+ """模仿 GR1RetargetConfig 的形式,但 Robotwin/Aloha 使用 14-dim state。"""
+ urdf_path: str = str(
+ Path(__file__).parent / "arx5_description_isaac.urdf"
+ )
+ camera_intrinsics: Dict[str, float] = field(
+ default_factory=lambda: dict(fx=717.28, fy=717.28, cx=320.0, cy=240.0)
+ )
+ T_foot_cam: np.ndarray = field(default_factory=lambda: T_FOOT_CAM_DEFAULT.copy())
+
+ base_link: str = "footprint"
+ left_ee_link: str = "fl_link6"
+ right_ee_link: str = "fr_link6"
+
+
+# ======================= 视频工具函数 =======================
+
+def transcode_video_to_h264(input_path: Path, output_path: Path = None) -> Path:
+ """
+ 将视频转码为 H.264 格式 (兼容 OpenCV)
+
+ 参数:
+ input_path: 输入视频路径
+ output_path: 输出视频路径,如果为 None 则创建临时文件
+
+ 返回:
+ 转码后的视频路径
+ """
+ if output_path is None:
+ fd, output_path = tempfile.mkstemp(suffix='.mp4')
+ os.close(fd)
+ output_path = Path(output_path)
+
+ print(f"正在将视频转码为 H.264 格式: {input_path.name}")
+
+ cmd = [
+ 'ffmpeg', '-y',
+ '-i', str(input_path),
+ '-c:v', 'libx264',
+ '-preset', 'fast',
+ '-crf', '18',
+ '-pix_fmt', 'yuv420p',
+ str(output_path)
+ ]
+
+ try:
+ subprocess.run(cmd, check=True, capture_output=True)
+ print(f"转码完成: {output_path}")
+ return output_path
+ except subprocess.CalledProcessError as e:
+ print(f"转码失败: {e.stderr.decode()}")
+ raise
+
+
+def check_video_codec(video_path: Path) -> str:
+ """检查视频编解码器"""
+ cmd = [
+ 'ffprobe', '-v', 'quiet',
+ '-select_streams', 'v:0',
+ '-show_entries', 'stream=codec_name',
+ '-of', 'default=noprint_wrappers=1:nokey=1',
+ str(video_path)
+ ]
+ try:
+ result = subprocess.run(cmd, capture_output=True, text=True, check=True)
+ return result.stdout.strip()
+ except:
+ return "unknown"
+
+# ======================= 核心类:AlohaRetargeter =======================
+
+class AlohaRetargeter:
+ """ALOHA-AGILEX 双臂机器人末端执行器投影器(使用固定 T_foot_cam)"""
+
+ def __init__(
+ self,
+ urdf_path: Path,
+ T_foot_cam: Optional[np.ndarray] = None,
+
+ ):
+ """
+ 初始化 ALOHA 投影器
+
+ 参数:
+ urdf_path: URDF 文件路径
+ T_foot_cam: 4x4 外参矩阵 ^foot T_cam(相机坐标系 → footprint)
+ """
+ print("正在初始化 AlohaRetargeter...")
+
+ cfg = RobotwinRetargetConfig()
+
+ self.T_foot_cam = np.asarray(T_foot_cam if T_foot_cam is not None else cfg.T_foot_cam, dtype=np.float64).reshape(4, 4)
+ self.T_base_to_camera = np.linalg.inv(self.T_foot_cam) # ^cam T_foot
+
+ robot_urdf = URDF.from_xml_file(str(urdf_path))
+ tree = kdl_tree_from_urdf_model(robot_urdf)
+
+ self.kin_left_arm = KDLKinematics(robot_urdf, cfg.base_link, cfg.left_ee_link, tree)
+ self.kin_right_arm = KDLKinematics(robot_urdf, cfg.base_link, cfg.right_ee_link, tree)
+
+ self.chain_left_arm = tree.getChain(cfg.base_link, cfg.left_ee_link)
+ self.chain_right_arm = tree.getChain(cfg.base_link, cfg.right_ee_link)
+
+ self._ik_last_solution = {"left": None, "right": None}
+
+ def reset_ik_cache(self, env_idx: int | None = None):
+ """
+ 清空 IK 历史缓存(robotwin 串行评测 env_idx 可忽略)。
+ """
+ self._ik_last_solution = {"left": None, "right": None}
+
+ # ------------ FK + 末端在相机坐标系下的位姿 ------------
+
+ def process_frame_kinematics_axisangle(
+ self,
+ action_vector: np.ndarray,
+ ) -> Tuple[Tuple[np.ndarray, np.ndarray], Tuple[np.ndarray, np.ndarray], Tuple[np.ndarray, np.ndarray]]:
+ action_vector = np.asarray(action_vector, dtype=np.float64)
+ if action_vector.ndim == 3:
+ # (B,T,14) -> (B,14) 取最后一步
+ action_vector = action_vector[:, -1, :]
+ if action_vector.ndim == 1:
+ action_vector = action_vector[None, :]
+ if action_vector.ndim != 2 or action_vector.shape[-1] != 14:
+ raise ValueError(f"action_vector 期望 (14,) 或 (B,14) 或 (B,T,14),实际 shape={action_vector.shape}")
+
+ action_slices = slice_action_vector(action_vector)
+ q_left_all = action_slices["left_arm"] # (B,6)
+ q_right_all = action_slices["right_arm"] # (B,6)
+
+ B = action_vector.shape[0]
+ left_pos = np.zeros((B, 3), dtype=np.float64)
+ right_pos = np.zeros((B, 3), dtype=np.float64)
+ left_axis = np.zeros((B, 3), dtype=np.float64)
+ right_axis = np.zeros((B, 3), dtype=np.float64)
+
+ for b in range(B):
+ q_left = q_left_all[b].astype(np.float64).tolist()
+ q_right = q_right_all[b].astype(np.float64).tolist()
+
+ T_base_left = np.asarray(self.kin_left_arm.forward(q_left), dtype=np.float64)
+ T_base_right = np.asarray(self.kin_right_arm.forward(q_right), dtype=np.float64)
+
+ T_cam_left = self.T_base_to_camera @ T_base_left
+ T_cam_right = self.T_base_to_camera @ T_base_right
+
+ left_pos[b] = T_cam_left[:3, 3].reshape(3)
+ right_pos[b] = T_cam_right[:3, 3].reshape(3)
+ left_axis[b] = R.from_matrix(T_cam_left[:3, :3]).as_rotvec().reshape(3)
+ right_axis[b] = R.from_matrix(T_cam_right[:3, :3]).as_rotvec().reshape(3)
+
+
+ left_q = np.asarray(q_left_all, dtype=np.float64).reshape(B, 6)
+ right_q = np.asarray(q_right_all, dtype=np.float64).reshape(B, 6)
+
+ # print(f"----------debug----------")
+ # print(f"left_pos:{left_pos}, left_axis:{left_axis}")
+ # print(f"right_pos:{right_pos}, right_axis:{right_axis}")
+ # print(f"left_q_shape:{left_q.shape}")
+ # print(f"left_q:{left_q}")
+ # print(f"right_q:{right_q}")
+
+ return (left_pos, left_axis), (right_pos, right_axis), (left_q, right_q)
+
+ # ------------ FK/IK 验证(保持原逻辑,可选) ------------
+ def verify_ik_solution(self, action_vector: np.ndarray, verbose: bool = True) -> Dict:
+ """
+ 验证 FK -> IK -> FK 的完整流程
+ """
+ action_slices = slice_action_vector(action_vector)
+
+ q_left_original = list(action_slices["left_arm"])
+ q_right_original = list(action_slices["right_arm"])
+
+ T_left_original = np.array(self.kin_left_arm.forward(q_left_original))
+ T_right_original = np.array(self.kin_right_arm.forward(q_right_original))
+
+ q_left_ik = self._solve_ik_kdl("left", T_left_original, q_left_original)
+ q_right_ik = self._solve_ik_kdl("right", T_right_original, q_right_original)
+
+ T_left_verified = None if q_left_ik is None else np.array(self.kin_left_arm.forward(q_left_ik))
+ T_right_verified = None if q_right_ik is None else np.array(self.kin_right_arm.forward(q_right_ik))
+
+ results = {
+ "left_arm": self._compute_errors(
+ q_left_original, q_left_ik, T_left_original, T_left_verified
+ ),
+ "right_arm": self._compute_errors(
+ q_right_original, q_right_ik, T_right_original, T_right_verified
+ ),
+ }
+
+ if verbose:
+ print("\n=== IK 验证结果 ===")
+ for arm_name, result in results.items():
+ print(f"\n{arm_name}:")
+ if result["ik_success"]:
+ print(f" 关节角度误差 (度): {result['joint_error_deg']:.4f}")
+ print(f" 位置误差 (m): {result['position_error']:.6f}")
+ print(f" 姿态误差 (度): {result['orientation_error_deg']:.4f}")
+ else:
+ print(" IK 求解失败")
+
+ return results
+
+ def _solve_ik_kdl(
+ self,
+ arm: str,
+ target_pose: np.ndarray,
+ q_init_arm: List[float],
+ max_iter: int = 200,
+ tol: float = 1e-6,
+ damping: float = 1e-3,
+ ) -> Optional[List[float]]:
+ assert arm in ("left", "right"), f"arm 必须是 'left' 或 'right',当前为 {arm}"
+
+
+ chain = self.chain_left_arm if arm == "left" else self.chain_right_arm
+ kin = self.kin_left_arm if arm == "left" else self.kin_right_arm
+ chain_label = arm
+
+ target_pose = np.asarray(target_pose, dtype=np.float64).reshape(4, 4)
+ target_frame = self._numpy_to_kdl_frame(target_pose)
+
+ num_joints = chain.getNrOfJoints()
+ wide = 2.0 * np.pi
+ global_lower = np.full((num_joints,), -wide, dtype=np.float64)
+ global_upper = np.full((num_joints,), +wide, dtype=np.float64)
+
+ q_init_arm = np.asarray(q_init_arm, dtype=np.float64).flatten()
+ if q_init_arm.shape[0] != num_joints:
+ # 防御:长度不对就用 0 初始化
+ q_init_arm = np.zeros((num_joints,), dtype=np.float64)
+
+ fallback = self._ik_last_solution.get(chain_label, None)
+ if fallback is None:
+ fallback = q_init_arm.tolist()
+
+ max_attempts = 5
+ eps_schedule = [tol, tol * 2, tol * 5, tol * 10, tol * 20]
+ seed_noise = 0.25 # rad
+
+ fk_solver = kdl.ChainFkSolverPos_recursive(chain)
+
+ def make_vel_solver(local_damping: float):
+ # 优先用 WDLS(更像 Pin 的 damping),没有就退回 pinv
+ try:
+ vel = kdl.ChainIkSolverVel_wdls(chain)
+ vel.setLambda(float(local_damping))
+ return vel
+ except Exception:
+ return kdl.ChainIkSolverVel_pinv(chain)
+
+ for attempt in range(max_attempts):
+ local_tol = float(eps_schedule[min(attempt, len(eps_schedule) - 1)])
+ local_margin = 0.75 * (attempt + 1) # rad
+ local_damping = float(damping) * (10.0 ** attempt)
+
+ seed = np.asarray(fallback, dtype=np.float64).copy()
+ if attempt > 0:
+ noise_scale = seed_noise * attempt
+ seed = seed + np.random.uniform(-noise_scale, noise_scale, size=seed.shape)
+
+ local_lower = np.maximum(global_lower, seed - local_margin)
+ local_upper = np.minimum(global_upper, seed + local_margin)
+ bad = local_lower >= local_upper
+ if np.any(bad):
+ local_lower[bad] = global_lower[bad]
+ local_upper[bad] = global_upper[bad]
+
+ q_min = kdl.JntArray(num_joints)
+ q_max = kdl.JntArray(num_joints)
+ for i in range(num_joints):
+ q_min[i] = float(local_lower[i])
+ q_max[i] = float(local_upper[i])
+
+ ik_vel_solver = make_vel_solver(local_damping)
+ ik_solver = kdl.ChainIkSolverPos_NR_JL(
+ chain,
+ q_min,
+ q_max,
+ fk_solver,
+ ik_vel_solver,
+ maxiter=int(max_iter),
+ eps=float(local_tol),
+ )
+
+ q_init_kdl = kdl.JntArray(num_joints)
+ for i in range(num_joints):
+ q_init_kdl[i] = float(np.clip(seed[i], local_lower[i], local_upper[i]))
+
+ q_out = kdl.JntArray(num_joints)
+ ret = ik_solver.CartToJnt(q_init_kdl, target_frame, q_out)
+
+ if ret >= 0:
+ q_sol = [float(q_out[i]) for i in range(num_joints)]
+ # 额外做一次 FK 误差校验,避免“形式成功但误差很大”
+ try:
+ T_fk = np.array(kin.forward(q_sol))
+ err = self._compute_errors(q_original=q_sol, q_ik=q_sol, T_original=target_pose, T_ik=T_fk)
+ if err["position_error"] is None:
+ continue
+ # 位置/姿态任意一个达标就接受(KDL 有时姿态收敛慢)
+ if (err["position_error"] < max(1e-4, 10 * local_tol)) or (err["orientation_error_deg"] < 1.0):
+ self._ik_last_solution[chain_label] = q_sol
+ return q_sol
+ except Exception:
+ self._ik_last_solution[chain_label] = q_sol
+ return q_sol
+
+ # 全失败:兜底返回(跟 Pin 一样尽量不返回 None)
+ if fallback is not None and len(fallback) == num_joints:
+ self._ik_last_solution[chain_label] = list(map(float, fallback))
+ return list(map(float, fallback))
+ return None
+
+ def _numpy_to_kdl_frame(self, T: np.ndarray) -> kdl.Frame:
+ """将 numpy 4x4 变换矩阵转换为 PyKDL Frame"""
+ rotation = kdl.Rotation(
+ T[0, 0], T[0, 1], T[0, 2],
+ T[1, 0], T[1, 1], T[1, 2],
+ T[2, 0], T[2, 1], T[2, 2],
+ )
+ position = kdl.Vector(T[0, 3], T[1, 3], T[2, 3])
+ return kdl.Frame(rotation, position)
+
+ def _compute_errors(
+ self,
+ q_original: List[float],
+ q_ik: Optional[List[float]],
+ T_original: np.ndarray,
+ T_ik: Optional[np.ndarray],
+ ) -> Dict:
+ """计算原始值和 IK 求解值之间的误差"""
+ if q_ik is None or T_ik is None:
+ return {
+ "ik_success": False,
+ "joint_error_deg": None,
+ "position_error": None,
+ "orientation_error_deg": None,
+ }
+
+ q_original_arr = np.array(q_original)
+ q_ik_arr = np.array(q_ik)
+ joint_error = np.linalg.norm(q_original_arr - q_ik_arr)
+ joint_error_deg = np.rad2deg(joint_error)
+
+ pos_original = T_original[:3, 3]
+ pos_ik = T_ik[:3, 3]
+ position_error = np.linalg.norm(pos_original - pos_ik)
+
+ R_original = T_original[:3, :3]
+ R_ik = T_ik[:3, :3]
+ R_error = R_original.T @ R_ik
+ trace = np.trace(R_error)
+ angle_error = np.arccos(np.clip((trace - 1) / 2, -1, 1))
+ orientation_error_deg = np.rad2deg(angle_error)
+
+ return {
+ "ik_success": True,
+ "joint_error_deg": joint_error_deg,
+ "position_error": position_error,
+ "orientation_error_deg": orientation_error_deg,
+ "q_original": q_original,
+ "q_ik": q_ik,
+ }
+
+ # ---------------------------------------------------------------------
+ # 新增:模仿 Pin 的 verify_ik_solution(从“相机系位姿”转回 base 系做 IK)
+ # ---------------------------------------------------------------------
+ def inverse_kinematics_from_camera_axisangle(
+ self,
+ left_hand_pos: np.ndarray,
+ left_hand_axisangle: np.ndarray,
+ right_hand_pos: np.ndarray,
+ right_hand_axisangle: np.ndarray,
+ current_action_vector: Optional[np.ndarray] = None,
+ q_init_left: Optional[np.ndarray] = None,
+ q_init_right: Optional[np.ndarray] = None,
+ max_iter: int = 200,
+ tol: float = 1e-6,
+ damping: float = 1e-3,
+ ) -> Tuple[Optional[np.ndarray], Optional[np.ndarray]]:
+ def _as_batch_3(x):
+ x = np.asarray(x, dtype=np.float64)
+ if x.ndim == 1:
+ x = x[None, :]
+ if x.ndim == 3:
+ x = x[:, -1, :]
+ if x.ndim != 2 or x.shape[-1] != 3:
+ raise ValueError(f"期望 (3,) 或 (B,3) 或 (B,T,3),实际 shape={x.shape}")
+ return x
+
+ left_hand_pos = _as_batch_3(left_hand_pos)
+ right_hand_pos = _as_batch_3(right_hand_pos)
+ left_hand_axisangle = _as_batch_3(left_hand_axisangle)
+ right_hand_axisangle = _as_batch_3(right_hand_axisangle)
+
+ B = left_hand_pos.shape[0]
+
+ # seed:优先 q_init_*;否则从 current_action_vector 里取;否则 0
+ if q_init_left is None or q_init_right is None:
+ if current_action_vector is None:
+ q_init_left = np.zeros((B, 6), dtype=np.float64)
+ q_init_right = np.zeros((B, 6), dtype=np.float64)
+ else:
+ a = np.asarray(current_action_vector, dtype=np.float64)
+ if a.ndim == 1:
+ a = a[None, :]
+ if a.ndim == 3:
+ a = a[:, -1, :]
+ if a.shape[-1] != 14:
+ raise ValueError(f"current_action_vector 最后一维必须是 14,实际 shape={a.shape}")
+ if a.shape[0] == 1 and B > 1:
+ a = np.repeat(a, B, axis=0)
+ q_init_left = a[:, 0:6]
+ q_init_right = a[:, 7:13]
+ else:
+ q_init_left = np.asarray(q_init_left, dtype=np.float64)
+ q_init_right = np.asarray(q_init_right, dtype=np.float64)
+ if q_init_left.ndim == 1:
+ q_init_left = q_init_left[None, :]
+ if q_init_right.ndim == 1:
+ q_init_right = q_init_right[None, :]
+ if q_init_left.shape[0] == 1 and B > 1:
+ q_init_left = np.repeat(q_init_left, B, axis=0)
+ if q_init_right.shape[0] == 1 and B > 1:
+ q_init_right = np.repeat(q_init_right, B, axis=0)
+ q_init_left = q_init_left.reshape(B, 6)
+ q_init_right = q_init_right.reshape(B, 6)
+
+ ql_out = np.zeros((B, 6), dtype=np.float64)
+ qr_out = np.zeros((B, 6), dtype=np.float64)
+
+ for b in range(B):
+ T_cam_left = np.eye(4, dtype=np.float64)
+ T_cam_left[:3, :3] = R.from_rotvec(left_hand_axisangle[b]).as_matrix()
+ T_cam_left[:3, 3] = left_hand_pos[b]
+
+ T_cam_right = np.eye(4, dtype=np.float64)
+ T_cam_right[:3, :3] = R.from_rotvec(right_hand_axisangle[b]).as_matrix()
+ T_cam_right[:3, 3] = right_hand_pos[b]
+
+ T_base_left = self.T_foot_cam @ T_cam_left
+ T_base_right = self.T_foot_cam @ T_cam_right
+
+ ql = self._solve_ik_kdl("left", T_base_left, q_init_left[b].tolist(), max_iter=max_iter, tol=tol, damping=damping)
+ qr = self._solve_ik_kdl("right", T_base_right, q_init_right[b].tolist(), max_iter=max_iter, tol=tol, damping=damping)
+
+ if ql is None or qr is None:
+ return None, None
+ ql_out[b] = np.asarray(ql, dtype=np.float64)[:6]
+ qr_out[b] = np.asarray(qr, dtype=np.float64)[:6]
+
+ return ql_out, qr_out
+
+ # ------------ 处理整段 episode:逐帧重投影 ------------
+
+ def process_episode(
+ self,
+ video_path: Path,
+ parquet_path: Path,
+ output_path: Path,
+ verify_ik: bool = False,
+ use_state: bool = True,
+ ):
+ """
+ 处理单个 episode:对每一帧做 FK + 投影,并写出新视频
+
+ 参数:
+ video_path: 输入视频路径
+ parquet_path: parquet 数据文件路径
+ output_path: 输出视频路径
+ verify_ik: 是否执行一次 IK 验证(用第一帧数据)
+ use_state: True 使用 observation.state,False 使用 action
+ """
+ print(f"开始处理 episode: {video_path.parent.name}")
+
+ # 读取数据
+ df = pd.read_parquet(parquet_path)
+ data_key = "observation.state" if use_state else "action"
+
+ if data_key not in df.columns:
+ raise KeyError(f"数据文件中找不到 '{data_key}' 列")
+
+ states = df[data_key].tolist()
+
+ # 检查视频编码,如是 AV1/VP9/HEVC 则转码
+ temp_video_path = None
+ actual_video_path = video_path
+
+ codec = check_video_codec(video_path)
+ print(f"视频编码: {codec}")
+
+ if codec in ["av1", "vp9", "hevc"]:
+ print(f"检测到 {codec} 编码,需要转码为 H.264...")
+ temp_video_path = transcode_video_to_h264(video_path)
+ actual_video_path = temp_video_path
+
+ # 打开视频
+ cap = cv2.VideoCapture(str(actual_video_path))
+ if not cap.isOpened():
+ if temp_video_path and temp_video_path.exists():
+ os.unlink(temp_video_path)
+ raise FileNotFoundError(f"无法打开视频: {video_path}")
+
+ fps = int(cap.get(cv2.CAP_PROP_FPS))
+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
+ num_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
+
+ print(f"视频信息: {width}x{height}, {fps}fps, {num_frames} 帧")
+ print(f"数据总数: {len(states)}")
+
+ # 输出视频
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
+ out = cv2.VideoWriter(str(output_path), fourcc, fps, (width, height))
+
+
+ # 验证第70帧的IK:
+ # frame_idx = 70
+ """
+ -0.886147 2.101878 1.805194 -1.295676 0.017645 1.012810 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 1.000000
+ -0.891970 2.105140 1.803110 -1.292860 0.017360 1.014650 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 1.000000
+ """
+ history_qpos = np.array([ -0.886147, 2.101878, 1.805194, -1.295676, 0.017645, 1.012810, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000])
+ current_qpos = np.array([ -0.891970, 2.105140, 1.803110, -1.292860, 0.017360, 1.014650, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000])
+ (left_pos, left_rot), (right_pos, right_rot), (T_base_to_left_ee, T_base_to_right_ee) = self.process_frame_kinematics(current_qpos)
+ print(f"FK: T_base_to_left_ee: {T_base_to_left_ee}")
+ # 可选:先做一次 IK 验证(第一帧)
+ if verify_ik and len(states) > 0:
+ print("\n执行 IK 验证(使用第一帧数据)...")
+ self.verify_ik_solution(history_qpos, current_qpos, left_pos, right_pos, left_rot, right_rot)
+
+ # 逐帧处理
+ for i in tqdm(range(min(num_frames, len(states))), desc="处理视频帧"):
+ ok, frame = cap.read()
+ if not ok:
+ break
+
+ # FK + 坐标变换:得到左右末端在相机坐标系下的位姿
+ (left_pos, left_rot), (right_pos, right_rot), _ = self.process_frame_kinematics(
+ np.array(states[i])
+ )
+
+ # 在图像上画投影点和小坐标轴
+ self._draw_projection(frame, left_pos, left_rot, color=(0, 0, 255), frame_idx=i) # 左手 红色
+ self._draw_projection(frame, right_pos, right_rot, color=(255, 0, 0), frame_idx=i) # 右手 蓝色
+
+ # 帧号文字
+ cv2.putText(
+ frame,
+ f"Frame: {i}",
+ (10, 30),
+ cv2.FONT_HERSHEY_SIMPLEX,
+ 0.7,
+ (0, 255, 0),
+ 2,
+ )
+
+ out.write(frame)
+
+ cap.release()
+ out.release()
+
+ if temp_video_path and Path(temp_video_path).exists():
+ os.unlink(temp_video_path)
+ print("已清理临时转码文件")
+
+ print(f"\n处理完成!输出视频: {output_path}")
+
+
+# ======================= 命令行入口 =======================
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="ALOHA-AGILEX 双臂机器人末端执行器投影可视化(使用固定 T_foot_cam)"
+ )
+ parser.add_argument(
+ "--dataset-root",
+ type=Path,
+ default=Path(
+ "/vla/users/lijiayi/robotwin_dataset/pick_dual_bottles-aloha-agilex_clean"
+ ),
+ help="LeRobot 数据集根目录",
+ )
+ parser.add_argument(
+ "--urdf-path",
+ type=Path,
+ default=Path(
+ "/vla/users/lijiayi/code/RoboTwin/assets/embodiments/aloha-agilex/urdf/arx5_description_isaac.urdf"
+ ),
+ help="URDF 文件路径",
+ )
+ parser.add_argument(
+ "--output-dir",
+ type=Path,
+ default=Path("/vla/users/lijiayi/robotwin_dataset/output_videos"),
+ help="输出目录",
+ )
+ parser.add_argument(
+ "--episode",
+ type=int,
+ default=0,
+ help="要处理的 episode 编号",
+ )
+ parser.add_argument(
+ "--camera",
+ type=str,
+ default="cam_high",
+ choices=["cam_high", "cam_left_wrist", "cam_right_wrist"],
+ help="使用的视频相机名称(决定读取哪个 mp4)",
+ )
+ parser.add_argument(
+ "--verify_ik",
+ action="store_true",
+ help="是否执行 IK 验证(仅第一帧)",
+ required=True,
+ )
+ parser.add_argument(
+ "--use-action",
+ action="store_true",
+ help="使用 action 而非 observation.state",
+ )
+
+ # 相机内参(可选,覆盖默认)
+ parser.add_argument("--fx", type=float, default=None, help="相机焦距 fx")
+ parser.add_argument("--fy", type=float, default=None, help="相机焦距 fy")
+ parser.add_argument("--cx", type=float, default=None, help="主点 cx")
+ parser.add_argument("--cy", type=float, default=None, help="主点 cy")
+
+ # 可选:从 RoboTwin 读取内参(只读内参,不再读外参)
+ parser.add_argument(
+ "--load-intrinsics-from-robotwin",
+ action="store_true",
+ help="从 RoboTwin 的 _camera_config.yml 自动加载相机内参",
+ )
+ parser.add_argument(
+ "--camera-type",
+ type=str,
+ default="Large_D435",
+ help="RoboTwin 相机类型 (D435/Large_D435/L515/Large_L515)",
+ )
+
+ args = parser.parse_args()
+
+ # 输出目录
+ args.output_dir.mkdir(parents=True, exist_ok=True)
+
+
+
+ # 初始化投影器(外参完全由 T_FOOT_CAM_DEFAULT 决定)
+ retargeter = AlohaRetargeter(
+ urdf_path=args.urdf_path,
+ T_foot_cam=T_FOOT_CAM_DEFAULT,
+ )
+ # 构建输入/输出路径
+ episode_str = f"episode_{args.episode:06d}"
+ parquet_path = (
+ args.dataset_root / f"data/chunk-000/{episode_str}.parquet"
+ )
+ video_path = (
+ args.dataset_root / f"videos/chunk-000/observation.images.{args.camera}/{episode_str}.mp4"
+ )
+ output_path = (
+ args.output_dir / f"{episode_str}_{args.camera}_projected.mp4"
+ )
+
+ # 处理 episode
+ retargeter.process_episode(
+ video_path=video_path,
+ parquet_path=parquet_path,
+ output_path=output_path,
+ verify_ik=args.verify_ik,
+ use_state=not args.use_action,
+ )
+
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/examples/Robotwin_ee/eval_files/run_parallel_eval_mxk.sh b/examples/Robotwin_ee/eval_files/run_parallel_eval_mxk.sh
new file mode 100644
index 0000000000000000000000000000000000000000..956d668748d4131e237e3dc20173d96bbd30f4f2
--- /dev/null
+++ b/examples/Robotwin_ee/eval_files/run_parallel_eval_mxk.sh
@@ -0,0 +1,214 @@
+#!/bin/bash
+# Copyright 2025 starVLA community. All rights reserved.
+# Licensed under the MIT License, Version 1.0 (the "License");
+# One-click script: Start server on GPU 0, run 50 tasks dynamically on GPUs 1-7
+
+# source /mnt/workspace/envs/conda3/bin/activate robot_njn
+# bash /mnt/workspace/users/hukejun/JoyRA/StarVLA/scripts/setup_kdl/set_kdl.sh
+# bash /mnt/workspace/users/hukejun/JoyRA/StarVLA/scripts/setup_kdl/set_pykdl.sh
+
+set -e
+
+#####################################################################
+# ======================= Configuration ============================
+#####################################################################
+# export LD_LIBRARY_PATH=/tmp/nvidia-gl-extract/usr/lib/x86_64-linux-gnu:$LD_LIBRARY_PATH
+export VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/nvidia_icd.json
+export CUROBO_TORCH_COMPILE=1
+
+# -------------------- Path Settings --------------------
+STARVLA_PATH=/mnt/workspace/users/maxiangkai/projects/MaskWAM
+ROBOTWIN_PATH=/mnt/workspace/users/maxiangkai/projects/WM4A/RoboTwin
+STAR_VLA_PYTHON=/mnt/workspace/envs/conda3/envs/starVLA_1/bin/python
+ROBOTWIN_PYTHON=/mnt/workspace/envs/conda3/envs/robot_njn/bin/python
+
+# -------------------- Model Settings --------------------
+
+# wm4a
+CKPT_SETTING="robotwin_wan22_masked_future_image"
+# CKPT_PATH=/mnt/workspace/users/yuanzhihao/code/starVLA/outputs/wan22_perceiver_masked_future_image/posttrain/robotwin_wan22_masked_future_image/checkpoints/steps_200000_pytorch_model.pt
+CKPT_PATH=/mnt/workspace/users/maxiangkai/projects/MaskWAM/outputs/joyra05mask_new_wm4a/robotwin_concat/checkpoints/steps_150000_pytorch_model.pt
+
+# joyra05
+# CKPT_SETTING="robotwin_clean_random_reversed-QwenFastWanPerceiver-mn-train-motus-fast-chunk50"
+# CKPT_PATH=/mnt/workspace/users/maxiangkai/models/${CKPT_SETTING}/checkpoints/steps_260000_pytorch_model.pt
+
+WAN_PATH=/mnt/workspace/users/maxiangkai/models/Wan2.2-TI2V-5B-Diffusers
+FAST_TOKENIZER_PATH=/mnt/workspace/users/maxiangkai/models/physical-intelligence-fast
+export FAST_TOKENIZER_PATH
+USE_BF16=true
+
+# -------------------- Server Settings --------------------
+SERVER_BASE_PORT=5693 # Per-GPU server ports: base + (gpu_id - EVAL_GPU_START_ID)
+SEED=42
+
+# -------------------- Eval Settings --------------------
+TASK_CONFIG="demo_clean"
+EVAL_SEED=0
+NUM_EVAL_GPUS=8 # Number of GPUs used for eval
+EVAL_GPU_START_ID=0 # Set 0 to include GPU0 as eval client
+SLOTS_PER_GPU=8 # Keep 1 for per-GPU single-task strategy
+NUM_TRAJ_WORKERS=8 # Keep 1 so each task is bound to one GPU
+TEST_NUM_PER_TASK=100 # Total trajectories per task
+
+# -------------------- Timing Settings --------------------
+SERVER_STARTUP_WAIT=240
+
+# -------------------- Output Settings --------------------
+# 统一运行时间戳:以本脚本被调用的时刻为准,作为固定值传递给所有子进程,
+# 保证 log 与 视频/图片 保存在同一个时间戳目录下。
+RUN_TIMESTAMP=$(date +"%Y-%m-%d %H:%M:%S")
+
+# 评估结果保存根目录(与 eval_policy.py 默认值保持一致)
+EVAL_SAVE_ROOT="/mnt/workspace/users/maxiangkai/projects/JoyRA_robotwin"
+
+# 本次运行的统一输出目录:${EVAL_SAVE_ROOT}/${CKPT_SETTING}/${RUN_TIMESTAMP}
+RUN_OUTPUT_DIR="${EVAL_SAVE_ROOT}/${CKPT_SETTING}/${RUN_TIMESTAMP}"
+# 日志统一保存到 LOG 子目录
+LOG_DIR="${RUN_OUTPUT_DIR}/LOG"
+mkdir -p "${LOG_DIR}"
+
+#####################################################################
+# ======================= Helper Functions =========================
+#####################################################################
+
+RED='\033[0;31m'
+GREEN='\033[0;32m'
+YELLOW='\033[0;33m'
+BLUE='\033[0;34m'
+NC='\033[0m'
+
+log_info() { echo -e "${GREEN}[INFO]${NC} $1"; }
+log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
+log_error() { echo -e "${RED}[ERROR]${NC} $1"; }
+log_step() { echo -e "${BLUE}[STEP]${NC} $1"; }
+
+cleanup() {
+ log_warn "Cleaning up..."
+ for pid in "${SERVER_PIDS[@]}"; do
+ if [ ! -z "$pid" ]; then
+ log_info "Stopping policy server (PID: $pid)..."
+ kill "$pid" 2>/dev/null || true
+ wait "$pid" 2>/dev/null || true
+ fi
+ done
+ log_info "Cleanup complete."
+}
+
+trap cleanup EXIT INT TERM
+
+#####################################################################
+# ======================= Main Script ==============================
+#####################################################################
+
+log_step "========== StarVLA 50-Task Dynamic Evaluation =========="
+log_info "Eval GPU range: ${EVAL_GPU_START_ID}-$((EVAL_GPU_START_ID + NUM_EVAL_GPUS - 1))"
+log_info "Slots per GPU: ${SLOTS_PER_GPU}"
+log_info "Trajectory workers per task: ${NUM_TRAJ_WORKERS}"
+log_info "Trajectories per task: ${TEST_NUM_PER_TASK}"
+log_info "Total Tasks: 50"
+log_info "Checkpoint: ${CKPT_PATH}"
+log_info "Server Base Port: ${SERVER_BASE_PORT}"
+log_info "Log Directory: ${LOG_DIR}"
+log_info "Server Python: ${STAR_VLA_PYTHON}"
+log_info "Eval Python: ${ROBOTWIN_PYTHON}"
+echo ""
+
+# -------------------- Step 1: Start Per-GPU Policy Servers --------------------
+log_step "Step 1: Starting policy servers (one per eval GPU)..."
+
+cd ${STARVLA_PATH}
+export PYTHONPATH=$(pwd):${PYTHONPATH}
+
+BF16_FLAG=""
+if [ "$USE_BF16" = true ]; then
+ BF16_FLAG="--use_bf16"
+fi
+
+SERVER_PIDS=()
+SERVER_PORTS=()
+SERVER_PORTS_ARG=""
+
+for ((idx=0; idx/dev/null; then
+ log_error "Policy server failed to start (PID: ${pid}, port: ${port})!"
+ exit 1
+ fi
+done
+log_info "All policy servers are running."
+log_info "Server mapping: ${SERVER_PORTS_ARG}"
+echo ""
+
+# -------------------- Step 2: Run Dynamic Task Scheduler --------------------
+log_step "Step 2: Running Dynamic Task Scheduler (50 tasks)..."
+
+set +e # Don't exit on error, capture exit code
+
+${STAR_VLA_PYTHON} ${STARVLA_PATH}/examples/Robotwin_ee/eval_files/dynamic_task_scheduler_50_mxk.py \
+ --mode run \
+ --num_gpus ${NUM_EVAL_GPUS} \
+ --gpu_start_id ${EVAL_GPU_START_ID} \
+ --slots_per_gpu ${SLOTS_PER_GPU} \
+ --num_traj_workers ${NUM_TRAJ_WORKERS} \
+ --test_num ${TEST_NUM_PER_TASK} \
+ --ckpt_path ${CKPT_PATH} \
+ --server_port ${SERVER_BASE_PORT} \
+ --server_ports "${SERVER_PORTS_ARG}" \
+ --task_config ${TASK_CONFIG} \
+ --ckpt_setting ${CKPT_SETTING} \
+ --eval_seed ${EVAL_SEED} \
+ --log_dir "${LOG_DIR}" \
+ --eval_save_root "${EVAL_SAVE_ROOT}" \
+ --eval_timestamp "${RUN_TIMESTAMP}" \
+ --starvla_path ${STARVLA_PATH} \
+ --robotwin_path ${ROBOTWIN_PATH} \
+ --python_path ${ROBOTWIN_PYTHON} \
+ --resource_log_interval 300
+# CPU监测
+# --resource_log_interval 30 间隔多少s打印
+# --disable_resource_monitor 不打印CPU监测
+SCHEDULER_EXIT_CODE=$?
+
+set -e
+
+echo ""
+
+# -------------------- Step 3: Summary --------------------
+log_step "Step 3: Evaluation Complete"
+
+if [ "$SCHEDULER_EXIT_CODE" -eq 0 ]; then
+ log_info "All 50 tasks completed successfully!"
+else
+ log_error "Some tasks failed. Check logs in: ${LOG_DIR}"
+fi
+
+exit $SCHEDULER_EXIT_CODE
diff --git a/examples/Robotwin_ee/eval_files/run_parallel_eval_mxk_back.sh b/examples/Robotwin_ee/eval_files/run_parallel_eval_mxk_back.sh
new file mode 100644
index 0000000000000000000000000000000000000000..aa40971019a48b8aa10de104de92776f10dc96d4
--- /dev/null
+++ b/examples/Robotwin_ee/eval_files/run_parallel_eval_mxk_back.sh
@@ -0,0 +1,38 @@
+#!/bin/bash
+
+EVAL_SCRIPT="$(cd "$(dirname "$0")" && pwd)/run_parallel_eval_mxk.sh"
+LOG_FILE="/mnt/workspace/users/maxiangkai/projects/WM4A/examples/Robotwin_ee/eval_files/eval_back_$(date +%Y%m%d_%H%M%S).log"
+mkdir -p "$(dirname "${LOG_FILE}")"
+
+if [ ! -f "${EVAL_SCRIPT}" ]; then
+ echo "ERROR: cannot find ${EVAL_SCRIPT}" >&2; exit 1
+fi
+
+nohup setsid bash "${EVAL_SCRIPT}" "$@" >"${LOG_FILE}" 2>&1 &
+EVAL_PID=$!
+disown "${EVAL_PID}" 2>/dev/null || true
+sleep 1
+
+ABS_LOG_FILE="$(cd "$(dirname "${LOG_FILE}")" && pwd)/$(basename "${LOG_FILE}")"
+
+cat </dev/null; echo ""; echo "Detached from log. Eval PID=${EVAL_PID} still running."; echo " Re-attach: tail -F ${ABS_LOG_FILE}"; exit 0' INT
+wait "${TAIL_PID}"
\ No newline at end of file
diff --git a/examples/Robotwin_ee/train_files/joyra05.sh b/examples/Robotwin_ee/train_files/joyra05.sh
new file mode 100644
index 0000000000000000000000000000000000000000..1969c713d763752d1a343800031abf94df5d3ae4
--- /dev/null
+++ b/examples/Robotwin_ee/train_files/joyra05.sh
@@ -0,0 +1,99 @@
+#!/usr/bin/env zsh
+set -euo pipefail
+
+# Cosmos-Predict2.5 Perceiver training with eval-time future-image visualization.
+# Action training uses Cosmos hidden states + Perceiver; eval additionally runs
+# the Cosmos2.5 decoder/generation path and saves pred future images.
+
+if [ -d /sys/class/infiniband ]; then
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
+else
+ RDMA_DEVICES=""
+fi
+
+if [ -n "${RDMA_DEVICES}" ]; then
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
+ export NCCL_IB_HCA
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
+ export NCCL_IB_DISABLE=0
+ export NCCL_NET_GDR_LEVEL=2
+else
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
+ export NCCL_IB_DISABLE=1
+fi
+
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS || true
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+
+cd /mnt/workspace/users/maxiangkai/projects/WM4A
+if [ -f /mnt/workspace/envs/conda3/bin/activate ]; then
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+fi
+
+NUM_GPUS_PER_NODE=${1:-8} # mytest
+
+Framework_name=QwenWanPerceiver
+base_vlm=/mnt/workspace/users/maxiangkai/models/Qwen3-VL-4B-Instruct
+base_wm=/mnt/workspace/users/maxiangkai/models/Wan2.2-TI2V-5B-Diffusers
+transformer_path=/mnt/workspace/users/maxiangkai/models/Motus_Wan2_2_5B_pretrain
+pretrained_checkpoint=/mnt/workspace/users/chidafeng/main_results/joyra05/pretrain/0529_joyra05_data_0530_QwenWanPerceiver_15wsteps_bs16/final_model/pytorch_model.pt
+config_yaml=/mnt/workspace/users/maxiangkai/projects/WM4A/examples/Robotwin_ee/train_files/starvla_cotrain_robotwin.yaml
+DIT_TYPE="DiT-B"
+data_root_dir=/mnt/workspace/datasets/
+data_mix=robotwin_ee
+
+run_root_dir=/mnt/workspace/users/maxiangkai/projects/WM4A/outputs/joyra05
+run_id=robotwin
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p "${output_dir}"
+export WANDB_MODE=offline
+export WANDB_DIR="${output_dir}/wandb"
+mkdir -p "${WANDB_DIR}"
+cp "$0" "${output_dir}/"
+cp ${config_yaml} ${output_dir}
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
+ starVLA/training/train_starvla.py \
+ --config_yaml ${config_yaml} \
+ --framework.name ${Framework_name} \
+ --framework.qwenvl.base_vlm "${base_vlm}" \
+ --framework.qwenvl.vl_hidden_dim 2048 \
+ --framework.world_model.base_wm ${base_wm} \
+ --framework.world_model.transformer_path ${transformer_path} \
+ --framework.world_model.extract_layers "[-1]" \
+ --framework.action_model.hidden_size 1024 \
+ --framework.action_model.diffusion_model_cfg.output_dim 1024 \
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
+ --datasets.vla_data.data_mix "${data_mix}" \
+ --datasets.vla_data.include_state true \
+ --datasets.vla_data.per_device_batch_size 8 \
+ --datasets.vla_data.num_workers 8 \
+ --datasets.vla_data.prefetch_factor 2 \
+ --datasets.vla_data.pin_memory true \
+ --datasets.vla_data.persistent_workers true \
+ --trainer.pretrained_checkpoint ${pretrained_checkpoint} \
+ --trainer.max_train_steps 300000 \
+ --trainer.save_interval 50000 \
+ --trainer.logging_frequency 500 \
+ --trainer.eval_interval 500 \
+ --trainer.num_warmup_steps 1000 \
+ --trainer.learning_rate.base 1e-5 \
+ --trainer.scheduler_specific_kwargs.min_lr 1.2e-6 \
+ --trainer.optimizer.betas "[0.9,0.999]" \
+ --trainer.optimizer.weight_decay 0.1 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project joyRA_robotwin_mxk \
+ --wandb_entity mxk \
+ 2>&1 | tee -a "${output_dir}/train.log"
diff --git a/examples/Robotwin_ee/train_files/joyra05mask.sh b/examples/Robotwin_ee/train_files/joyra05mask.sh
new file mode 100644
index 0000000000000000000000000000000000000000..f5a8ae2dc6142df1bd4ee93a9285ff2e226a6800
--- /dev/null
+++ b/examples/Robotwin_ee/train_files/joyra05mask.sh
@@ -0,0 +1,123 @@
+#!/usr/bin/env zsh
+set -euo pipefail
+
+# Cosmos-Predict2.5 Perceiver training with eval-time future-image visualization.
+# Action training uses Cosmos hidden states + Perceiver; eval additionally runs
+# the Cosmos2.5 decoder/generation path and saves pred future images.
+
+if [ -d /sys/class/infiniband ]; then
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
+else
+ RDMA_DEVICES=""
+fi
+
+if [ -n "${RDMA_DEVICES}" ]; then
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
+ export NCCL_IB_HCA
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
+ export NCCL_IB_DISABLE=0
+ export NCCL_NET_GDR_LEVEL=2
+else
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
+ export NCCL_IB_DISABLE=1
+fi
+
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS || true
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+
+cd /mnt/workspace/users/maxiangkai/projects/WM4A
+if [ -f /mnt/workspace/envs/conda3/bin/activate ]; then
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+fi
+
+NUM_GPUS_PER_NODE=${1:-8} # mytest
+
+Framework_name=QwenWanPerceiverMask
+base_vlm=/mnt/workspace/users/maxiangkai/models/Qwen3-VL-4B-Instruct
+base_wm=/mnt/workspace/users/maxiangkai/models/Wan2.2-TI2V-5B-Diffusers
+transformer_path=/mnt/workspace/users/maxiangkai/models/Motus_Wan2_2_5B_pretrain
+pretrained_checkpoint=/mnt/workspace/users/chidafeng/main_results/joyra05/pretrain/0529_joyra05_data_0530_QwenWanPerceiver_15wsteps_bs16/final_model/pytorch_model.pt
+config_yaml=/mnt/workspace/users/maxiangkai/projects/WM4A/examples/Robotwin/train_files/starvla_cotrain_robotwin.yaml
+DIT_TYPE="DiT-B"
+data_root_dir=/mnt/workspace/datasets/
+data_mix=robotwin_ee
+
+run_root_dir=/mnt/workspace/users/maxiangkai/projects/WM4A/outputs/joyra05mask
+run_id=robotwin # mytest
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p "${output_dir}"
+export WANDB_MODE=offline
+export WANDB_DIR="${output_dir}/wandb"
+mkdir -p "${WANDB_DIR}"
+cp "$0" "${output_dir}/"
+cp ${config_yaml} ${output_dir}
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
+ starVLA/training/train_starvla_zero2.py \
+ --config_yaml ${config_yaml} \
+ --framework.name ${Framework_name} \
+ --framework.qwenvl.base_vlm "${base_vlm}" \
+ --framework.qwenvl.vl_hidden_dim 2048 \
+ --framework.qwenvl.is_frozen false \
+ --framework.world_model.base_wm ${base_wm} \
+ --framework.world_model.transformer_path ${transformer_path} \
+ --framework.world_model.extract_layers "[-1]" \
+ --framework.action_model.hidden_size 1024 \
+ --framework.action_model.diffusion_model_cfg.output_dim 1024 \
+ --framework.future_image_training.enabled true \
+ --framework.future_image_training.loss_weight 1.0 \
+ --framework.future_image_training.train_time_distribution logitnormal \
+ --framework.future_image_training.shift 5.0 \
+ --framework.future_image_training.change_mask_enabled true \
+ --framework.future_image_training.change_mask_top_ratio 0.25 \
+ --framework.future_image_training.change_mask_static_weight 0.05 \
+ --framework.future_image_training.change_mask_soft_loss true \
+ --framework.future_image_training.masked_denoising false \
+ --framework.future_image_training.condition_static_regions false \
+ --framework.future_image_generation.enabled true \
+ --framework.future_image_generation.conditioning_mode auto \
+ --framework.future_image_generation.max_samples 8 \
+ --framework.future_image_generation.height 224 \
+ --framework.future_image_generation.width 224 \
+ --framework.future_image_generation.num_frames 9 \
+ --framework.future_image_generation.num_inference_steps 20 \
+ --framework.future_image_generation.guidance_scale 7.0 \
+ --framework.future_image_generation.output_type pil \
+ --framework.future_image_generation.future_frame_index -1 \
+ --framework.future_image_generation.num_latent_conditional_frames 1 \
+ --framework.future_image_generation.return_full_video false \
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
+ --datasets.vla_data.data_mix "${data_mix}" \
+ --datasets.vla_data.future_video_delta_indices "[16]" \
+ --datasets.vla_data.include_state true \
+ --datasets.vla_data.per_device_batch_size 2 \
+ --datasets.vla_data.num_workers 8 \
+ --datasets.vla_data.prefetch_factor 2 \
+ --datasets.vla_data.pin_memory true \
+ --datasets.vla_data.persistent_workers true \
+ --trainer.pretrained_checkpoint ${pretrained_checkpoint} \
+ --trainer.max_train_steps 300000 \
+ --trainer.save_interval 50000 \
+ --trainer.logging_frequency 500 \
+ --trainer.eval_interval 500 \
+ --trainer.num_warmup_steps 1000 \
+ --trainer.learning_rate.base 1e-5 \
+ --trainer.scheduler_specific_kwargs.min_lr 1.2e-6 \
+ --trainer.optimizer.betas "[0.9,0.999]" \
+ --trainer.optimizer.weight_decay 0.1 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project joyRA_robotwin_mxk \
+ --wandb_entity mxk \
+ 2>&1 | tee -a "${output_dir}/train.log"
diff --git a/examples/Robotwin_ee/train_files/joyra05mask_frozen_vlm.sh b/examples/Robotwin_ee/train_files/joyra05mask_frozen_vlm.sh
new file mode 100644
index 0000000000000000000000000000000000000000..33ab86f96b450884d37c12b446e13ff5fba872bc
--- /dev/null
+++ b/examples/Robotwin_ee/train_files/joyra05mask_frozen_vlm.sh
@@ -0,0 +1,124 @@
+#!/usr/bin/env zsh
+set -euo pipefail
+
+# Cosmos-Predict2.5 Perceiver training with eval-time future-image visualization.
+# Action training uses Cosmos hidden states + Perceiver; eval additionally runs
+# the Cosmos2.5 decoder/generation path and saves pred future images.
+
+if [ -d /sys/class/infiniband ]; then
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
+else
+ RDMA_DEVICES=""
+fi
+
+if [ -n "${RDMA_DEVICES}" ]; then
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
+ export NCCL_IB_HCA
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
+ export NCCL_IB_DISABLE=0
+ export NCCL_NET_GDR_LEVEL=2
+else
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
+ export NCCL_IB_DISABLE=1
+fi
+
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS || true
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+
+cd /mnt/workspace/users/maxiangkai/projects/WM4A
+if [ -f /mnt/workspace/envs/conda3/bin/activate ]; then
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+fi
+
+NUM_GPUS_PER_NODE=${1:-8} # mytest
+
+Framework_name=QwenWanPerceiverMask
+base_vlm=/mnt/workspace/users/maxiangkai/models/Qwen3-VL-4B-Instruct
+base_wm=/mnt/workspace/users/maxiangkai/models/Wan2.2-TI2V-5B-Diffusers
+transformer_path=/mnt/workspace/users/maxiangkai/models/Motus_Wan2_2_5B_pretrain
+pretrained_checkpoint=/mnt/workspace/users/chidafeng/main_results/joyra05/pretrain/0529_joyra05_data_0530_QwenWanPerceiver_15wsteps_bs16/final_model/pytorch_model.pt
+config_yaml=/mnt/workspace/users/maxiangkai/projects/WM4A/examples/Robotwin/train_files/starvla_cotrain_robotwin.yaml
+DIT_TYPE="DiT-B"
+data_root_dir=/mnt/workspace/datasets/
+data_mix=robotwin_ee
+
+run_root_dir=/mnt/workspace/users/maxiangkai/projects/WM4A/outputs/joyra05mask_frozen_vlm
+run_id=robotwin # mytest
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p "${output_dir}"
+export WANDB_MODE=offline
+export WANDB_DIR="${output_dir}/wandb"
+mkdir -p "${WANDB_DIR}"
+cp "$0" "${output_dir}/"
+cp ${config_yaml} ${output_dir}
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
+ starVLA/training/train_starvla_zero2.py \
+ --config_yaml ${config_yaml} \
+ --framework.name ${Framework_name} \
+ --framework.qwenvl.base_vlm "${base_vlm}" \
+ --framework.qwenvl.vl_hidden_dim 2048 \
+ --framework.qwenvl.is_frozen true \
+ --framework.world_model.base_wm ${base_wm} \
+ --framework.world_model.transformer_path ${transformer_path} \
+ --framework.world_model.extract_layers "[-1]" \
+ --framework.action_model.hidden_size 1024 \
+ --framework.action_model.diffusion_model_cfg.output_dim 1024 \
+ --framework.future_image_training.enabled true \
+ --framework.future_image_training.loss_weight 1.0 \
+ --framework.future_image_training.train_time_distribution logitnormal \
+ --framework.future_image_training.shift 5.0 \
+ --framework.future_image_training.change_mask_enabled true \
+ --framework.future_image_training.change_mask_top_ratio 0.25 \
+ --framework.future_image_training.change_mask_static_weight 0.05 \
+ --framework.future_image_training.change_mask_soft_loss true \
+ --framework.future_image_training.masked_denoising false \
+ --framework.future_image_training.condition_static_regions false \
+ --framework.future_image_generation.enabled true \
+ --framework.future_image_generation.conditioning_mode auto \
+ --framework.future_image_generation.max_samples 8 \
+ --framework.future_image_generation.height 224 \
+ --framework.future_image_generation.width 224 \
+ --framework.future_image_generation.num_frames 9 \
+ --framework.future_image_generation.num_inference_steps 20 \
+ --framework.future_image_generation.guidance_scale 7.0 \
+ --framework.future_image_generation.output_type pil \
+ --framework.future_image_generation.future_frame_index -1 \
+ --framework.future_image_generation.num_latent_conditional_frames 1 \
+ --framework.future_image_generation.return_full_video false \
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
+ --datasets.vla_data.data_mix "${data_mix}" \
+ --datasets.vla_data.future_video_delta_indices "[16]" \
+ --datasets.vla_data.include_state true \
+ --datasets.vla_data.per_device_batch_size 2 \
+ --datasets.vla_data.num_workers 8 \
+ --datasets.vla_data.prefetch_factor 2 \
+ --datasets.vla_data.pin_memory true \
+ --datasets.vla_data.persistent_workers true \
+ --trainer.pretrained_checkpoint ${pretrained_checkpoint} \
+ --trainer.max_train_steps 300000 \
+ --trainer.save_interval 50000 \
+ --trainer.logging_frequency 500 \
+ --trainer.eval_interval 500 \
+ --trainer.eval_interval 500 \
+ --trainer.num_warmup_steps 1000 \
+ --trainer.learning_rate.base 1e-5 \
+ --trainer.scheduler_specific_kwargs.min_lr 1.2e-6 \
+ --trainer.optimizer.betas "[0.9,0.999]" \
+ --trainer.optimizer.weight_decay 0.1 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project joyRA_robotwin_mxk \
+ --wandb_entity mxk \
+ 2>&1 | tee -a "${output_dir}/train.log"
diff --git a/examples/Robotwin_ee/train_files/joyra05mask_frozen_vlm_newwan.sh b/examples/Robotwin_ee/train_files/joyra05mask_frozen_vlm_newwan.sh
new file mode 100644
index 0000000000000000000000000000000000000000..4fd2110ee4bc86fe510be7931a2e60e21a739481
--- /dev/null
+++ b/examples/Robotwin_ee/train_files/joyra05mask_frozen_vlm_newwan.sh
@@ -0,0 +1,124 @@
+#!/usr/bin/env zsh
+set -euo pipefail
+
+# Cosmos-Predict2.5 Perceiver training with eval-time future-image visualization.
+# Action training uses Cosmos hidden states + Perceiver; eval additionally runs
+# the Cosmos2.5 decoder/generation path and saves pred future images.
+
+if [ -d /sys/class/infiniband ]; then
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
+else
+ RDMA_DEVICES=""
+fi
+
+if [ -n "${RDMA_DEVICES}" ]; then
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
+ export NCCL_IB_HCA
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
+ export NCCL_IB_DISABLE=0
+ export NCCL_NET_GDR_LEVEL=2
+else
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
+ export NCCL_IB_DISABLE=1
+fi
+
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS || true
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+
+cd /mnt/workspace/users/maxiangkai/projects/WM4A
+if [ -f /mnt/workspace/envs/conda3/bin/activate ]; then
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+fi
+
+NUM_GPUS_PER_NODE=${1:-8} # mytest
+
+Framework_name=QwenWanPerceiverMask
+base_vlm=/mnt/workspace/users/maxiangkai/models/Qwen3-VL-4B-Instruct
+base_wm=/mnt/workspace/users/xiangzhiyuan/FastWAM/converted/step_115000_Wan2.2-TI2V-5B-Diffusers
+transformer_path=/mnt/workspace/users/maxiangkai/models/Motus_Wan2_2_5B_pretrain
+pretrained_checkpoint=/mnt/workspace/users/chidafeng/main_results/joyra05/pretrain/0529_joyra05_data_0530_QwenWanPerceiver_15wsteps_bs16/final_model/pytorch_model.pt
+config_yaml=/mnt/workspace/users/maxiangkai/projects/WM4A/examples/Robotwin/train_files/starvla_cotrain_robotwin.yaml
+DIT_TYPE="DiT-B"
+data_root_dir=/mnt/workspace/datasets/
+data_mix=robotwin_ee
+
+run_root_dir=/mnt/workspace/users/maxiangkai/projects/WM4A/outputs/joyra05mask_frozen_vlm_newwan
+run_id=robotwin # mytest
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p "${output_dir}"
+export WANDB_MODE=offline
+export WANDB_DIR="${output_dir}/wandb"
+mkdir -p "${WANDB_DIR}"
+cp "$0" "${output_dir}/"
+cp ${config_yaml} ${output_dir}
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
+ starVLA/training/train_starvla_zero2.py \
+ --config_yaml ${config_yaml} \
+ --framework.name ${Framework_name} \
+ --framework.qwenvl.base_vlm "${base_vlm}" \
+ --framework.qwenvl.vl_hidden_dim 2048 \
+ --framework.qwenvl.is_frozen true \
+ --framework.world_model.base_wm ${base_wm} \
+ --framework.world_model.transformer_path ${transformer_path} \
+ --framework.world_model.extract_layers "[-1]" \
+ --framework.action_model.hidden_size 1024 \
+ --framework.action_model.diffusion_model_cfg.output_dim 1024 \
+ --framework.future_image_training.enabled true \
+ --framework.future_image_training.loss_weight 1.0 \
+ --framework.future_image_training.train_time_distribution logitnormal \
+ --framework.future_image_training.shift 5.0 \
+ --framework.future_image_training.change_mask_enabled true \
+ --framework.future_image_training.change_mask_top_ratio 0.25 \
+ --framework.future_image_training.change_mask_static_weight 0.05 \
+ --framework.future_image_training.change_mask_soft_loss true \
+ --framework.future_image_training.masked_denoising false \
+ --framework.future_image_training.condition_static_regions false \
+ --framework.future_image_generation.enabled true \
+ --framework.future_image_generation.conditioning_mode auto \
+ --framework.future_image_generation.max_samples 8 \
+ --framework.future_image_generation.height 224 \
+ --framework.future_image_generation.width 224 \
+ --framework.future_image_generation.num_frames 9 \
+ --framework.future_image_generation.num_inference_steps 20 \
+ --framework.future_image_generation.guidance_scale 7.0 \
+ --framework.future_image_generation.output_type pil \
+ --framework.future_image_generation.future_frame_index -1 \
+ --framework.future_image_generation.num_latent_conditional_frames 1 \
+ --framework.future_image_generation.return_full_video false \
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
+ --datasets.vla_data.data_mix "${data_mix}" \
+ --datasets.vla_data.future_video_delta_indices "[16]" \
+ --datasets.vla_data.include_state true \
+ --datasets.vla_data.per_device_batch_size 2 \
+ --datasets.vla_data.num_workers 8 \
+ --datasets.vla_data.prefetch_factor 2 \
+ --datasets.vla_data.pin_memory true \
+ --datasets.vla_data.persistent_workers true \
+ --trainer.pretrained_checkpoint ${pretrained_checkpoint} \
+ --trainer.max_train_steps 300000 \
+ --trainer.save_interval 50000 \
+ --trainer.logging_frequency 500 \
+ --trainer.eval_interval 500 \
+ --trainer.eval_interval 500 \
+ --trainer.num_warmup_steps 1000 \
+ --trainer.learning_rate.base 1e-5 \
+ --trainer.scheduler_specific_kwargs.min_lr 1.2e-6 \
+ --trainer.optimizer.betas "[0.9,0.999]" \
+ --trainer.optimizer.weight_decay 0.1 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project joyRA_robotwin_mxk \
+ --wandb_entity mxk \
+ 2>&1 | tee -a "${output_dir}/train.log"
diff --git a/examples/Robotwin_ee/train_files/joyra05mask_newwan.sh b/examples/Robotwin_ee/train_files/joyra05mask_newwan.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e84e7a43d5c9ebdef124d3d8aa80b0011fce7db3
--- /dev/null
+++ b/examples/Robotwin_ee/train_files/joyra05mask_newwan.sh
@@ -0,0 +1,123 @@
+#!/usr/bin/env zsh
+set -euo pipefail
+
+# Cosmos-Predict2.5 Perceiver training with eval-time future-image visualization.
+# Action training uses Cosmos hidden states + Perceiver; eval additionally runs
+# the Cosmos2.5 decoder/generation path and saves pred future images.
+
+if [ -d /sys/class/infiniband ]; then
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
+else
+ RDMA_DEVICES=""
+fi
+
+if [ -n "${RDMA_DEVICES}" ]; then
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
+ export NCCL_IB_HCA
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
+ export NCCL_IB_DISABLE=0
+ export NCCL_NET_GDR_LEVEL=2
+else
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
+ export NCCL_IB_DISABLE=1
+fi
+
+export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
+export NCCL_DEBUG=WARN
+unset NCCL_DEBUG_SUBSYS || true
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000
+export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
+
+cd /mnt/workspace/users/maxiangkai/projects/WM4A
+if [ -f /mnt/workspace/envs/conda3/bin/activate ]; then
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
+fi
+
+NUM_GPUS_PER_NODE=${1:-8} # mytest
+
+Framework_name=QwenWanPerceiverMask
+base_vlm=/mnt/workspace/users/maxiangkai/models/Qwen3-VL-4B-Instruct
+base_wm=/mnt/workspace/users/xiangzhiyuan/FastWAM/converted/step_115000_Wan2.2-TI2V-5B-Diffusers
+transformer_path=/mnt/workspace/users/maxiangkai/models/Motus_Wan2_2_5B_pretrain
+pretrained_checkpoint=/mnt/workspace/users/chidafeng/main_results/joyra05/pretrain/0529_joyra05_data_0530_QwenWanPerceiver_15wsteps_bs16/final_model/pytorch_model.pt
+config_yaml=/mnt/workspace/users/maxiangkai/projects/WM4A/examples/Robotwin/train_files/starvla_cotrain_robotwin.yaml
+DIT_TYPE="DiT-B"
+data_root_dir=/mnt/workspace/datasets/
+data_mix=robotwin_ee
+
+run_root_dir=/mnt/workspace/users/maxiangkai/projects/WM4A/outputs/joyra05mask_newwan
+run_id=robotwin # mytest
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p "${output_dir}"
+export WANDB_MODE=offline
+export WANDB_DIR="${output_dir}/wandb"
+mkdir -p "${WANDB_DIR}"
+cp "$0" "${output_dir}/"
+cp ${config_yaml} ${output_dir}
+
+env IS_TORCHRUN=1 torchrun \
+ --nnodes=${PET_NNODES:-1} \
+ --node_rank=${PET_NODE_RANK:-0} \
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
+ --master_port=${PET_MASTER_PORT:-29500} \
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
+ starVLA/training/train_starvla_zero2.py \
+ --config_yaml ${config_yaml} \
+ --framework.name ${Framework_name} \
+ --framework.qwenvl.base_vlm "${base_vlm}" \
+ --framework.qwenvl.vl_hidden_dim 2048 \
+ --framework.qwenvl.is_frozen false \
+ --framework.world_model.base_wm ${base_wm} \
+ --framework.world_model.transformer_path ${transformer_path} \
+ --framework.world_model.extract_layers "[-1]" \
+ --framework.action_model.hidden_size 1024 \
+ --framework.action_model.diffusion_model_cfg.output_dim 1024 \
+ --framework.future_image_training.enabled true \
+ --framework.future_image_training.loss_weight 1.0 \
+ --framework.future_image_training.train_time_distribution logitnormal \
+ --framework.future_image_training.shift 5.0 \
+ --framework.future_image_training.change_mask_enabled true \
+ --framework.future_image_training.change_mask_top_ratio 0.25 \
+ --framework.future_image_training.change_mask_static_weight 0.05 \
+ --framework.future_image_training.change_mask_soft_loss true \
+ --framework.future_image_training.masked_denoising false \
+ --framework.future_image_training.condition_static_regions false \
+ --framework.future_image_generation.enabled true \
+ --framework.future_image_generation.conditioning_mode auto \
+ --framework.future_image_generation.max_samples 8 \
+ --framework.future_image_generation.height 224 \
+ --framework.future_image_generation.width 224 \
+ --framework.future_image_generation.num_frames 9 \
+ --framework.future_image_generation.num_inference_steps 20 \
+ --framework.future_image_generation.guidance_scale 7.0 \
+ --framework.future_image_generation.output_type pil \
+ --framework.future_image_generation.future_frame_index -1 \
+ --framework.future_image_generation.num_latent_conditional_frames 1 \
+ --framework.future_image_generation.return_full_video false \
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
+ --datasets.vla_data.data_mix "${data_mix}" \
+ --datasets.vla_data.future_video_delta_indices "[16]" \
+ --datasets.vla_data.include_state true \
+ --datasets.vla_data.per_device_batch_size 2 \
+ --datasets.vla_data.num_workers 8 \
+ --datasets.vla_data.prefetch_factor 2 \
+ --datasets.vla_data.pin_memory true \
+ --datasets.vla_data.persistent_workers true \
+ --trainer.pretrained_checkpoint ${pretrained_checkpoint} \
+ --trainer.max_train_steps 300000 \
+ --trainer.save_interval 50000 \
+ --trainer.logging_frequency 500 \
+ --trainer.eval_interval 500 \
+ --trainer.num_warmup_steps 1000 \
+ --trainer.learning_rate.base 1e-5 \
+ --trainer.scheduler_specific_kwargs.min_lr 1.2e-6 \
+ --trainer.optimizer.betas "[0.9,0.999]" \
+ --trainer.optimizer.weight_decay 0.1 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project joyRA_robotwin_mxk \
+ --wandb_entity mxk \
+ 2>&1 | tee -a "${output_dir}/train.log"
diff --git a/examples/Robotwin_ee/train_files/starvla_cotrain_robotwin.yaml b/examples/Robotwin_ee/train_files/starvla_cotrain_robotwin.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..e16182ef5190516b4e9478e08876406ff8dbe1bc
--- /dev/null
+++ b/examples/Robotwin_ee/train_files/starvla_cotrain_robotwin.yaml
@@ -0,0 +1,111 @@
+run_id: qwenact
+run_root_dir: results/Checkpoints
+seed: 42
+trackers: [jsonl, wandb]
+wandb_entity: your_wandb_entity
+wandb_project: starvla
+is_debug: false
+
+framework:
+ name: '' # override in bash
+ qwenvl:
+ base_vlm: ./playground/Pretrained_models/Qwen3-VL-4B-Instruct
+ attn_implementation: flash_attention_2
+ vl_hidden_dim: 2048
+ dino:
+ dino_backbone: dinov2_vits14
+
+ action_model:
+ action_model_type: DiT-B
+ hidden_size: 2560 # 和 DiT 最后的 projection 对应,用于 ActionDecoder
+ add_pos_embed: True
+ max_seq_len: 1024
+ action_dim: 32
+ state_dim: 64
+ future_action_window_size: 49
+ action_horizon: 50
+ past_action_window_size: 0
+ repeated_diffusion_steps: 8
+ noise_beta_alpha: 1.5
+ noise_beta_beta: 1.0
+ noise_s: 0.999
+ num_timestep_buckets: 1000
+ num_inference_timesteps: 20
+ num_target_vision_tokens: 32
+ max_num_embodiments: 32
+ use_category_specific: false
+ diffusion_model_cfg: # DiT Transformers 的参数
+ cross_attention_dim: 2048 # VLM 的 dim
+ dropout: 0.2
+ final_dropout: true
+ interleave_self_attention: true
+ norm_type: "ada_norm"
+ num_layers: 16
+ output_dim: 2560
+ positional_embeddings: null
+
+datasets:
+ vlm_data:
+ dataset_py: vlm_datasets
+ dataformat: llava_json
+ dataset_use: asv2_conversation_en,asv2_detailed_description_en,asv2_region_captioning_en,coco_internvl_longcap_en,coco_karpathy_train_567_en,coco_negative_gpt4o_en,coco_poetry_zh,coco_rem_en_zh,cocorem_exist_yorn_en,cocotextv2_en,cocotextv2_gpt4o_en,okvqa_en,refcoco_grounding_aug_en,refcoco_grounding_en,tallyqa_coco_en,toloka_grounding_aug_en,vqav2_en,vsr_en
+ eval_dataset: aokvqa_cauldron_llava_format
+ data_flatten: false
+ base_interval: 2
+ max_pixels: 50176
+ min_pixels: 784
+ model_max_length: 2048
+ model_type: qwen2.5vl
+ per_device_batch_size: 4
+
+ vla_data:
+ dataset_py: lerobot_datasets
+ data_root_dir: playground/Datasets/RoboTwin
+ data_mix: robotwin # bridge_rt_1
+ action_type: delta_ee
+ default_image_resolution: [3, 224, 224]
+ per_device_batch_size: 16
+ load_all_data_for_training: true
+ obs: ["image_0"]
+ image_size: [224,224]
+ delete_pause_frame: false
+
+trainer:
+ epochs: 100
+ max_train_steps: 100000
+ num_warmup_steps: 5000
+ save_interval: 5000
+ eval_interval: 100
+ learning_rate:
+ base: 1e-05
+ qwen_vl_interface: 1.0e-05
+ action_model: 1.0e-04
+ lr_scheduler_type: cosine_with_min_lr
+ scheduler_specific_kwargs:
+ min_lr: 5.0e-07
+ freeze_modules: ''
+ loss_scale:
+ vla: 1.0
+ vlm: 0.1
+ # pretrained_checkpoint: ./results/Checkpoints/1_need/0601_qwenact_fixqwen_32gpus_lr_1e-3_qformer_36_37/steps_100000/pytorch_model.pt
+ # reload_modules: 'action_model,layer_qformer' # warning: this may cause model to not converge
+ repeated_diffusion_steps: 4
+ max_grad_norm: 1.0
+ warmup_ratio: 0.1
+ weight_decay: 0.0
+ logging_frequency: 10
+ gradient_clipping: 1.0
+ gradient_accumulation_steps: 1
+
+ optimizer:
+ name: AdamW
+ betas: [0.9, 0.95]
+ eps: 1.0e-08
+ weight_decay: 1.0e-08
+
+ # parameters to be determined
+ is_resume: false
+ resume_epoch: null
+ resume_step: null
+ enable_gradient_checkpointing: true
+ enable_mixed_precision_training: true
diff --git a/examples/SimplerEnv/README.md b/examples/SimplerEnv/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..4204d6974db8e337dbfd185ed368a2c6a740b6c6
--- /dev/null
+++ b/examples/SimplerEnv/README.md
@@ -0,0 +1,155 @@
+This document provides instructions for reproducing our **experimental results** with SimplerEnv.
+
+
+The evaluation process consists of two main parts:
+
+1. Setting up the `simpler_env` environment and dependencies.
+2. Running the evaluation by launching services in both `starVLA` and `simpler_env` environments.
+
+We have verified that this workflow runs successfully on both **NVIDIA A100** and **RTX 4090** GPUs.
+
+## 📦 1. Environment Setup
+
+To set up the environment, please first follow the official [SimplerEnv repository](https://github.com/simpler-env/SimplerEnv) to install the base `simpler_env` environment.
+
+Afterwards, inside the `simpler_env` environment, install the following dependencies:
+
+```bash
+conda activate simpler_env
+pip install tyro matplotlib mediapy websockets msgpack
+pip install numpy==1.24.4
+```
+
+⚠️ **Common Issues**
+When testing SimplerEnv on NVIDIA A100, you may encounter the following error:
+`libvulkan.so.1: cannot open shared object file: No such file or directory`
+You can refer to this link to fix: [Installation Guide – Vulkan Section](https://maniskill.readthedocs.io/en/latest/user_guide/getting_started/installation.html#vulkan)
+
+
+## 🔧 Verification Your SimplerEnv
+We provide a minimal environment verification script:
+
+```bash
+python examples/SimplerEnv/test_your_simplerEnv.py
+```
+
+If you see the "✅ Env built successfully" message, it means SimplerEnv is installed correctly and ready to use.
+
+
+---
+
+
+## 🚀 2. Eval SimplerEnv
+
+The evaluation should be run **from the repository root** using **two separate terminals/machines**, one for each environment:
+
+- **starVLA environment**: runs the policy inference server.
+- **simpler_env environment**: runs the simulation eval code.
+
+
+### Step 0. Download offical checkpoint
+
+1) Download the checkpoint:[Qwen3VL-GR00T-Bridge-RT-1](https://huggingface.co/StarVLA/Qwen3VL-GR00T-Bridge-RT-1)
+
+
+
+### Step 1. Start the server (starVLA environment)
+
+In the first terminal, activate the `starVLA` conda environment and run:
+
+```bash
+bash examples/SimplerEnv/eval_files/run_policy_server.sh
+```
+
+⚠️ **Note:** Please ensure that you specify the correct checkpoint path in
+`run_policy_server.sh`
+
+---
+
+
+### Step 2. Start the simulation (simpler_env environment)
+
+In the second terminal, activate the `simpler_env` conda environment and run:
+
+```bash
+export MODEL_PATH=.../checkpoints/steps_50000_pytorch_model.pt # for read normonization json and get name to save video under ckpt dir
+bash examples/SimplerEnv/start_simpler_env.sh ${MODEL_PATH}
+```
+This script will automatically launch the WidowX Robot evaluation tasks, reproducing the benchmark results reported above.
+
+⚠️ **Note:** Please ensure that you specify the correct `SimplerEnv_PATH`in
+`start_simpler_env.sh`
+
+
+⚠️ **Common Issues**
+
+When run policy server but `NotImplementedError:Framework QwenGR00T is not implemented`, you may need to `python QwenGR00T.py` to check your env.
+
+
+
+# 🚀 Training on OXE
+
+## Data Preparation
+
+
+Steps:
+1) Download a LeRobot-format OXE dataset
+- [bridge_orig_lerobot](https://huggingface.co/datasets/IPEC-COMMUNITY/bridge_orig_lerobot)
+- [fractal20220817_data_lerobot](https://huggingface.co/datasets/IPEC-COMMUNITY/fractal20220817_data_lerobot)
+
+2) Including `modality.json` in each `*lerobot/meta/modality.json`
+- [bridge modality](./train_files/modality.json). Rename as modality.json and put it as `bridge_orig_lerobot/meta/modality.json`
+- [fractal modality](./train_files/fractal_modality.json). Rename as `modality.json` and put it as `fractal20220817_data_lerobot/meta/modality.json`
+
+3) Add your dataset path to `config.yaml`:
+ ```yaml
+ datasets:
+ vla_data:
+ dataset_py: lerobot_datasets
+ data_root_dir: playground/Datasets/OXE_LEROBOT_DATASET # path to your dataset
+ data_mix: bridge_rt_1
+ ```
+
+
+### Check Your Dataoader
+We provide a simple way to check your dataloader. Make sure you can load batched data:
+
+```bash
+python starVLA/dataloader/lerobot_datasets.py --config_yaml examples/SimplerEnv/train_files/starvla_cotrain_oxe.yaml
+```
+
+## Framework Preparation
+
+Before running, you need to ensure that your framework can `forward` and `predict_action` using a fake data example.
+
+Try the following command:
+
+```bash
+python starVLA/model/framework/QwenGR00T.py --config_yaml examples/SimplerEnv/train_files/starvla_cotrain_oxe.yaml
+```
+
+Note: You can modify the following code snippet to align with your dataset:
+
+```python
+ # Generate a fake sample
+ image = Image.fromarray(np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8))
+ # Create a sample
+ sample = {
+ "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), # action_chunk, action_dim
+ "image": [image, image], # two views
+ "lang": "This is a fake for testing.",
+ "state": np.random.uniform(-1, 1, size=(1, 7)).astype(np.float16), # chunk, state_dim
+ }
+```
+
+## Training
+
+Once everything is ready, use our provided script to start training:
+
+```bash
+bash ./examples/SimplerEnv/train_files/run_oxe_train.sh
+```
+
+⚠️ **Note:** Ensure that the script explicitly uses the validated config path in `run_lerobot_datasets.sh`. If not already passed, add the `--config_yaml` argument.
+
+
diff --git a/examples/SimplerEnv/eval_files/adaptive_ensemble.py b/examples/SimplerEnv/eval_files/adaptive_ensemble.py
new file mode 100644
index 0000000000000000000000000000000000000000..520f85cc53c72aff24208476cc96a6042f4fb6c7
--- /dev/null
+++ b/examples/SimplerEnv/eval_files/adaptive_ensemble.py
@@ -0,0 +1,44 @@
+"""
+adaptive_ensemble.py
+
+"""
+
+from collections import deque
+import numpy as np
+
+
+class AdaptiveEnsembler:
+ def __init__(self, pred_action_horizon, adaptive_ensemble_alpha=0.0):
+ self.pred_action_horizon = pred_action_horizon
+ self.action_history = deque(maxlen=self.pred_action_horizon)
+ self.adaptive_ensemble_alpha = adaptive_ensemble_alpha
+
+ def reset(self):
+ self.action_history.clear()
+
+ def ensemble_action(self, cur_action):
+ self.action_history.append(cur_action)
+ num_actions = len(self.action_history)
+ if cur_action.ndim == 1:
+ curr_act_preds = np.stack(self.action_history)
+ else:
+ curr_act_preds = np.stack(
+ [pred_actions[i] for (i, pred_actions) in zip(range(num_actions - 1, -1, -1), self.action_history)]
+ )
+
+ # calculate cosine similarity between the current prediction and all previous predictions
+ ref = curr_act_preds[num_actions-1, :]
+ previous_pred = curr_act_preds
+ dot_product = np.sum(previous_pred * ref, axis=1)
+ norm_previous_pred = np.linalg.norm(previous_pred, axis=1)
+ norm_ref = np.linalg.norm(ref)
+ cos_similarity = dot_product / (norm_previous_pred * norm_ref + 1e-7)
+
+ # compute the weights for each prediction
+ weights = np.exp(self.adaptive_ensemble_alpha * cos_similarity)
+ weights = weights / weights.sum()
+
+ # compute the weighted average across all predictions for this timestep
+ cur_action = np.sum(weights[:, None] * curr_act_preds, axis=0)
+
+ return cur_action
\ No newline at end of file
diff --git a/examples/SimplerEnv/eval_files/auto_eval_scripts/README.md b/examples/SimplerEnv/eval_files/auto_eval_scripts/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..48b1952d12275106e509442490c2a4a67168a12a
--- /dev/null
+++ b/examples/SimplerEnv/eval_files/auto_eval_scripts/README.md
@@ -0,0 +1,7 @@
+# Auto Evaluation Scripts
+
+This folder contains the scripts we use internally to run quick evaluations across every task.
+A fully automated run depends on our in-house platform setup, so the scripts may not work unchanged on your own infrastructure.
+Please treat them as references and consult `run_policy_server.sh` and `start_simpler_env.sh` for the underlying workflow.
+
+
diff --git a/examples/SimplerEnv/eval_files/auto_eval_scripts/calc_metrics_evaluation_videos.py b/examples/SimplerEnv/eval_files/auto_eval_scripts/calc_metrics_evaluation_videos.py
new file mode 100644
index 0000000000000000000000000000000000000000..c58ec82b539d2c491d509d20db47701e97b20a44
--- /dev/null
+++ b/examples/SimplerEnv/eval_files/auto_eval_scripts/calc_metrics_evaluation_videos.py
@@ -0,0 +1,1020 @@
+# Calculate metrics for each task
+# copy from simpler_env/simpler_env/evaluation/calc_task_stats.py
+
+import argparse
+import glob
+from pathlib import Path
+
+import numpy as np
+from scipy.stats import kruskal
+
+from simpler_env.utils.metrics import (
+ construct_unordered_trial_results,
+ get_dir_stats,
+ mean_maximum_rank_violation,
+ pearson_correlation,
+ print_all_kruskal_results,
+)
+
+
+
+def calc_pick_coke_can_stats(root_result_dir):
+ print("***Pick coke can results***")
+ # If you use a new checkpoint, please update the real evaluation results here
+ coke_can_real_success = {
+ "horizontal": {
+ "QWenACT": 0.0,
+ },
+ "vertical": {
+ "QWenACT": 0.0,
+ },
+ "standing": {
+ "QWenACT": 0.0,
+ },
+ }
+
+ ckpt_alias_keys = list(coke_can_real_success["horizontal"].keys())
+ coke_can_orientation_map_dict = {
+ "horizontal": "lr_switch",
+ "vertical": "laid_vertically",
+ "standing": "upright",
+ }
+ n_orientations = len(coke_can_orientation_map_dict) # number of coke can orientations
+ n_trials_per_ckpt_per_orientation = (
+ 25 # number of trials per checkpoint per coke can orientation; update if it is different
+ )
+ # extra patterns required in file name; if you are using different visual matching overlay image, please update here
+ extra_pattern_require_sim_variants = ["rgb_overlay_None"]
+ extra_pattern_require_visual_matching = ["rgb_overlay_google_coke_can_real_eval_1"]
+
+ # get simulation variant success
+ coke_can_sim_variant_success = {
+ k1: {k2: [] for k2 in ckpt_alias_keys} for k1 in coke_can_orientation_map_dict.keys()
+ }
+
+ # hardcoded variant aggregation result dirs; if you have new variants, please update here
+ base_variants = [
+ "google_pick_coke_can_1_v4/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/GraspSingleOpenedCokeCanInScene-v0_{}_True",
+ ]
+ base_visual_matching_variants = []
+ for visual_matching_urdf_version in [
+ "None",
+ "recolor_tabletop_visual_matching_1",
+ "recolor_tabletop_visual_matching_2",
+ "recolor_cabinet_visual_matching_1",
+ ]:
+ base_visual_matching_variants.append(
+ "google_pick_coke_can_1_v4/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/GraspSingleOpenedCokeCanInScene-v0_{}_True"
+ + f"_urdf_version_{visual_matching_urdf_version}"
+ )
+
+ background_variants = [
+ "google_pick_coke_can_1_v4_alt_background/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/GraspSingleOpenedCokeCanInScene-v0_{}_True",
+ "google_pick_coke_can_1_v4_alt_background_2/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/GraspSingleOpenedCokeCanInScene-v0_{}_True",
+ ]
+ lighting_variants = [
+ "google_pick_coke_can_1_v4/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/GraspSingleOpenedCokeCanInScene-v0_{}_True_slightly_brighter_lighting_True",
+ "google_pick_coke_can_1_v4/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/GraspSingleOpenedCokeCanInScene-v0_{}_True_slightly_darker_lighting_True",
+ ]
+ distractor_variants = [
+ "google_pick_coke_can_1_v4/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/GraspSingleOpenedCokeCanDistractorInScene-v0_{}_True",
+ "google_pick_coke_can_1_v4/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/GraspSingleOpenedCokeCanDistractorInScene-v0_{}_True_distractor_config_more",
+ ]
+ table_texture_variants = [
+ "Baked_sc1_staging_objaverse_cabinet1_h870/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/GraspSingleOpenedCokeCanInScene-v0_{}_True",
+ "Baked_sc1_staging_objaverse_cabinet2_h870/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/GraspSingleOpenedCokeCanInScene-v0_{}_True",
+ ]
+ # camera_variants = [
+ # 'google_pick_coke_can_1_v4/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/GraspSingleOpenedCokeCanAltGoogleCameraInScene-v0_{}_True',
+ # 'google_pick_coke_can_1_v4/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/GraspSingleOpenedCokeCanAltGoogleCamera2InScene-v0_{}_True',
+ # ] # we only consider camera variants when investigating the effect of different robustness factors on the same policy's performance
+
+ for coke_can_orientation in coke_can_orientation_map_dict.keys():
+ for ckpt_alias in ckpt_alias_keys:
+ for variant in (
+ base_variants + background_variants + lighting_variants + distractor_variants + table_texture_variants
+ ):
+ variant = variant.format(coke_can_orientation_map_dict[coke_can_orientation])
+ variant = f"{root_result_dir}/{CKPT_MAPPING[ckpt_alias]}/{variant}"
+ avg_sim_success = np.mean(
+ get_dir_stats(
+ variant,
+ extra_pattern_require=extra_pattern_require_sim_variants,
+ )
+ )
+ if np.isnan(avg_sim_success):
+ print(f"WARNING: avg_sim_success is nan for {variant}")
+ coke_can_sim_variant_success[coke_can_orientation][ckpt_alias].append(avg_sim_success)
+
+ coke_can_sim_variant_success[coke_can_orientation][ckpt_alias] = np.mean(
+ coke_can_sim_variant_success[coke_can_orientation][ckpt_alias]
+ )
+
+ print("-" * 20)
+ for coke_can_orientation in coke_can_orientation_map_dict.keys():
+ print(
+ f"{coke_can_orientation} sim variant avg success",
+ coke_can_sim_variant_success[coke_can_orientation],
+ )
+ print(
+ f"{coke_can_orientation} real success",
+ coke_can_real_success[coke_can_orientation],
+ )
+ print(
+ f"{coke_can_orientation} MMRV",
+ mean_maximum_rank_violation(
+ list(coke_can_sim_variant_success[coke_can_orientation].values()),
+ list(coke_can_real_success[coke_can_orientation].values()),
+ ),
+ )
+ print(
+ f"{coke_can_orientation} pearson correlation",
+ pearson_correlation(
+ list(coke_can_sim_variant_success[coke_can_orientation].values()),
+ list(coke_can_real_success[coke_can_orientation].values()),
+ ),
+ )
+
+ avg_orientation_sim_variant_results = []
+ avg_orientation_real_results = []
+ for ckpt_alias in ckpt_alias_keys:
+ avg_orientation_sim_variant_results.append([])
+ avg_orientation_real_results.append([])
+ for coke_can_orientation in coke_can_orientation_map_dict.keys():
+ avg_orientation_sim_variant_results[-1].append(
+ coke_can_sim_variant_success[coke_can_orientation][ckpt_alias]
+ )
+ avg_orientation_real_results[-1].append(coke_can_real_success[coke_can_orientation][ckpt_alias])
+ avg_orientation_sim_variant_results[-1] = np.mean(avg_orientation_sim_variant_results[-1])
+ avg_orientation_real_results[-1] = np.mean(avg_orientation_real_results[-1])
+ print("avg_orientation_sim_variant_results", avg_orientation_sim_variant_results)
+ print("avg_orientation_real_results", avg_orientation_real_results)
+ print(
+ "mean_maximum_rank_violation(avg_orientation_sim_variant_results, avg_orientation_real_results)",
+ mean_maximum_rank_violation(avg_orientation_sim_variant_results, avg_orientation_real_results),
+ )
+ print(
+ "pearson_correlation(avg_orientation_sim_variant_results, avg_orientation_real_results)",
+ pearson_correlation(avg_orientation_sim_variant_results, avg_orientation_real_results),
+ )
+ print("-" * 20)
+
+ # get visual matching success
+ coke_can_sim_visual_matching_success = {
+ k1: {k2: [] for k2 in ckpt_alias_keys} for k1 in coke_can_orientation_map_dict.keys()
+ }
+ for coke_can_orientation in coke_can_orientation_map_dict.keys():
+ for ckpt_alias in ckpt_alias_keys:
+ for variant in base_visual_matching_variants:
+ variant = variant.format(coke_can_orientation_map_dict[coke_can_orientation])
+ variant = f"{root_result_dir}/{CKPT_MAPPING[ckpt_alias]}/{variant}"
+ avg_sim_success = np.mean(
+ get_dir_stats(
+ variant,
+ extra_pattern_require=extra_pattern_require_visual_matching,
+ )
+ )
+ if np.isnan(avg_sim_success):
+ print(f"WARNING: avg_sim_success is nan for {variant}")
+ coke_can_sim_visual_matching_success[coke_can_orientation][ckpt_alias].append(avg_sim_success)
+ print(f"Orientation {coke_can_orientation}, ckpt {ckpt_alias} all robot arm visual matching success: {coke_can_sim_visual_matching_success[coke_can_orientation][ckpt_alias]}")
+ coke_can_sim_visual_matching_success[coke_can_orientation][ckpt_alias] = np.mean(
+ coke_can_sim_visual_matching_success[coke_can_orientation][ckpt_alias]
+ )
+
+ for coke_can_orientation in coke_can_orientation_map_dict.keys():
+ print(
+ f"{coke_can_orientation} visual matching sim success",
+ coke_can_sim_visual_matching_success[coke_can_orientation],
+ )
+ print(
+ f"{coke_can_orientation} real success",
+ coke_can_real_success[coke_can_orientation],
+ )
+ print(
+ f"{coke_can_orientation} MMRV",
+ mean_maximum_rank_violation(
+ list(coke_can_sim_visual_matching_success[coke_can_orientation].values()),
+ list(coke_can_real_success[coke_can_orientation].values()),
+ ),
+ )
+ print(
+ f"{coke_can_orientation} pearson correlation",
+ pearson_correlation(
+ list(coke_can_sim_visual_matching_success[coke_can_orientation].values()),
+ list(coke_can_real_success[coke_can_orientation].values()),
+ ),
+ )
+ print_all_kruskal_results(
+ construct_unordered_trial_results(
+ n_trials_per_ckpt_per_orientation,
+ list(coke_can_sim_visual_matching_success[coke_can_orientation].values()),
+ ),
+ construct_unordered_trial_results(
+ n_trials_per_ckpt_per_orientation,
+ list(coke_can_real_success[coke_can_orientation].values()),
+ ),
+ f"{coke_can_orientation} kruskal:",
+ )
+
+ avg_orientation_sim_visual_matching_results = []
+ avg_orientation_real_results = []
+ for ckpt_alias in ckpt_alias_keys:
+ avg_orientation_sim_visual_matching_results.append([])
+ avg_orientation_real_results.append([])
+ for coke_can_orientation in coke_can_orientation_map_dict.keys():
+ avg_orientation_sim_visual_matching_results[-1].append(
+ coke_can_sim_visual_matching_success[coke_can_orientation][ckpt_alias]
+ )
+ avg_orientation_real_results[-1].append(coke_can_real_success[coke_can_orientation][ckpt_alias])
+ avg_orientation_sim_visual_matching_results[-1] = np.mean(avg_orientation_sim_visual_matching_results[-1])
+ avg_orientation_real_results[-1] = np.mean(avg_orientation_real_results[-1])
+ print(
+ "avg_orientation_sim_visual_matching_results",
+ avg_orientation_sim_visual_matching_results,
+ )
+ print("avg_orientation_real_results", avg_orientation_real_results)
+ print(
+ "mean_maximum_rank_violation(avg_orientation_sim_visual_matching_results, avg_orientation_real_results)",
+ mean_maximum_rank_violation(avg_orientation_sim_visual_matching_results, avg_orientation_real_results),
+ )
+ print(
+ "pearson_correlation(avg_orientation_sim_visual_matching_results, avg_orientation_real_results)",
+ pearson_correlation(avg_orientation_sim_visual_matching_results, avg_orientation_real_results),
+ )
+ print_all_kruskal_results(
+ construct_unordered_trial_results(
+ n_trials_per_ckpt_per_orientation * n_orientations,
+ avg_orientation_sim_visual_matching_results,
+ ),
+ construct_unordered_trial_results(
+ n_trials_per_ckpt_per_orientation * n_orientations,
+ avg_orientation_real_results,
+ ),
+ "avg kruskal:",
+ )
+
+ print("*" * 20)
+ for _ in range(3):
+ print()
+
+
+def calc_move_near_stats(root_result_dir):
+ print("***Move Near results***")
+ # If you use a new checkpoint, please update the real evaluation results here
+ move_near_real_success = {
+ "QWenACT": 0.0,
+ }
+
+ ckpt_alias_keys = list(move_near_real_success.keys())
+ n_trials_per_ckpt = 60 # number of trials per checkpoint; update if it's different
+
+ # extra patterns required in file name; if you are using different visual matching overlay image, please update here
+ extra_pattern_require_sim_variants = ["rgb_overlay_None"]
+ extra_pattern_require_visual_matching = ["rgb_overlay_google_move_near_real_eval_1"]
+
+ # get simulation variant success
+ move_near_sim_variant_success = {k: [] for k in ckpt_alias_keys}
+
+ # hardcoded variant aggregation result dirs; if you have new variants, please update here
+ base_variants = [
+ "google_pick_coke_can_1_v4/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/MoveNearGoogleInScene-v0",
+ ]
+ base_visual_matching_variants = []
+ for visual_matching_urdf_version in [
+ "None",
+ "recolor_tabletop_visual_matching_1",
+ "recolor_tabletop_visual_matching_2",
+ "recolor_cabinet_visual_matching_1",
+ ]:
+ base_visual_matching_variants.append(
+ f"google_pick_coke_can_1_v4/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/MoveNearGoogleBakedTexInScene-v0_urdf_version_{visual_matching_urdf_version}_baked_except_bpb_orange"
+ )
+
+ background_variants = [
+ "google_pick_coke_can_1_v4_alt_background/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/MoveNearGoogleInScene-v0",
+ "google_pick_coke_can_1_v4_alt_background_2/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/MoveNearGoogleInScene-v0",
+ ]
+ lighting_variants = [
+ "google_pick_coke_can_1_v4/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/MoveNearGoogleInScene-v0_slightly_brighter_lighting_True",
+ "google_pick_coke_can_1_v4/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/MoveNearGoogleInScene-v0_slightly_darker_lighting_True",
+ ]
+ distractor_variants = [
+ "google_pick_coke_can_1_v4/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/MoveNearGoogleInScene-v0_no_distractor_True",
+ ]
+ table_texture_variants = [
+ "Baked_sc1_staging_objaverse_cabinet1_h870/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/MoveNearGoogleInScene-v0",
+ "Baked_sc1_staging_objaverse_cabinet2_h870/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/MoveNearGoogleInScene-v0",
+ ]
+ # camera_variants = [
+ # 'google_pick_coke_can_1_v4/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/MoveNearAltGoogleCameraInScene-v0',
+ # 'google_pick_coke_can_1_v4/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/MoveNearAltGoogleCamera2InScene-v0',
+ # ] # we only consider camera variants when investigating the effect of different robustness factors on the same policy's performance
+
+ for ckpt_alias in ckpt_alias_keys:
+ for variant in (
+ base_variants + background_variants + lighting_variants + distractor_variants + table_texture_variants
+ ):
+ variant = f"{root_result_dir}/{CKPT_MAPPING[ckpt_alias]}/{variant}"
+ avg_sim_success = np.mean(get_dir_stats(variant, extra_pattern_require=extra_pattern_require_sim_variants))
+ if np.isnan(avg_sim_success):
+ print(f"WARNING: avg_sim_success is nan for {variant}")
+ move_near_sim_variant_success[ckpt_alias].append(avg_sim_success)
+ move_near_sim_variant_success[ckpt_alias] = np.mean(move_near_sim_variant_success[ckpt_alias])
+
+ print("-" * 20)
+ print("sim variant avg success", move_near_sim_variant_success)
+ print("real success", move_near_real_success)
+ print(
+ "MMRV",
+ mean_maximum_rank_violation(
+ list(move_near_sim_variant_success.values()),
+ list(move_near_real_success.values()),
+ ),
+ )
+ print(
+ "pearson correlation",
+ pearson_correlation(
+ list(move_near_sim_variant_success.values()),
+ list(move_near_real_success.values()),
+ ),
+ )
+ print("-" * 20)
+
+ # get visual matching success
+ move_near_sim_visual_matching_success = {k: [] for k in ckpt_alias_keys}
+ for ckpt_alias in ckpt_alias_keys:
+ for variant in base_visual_matching_variants:
+ variant = f"{root_result_dir}/{CKPT_MAPPING[ckpt_alias]}/{variant}"
+ avg_sim_success = np.mean(
+ get_dir_stats(variant, extra_pattern_require=extra_pattern_require_visual_matching)
+ )
+ if np.isnan(avg_sim_success):
+ print(f"WARNING: avg_sim_success is nan for {variant}")
+ move_near_sim_visual_matching_success[ckpt_alias].append(avg_sim_success)
+
+ print(f"Ckpt {ckpt_alias} all robot arm visual matching success: {move_near_sim_visual_matching_success[ckpt_alias]}")
+ move_near_sim_visual_matching_success[ckpt_alias] = np.mean(move_near_sim_visual_matching_success[ckpt_alias])
+
+
+ print("sim visual matching success", move_near_sim_visual_matching_success)
+ print("real success", move_near_real_success)
+ print(
+ "visual matching MMRV",
+ mean_maximum_rank_violation(
+ list(move_near_sim_visual_matching_success.values()),
+ list(move_near_real_success.values()),
+ ),
+ )
+ print(
+ "visual matching pearson correlation",
+ pearson_correlation(
+ list(move_near_sim_visual_matching_success.values()),
+ list(move_near_real_success.values()),
+ ),
+ )
+ print_all_kruskal_results(
+ construct_unordered_trial_results(n_trials_per_ckpt, list(move_near_sim_visual_matching_success.values())),
+ construct_unordered_trial_results(n_trials_per_ckpt, list(move_near_real_success.values())),
+ "avg kruskal:",
+ )
+
+ print("*" * 20)
+ for _ in range(3):
+ print()
+
+
+def calc_drawer_stats(root_result_dir):
+ print("***Drawer results***")
+ # If you use a new checkpoint, please update the real evaluation results here
+ drawer_real_success = {
+ "open": {
+ "QWenACT": 0.0,
+ },
+ "close": {
+ "QWenACT": 0.0,
+ },
+ }
+
+ ckpt_alias_keys = list(drawer_real_success["open"].keys())
+ drawer_task_map_dict = {
+ "open": [
+ "OpenTopDrawerCustomInScene-v0",
+ "OpenMiddleDrawerCustomInScene-v0",
+ "OpenBottomDrawerCustomInScene-v0",
+ ],
+ "close": [
+ "CloseTopDrawerCustomInScene-v0",
+ "CloseMiddleDrawerCustomInScene-v0",
+ "CloseBottomDrawerCustomInScene-v0",
+ ],
+ }
+ n_tasks = len(drawer_task_map_dict)
+ n_trials_per_ckpt_per_task = (
+ 27 # number of trials per checkpoint for all open / all close tasks; update if it is different
+ )
+ # extra patterns required in file name; if you are using different visual matching overlay image, please update here
+ extra_pattern_require_sim_variants = ["rgb_overlay_None"]
+ extra_pattern_require_visual_matching = ["rgb_overlay_open_drawer"]
+
+ # get simulation variant success
+ drawer_sim_variant_success = {k1: {k2: [] for k2 in ckpt_alias_keys} for k1 in drawer_task_map_dict.keys()}
+
+ # hardcoded variant aggregation result dirs; if you have new variants, please update here
+ base_variants = [
+ "frl_apartment_stage_simple/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/{}_shader_dir_rt",
+ ]
+ base_visual_matching_variants = []
+ for visual_matching_urdf_version in [
+ "None",
+ "recolor_tabletop_visual_matching_1",
+ "recolor_tabletop_visual_matching_2",
+ "recolor_cabinet_visual_matching_1",
+ ]:
+ urdf_version_str = f"urdf_version_{visual_matching_urdf_version}"
+ base_visual_matching_variants.append(
+ "dummy_drawer/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/{}_shader_dir_rt_station_name_mk_station_recolor_light_mode_simple_disable_bad_material_True_"
+ + urdf_version_str
+ )
+
+ background_variants = [
+ "modern_bedroom_no_roof/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/{}_shader_dir_rt",
+ "modern_office_no_roof/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/{}_shader_dir_rt",
+ ]
+ lighting_variants = [
+ "frl_apartment_stage_simple/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/{}_shader_dir_rt_light_mode_brighter",
+ "frl_apartment_stage_simple/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/{}_shader_dir_rt_light_mode_darker",
+ ]
+ table_texture_variants = [
+ "frl_apartment_stage_simple/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/{}_shader_dir_rt_station_name_mk_station2",
+ "frl_apartment_stage_simple/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/{}_shader_dir_rt_station_name_mk_station3",
+ ]
+
+ for drawer_task in drawer_task_map_dict.keys():
+ for ckpt_alias in ckpt_alias_keys:
+ for specific_task in drawer_task_map_dict[drawer_task]:
+ for variant in base_variants + background_variants + lighting_variants + table_texture_variants:
+ variant = variant.format(specific_task)
+ variant = f"{root_result_dir}/{CKPT_MAPPING[ckpt_alias]}/{variant}"
+ avg_sim_success = np.mean(
+ get_dir_stats(
+ variant,
+ extra_pattern_require=extra_pattern_require_sim_variants,
+ )
+ )
+ # OpenBottomDrawerCustomInScene-v0_shader_dir_rt_station_name_mk_station3
+ if np.isnan(avg_sim_success):
+ print(f"WARNING: avg_sim_success is nan for {variant}")
+ drawer_sim_variant_success[drawer_task][ckpt_alias].append(avg_sim_success)
+ drawer_sim_variant_success[drawer_task][ckpt_alias] = np.mean(
+ drawer_sim_variant_success[drawer_task][ckpt_alias]
+ )
+
+ print("-" * 20)
+ for drawer_task in drawer_task_map_dict.keys():
+ print(
+ f"{drawer_task} sim variant avg success",
+ drawer_sim_variant_success[drawer_task],
+ )
+ print(f"{drawer_task} real success", drawer_real_success[drawer_task])
+ print(
+ f"{drawer_task} MMRV",
+ mean_maximum_rank_violation(
+ list(drawer_sim_variant_success[drawer_task].values()),
+ list(drawer_real_success[drawer_task].values()),
+ ),
+ )
+ print(
+ f"{drawer_task} pearson correlation",
+ pearson_correlation(
+ list(drawer_sim_variant_success[drawer_task].values()),
+ list(drawer_real_success[drawer_task].values()),
+ ),
+ )
+
+ avg_sim_variant_results = []
+ avg_real_results = []
+ for ckpt_alias in ckpt_alias_keys:
+ avg_sim_variant_results.append([])
+ avg_real_results.append([])
+ for drawer_task in drawer_task_map_dict.keys():
+ avg_sim_variant_results[-1].append(drawer_sim_variant_success[drawer_task][ckpt_alias])
+ avg_real_results[-1].append(drawer_real_success[drawer_task][ckpt_alias])
+ avg_sim_variant_results[-1] = np.mean(avg_sim_variant_results[-1])
+ avg_real_results[-1] = np.mean(avg_real_results[-1])
+ print("avg_sim_variant_results", avg_sim_variant_results)
+ print("avg_real_results", avg_real_results)
+ print(
+ "mean_maximum_rank_violation(avg_sim_variant_results, avg_real_results)",
+ mean_maximum_rank_violation(avg_sim_variant_results, avg_real_results),
+ )
+ print(
+ "pearson_correlation(avg_sim_variant_results, avg_real_results)",
+ pearson_correlation(avg_sim_variant_results, avg_real_results),
+ )
+ print("-" * 20)
+
+ # get visual matching success
+ drawer_sim_visual_matching_success = {k1: {k2: [] for k2 in ckpt_alias_keys} for k1 in drawer_task_map_dict.keys()}
+ for drawer_task in drawer_task_map_dict.keys():
+ for ckpt_alias in ckpt_alias_keys:
+ for specific_task in drawer_task_map_dict[drawer_task]:
+ for variant in base_visual_matching_variants:
+ variant = variant.format(specific_task)
+ variant = f"{root_result_dir}/{CKPT_MAPPING[ckpt_alias]}/{variant}"
+ avg_sim_success = np.mean(
+ get_dir_stats(
+ variant,
+ extra_pattern_require=extra_pattern_require_visual_matching,
+ )
+ )
+ if np.isnan(avg_sim_success):
+ print(f"WARNING: avg_sim_success is nan for {variant}")
+ drawer_sim_visual_matching_success[drawer_task][ckpt_alias].append(avg_sim_success)
+ tmp_variant_avg_each_robot_arm = []
+ for i in range(len(base_visual_matching_variants)):
+ tmp_variant_avg_each_robot_arm.append(
+ np.mean(drawer_sim_visual_matching_success[drawer_task][ckpt_alias][i::len(drawer_task_map_dict[drawer_task])])
+ )
+ print(f"Drawer task {drawer_task}, ckpt {ckpt_alias} all robot arm visual matching success: {tmp_variant_avg_each_robot_arm}")
+ drawer_sim_visual_matching_success[drawer_task][ckpt_alias] = np.mean(
+ drawer_sim_visual_matching_success[drawer_task][ckpt_alias]
+ )
+
+ for drawer_task in drawer_task_map_dict.keys():
+ print(
+ f"{drawer_task} visual matching sim success",
+ drawer_sim_visual_matching_success[drawer_task],
+ )
+ print(f"{drawer_task} real success", drawer_real_success[drawer_task])
+ print(
+ f"{drawer_task} MMRV",
+ mean_maximum_rank_violation(
+ list(drawer_sim_visual_matching_success[drawer_task].values()),
+ list(drawer_real_success[drawer_task].values()),
+ ),
+ )
+ print(
+ f"{drawer_task} pearson correlation",
+ pearson_correlation(
+ list(drawer_sim_visual_matching_success[drawer_task].values()),
+ list(drawer_real_success[drawer_task].values()),
+ ),
+ )
+ print_all_kruskal_results(
+ construct_unordered_trial_results(
+ n_trials_per_ckpt_per_task,
+ list(drawer_sim_visual_matching_success[drawer_task].values()),
+ ),
+ construct_unordered_trial_results(
+ n_trials_per_ckpt_per_task,
+ list(drawer_real_success[drawer_task].values()),
+ ),
+ f"{drawer_task} kruskal:",
+ )
+
+ avg_sim_visual_matching_results = []
+ avg_real_results = []
+ for ckpt_alias in ckpt_alias_keys:
+ avg_sim_visual_matching_results.append([])
+ avg_real_results.append([])
+ for drawer_task in drawer_task_map_dict.keys():
+ avg_sim_visual_matching_results[-1].append(drawer_sim_visual_matching_success[drawer_task][ckpt_alias])
+ avg_real_results[-1].append(drawer_real_success[drawer_task][ckpt_alias])
+ avg_sim_visual_matching_results[-1] = np.mean(avg_sim_visual_matching_results[-1])
+ avg_real_results[-1] = np.mean(avg_real_results[-1])
+ print("avg_sim_visual_matching_results", avg_sim_visual_matching_results)
+ print("avg_real_results", avg_real_results)
+ print(
+ "mean_maximum_rank_violation(avg_sim_visual_matching_results, avg_real_results)",
+ mean_maximum_rank_violation(avg_sim_visual_matching_results, avg_real_results),
+ )
+ print(
+ "pearson_correlation(avg_sim_visual_matching_results, avg_real_results)",
+ pearson_correlation(avg_sim_visual_matching_results, avg_real_results),
+ )
+ print_all_kruskal_results(
+ construct_unordered_trial_results(n_trials_per_ckpt_per_task * n_tasks, avg_sim_visual_matching_results),
+ construct_unordered_trial_results(n_trials_per_ckpt_per_task * n_tasks, avg_real_results),
+ "avg kruskal:",
+ )
+
+ print("*" * 20)
+ for _ in range(3):
+ print()
+
+
+def calc_long_horizon_apple_in_drawer_stats(root_result_dir):
+ print("***Drawer results***")
+ # If you use a new checkpoint, please update the real evaluation results here
+ drawer_real_success = {
+ "put_apple_into_top_drawer": {
+ "QWenACT": 0.0,
+ },
+ }
+
+ ckpt_alias_keys = list(drawer_real_success["put_apple_into_top_drawer"].keys())
+ drawer_task_map_dict = {
+ "put_apple_into_top_drawer": [
+ "PlaceIntoClosedTopDrawerCustomInScene-v0",
+ ],
+ }
+ n_tasks = len(drawer_task_map_dict)
+ n_trials_per_ckpt_per_task = (
+ 27 # number of trials per checkpoint for each key in drawer_task_map_dict; update if it is different
+ )
+ # extra patterns required in file name; if you are using different visual matching overlay image, please update here
+ extra_pattern_require_sim_variants = ["rgb_overlay_None", "apple"]
+ extra_pattern_require_visual_matching = ["rgb_overlay_open_drawer", "apple"]
+ extra_log_str_variant_agg = "model_ids_apple"
+ extra_log_str_visual_matching = "model_ids_baked_apple_v2"
+
+ # get simulation variant success
+ drawer_sim_variant_success = {k1: {k2: [] for k2 in ckpt_alias_keys} for k1 in drawer_task_map_dict.keys()}
+
+ # hardcoded variant aggregation result dirs; if you have new variants, please update here
+ base_variants = [
+ "frl_apartment_stage_simple/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/{}_shader_dir_rt",
+ ]
+ base_visual_matching_variants = []
+ for visual_matching_urdf_version in [
+ "None",
+ "recolor_tabletop_visual_matching_1",
+ "recolor_tabletop_visual_matching_2",
+ "recolor_cabinet_visual_matching_1",
+ ]:
+ urdf_version_str = f"urdf_version_{visual_matching_urdf_version}"
+ base_visual_matching_variants.append(
+ "dummy_drawer/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/{}_shader_dir_rt_station_name_mk_station_recolor_light_mode_simple_disable_bad_material_True_"
+ + urdf_version_str
+ )
+
+ background_variants = [
+ "modern_bedroom_no_roof/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/{}_shader_dir_rt",
+ "modern_office_no_roof/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/{}_shader_dir_rt",
+ ]
+ lighting_variants = [
+ "frl_apartment_stage_simple/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/{}_shader_dir_rt_light_mode_brighter",
+ "frl_apartment_stage_simple/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/{}_shader_dir_rt_light_mode_darker",
+ ]
+ table_texture_variants = [
+ "frl_apartment_stage_simple/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/{}_shader_dir_rt_station_name_mk_station2",
+ "frl_apartment_stage_simple/arm_pd_ee_delta_pose_align_interpolate_by_planner_gripper_pd_joint_target_delta_pos_interpolate_by_planner/{}_shader_dir_rt_station_name_mk_station3",
+ ]
+
+ for drawer_task in drawer_task_map_dict.keys():
+ for ckpt_alias in ckpt_alias_keys:
+ for specific_task in drawer_task_map_dict[drawer_task]:
+ for variant in base_variants + background_variants + lighting_variants + table_texture_variants:
+ variant = variant.format(specific_task) + f"_{extra_log_str_variant_agg}"
+ variant = f"{root_result_dir}/{CKPT_MAPPING[ckpt_alias]}/{variant}"
+ avg_sim_success = np.mean(
+ get_dir_stats(
+ variant,
+ extra_pattern_require=extra_pattern_require_sim_variants,
+ )
+ )
+ if np.isnan(avg_sim_success):
+ print(f"WARNING: avg_sim_success is nan for {variant}")
+ drawer_sim_variant_success[drawer_task][ckpt_alias].append(avg_sim_success)
+ drawer_sim_variant_success[drawer_task][ckpt_alias] = np.mean(
+ drawer_sim_variant_success[drawer_task][ckpt_alias]
+ )
+
+ print("-" * 20)
+ for drawer_task in drawer_task_map_dict.keys():
+ print(
+ f"{drawer_task} sim variant avg success",
+ drawer_sim_variant_success[drawer_task],
+ )
+ print(f"{drawer_task} real success", drawer_real_success[drawer_task])
+ print(
+ f"{drawer_task} MMRV",
+ mean_maximum_rank_violation(
+ list(drawer_sim_variant_success[drawer_task].values()),
+ list(drawer_real_success[drawer_task].values()),
+ ),
+ )
+ print(
+ f"{drawer_task} pearson correlation",
+ pearson_correlation(
+ list(drawer_sim_variant_success[drawer_task].values()),
+ list(drawer_real_success[drawer_task].values()),
+ ),
+ )
+
+ avg_sim_variant_results = []
+ avg_real_results = []
+ for ckpt_alias in ckpt_alias_keys:
+ avg_sim_variant_results.append([])
+ avg_real_results.append([])
+ for drawer_task in drawer_task_map_dict.keys():
+ avg_sim_variant_results[-1].append(drawer_sim_variant_success[drawer_task][ckpt_alias])
+ avg_real_results[-1].append(drawer_real_success[drawer_task][ckpt_alias])
+ avg_sim_variant_results[-1] = np.mean(avg_sim_variant_results[-1])
+ avg_real_results[-1] = np.mean(avg_real_results[-1])
+ print("avg_sim_variant_results", avg_sim_variant_results)
+ print("avg_real_results", avg_real_results)
+ print(
+ "mean_maximum_rank_violation(avg_sim_variant_results, avg_real_results)",
+ mean_maximum_rank_violation(avg_sim_variant_results, avg_real_results),
+ )
+ print(
+ "pearson_correlation(avg_sim_variant_results, avg_real_results)",
+ pearson_correlation(avg_sim_variant_results, avg_real_results),
+ )
+ print("-" * 20)
+
+ # get visual matching success
+ drawer_sim_visual_matching_success = {k1: {k2: [] for k2 in ckpt_alias_keys} for k1 in drawer_task_map_dict.keys()}
+ for drawer_task in drawer_task_map_dict.keys():
+ for ckpt_alias in ckpt_alias_keys:
+ for specific_task in drawer_task_map_dict[drawer_task]:
+ for variant in base_visual_matching_variants:
+ variant = variant.format(specific_task) + f"_{extra_log_str_visual_matching}"
+ variant = f"{root_result_dir}/{CKPT_MAPPING[ckpt_alias]}/{variant}"
+ avg_sim_success = np.mean(
+ get_dir_stats(
+ variant,
+ extra_pattern_require=extra_pattern_require_visual_matching,
+ )
+ )
+ if np.isnan(avg_sim_success):
+ print(f"WARNING: avg_sim_success is nan for {variant}")
+ drawer_sim_visual_matching_success[drawer_task][ckpt_alias].append(avg_sim_success)
+ tmp_variant_avg_each_robot_arm = []
+ for i in range(len(base_visual_matching_variants)):
+ tmp_variant_avg_each_robot_arm.append(
+ np.mean(drawer_sim_visual_matching_success[drawer_task][ckpt_alias][i::len(drawer_task_map_dict[drawer_task])])
+ )
+ print(f"Drawer task {drawer_task}, ckpt {ckpt_alias} all robot arm visual matching success: {tmp_variant_avg_each_robot_arm}")
+ drawer_sim_visual_matching_success[drawer_task][ckpt_alias] = np.mean(
+ drawer_sim_visual_matching_success[drawer_task][ckpt_alias]
+ )
+
+ for drawer_task in drawer_task_map_dict.keys():
+ print(
+ f"{drawer_task} visual matching sim success",
+ drawer_sim_visual_matching_success[drawer_task],
+ )
+ print(f"{drawer_task} real success", drawer_real_success[drawer_task])
+ print(
+ f"{drawer_task} MMRV",
+ mean_maximum_rank_violation(
+ list(drawer_sim_visual_matching_success[drawer_task].values()),
+ list(drawer_real_success[drawer_task].values()),
+ ),
+ )
+ print(
+ f"{drawer_task} pearson correlation",
+ pearson_correlation(
+ list(drawer_sim_visual_matching_success[drawer_task].values()),
+ list(drawer_real_success[drawer_task].values()),
+ ),
+ )
+ print_all_kruskal_results(
+ construct_unordered_trial_results(
+ n_trials_per_ckpt_per_task,
+ list(drawer_sim_visual_matching_success[drawer_task].values()),
+ ),
+ construct_unordered_trial_results(
+ n_trials_per_ckpt_per_task,
+ list(drawer_real_success[drawer_task].values()),
+ ),
+ f"{drawer_task} kruskal:",
+ )
+
+ avg_sim_visual_matching_results = []
+ avg_real_results = []
+ for ckpt_alias in ckpt_alias_keys:
+ avg_sim_visual_matching_results.append([])
+ avg_real_results.append([])
+ for drawer_task in drawer_task_map_dict.keys():
+ avg_sim_visual_matching_results[-1].append(drawer_sim_visual_matching_success[drawer_task][ckpt_alias])
+ avg_real_results[-1].append(drawer_real_success[drawer_task][ckpt_alias])
+ avg_sim_visual_matching_results[-1] = np.mean(avg_sim_visual_matching_results[-1])
+ avg_real_results[-1] = np.mean(avg_real_results[-1])
+ print("avg_sim_visual_matching_results", avg_sim_visual_matching_results)
+ print("avg_real_results", avg_real_results)
+ print(
+ "mean_maximum_rank_violation(avg_sim_visual_matching_results, avg_real_results)",
+ mean_maximum_rank_violation(avg_sim_visual_matching_results, avg_real_results),
+ )
+ print(
+ "pearson_correlation(avg_sim_visual_matching_results, avg_real_results)",
+ pearson_correlation(avg_sim_visual_matching_results, avg_real_results),
+ )
+ print_all_kruskal_results(
+ construct_unordered_trial_results(n_trials_per_ckpt_per_task * n_tasks, avg_sim_visual_matching_results),
+ construct_unordered_trial_results(n_trials_per_ckpt_per_task * n_tasks, avg_real_results),
+ "avg kruskal:",
+ )
+
+ print("*" * 20)
+ for _ in range(3):
+ print()
+
+
+def calc_bridge_put_on_env_stats(root_result_dir):
+ print("***Bridge Put On Env results***")
+ # If you use a new checkpoint, please update the real evaluation results here
+ real_partial_success_dict = {
+ "put_spoon_on_tablecloth": {
+ "QWenACT": 0.0,
+ },
+ "put_carrot_on_plate": {
+ "QWenACT": 0.0,
+ },
+ "stack_green_block_on_yellow_block": {
+ "QWenACT": 0.0,
+ },
+ "put_eggplant_in_basket": {
+ "QWenACT": 0.0,
+ },
+ }
+ real_success_dict = {
+ "put_spoon_on_tablecloth": {
+ "QWenACT": 0.0,
+ },
+ "put_carrot_on_plate": {
+ "QWenACT": 0.0,
+ },
+ "stack_green_block_on_yellow_block": {
+ "QWenACT": 0.0,
+ },
+ "put_eggplant_in_basket": {
+ "QWenACT": 0.0,
+ },
+ }
+
+ tasks = list(real_success_dict.keys())
+ ckpt_alias_keys = list(real_success_dict[tasks[0]].keys())
+ n_trials_per_ckpt = 24 # number of trials per checkpoint; update if it's different
+ octo_seed_range = [
+ 0,
+ 2,
+ 4,
+ ] # we average octo performance over different random seeds to reduce variance
+
+ # extra patterns required in file name; if you are using different visual matching overlay image, please update here
+ extra_pattern_require_visual_matching = {
+ "put_spoon_on_tablecloth": "rgb_overlay_bridge_real_eval_1",
+ "put_carrot_on_plate": "rgb_overlay_bridge_real_eval_1",
+ "stack_green_block_on_yellow_block": "rgb_overlay_bridge_real_eval_1",
+ "put_eggplant_in_basket": "rgb_overlay_bridge_sink",
+ }
+
+ # hardcoded; if you have new variants, please update here
+ base_visual_matching_variants_dict = {
+ "put_spoon_on_tablecloth": [
+ "bridge_table_1_v1/arm_pd_ee_target_delta_pose_align2_gripper_pd_joint_pos/PutSpoonOnTableClothInScene-v0",
+ ],
+ "put_carrot_on_plate": [
+ "bridge_table_1_v1/arm_pd_ee_target_delta_pose_align2_gripper_pd_joint_pos/PutCarrotOnPlateInScene-v0",
+ ],
+ "stack_green_block_on_yellow_block": [
+ "bridge_table_1_v1/arm_pd_ee_target_delta_pose_align2_gripper_pd_joint_pos/StackGreenCubeOnYellowCubeBakedTexInScene-v0",
+ ],
+ "put_eggplant_in_basket": [
+ "bridge_table_1_v2/arm_pd_ee_target_delta_pose_align2_gripper_pd_joint_pos/PutEggplantInBasketScene-v0",
+ ],
+ }
+
+ # success pattern; if different, please update here
+ succ_fail_pattern = ["success_obj_episode", "failure_obj_episode"]
+ # partial success pattern; if different, please update here
+ partial_succ_fail_pattern = ["is_src_obj_grasped_True", "is_src_obj_grasped_False"]
+ # partial_succ_fail_pattern = ['consecutive_grasp_True', 'consecutive_grasp_False']
+
+ # get visual matching success
+ for task in tasks:
+ real_success = real_success_dict[task]
+ real_partial_success = real_partial_success_dict[task]
+ print("*" * 10, f"Results for {task}", "*" * 10)
+
+ sim_visual_matching_success = {k: [] for k in ckpt_alias_keys}
+ sim_visual_matching_partial_success = {k: [] for k in ckpt_alias_keys}
+ for ckpt_alias in ckpt_alias_keys:
+ base_visual_matching_variants = base_visual_matching_variants_dict[task]
+ if "octo" in ckpt_alias:
+ # we average octo performance over different random seeds
+ tmp = []
+ for seed in octo_seed_range:
+ tmp.extend([f"{variant}_octo_init_rng_{seed}" for variant in base_visual_matching_variants])
+ base_visual_matching_variants = tmp
+ for variant in base_visual_matching_variants:
+ variant = f"{root_result_dir}/{CKPT_MAPPING[ckpt_alias]}/{variant}"
+ avg_sim_success = np.mean(
+ get_dir_stats(
+ variant,
+ extra_pattern_require=extra_pattern_require_visual_matching[task],
+ succ_fail_pattern=succ_fail_pattern,
+ )
+ )
+ avg_sim_partial_success = np.mean(
+ get_dir_stats(
+ variant,
+ extra_pattern_require=extra_pattern_require_visual_matching[task],
+ succ_fail_pattern=partial_succ_fail_pattern,
+ )
+ )
+ if np.isnan(avg_sim_success) or np.isnan(avg_sim_partial_success):
+ print(f"WARNING: avg_sim_success is nan for {variant}")
+ sim_visual_matching_success[ckpt_alias].append(avg_sim_success)
+ sim_visual_matching_partial_success[ckpt_alias].append(avg_sim_partial_success)
+ sim_visual_matching_success[ckpt_alias] = np.mean(sim_visual_matching_success[ckpt_alias])
+ sim_visual_matching_partial_success[ckpt_alias] = np.mean(sim_visual_matching_partial_success[ckpt_alias])
+
+ print("sim visual matching partial success", sim_visual_matching_partial_success)
+ print("real partial success", real_partial_success)
+ print(
+ "visual matching MMRV (partial success)",
+ mean_maximum_rank_violation(
+ list(sim_visual_matching_partial_success.values()),
+ list(real_partial_success.values()),
+ ),
+ )
+ print(
+ "visual matching pearson correlation (partial success) ",
+ pearson_correlation(
+ list(sim_visual_matching_partial_success.values()),
+ list(real_partial_success.values()),
+ ),
+ )
+ print_all_kruskal_results(
+ construct_unordered_trial_results(n_trials_per_ckpt, list(sim_visual_matching_partial_success.values())),
+ construct_unordered_trial_results(n_trials_per_ckpt, list(real_partial_success.values())),
+ "avg kruskal (partial success):",
+ )
+
+ print("sim visual matching success", sim_visual_matching_success)
+ print("real success", real_success)
+ print(
+ "visual matching MMRV",
+ mean_maximum_rank_violation(list(sim_visual_matching_success.values()), list(real_success.values())),
+ )
+ print(
+ "visual matching pearson correlation",
+ pearson_correlation(list(sim_visual_matching_success.values()), list(real_success.values())),
+ )
+ print_all_kruskal_results(
+ construct_unordered_trial_results(n_trials_per_ckpt, list(sim_visual_matching_success.values())),
+ construct_unordered_trial_results(n_trials_per_ckpt, list(real_success.values())),
+ "avg kruskal:",
+ )
+
+ print("*" * 20)
+ for _ in range(3):
+ print()
+
+
+# Define checkpoint alias-to-directory mapping; If you use a new checkpoint, please update the dict
+
+CKPT_MAPPING = {
+ "rt-2-x": "rt_2_x",
+ "rt-1-converged": "rt_1_tf_trained_for_000400120",
+ "rt-1-15pct": "rt_1_tf_trained_for_000058240",
+ "rt-1-x": "rt_1_x_tf_trained_for_002272480_step",
+ "rt-1-begin": "rt_1_tf_trained_for_000001120",
+ "octo-base": "octo-base",
+ "octo-small": "octo-small",
+ "octo-server": "octo-server",
+ "QWenACT": "steps_33333_pytorch_model.pt",
+}
+
+
+parser = argparse.ArgumentParser()
+model_path = "/mnt/petrelfs/yejinhui/Projects/llavavla/results/Checkpoints/1_need/QwenGR00T/videos/steps_30000_pytorch_model.pt"
+
+# 获得 文件名字
+model_name = model_path.split("/")[-1]
+model_path = model_path.replace(model_name, "")
+parser.add_argument("--task", type=str, default="long_horizon_apple_in_drawer", help="task name")
+parser.add_argument("--log-dir-root", type=str, default=f"{model_path}", help="log directory")
+
+args = parser.parse_args()
+
+
+CKPT_MAPPING["QWenACT"] = model_name
+
+if args.task == "pick_coke_can":
+ calc_pick_coke_can_stats(args.log_dir_root)
+elif args.task == "move_near":
+ calc_move_near_stats(args.log_dir_root)
+elif args.task == "drawer":
+ calc_drawer_stats(args.log_dir_root)
+elif args.task == "long_horizon_apple_in_drawer":
+ calc_long_horizon_apple_in_drawer_stats(args.log_dir_root)
+elif args.task == "bridge_put_on":
+ calc_bridge_put_on_env_stats(args.log_dir_root)
+else:
+ raise ValueError(f"Unknown task: {args.task}")
+
+exit(0)
+
+"""
+octo-base variant aggregation:
+pick coke can ([horizontal, vertical, standing, avg]): default urdf [0.00, 0.00, 0.00, 0.00]; recolor_sim urdf [0.009, 0.00, 0.0267, 0.012]
+move near: default urdf 0.03125; recolor_sim urdf 0.033
+drawer ([open, close, avg]): default urdf [0.00, 0.021, 0.011]; recolor_sim urdf [0.00, 0.016, 0.008]
+"""
\ No newline at end of file
diff --git a/examples/SimplerEnv/eval_files/auto_eval_scripts/check_ports_range.sh b/examples/SimplerEnv/eval_files/auto_eval_scripts/check_ports_range.sh
new file mode 100644
index 0000000000000000000000000000000000000000..128af47f6de293c6cf8d78bcecf5364e6bf762ad
--- /dev/null
+++ b/examples/SimplerEnv/eval_files/auto_eval_scripts/check_ports_range.sh
@@ -0,0 +1,18 @@
+#!/bin/bash
+# Check port availability ahead of time to prepare for parallel testing
+# Target port range
+start_port=5400
+end_port=5500
+
+echo "Checking whether ports ${start_port}-${end_port} are available..."
+
+for port in $(seq $start_port $end_port); do
+ # Determine if the port is already in use
+ if lsof -iTCP:$port -sTCP:LISTEN > /dev/null 2>&1; then
+ echo "Port $port is in use"
+ else
+ echo "Port $port is available"
+ fi
+done
+
+echo "Port check complete!"
\ No newline at end of file
diff --git a/examples/SimplerEnv/eval_files/auto_eval_scripts/star_bridge.sh b/examples/SimplerEnv/eval_files/auto_eval_scripts/star_bridge.sh
new file mode 100644
index 0000000000000000000000000000000000000000..cfd31f50deeb86ead86303c5ae6b98127aca2f61
--- /dev/null
+++ b/examples/SimplerEnv/eval_files/auto_eval_scripts/star_bridge.sh
@@ -0,0 +1,231 @@
+#!/bin/bash
+
+echo `which python`
+# Environment setup
+cd /mnt/petrelfs/yejinhui/Projects/starVLA
+export star_vla_python=/mnt/petrelfs/share/yejinhui/Envs/miniconda3/envs/starVLA/bin/python
+export sim_python=/mnt/petrelfs/share/yejinhui/Envs/miniconda3/envs/dinoact/bin/python
+export SimplerEnv_PATH=/mnt/petrelfs/share/yejinhui/Projects/SimplerEnv
+export PYTHONPATH=$(pwd):${PYTHONPATH}
+base_port=6350
+
+# export DEBUG=1
+
+
+MODEL_PATH=$1
+# MODEL_PATH=/mnt/petrelfs/yejinhui/Projects/starVLA/results/Checkpoints/1120_bridge_rt_1_QwenDual_florence/checkpoints/steps_11000_pytorch_model.pt
+TSET_NUM=4 # repeat each task 4 times
+run_count=0
+
+if [ -z "$MODEL_PATH" ]; then
+ echo "❌ MODEL_PATH not provided as the first argument; using default"
+ export MODEL_PATH="/mnt/petrelfs/yejinhui/Projects/starVLA/results/Checkpoints/1007_qwenLargefm/checkpoints/steps_20000_pytorch_model.pt"
+fi
+
+ckpt_path=${MODEL_PATH}
+
+# Helper to launch policy servers
+policyserver_pids=()
+eval_pids=()
+
+
+
+start_service() {
+ local gpu_id=$1
+ local ckpt_path=$2
+ local port=$3
+ local server_log_dir="$(dirname "${ckpt_path}")/server_logs"
+ local svc_log="${server_log_dir}/$(basename "${ckpt_path%.*}")_policy_server_${port}.log"
+ mkdir -p "${server_log_dir}"
+
+ # Pre-check the port and free it if already occupied
+ if lsof -iTCP:"${port}" -sTCP:LISTEN -t >/dev/null ; then
+ echo "⚠️ Port ${port} is occupied; attempting to free it..."
+ lsof -iTCP:"${port}" -sTCP:LISTEN -t | xargs kill -9
+ sleep 2
+ if lsof -iTCP:"${port}" -sTCP:LISTEN -t >/dev/null ; then
+ echo "❌ Unable to free port ${port}; please investigate manually"
+ exit 1
+ else
+ echo "✅ Port ${port} successfully freed"
+ fi
+ fi
+ echo "▶️ Starting service on GPU ${gpu_id}, port ${port}"
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${star_vla_python} deployment/model_server/server_policy.py \
+ --ckpt_path ${ckpt_path} \
+ --port ${port} \
+ --use_bf16 \
+ > "${svc_log}" 2>&1 &
+
+ local pid=$! # capture PID immediately
+ policyserver_pids+=($pid)
+ sleep 10
+}
+
+# Helper to stop every service
+stop_all_services() {
+ # Wait for every evaluation job to complete
+ if [ "${#eval_pids[@]}" -gt 0 ]; then
+ echo "⏳ Waiting for evaluation jobs to finish..."
+ for pid in "${eval_pids[@]}"; do
+ if ps -p "$pid" > /dev/null 2>&1; then
+ wait "$pid"
+ status=$?
+ if [ $status -ne 0 ]; then
+ echo "Warning: evaluation job $pid exited abnormally (status: $status)"
+ fi
+ fi
+ done
+ fi
+
+ # Stop all services
+ if [ "${#policyserver_pids[@]}" -gt 0 ]; then
+ echo "⏳ Stopping service processes..."
+ for pid in "${policyserver_pids[@]}"; do
+ if ps -p "$pid" > /dev/null 2>&1; then
+ kill "$pid" 2>/dev/null
+ wait "$pid" 2>/dev/null
+ else
+ echo "⚠️ Service process $pid no longer exists (might have exited early)"
+ fi
+ done
+ fi
+
+ # Clear PID arrays
+ eval_pids=()
+ policyserver_pids=()
+ echo "✅ All services and tasks stopped"
+}
+
+# Retrieve CUDA_VISIBLE_DEVICES list on this host
+IFS=',' read -r -a CUDA_DEVICES <<< "$CUDA_VISIBLE_DEVICES" # convert comma-separated GPU list to an array
+NUM_GPUS=${#CUDA_DEVICES[@]} # count available GPUs
+
+
+
+# Debug info
+echo "CUDA_VISIBLE_DEVICES: $CUDA_VISIBLE_DEVICES"
+echo "CUDA_DEVICES: ${CUDA_DEVICES[@]}"
+echo "NUM_GPUS: $NUM_GPUS"
+
+scene_name=bridge_table_1_v1
+robot=widowx
+rgb_overlay_path=${SimplerEnv_PATH}/ManiSkill2_real2sim/data/real_inpainting/bridge_real_eval_1.png
+robot_init_x=0.147
+robot_init_y=0.028
+
+# Task list: each entry defines an env-name
+declare -a ENV_NAMES=(
+ StackGreenCubeOnYellowCubeBakedTexInScene-v0
+ PutCarrotOnPlateInScene-v0
+ PutSpoonOnTableClothInScene-v0
+)
+
+
+for i in "${!ENV_NAMES[@]}"; do
+ env="${ENV_NAMES[i]}"
+ for ((run_idx=1; run_idx<=TSET_NUM; run_idx++)); do
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]}
+
+ ckpt_dir=$(dirname "${ckpt_path}")
+ ckpt_base=$(basename "${ckpt_path}")
+ ckpt_name="${ckpt_base%.*}" # strip .pt or .bin suffix
+
+ tag="run${run_idx}"
+ task_log="${ckpt_dir}/${ckpt_name}_infer_${env}.log.${tag}"
+
+ echo "▶️ Launching task [${env}] run#${run_idx} on GPU $gpu_id, log → ${task_log}"
+
+ # Launch service and capture the process ID
+ port=$((base_port + run_count))
+ start_service ${gpu_id} ${ckpt_path} ${port}
+
+
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/eval_files/start_simpler_env.py \
+ --port $port \
+ --ckpt-path ${ckpt_path} \
+ --robot ${robot} \
+ --policy-setup widowx_bridge \
+ --control-freq 5 \
+ --sim-freq 500 \
+ --max-episode-steps 120 \
+ --env-name "${env}" \
+ --scene-name ${scene_name} \
+ --rgb-overlay-path ${rgb_overlay_path} \
+ --robot-init-x ${robot_init_x} ${robot_init_x} 1 \
+ --robot-init-y ${robot_init_y} ${robot_init_y} 1 \
+ --obj-variation-mode episode \
+ --obj-episode-range 0 24 \
+ --robot-init-rot-quat-center 0 0 0 1 \
+ --robot-init-rot-rpy-range 0 0 1 0 0 1 0 0 1 \
+ > "${task_log}" 2>&1 &
+
+ eval_pids+=($!)
+ run_count=$((run_count + 1))
+ done
+done
+
+# V2 variant: run PutEggplantInBasketScene-v0 five times as well
+declare -a ENV_NAMES_V2=(
+ PutEggplantInBasketScene-v0
+)
+
+scene_name=bridge_table_1_v2
+robot=widowx_sink_camera_setup
+
+rgb_overlay_path=${SimplerEnv_PATH}/ManiSkill2_real2sim/data/real_inpainting/bridge_sink.png
+robot_init_x=0.127
+robot_init_y=0.06
+
+for i in "${!ENV_NAMES_V2[@]}"; do
+ env="${ENV_NAMES_V2[i]}"
+ for ((run_idx=1; run_idx<=TSET_NUM; run_idx++)); do
+ gpu_id=${CUDA_DEVICES[$(((run_count) % NUM_GPUS))]} # map to GPU ID in CUDA_VISIBLE_DEVICES
+ ckpt_dir=$(dirname "${ckpt_path}")
+ ckpt_base=$(basename "${ckpt_path}")
+ ckpt_name="${ckpt_base%.*}"
+
+ tag="run${run_idx}"
+ task_log="${ckpt_dir}/${ckpt_name}_infer_${env}.log.${tag}"
+
+ echo "▶️ Launching V2 task [${env}] run#${run_idx} on GPU $gpu_id, log → ${task_log}"
+
+ # Launch service and capture the process ID
+ echo "server start run#${run_idx}"
+ port=$((base_port + run_count))
+ server_pid=$(start_service ${gpu_id} ${ckpt_path} ${port})
+
+ echo "sim start run#${run_idx}"
+ ${sim_python} examples/SimplerEnv/eval_files/start_simpler_env.py \
+ --ckpt-path ${ckpt_path} \
+ --port $port \
+ --robot ${robot} \
+ --policy-setup widowx_bridge \
+ --control-freq 5 \
+ --sim-freq 500 \
+ --max-episode-steps 120 \
+ --env-name "${env}" \
+ --scene-name ${scene_name} \
+ --rgb-overlay-path ${rgb_overlay_path} \
+ --robot-init-x ${robot_init_x} ${robot_init_x} 1 \
+ --robot-init-y ${robot_init_y} ${robot_init_y} 1 \
+ --obj-variation-mode episode \
+ --obj-episode-range 0 24 \
+ --robot-init-rot-quat-center 0 0 0 1 \
+ --robot-init-rot-rpy-range 0 0 1 0 0 1 0 0 1 \
+ 2>&1 | tee "${task_log}" &
+
+ eval_pids+=($!)
+ echo "sim end run#${run_idx}"
+
+ run_count=$((run_count + 1))
+ done
+done
+
+
+
+stop_all_services
+wait
+echo "✅ All evaluations finished"
+
+
diff --git a/examples/SimplerEnv/eval_files/auto_eval_scripts/star_drawer_variant_agg.sh b/examples/SimplerEnv/eval_files/auto_eval_scripts/star_drawer_variant_agg.sh
new file mode 100644
index 0000000000000000000000000000000000000000..8241ad950e2b9abd11984e820127705ee376782a
--- /dev/null
+++ b/examples/SimplerEnv/eval_files/auto_eval_scripts/star_drawer_variant_agg.sh
@@ -0,0 +1,235 @@
+# Use all 8 GPUs and run tasks in the background
+
+
+
+# Environment setup
+cd /mnt/petrelfs/yejinhui/Projects/llavavla
+export starvla_python=/mnt/petrelfs/share/yejinhui/Envs/miniconda3/envs/starvlaSAM/bin/python
+export sim_python=/mnt/petrelfs/share/yejinhui/Envs/miniconda3/envs/dinoact/bin/python
+export SimplerEnv_PATH=/mnt/petrelfs/share/yejinhui/Projects/SimplerEnv
+export PYTHONPATH=$(pwd):${PYTHONPATH}
+base_port=5500
+
+MODEL_PATH=$1
+
+# Optional: allow overriding via argument
+if [ -z "$MODEL_PATH" ]; then
+ echo "❌ MODEL_PATH not provided as the first argument; using default"
+ export MODEL_PATH="/mnt/petrelfs/yejinhui/Projects/llavavla/results/Checkpoints/1_need/QwenGR00T/checkpoints/steps_30000_pytorch_model.pt"
+fi
+
+export ckpt_path=${MODEL_PATH}
+
+# Helper to launch policy servers
+policyserver_pids=()
+eval_pids=()
+
+task_name=drawer_va
+
+
+start_service() {
+ local gpu_id=$1
+ local ckpt_path=$2
+ local port=$3
+ local server_log_dir="$(dirname "${ckpt_path}")/server_logs"
+ local svc_log="${server_log_dir}/$(basename "${ckpt_path%.*}")_${task_name}_${port}.log"
+ mkdir -p "${server_log_dir}"
+
+ echo "▶️ Starting service on GPU ${gpu_id}, port ${port}"
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${starvla_python} deployment/model_server/server_policy.py \
+ --ckpt_path ${ckpt_path} \
+ --port ${port} \
+ --use_bf16 \
+ > "${svc_log}" 2>&1 &
+
+ local pid=$! # Capture PID immediately
+ policyserver_pids+=($pid)
+ sleep 20
+}
+
+# Helper to stop all services
+stop_all_services() {
+ # Wait for evaluation jobs to finish
+ echo "⏳ Waiting for evaluation jobs to finish..."
+ for pid in "${eval_pids[@]}"; do
+ if ps -p "$pid" > /dev/null 2>&1; then
+ wait "$pid"
+ status=$?
+ if [ $status -ne 0 ]; then
+ echo "⚠️ Warning: evaluation job $pid exited abnormally (status: $status)"
+ fi
+ fi
+ done
+
+ # Stop policy servers
+ echo "⏳ Stopping service processes..."
+ for pid in "${policyserver_pids[@]}"; do
+ if ps -p "$pid" > /dev/null 2>&1; then
+ kill "$pid" 2>/dev/null
+ wait "$pid" 2>/dev/null
+ else
+ echo "⚠️ Service process $pid no longer exists (may have exited early)"
+ fi
+ done
+
+
+ # Reset PID arrays
+ eval_pids=()
+ policyserver_pids=()
+ echo "✅ All services and jobs have stopped"
+}
+
+
+
+# Derive CUDA device list from CUDA_VISIBLE_DEVICES
+IFS=',' read -r -a CUDA_DEVICES <<< "$CUDA_VISIBLE_DEVICES" # Convert comma-separated GPU list into array
+NUM_GPUS=${#CUDA_DEVICES[@]} # Count available GPUs
+
+declare -a ckpt_paths=(
+ ${MODEL_PATH}
+)
+# CogACT/CogACT-Large CogACT/CogACT-Small
+declare -a env_names=(
+ CloseTopDrawerCustomInScene-v0
+ CloseMiddleDrawerCustomInScene-v0
+ CloseBottomDrawerCustomInScene-v0
+ OpenTopDrawerCustomInScene-v0
+ OpenMiddleDrawerCustomInScene-v0
+ OpenBottomDrawerCustomInScene-v0
+)
+
+EXTRA_ARGS="--enable-raytracing"
+
+# Round-robin assignment across 8 GPUs
+total_gpus=8
+run_count=0
+
+# base setup
+scene_name=frl_apartment_stage_simple
+
+EvalSim() {
+ echo "Running on GPU ${gpu_id}: ${ckpt_path} ${env_name}"
+ # Launch service and capture its PID
+ port=$((base_port + run_count))
+ start_service ${gpu_id} ${ckpt_path} ${port}
+
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/eval_files/start_simpler_env.py --ckpt-path ${ckpt_path} \
+ --robot google_robot_static \
+ --port $port \
+ --control-freq 3 --sim-freq 513 --max-episode-steps 113 \
+ --env-name ${env_name} --scene-name ${scene_name} \
+ --robot-init-x 0.65 0.85 3 --robot-init-y -0.2 0.2 3 \
+ --robot-init-rot-quat-center 0 0 0 1 --robot-init-rot-rpy-range 0 0 1 0 0 1 0.0 0.0 1 \
+ --obj-init-x-range 0 0 1 --obj-init-y-range 0 0 1 \
+ ${EXTRA_ARGS}
+
+ eval_pids+=($!)
+}
+
+for ckpt_path in "${ckpt_paths[@]}"; do
+ for env_name in "${env_names[@]}"; do
+
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]} # Map to CUDA_VISIBLE_DEVICES GPU ID
+ if (( (run_count + 1) == 32 )); then
+ EvalSim
+ else
+ EvalSim &
+ fi
+ run_count=$((run_count + 1))
+ sleep 2
+ done
+done
+
+# Background variants
+declare -a scene_names=(
+ "modern_bedroom_no_roof"
+ "modern_office_no_roof"
+)
+
+for scene_name in "${scene_names[@]}"; do
+ for ckpt_path in "${ckpt_paths[@]}"; do
+ for env_name in "${env_names[@]}"; do
+ EXTRA_ARGS="--additional-env-build-kwargs shader_dir=rt"
+
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]} # Map to CUDA_VISIBLE_DEVICES GPU ID
+ if (( (run_count + 1) == 32 )); then
+ EvalSim
+ else
+ EvalSim &
+ fi
+ run_count=$((run_count + 1))
+ sleep 2
+ done
+ done
+done
+
+# Lighting variants
+scene_name=frl_apartment_stage_simple
+
+for ckpt_path in "${ckpt_paths[@]}"; do
+ for env_name in "${env_names[@]}"; do
+ EXTRA_ARGS="--additional-env-build-kwargs shader_dir=rt light_mode=brighter"
+
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]} # Map to CUDA_VISIBLE_DEVICES GPU ID
+ if (( (run_count + 1) == 32 )); then
+ EvalSim
+ else
+ EvalSim &
+ fi
+ run_count=$((run_count + 1))
+
+ EXTRA_ARGS="--additional-env-build-kwargs shader_dir=rt light_mode=darker"
+
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]} # Map to CUDA_VISIBLE_DEVICES GPU ID
+ if (( (run_count + 1) % 32 == 0 )); then
+ EvalSim
+ else
+ EvalSim &
+ fi
+ run_count=$((run_count + 1))
+ sleep 2
+ done
+done
+
+# New cabinet variants
+scene_name=frl_apartment_stage_simple
+
+for ckpt_path in "${ckpt_paths[@]}"; do
+ for env_name in "${env_names[@]}"; do
+ EXTRA_ARGS="--additional-env-build-kwargs shader_dir=rt station_name=mk_station2"
+
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]} # Map to CUDA_VISIBLE_DEVICES GPU ID
+ if (( (run_count + 1) % 32 == 0 )); then
+ EvalSim
+ else
+ EvalSim &
+ fi
+ run_count=$((run_count + 1))
+ sleep 2
+
+ EXTRA_ARGS="--additional-env-build-kwargs shader_dir=rt station_name=mk_station3"
+
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]} # Map to CUDA_VISIBLE_DEVICES GPU ID
+ if (( (run_count + 1) % 32 == 0 )); then
+ EvalSim
+ else
+ EvalSim &
+ fi
+ run_count=$((run_count + 1))
+ sleep 2
+ done
+done
+
+
+# stop_all_services
+# wait
+# echo "✅ All evaluations completed"
+
+
+# 判断是否还有 评测的sim 在跑
+while pgrep -f "examples/SimplerEnv/eval_files/start_simpler_env.py" > /dev/null; do
+ echo "Waiting for all evaluation environments to finish..."
+ sleep 300
+done
+
+
diff --git a/examples/SimplerEnv/eval_files/auto_eval_scripts/star_drawer_visual_matching.sh b/examples/SimplerEnv/eval_files/auto_eval_scripts/star_drawer_visual_matching.sh
new file mode 100644
index 0000000000000000000000000000000000000000..840111828f63c1e75419b05cd1ffe5706be2900b
--- /dev/null
+++ b/examples/SimplerEnv/eval_files/auto_eval_scripts/star_drawer_visual_matching.sh
@@ -0,0 +1,250 @@
+# Use all 8 GPUs and run tasks in the background
+
+
+# Environment setup
+cd /mnt/petrelfs/yejinhui/Projects/llavavla
+export star_vla_python=/mnt/petrelfs/share/yejinhui/Envs/miniconda3/envs/starvlaSAM/bin/python
+export sim_python=/mnt/petrelfs/share/yejinhui/Envs/miniconda3/envs/dinoact/bin/python
+export SimplerEnv_PATH=/mnt/petrelfs/share/yejinhui/Projects/SimplerEnv
+export PYTHONPATH=$(pwd):${PYTHONPATH}
+base_port=5500
+
+
+MODEL_PATH=$1
+
+# Optional: allow overriding via argument
+if [ -z "$MODEL_PATH" ]; then
+ echo "❌ MODEL_PATH not provided as the first argument; using default"
+export MODEL_PATH="/mnt/petrelfs/yejinhui/Projects/llavavla/results/Checkpoints/1017_QwenOFT/checkpoints/steps_65000_pytorch_model.pt"
+fi
+
+
+# Helper to launch policy servers
+policyserver_pids=()
+eval_pids=()
+
+task_name=drawer_vm
+
+start_service() {
+ local gpu_id=$1
+ local ckpt_path=$2
+ local port=$3
+ local server_log_dir="$(dirname "${ckpt_path}")/server_logs"
+ local svc_log="${server_log_dir}/$(basename "${ckpt_path%.*}")_${task_name}_${port}.log"
+ mkdir -p "${server_log_dir}"
+
+ echo "▶️ Starting service on GPU ${gpu_id}, port ${port}"
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${star_vla_python} deployment/model_server/server_policy.py \
+ --ckpt_path ${ckpt_path} \
+ --port ${port} \
+ --use_bf16 \
+ > "${svc_log}" 2>&1 &
+
+ local pid=$! # capture PID immediately
+ policyserver_pids+=($pid)
+ sleep 10
+}
+
+# Helper to stop every service
+stop_all_services() {
+ # Wait for every evaluation job to complete
+ if [ "${#eval_pids[@]}" -gt 0 ]; then
+ echo "⏳ Waiting for evaluation jobs to finish..."
+ for pid in "${eval_pids[@]}"; do
+ if ps -p "$pid" > /dev/null 2>&1; then
+ wait "$pid"
+ status=$?
+ if [ $status -ne 0 ]; then
+ echo "Warning: evaluation job $pid exited abnormally (status: $status)"
+ fi
+ fi
+ done
+ fi
+
+ # Stop all services
+ if [ "${#policyserver_pids[@]}" -gt 0 ]; then
+ echo "⏳ Stopping service processes..."
+ for pid in "${policyserver_pids[@]}"; do
+ if ps -p "$pid" > /dev/null 2>&1; then
+ kill "$pid" 2>/dev/null
+ wait "$pid" 2>/dev/null
+ else
+ echo "⚠️ Service process $pid no longer exists (might have exited early)"
+ fi
+ done
+ fi
+
+ # Clear PID arrays
+ eval_pids=()
+ policyserver_pids=()
+ echo "✅ All services and tasks stopped"
+}
+
+
+
+
+# Retrieve CUDA_VISIBLE_DEVICES list on this host
+IFS=',' read -r -a CUDA_DEVICES <<< "$CUDA_VISIBLE_DEVICES" # convert comma-separated GPU list to an array
+NUM_GPUS=${#CUDA_DEVICES[@]} # count available GPUs
+
+declare -a ckpt_paths=(
+ ${MODEL_PATH}
+)
+
+declare -a env_names=(
+ OpenTopDrawerCustomInScene-v0
+ OpenMiddleDrawerCustomInScene-v0
+ OpenBottomDrawerCustomInScene-v0
+ CloseTopDrawerCustomInScene-v0
+ CloseMiddleDrawerCustomInScene-v0
+ CloseBottomDrawerCustomInScene-v0
+)
+
+# URDF variations
+declare -a urdf_version_arr=("recolor_cabinet_visual_matching_1" "recolor_tabletop_visual_matching_1" "recolor_tabletop_visual_matching_2" None)
+
+# Use 8 GPUs in a round-robin manner
+total_gpus=8
+run_count=0
+
+for urdf_version in "${urdf_version_arr[@]}"; do
+
+ EXTRA_ARGS="--enable-raytracing --additional-env-build-kwargs station_name=mk_station_recolor light_mode=simple disable_bad_material=True urdf_version=${urdf_version}"
+
+ EvalSim() {
+ # A0
+
+ # Launch service and capture the process ID
+ port=$((base_port + run_count))
+ start_service ${gpu_id} ${ckpt_path} ${port}
+
+
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/eval_files/start_simpler_env.py --ckpt-path ${ckpt_path} \
+ --robot google_robot_static \
+ --port $port \
+ --control-freq 3 --sim-freq 513 --max-episode-steps 113 \
+ --env-name ${env_name} --scene-name dummy_drawer \
+ --robot-init-x 0.644 0.644 1 --robot-init-y -0.179 -0.179 1 \
+ --robot-init-rot-quat-center 0 0 0 1 --robot-init-rot-rpy-range 0 0 1 0 0 1 -0.03 -0.03 1 \
+ --obj-init-x-range 0 0 1 --obj-init-y-range 0 0 1 \
+ --rgb-overlay-path ${SimplerEnv_PATH}/ManiSkill2_real2sim/data/real_inpainting/open_drawer_a0.png \
+ ${EXTRA_ARGS}
+
+ # A1
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/eval_files/start_simpler_env.py --ckpt-path ${ckpt_path} \
+ --robot google_robot_static \
+ --port $port \
+ --control-freq 3 --sim-freq 513 --max-episode-steps 113 \
+ --env-name ${env_name} --scene-name dummy_drawer \
+ --robot-init-x 0.765 0.765 1 --robot-init-y -0.182 -0.182 1 \
+ --robot-init-rot-quat-center 0 0 0 1 --robot-init-rot-rpy-range 0 0 1 0 0 1 -0.02 -0.02 1 \
+ --obj-init-x-range 0 0 1 --obj-init-y-range 0 0 1 \
+ --rgb-overlay-path ${SimplerEnv_PATH}/ManiSkill2_real2sim/data/real_inpainting/open_drawer_a1.png \
+ ${EXTRA_ARGS}
+
+ # A2
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/eval_files/start_simpler_env.py --ckpt-path ${ckpt_path} \
+ --robot google_robot_static \
+ --port $port \
+ --control-freq 3 --sim-freq 513 --max-episode-steps 113 \
+ --env-name ${env_name} --scene-name dummy_drawer \
+ --robot-init-x 0.889 0.889 1 --robot-init-y -0.203 -0.203 1 \
+ --robot-init-rot-quat-center 0 0 0 1 --robot-init-rot-rpy-range 0 0 1 0 0 1 -0.06 -0.06 1 \
+ --obj-init-x-range 0 0 1 --obj-init-y-range 0 0 1 \
+ --rgb-overlay-path ${SimplerEnv_PATH}/ManiSkill2_real2sim/data/real_inpainting/open_drawer_a2.png \
+ ${EXTRA_ARGS}
+
+ # B0
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/eval_files/start_simpler_env.py --ckpt-path ${ckpt_path} \
+ --robot google_robot_static \
+ --port $port \
+ --control-freq 3 --sim-freq 513 --max-episode-steps 113 \
+ --env-name ${env_name} --scene-name dummy_drawer \
+ --robot-init-x 0.652 0.652 1 --robot-init-y 0.009 0.009 1 \
+ --robot-init-rot-quat-center 0 0 0 1 --robot-init-rot-rpy-range 0 0 1 0 0 1 0 0 1 \
+ --obj-init-x-range 0 0 1 --obj-init-y-range 0 0 1 \
+ --rgb-overlay-path ${SimplerEnv_PATH}/ManiSkill2_real2sim/data/real_inpainting/open_drawer_b0.png \
+ ${EXTRA_ARGS}
+
+ # B1
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/eval_files/start_simpler_env.py --ckpt-path ${ckpt_path} \
+ --robot google_robot_static \
+ --port $port \
+ --control-freq 3 --sim-freq 513 --max-episode-steps 113 \
+ --env-name ${env_name} --scene-name dummy_drawer \
+ --robot-init-x 0.752 0.752 1 --robot-init-y 0.009 0.009 1 \
+ --robot-init-rot-quat-center 0 0 0 1 --robot-init-rot-rpy-range 0 0 1 0 0 1 0 0 1 \
+ --obj-init-x-range 0 0 1 --obj-init-y-range 0 0 1 \
+ --rgb-overlay-path ${SimplerEnv_PATH}/ManiSkill2_real2sim/data/real_inpainting/open_drawer_b1.png \
+ ${EXTRA_ARGS}
+
+ # B2
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/eval_files/start_simpler_env.py --ckpt-path ${ckpt_path} \
+ --robot google_robot_static \
+ --port $port \
+ --control-freq 3 --sim-freq 513 --max-episode-steps 113 \
+ --env-name ${env_name} --scene-name dummy_drawer \
+ --robot-init-x 0.851 0.851 1 --robot-init-y 0.035 0.035 1 \
+ --robot-init-rot-quat-center 0 0 0 1 --robot-init-rot-rpy-range 0 0 1 0 0 1 0 0 1 \
+ --obj-init-x-range 0 0 1 --obj-init-y-range 0 0 1 \
+ --rgb-overlay-path ${SimplerEnv_PATH}/ManiSkill2_real2sim/data/real_inpainting/open_drawer_b2.png \
+ ${EXTRA_ARGS}
+
+ # C0
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/eval_files/start_simpler_env.py --ckpt-path ${ckpt_path} \
+ --robot google_robot_static \
+ --port $port \
+ --control-freq 3 --sim-freq 513 --max-episode-steps 113 \
+ --env-name ${env_name} --scene-name dummy_drawer \
+ --robot-init-x 0.665 0.665 1 --robot-init-y 0.224 0.224 1 \
+ --robot-init-rot-quat-center 0 0 0 1 --robot-init-rot-rpy-range 0 0 1 0 0 1 0 0 1 \
+ --obj-init-x-range 0 0 1 --obj-init-y-range 0 0 1 \
+ --rgb-overlay-path ${SimplerEnv_PATH}/ManiSkill2_real2sim/data/real_inpainting/open_drawer_c0.png \
+ ${EXTRA_ARGS}
+
+ # C1
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/eval_files/start_simpler_env.py --ckpt-path ${ckpt_path} \
+ --robot google_robot_static \
+ --port $port \
+ --control-freq 3 --sim-freq 513 --max-episode-steps 113 \
+ --env-name ${env_name} --scene-name dummy_drawer \
+ --robot-init-x 0.765 0.765 1 --robot-init-y 0.222 0.222 1 \
+ --robot-init-rot-quat-center 0 0 0 1 --robot-init-rot-rpy-range 0 0 1 0 0 1 -0.025 -0.025 1 \
+ --obj-init-x-range 0 0 1 --obj-init-y-range 0 0 1 \
+ --rgb-overlay-path ${SimplerEnv_PATH}/ManiSkill2_real2sim/data/real_inpainting/open_drawer_c1.png \
+ ${EXTRA_ARGS}
+
+ # C2
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/eval_files/start_simpler_env.py --ckpt-path ${ckpt_path} \
+ --robot google_robot_static \
+ --port $port \
+ --control-freq 3 --sim-freq 513 --max-episode-steps 113 \
+ --env-name ${env_name} --scene-name dummy_drawer \
+ --robot-init-x 0.865 0.865 1 --robot-init-y 0.222 0.222 1 \
+ --robot-init-rot-quat-center 0 0 0 1 --robot-init-rot-rpy-range 0 0 1 0 0 1 -0.025 -0.025 1 \
+ --obj-init-x-range 0 0 1 --obj-init-y-range 0 0 1 \
+ --rgb-overlay-path ${SimplerEnv_PATH}/ManiSkill2_real2sim/data/real_inpainting/open_drawer_c2.png \
+ ${EXTRA_ARGS}
+ }
+ # 32 = 4*8 GPUs, at most four runs per GPU
+ for ckpt_path in "${ckpt_paths[@]}"; do
+ for env_name in "${env_names[@]}"; do
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]} # map to GPU ID in CUDA_VISIBLE_DEVICES
+ if (( (run_count + 1) % 32 == 0 )); then
+ EvalSim
+ else
+ EvalSim &
+ eval_pids+=($!)
+ fi
+
+ sleep 15
+ run_count=$((run_count + 1))
+ done
+ done
+
+done
+
+# Wait for all background jobs
+stop_all_services
+# wait
+echo "✅ All evaluations finished"
\ No newline at end of file
diff --git a/examples/SimplerEnv/eval_files/auto_eval_scripts/star_move_near_variant_agg.sh b/examples/SimplerEnv/eval_files/auto_eval_scripts/star_move_near_variant_agg.sh
new file mode 100644
index 0000000000000000000000000000000000000000..ee7dc8a79d9ca9756080d89ab3a9af90e313b60e
--- /dev/null
+++ b/examples/SimplerEnv/eval_files/auto_eval_scripts/star_move_near_variant_agg.sh
@@ -0,0 +1,255 @@
+# Define environment
+cd /mnt/petrelfs/yejinhui/Projects/llavavla
+export starvla_python=/mnt/petrelfs/share/yejinhui/Envs/miniconda3/envs/starvlaSAM/bin/python
+export sim_python=/mnt/petrelfs/share/yejinhui/Envs/miniconda3/envs/dinoact/bin/python
+export SimplerEnv_PATH=/mnt/petrelfs/share/yejinhui/Projects/SimplerEnv
+export PYTHONPATH=$(pwd):${PYTHONPATH}
+base_port=5500
+
+MODEL_PATH=$1
+
+# Optional: check whether MODEL_PATH argument is provided
+if [ -z "$MODEL_PATH" ]; then
+ echo "❌ MODEL_PATH not provided as the first argument, using default value"
+ export MODEL_PATH="/mnt/petrelfs/yejinhui/Projects/llavavla/results/Checkpoints/1003_qwenfast/checkpoints/steps_10000_pytorch_model.pt"
+fi
+
+export ckpt_path=${MODEL_PATH}
+
+# Define a function to start the service
+policyserver_pids=()
+eval_pids=()
+
+
+task_name=near_va
+
+
+start_service() {
+ local gpu_id=$1
+ local ckpt_path=$2
+ local port=$3
+ local server_log_dir="$(dirname "${ckpt_path}")/server_logs"
+ local svc_log="${server_log_dir}/$(basename "${ckpt_path%.*}")_${task_name}_${port}.log"
+ mkdir -p "${server_log_dir}"
+
+ echo "▶️ Starting service on GPU ${gpu_id}, port ${port}"
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${starvla_python} deployment/model_server/server_policy.py \
+ --ckpt_path ${ckpt_path} \
+ --port ${port} \
+ --use_bf16 \
+ > "${svc_log}" 2>&1 &
+
+ local pid=$! # Capture PID immediately
+ policyserver_pids+=($pid)
+ sleep 20
+}
+
+# Define a function to stop all services
+stop_all_services() {
+ # Wait for all evaluation tasks to complete
+ echo "⏳ Waiting for evaluation tasks to complete..."
+ for pid in "${eval_pids[@]}"; do
+ if ps -p "$pid" > /dev/null 2>&1; then
+ wait "$pid"
+ status=$?
+ if [ $status -ne 0 ]; then
+ echo "Warning: Evaluation task $pid exited abnormally (status: $status)"
+ fi
+ fi
+ done
+
+ # Stop all services
+ echo "⏳ Stopping service processes..."
+ for pid in "${policyserver_pids[@]}"; do
+ if ps -p "$pid" > /dev/null 2>&1; then
+ kill "$pid" 2>/dev/null
+ wait "$pid" 2>/dev/null
+ else
+ echo "⚠️ Service process $pid no longer exists (may have exited early)"
+ fi
+ done
+
+
+ # Clear PID arrays
+ eval_pids=()
+ policyserver_pids=()
+ echo "✅ All services and tasks stopped"
+}
+
+# Retrieve the CUDA_VISIBLE_DEVICES list from the current system
+IFS=',' read -r -a CUDA_DEVICES <<< "$CUDA_VISIBLE_DEVICES" # Convert comma-separated GPU list into array
+NUM_GPUS=${#CUDA_DEVICES[@]} # Get number of available GPUs
+
+
+
+policy_model=Qwenpi
+
+declare -a arr=(
+ ${MODEL_PATH}
+)
+
+# Variables for round-robin allocation
+total_gpus=8
+run_count=0
+
+# CogACT/CogACT-Large CogACT/CogACT-Small
+for ckpt_path in "${arr[@]}"; do
+ echo "$ckpt_path"
+done
+
+# base setup
+env_name=MoveNearGoogleInScene-v0
+scene_name=google_pick_coke_can_1_v4
+
+for ckpt_path in "${arr[@]}"; do
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]} # 映射到 CUDA_VISIBLE_DEVICES 中的 GPU ID
+ # 启动服务并获取服务进程的 PID
+ port=$((base_port + run_count))
+ start_service ${gpu_id} ${ckpt_path} ${port}
+
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/eval_files/start_simpler_env.py --ckpt-path ${ckpt_path} \
+ --robot google_robot_static \
+ --port $port \
+ --control-freq 3 --sim-freq 513 --max-episode-steps 80 \
+ --env-name ${env_name} --scene-name ${scene_name} \
+ --robot-init-x 0.35 0.35 1 --robot-init-y 0.21 0.21 1 --obj-variation-mode episode --obj-episode-range 0 60 \
+ --robot-init-rot-quat-center 0 0 0 1 --robot-init-rot-rpy-range 0 0 1 0 0 1 -0.09 -0.09 1 &
+ eval_pids+=($!)
+ run_count=$((run_count + 1))
+done
+
+# distractor
+for ckpt_path in "${arr[@]}"; do
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]} # 映射到 CUDA_VISIBLE_DEVICES 中的 GPU ID
+ # 启动服务并获取服务进程的 PID
+ port=$((base_port + run_count))
+ start_service ${gpu_id} ${ckpt_path} ${port}
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/eval_files/start_simpler_env.py --ckpt-path ${ckpt_path} \
+ --robot google_robot_static \
+ --port $port \
+ --control-freq 3 --sim-freq 513 --max-episode-steps 80 \
+ --env-name ${env_name} --scene-name ${scene_name} \
+ --robot-init-x 0.35 0.35 1 --robot-init-y 0.21 0.21 1 --obj-variation-mode episode --obj-episode-range 0 60 \
+ --robot-init-rot-quat-center 0 0 0 1 --robot-init-rot-rpy-range 0 0 1 0 0 1 -0.09 -0.09 1 \
+ --additional-env-build-kwargs no_distractor=True &
+ eval_pids+=($!)
+ run_count=$((run_count + 1))
+done
+
+# backgrounds
+env_name=MoveNearGoogleInScene-v0
+declare -a scene_arr=("google_pick_coke_can_1_v4_alt_background" \
+ "google_pick_coke_can_1_v4_alt_background_2")
+for scene_name in "${scene_arr[@]}"; do
+ for ckpt_path in "${arr[@]}"; do
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]} # 映射到 CUDA_VISIBLE_DEVICES 中的 GPU ID
+ # 启动服务并获取服务进程的 PID
+ port=$((base_port + run_count))
+ start_service ${gpu_id} ${ckpt_path} ${port}
+
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/eval_files/start_simpler_env.py --ckpt-path ${ckpt_path} \
+ --robot google_robot_static \
+ --port $port \
+ --control-freq 3 --sim-freq 513 --max-episode-steps 80 \
+ --env-name ${env_name} --scene-name ${scene_name} \
+ --robot-init-x 0.35 0.35 1 --robot-init-y 0.21 0.21 1 --obj-variation-mode episode --obj-episode-range 0 60 \
+ --robot-init-rot-quat-center 0 0 0 1 --robot-init-rot-rpy-range 0 0 1 0 0 1 -0.09 -0.09 1 &
+
+ eval_pids+=($!)
+ run_count=$((run_count + 1))
+ done
+done
+
+# lighting
+env_name=MoveNearGoogleInScene-v0
+scene_name=google_pick_coke_can_1_v4
+
+for ckpt_path in "${arr[@]}"; do
+ # Slightly darker
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]} # 映射到 CUDA_VISIBLE_DEVICES 中的 GPU ID
+ # 启动服务并获取服务进程的 PID
+ port=$((base_port + run_count))
+ start_service ${gpu_id} ${ckpt_path} ${port}
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/eval_files/start_simpler_env.py --ckpt-path ${ckpt_path} \
+ --robot google_robot_static \
+ --port $port \
+ --control-freq 3 --sim-freq 513 --max-episode-steps 80 \
+ --env-name ${env_name} --scene-name ${scene_name} \
+ --robot-init-x 0.35 0.35 1 --robot-init-y 0.21 0.21 1 --obj-variation-mode episode --obj-episode-range 0 60 \
+ --robot-init-rot-quat-center 0 0 0 1 --robot-init-rot-rpy-range 0 0 1 0 0 1 -0.09 -0.09 1 \
+ --additional-env-build-kwargs slightly_darker_lighting=True &
+
+ eval_pids+=($!)
+ run_count=$((run_count + 1))
+
+ # Slightly brighter
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]} # 映射到 CUDA_VISIBLE_DEVICES 中的 GPU ID
+ # 启动服务并获取服务进程的 PID
+ port=$((base_port + run_count))
+ start_service ${gpu_id} ${ckpt_path} ${port}
+
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/eval_files/start_simpler_env.py --ckpt-path ${ckpt_path} \
+ --robot google_robot_static \
+ --port $port \
+ --control-freq 3 --sim-freq 513 --max-episode-steps 80 \
+ --env-name ${env_name} --scene-name ${scene_name} \
+ --robot-init-x 0.35 0.35 1 --robot-init-y 0.21 0.21 1 --obj-variation-mode episode --obj-episode-range 0 60 \
+ --robot-init-rot-quat-center 0 0 0 1 --robot-init-rot-rpy-range 0 0 1 0 0 1 -0.09 -0.09 1 \
+ --additional-env-build-kwargs slightly_brighter_lighting=True &
+
+ eval_pids+=($!)
+ run_count=$((run_count + 1))
+done
+
+# table textures
+env_name=MoveNearGoogleInScene-v0
+declare -a table_scene_arr=("Baked_sc1_staging_objaverse_cabinet1_h870" \
+ "Baked_sc1_staging_objaverse_cabinet2_h870")
+
+for scene_name in "${table_scene_arr[@]}"; do
+ for ckpt_path in "${arr[@]}"; do
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]}
+ port=$((base_port + run_count))
+ start_service ${gpu_id} ${ckpt_path} ${port}
+
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/eval_files/start_simpler_env.py --ckpt-path ${ckpt_path} \
+ --robot google_robot_static \
+ --port $port \
+ --control-freq 3 --sim-freq 513 --max-episode-steps 80 \
+ --env-name ${env_name} --scene-name ${scene_name} \
+ --robot-init-x 0.35 0.35 1 --robot-init-y 0.21 0.21 1 --obj-variation-mode episode --obj-episode-range 0 60 \
+ --robot-init-rot-quat-center 0 0 0 1 --robot-init-rot-rpy-range 0 0 1 0 0 1 -0.09 -0.09 1 &
+
+ eval_pids+=($!)
+ run_count=$((run_count + 1))
+ done
+done
+
+# camera orientations
+declare -a env_arr=("MoveNearAltGoogleCameraInScene-v0" \
+ "MoveNearAltGoogleCamera2InScene-v0")
+scene_name=google_pick_coke_can_1_v4
+
+for env_name in "${env_arr[@]}"; do
+ for ckpt_path in "${arr[@]}"; do
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]}
+ port=$((base_port + run_count))
+ start_service ${gpu_id} ${ckpt_path} ${port}
+
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/eval_files/start_simpler_env.py --ckpt-path ${ckpt_path} \
+ --robot google_robot_static \
+ --port $port \
+ --control-freq 3 --sim-freq 513 --max-episode-steps 80 \
+ --env-name ${env_name} --scene-name ${scene_name} \
+ --robot-init-x 0.35 0.35 1 --robot-init-y 0.21 0.21 1 --obj-variation-mode episode --obj-episode-range 0 60 \
+ --robot-init-rot-quat-center 0 0 0 1 --robot-init-rot-rpy-range 0 0 1 0 0 1 -0.09 -0.09 1 &
+ eval_pids+=($!)
+ run_count=$((run_count + 1))
+ done
+done
+
+# Wait for all background tasks to finish
+stop_all_services
+# wait
+echo "✅ All tests completed"
+
diff --git a/examples/SimplerEnv/eval_files/auto_eval_scripts/star_move_near_visual_matching.sh b/examples/SimplerEnv/eval_files/auto_eval_scripts/star_move_near_visual_matching.sh
new file mode 100644
index 0000000000000000000000000000000000000000..d18bf8e0d86dc0dda2180cac2ba4b6fcba804c7d
--- /dev/null
+++ b/examples/SimplerEnv/eval_files/auto_eval_scripts/star_move_near_visual_matching.sh
@@ -0,0 +1,131 @@
+
+# Environment setup
+cd /mnt/petrelfs/yejinhui/Projects/llavavla
+export starvla_python=/mnt/petrelfs/share/yejinhui/Envs/miniconda3/envs/starvlaSAM/bin/python
+export sim_python=/mnt/petrelfs/share/yejinhui/Envs/miniconda3/envs/dinoact/bin/python
+export SimplerEnv_PATH=/mnt/petrelfs/share/yejinhui/Projects/SimplerEnv
+export PYTHONPATH=$(pwd):${PYTHONPATH}
+base_port=5500
+
+MODEL_PATH=$1
+
+# Optional: allow overriding via argument
+if [ -z "$MODEL_PATH" ]; then
+ echo "❌ MODEL_PATH not provided as the first argument; using default"
+ export MODEL_PATH="/mnt/petrelfs/yejinhui/Projects/llavavla/results/Checkpoints/1003_qwenfast/checkpoints/steps_10000_pytorch_model.pt"
+fi
+
+export ckpt_path=${MODEL_PATH}
+
+# Helper to launch policy servers
+policyserver_pids=()
+eval_pids=()
+
+task_name=near_vm
+
+
+start_service() {
+ local gpu_id=$1
+ local ckpt_path=$2
+ local port=$3
+ local server_log_dir="$(dirname "${ckpt_path}")/server_logs"
+ local svc_log="${server_log_dir}/$(basename "${ckpt_path%.*}")_${task_name}_${port}.log"
+ mkdir -p "${server_log_dir}"
+
+ echo "▶️ Starting service on GPU ${gpu_id}, port ${port}"
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${starvla_python} deployment/model_server/server_policy.py \
+ --ckpt_path ${ckpt_path} \
+ --port ${port} \
+ --use_bf16 \
+ > "${svc_log}" 2>&1 &
+
+ local pid=$! # capture PID immediately
+ policyserver_pids+=($pid)
+ sleep 20
+}
+
+# Helper to stop every service
+stop_all_services() {
+ # Wait for every evaluation job to complete
+ echo "⏳ Waiting for evaluation jobs to finish..."
+ for pid in "${eval_pids[@]}"; do
+ if ps -p "$pid" > /dev/null 2>&1; then
+ wait "$pid"
+ status=$?
+ if [ $status -ne 0 ]; then
+ echo "Warning: evaluation job $pid exited abnormally (status: $status)"
+ fi
+ fi
+ done
+
+ # Stop all services
+ echo "⏳ Stopping service processes..."
+ for pid in "${policyserver_pids[@]}"; do
+ if ps -p "$pid" > /dev/null 2>&1; then
+ kill "$pid" 2>/dev/null
+ wait "$pid" 2>/dev/null
+ else
+ echo "⚠️ Service process $pid no longer exists (might have exited early)"
+ fi
+ done
+
+
+ # Clear PID arrays
+ eval_pids=()
+ policyserver_pids=()
+ echo "✅ All services and tasks stopped"
+}
+
+# Retrieve CUDA_VISIBLE_DEVICES list on this host
+IFS=',' read -r -a CUDA_DEVICES <<< "$CUDA_VISIBLE_DEVICES" # convert comma-separated GPU list to an array
+NUM_GPUS=${#CUDA_DEVICES[@]} # count available GPUs
+
+
+policy_model=Qwenpi
+
+declare -a arr=(
+ ${MODEL_PATH}
+)
+env_name=MoveNearGoogleBakedTexInScene-v0
+# env_name=MoveNearGoogleBakedTexInScene-v1
+scene_name=google_pick_coke_can_1_v4
+rgb_overlay_path=${SimplerEnv_PATH}/ManiSkill2_real2sim/data/real_inpainting/google_move_near_real_eval_1.png
+
+# URDF variations
+declare -a urdf_version_arr=(None "recolor_tabletop_visual_matching_1" "recolor_tabletop_visual_matching_2" "recolor_cabinet_visual_matching_1")
+
+# Variables for round-robin assignment
+total_gpus=8
+run_count=0
+
+for ckpt_path in "${arr[@]}"; do
+ echo "$ckpt_path"
+done
+
+for urdf_version in "${urdf_version_arr[@]}"; do
+ for ckpt_path in "${arr[@]}"; do
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]} # map to GPU ID in CUDA_VISIBLE_DEVICES
+ # Launch service and capture the process ID
+ port=$((base_port + run_count))
+ start_service ${gpu_id} ${ckpt_path} ${port}
+
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/start_simpler_env.py --ckpt-path ${ckpt_path} \
+ --robot google_robot_static \
+ --port $port \
+ --control-freq 3 --sim-freq 513 --max-episode-steps 80 \
+ --env-name ${env_name} --scene-name ${scene_name} \
+ --rgb-overlay-path ${rgb_overlay_path} \
+ --robot-init-x 0.35 0.35 1 --robot-init-y 0.21 0.21 1 --obj-variation-mode episode --obj-episode-range 0 60 \
+ --robot-init-rot-quat-center 0 0 0 1 --robot-init-rot-rpy-range 0 0 1 0 0 1 -0.09 -0.09 1 \
+ --additional-env-build-kwargs urdf_version=${urdf_version} \
+ --additional-env-save-tags baked_except_bpb_orange &
+
+ eval_pids+=($!)
+ run_count=$((run_run_count + 1))
+ done
+done
+
+stop_all_services
+# wait
+echo "✅ All evaluations finished"
+
diff --git a/examples/SimplerEnv/eval_files/auto_eval_scripts/star_pick_coke_can_variant_agg.sh b/examples/SimplerEnv/eval_files/auto_eval_scripts/star_pick_coke_can_variant_agg.sh
new file mode 100644
index 0000000000000000000000000000000000000000..cbc39451690a10ecb9bbd7b7d453f4b065acf7ff
--- /dev/null
+++ b/examples/SimplerEnv/eval_files/auto_eval_scripts/star_pick_coke_can_variant_agg.sh
@@ -0,0 +1,288 @@
+# Environment setup
+cd /mnt/petrelfs/yejinhui/Projects/llavavla
+export starvla_python=/mnt/petrelfs/share/yejinhui/Envs/miniconda3/envs/starvlaSAM/bin/python
+export sim_python=/mnt/petrelfs/share/yejinhui/Envs/miniconda3/envs/dinoact/bin/python
+export SimplerEnv_PATH=/mnt/petrelfs/share/yejinhui/Projects/SimplerEnv
+export PYTHONPATH=$(pwd):${PYTHONPATH}
+base_port=5500
+
+MODEL_PATH=$1
+
+# Optional: allow overriding via argument
+if [ -z "$MODEL_PATH" ]; then
+ echo "❌ MODEL_PATH not provided as the first argument; using default"
+ export MODEL_PATH="/mnt/petrelfs/yejinhui/Projects/llavavla/results/Checkpoints/1003_qwenfast/checkpoints/steps_10000_pytorch_model.pt"
+fi
+
+export ckpt_path=${MODEL_PATH}
+
+# Helper to launch policy servers
+policyserver_pids=()
+eval_pids=()
+
+task_name=pick_coke_va
+
+
+start_service() {
+ local gpu_id=$1
+ local ckpt_path=$2
+ local port=$3
+ local server_log_dir="$(dirname "${ckpt_path}")/server_logs"
+ local svc_log="${server_log_dir}/$(basename "${ckpt_path%.*}")_${task_name}_${port}.log"
+ mkdir -p "${server_log_dir}"
+ echo "▶️ Starting service on GPU ${gpu_id}, port ${port}"
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${starvla_python} deployment/model_server/server_policy.py \
+ --ckpt_path ${ckpt_path} \
+ --port ${port} \
+ --use_bf16 \
+ > "${svc_log}" 2>&1 &
+
+ local pid=$! # Capture PID immediately
+ policyserver_pids+=($pid)
+ sleep 20
+}
+
+# Helper to stop all services
+stop_all_services() {
+ # Wait for evaluation jobs to finish
+ echo "⏳ Waiting for evaluation jobs to finish..."
+ for pid in "${eval_pids[@]}"; do
+ if ps -p "$pid" > /dev/null 2>&1; then
+ wait "$pid"
+ status=$?
+ if [ $status -ne 0 ]; then
+ echo "⚠️ Warning: evaluation job $pid exited abnormally (status: $status)"
+ fi
+ fi
+ done
+
+ # Stop policy servers
+ echo "⏳ Stopping service processes..."
+ for pid in "${policyserver_pids[@]}"; do
+ if ps -p "$pid" > /dev/null 2>&1; then
+ kill "$pid" 2>/dev/null
+ wait "$pid" 2>/dev/null
+ else
+ echo "⚠️ Service process $pid no longer exists (may have exited early)"
+ fi
+ done
+ # Reset PID arrays
+ eval_pids=()
+ policyserver_pids=()
+ echo "✅ All services and jobs have stopped"
+}
+
+
+# Derive CUDA device list from CUDA_VISIBLE_DEVICES
+IFS=',' read -r -a CUDA_DEVICES <<< "$CUDA_VISIBLE_DEVICES" # Convert comma-separated GPU list into array
+NUM_GPUS=${#CUDA_DEVICES[@]} # Count available GPUs
+
+
+declare -a arr=(${MODEL_PATH})
+
+# Round-robin bookkeeping
+total_gpus=8
+run_count=0
+
+# lr_switch=laying horizontally but flipped left-right to match real eval; upright=standing; laid_vertically=laying vertically
+declare -a coke_can_options_arr=("lr_switch=True" "upright=True" "laid_vertically=True")
+
+for ckpt_path in "${arr[@]}"; do
+ echo "$ckpt_path"
+done
+
+# base setup
+env_name=GraspSingleOpenedCokeCanInScene-v0
+scene_name=google_pick_coke_can_1_v4
+
+for coke_can_option in "${coke_can_options_arr[@]}"; do
+ for ckpt_path in "${arr[@]}"; do
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]} # Map to CUDA_VISIBLE_DEVICES GPU ID
+ # Launch service and capture its PID
+ port=$((base_port + run_count))
+ start_service ${gpu_id} ${ckpt_path} ${port}
+
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/eval_files/start_simpler_env.py --ckpt-path ${ckpt_path} \
+ --robot google_robot_static \
+ --port ${port} \
+ --control-freq 3 --sim-freq 513 --max-episode-steps 80 \
+ --env-name ${env_name} --scene-name ${scene_name} \
+ --robot-init-x 0.35 0.35 1 --robot-init-y 0.20 0.20 1 --obj-init-x -0.35 -0.12 5 --obj-init-y -0.02 0.42 5 \
+ --robot-init-rot-quat-center 0 0 0 1 --robot-init-rot-rpy-range 0 0 1 0 0 1 0 0 1 \
+ --additional-env-build-kwargs ${coke_can_option} &
+
+ eval_pids+=($!) # Track evaluation job PID
+ run_count=$((run_count + 1))
+ done
+done
+
+# table textures
+env_name=GraspSingleOpenedCokeCanInScene-v0
+declare -a scene_arr=("Baked_sc1_staging_objaverse_cabinet1_h870" \
+ "Baked_sc1_staging_objaverse_cabinet2_h870")
+
+for coke_can_option in "${coke_can_options_arr[@]}"; do
+ for scene_name in "${scene_arr[@]}"; do
+ for ckpt_path in "${arr[@]}"; do
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]} # Map to CUDA_VISIBLE_DEVICES GPU ID
+ # Launch service and capture its PID
+ port=$((base_port + run_count))
+ start_service ${gpu_id} ${ckpt_path} ${port}
+
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/eval_files/start_simpler_env.py --ckpt-path ${ckpt_path} \
+ --robot google_robot_static \
+ --port ${port} \
+ --control-freq 3 --sim-freq 513 --max-episode-steps 80 \
+ --env-name ${env_name} --scene-name ${scene_name} \
+ --robot-init-x 0.35 0.35 1 --robot-init-y 0.20 0.20 1 --obj-init-x -0.35 -0.12 5 --obj-init-y -0.02 0.42 5 \
+ --robot-init-rot-quat-center 0 0 0 1 --robot-init-rot-rpy-range 0 0 1 0 0 1 0 0 1 \
+ --additional-env-build-kwargs ${coke_can_option} &
+
+ eval_pids+=($!) # Track evaluation job PID
+ run_count=$((run_count + 1))
+ done
+ done
+done
+
+# distractors
+env_name=GraspSingleOpenedCokeCanDistractorInScene-v0
+scene_name=google_pick_coke_can_1_v4
+
+for coke_can_option in "${coke_can_options_arr[@]}"; do
+ for ckpt_path in "${arr[@]}"; do
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]} # Map to CUDA_VISIBLE_DEVICES GPU ID
+ # Launch service and capture its PID
+ port=$((base_port + run_count))
+ start_service ${gpu_id} ${ckpt_path} ${port}
+
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/eval_files/start_simpler_env.py --ckpt-path ${ckpt_path} \
+ --robot google_robot_static \
+ --port ${port} \
+ --control-freq 3 --sim-freq 513 --max-episode-steps 80 \
+ --env-name ${env_name} --scene-name ${scene_name} \
+ --robot-init-x 0.35 0.35 1 --robot-init-y 0.20 0.20 1 --obj-init-x -0.35 -0.12 5 --obj-init-y -0.02 0.42 5 \
+ --robot-init-rot-quat-center 0 0 0 1 --robot-init-rot-rpy-range 0 0 1 0 0 1 0 0 1 \
+ --additional-env-build-kwargs ${coke_can_option} &
+
+ eval_pids+=($!) # Track evaluation job PID
+ run_count=$((run_count + 1))
+
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]} # Map to CUDA_VISIBLE_DEVICES GPU ID
+ # Launch service and capture its PID
+ port=$((base_port + run_count))
+ start_service ${gpu_id} ${ckpt_path} ${port}
+
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/eval_files/start_simpler_env.py --ckpt-path ${ckpt_path} \
+ --robot google_robot_static \
+ --port ${port} \
+ --control-freq 3 --sim-freq 513 --max-episode-steps 80 \
+ --env-name ${env_name} --scene-name ${scene_name} \
+ --robot-init-x 0.35 0.35 1 --robot-init-y 0.20 0.20 1 --obj-init-x -0.35 -0.12 5 --obj-init-y -0.02 0.42 5 \
+ --robot-init-rot-quat-center 0 0 0 1 --robot-init-rot-rpy-range 0 0 1 0 0 1 0 0 1 \
+ --additional-env-build-kwargs ${coke_can_option} distractor_config=more &
+
+ eval_pids+=($!) # Track evaluation job PID
+ run_count=$((run_count + 1))
+ done
+done
+
+# backgrounds
+env_name=GraspSingleOpenedCokeCanInScene-v0
+declare -a bg_scene_arr=("google_pick_coke_can_1_v4_alt_background" \
+ "google_pick_coke_can_1_v4_alt_background_2")
+
+for coke_can_option in "${coke_can_options_arr[@]}"; do
+ for scene_name in "${bg_scene_arr[@]}"; do
+ for ckpt_path in "${arr[@]}"; do
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]} # Map to CUDA_VISIBLE_DEVICES GPU ID
+ # Launch service and capture its PID
+ port=$((base_port + run_count))
+ start_service ${gpu_id} ${ckpt_path} ${port}
+
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/eval_files/start_simpler_env.py --ckpt-path ${ckpt_path} \
+ --robot google_robot_static \
+ --port ${port} \
+ --control-freq 3 --sim-freq 513 --max-episode-steps 80 \
+ --env-name ${env_name} --scene-name ${scene_name} \
+ --robot-init-x 0.35 0.35 1 --robot-init-y 0.20 0.20 1 --obj-init-x -0.35 -0.12 5 --obj-init-y -0.02 0.42 5 \
+ --robot-init-rot-quat-center 0 0 0 1 --robot-init-rot-rpy-range 0 0 1 0 0 1 0 0 1 \
+ --additional-env-build-kwargs ${coke_can_option} &
+
+ eval_pids+=($!) # Track evaluation job PID
+ run_count=$((run_count + 1))
+ done
+ done
+done
+
+# lightings
+env_name=GraspSingleOpenedCokeCanInScene-v0
+scene_name=google_pick_coke_can_1_v4
+
+for coke_can_option in "${coke_can_options_arr[@]}"; do
+ for ckpt_path in "${arr[@]}"; do
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]} # Map to CUDA_VISIBLE_DEVICES GPU ID
+ # Launch service and capture its PID
+ port=$((base_port + run_count))
+ start_service ${gpu_id} ${ckpt_path} ${port}
+
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/eval_files/start_simpler_env.py --ckpt-path ${ckpt_path} \
+ --robot google_robot_static \
+ --port ${port} \
+ --control-freq 3 --sim-freq 513 --max-episode-steps 80 \
+ --env-name ${env_name} --scene-name ${scene_name} \
+ --robot-init-x 0.35 0.35 1 --robot-init-y 0.20 0.20 1 --obj-init-x -0.35 -0.12 5 --obj-init-y -0.02 0.42 5 \
+ --robot-init-rot-quat-center 0 0 0 1 --robot-init-rot-rpy-range 0 0 1 0 0 1 0 0 1 \
+ --additional-env-build-kwargs ${coke_can_option} slightly_darker_lighting=True &
+
+ eval_pids+=($!) # Track evaluation job PID
+ run_count=$((run_count + 1))
+
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]} # Map to CUDA_VISIBLE_DEVICES GPU ID
+ # Launch service and capture its PID
+ port=$((base_port + run_count))
+ start_service ${gpu_id} ${ckpt_path} ${port}
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/eval_files/start_simpler_env.py --ckpt-path ${ckpt_path} \
+ --robot google_robot_static \
+ --port ${port} \
+ --control-freq 3 --sim-freq 513 --max-episode-steps 80 \
+ --env-name ${env_name} --scene-name ${scene_name} \
+ --robot-init-x 0.35 0.35 1 --robot-init-y 0.20 0.20 1 --obj-init-x -0.35 -0.12 5 --obj-init-y -0.02 0.42 5 \
+ --robot-init-rot-quat-center 0 0 0 1 --robot-init-rot-rpy-range 0 0 1 0 0 1 0 0 1 \
+ --additional-env-build-kwargs ${coke_can_option} slightly_brighter_lighting=True &
+
+ eval_pids+=($!) # Track evaluation job PID
+ run_count=$((run_count + 1))
+ done
+done
+
+# camera orientations
+declare -a env_arr=("GraspSingleOpenedCokeCanAltGoogleCameraInScene-v0" \
+ "GraspSingleOpenedCokeCanAltGoogleCamera2InScene-v0")
+scene_name=google_pick_coke_can_1_v4
+
+for coke_can_option in "${coke_can_options_arr[@]}"; do
+ for env_name in "${env_arr[@]}"; do
+ for ckpt_path in "${arr[@]}"; do
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]} # Map to CUDA_VISIBLE_DEVICES GPU ID
+ # Launch service and capture its PID
+ port=$((base_port + run_count))
+ start_service ${gpu_id} ${ckpt_path} ${port}
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/eval_files/start_simpler_env.py --ckpt-path ${ckpt_path} \
+ --robot google_robot_static \
+ --port ${port} \
+ --control-freq 3 --sim-freq 513 --max-episode-steps 80 \
+ --env-name ${env_name} --scene-name ${scene_name} \
+ --robot-init-x 0.35 0.35 1 --robot-init-y 0.20 0.20 1 --obj-init-x -0.35 -0.12 5 --obj-init-y -0.02 0.42 5 \
+ --robot-init-rot-quat-center 0 0 0 1 --robot-init-rot-rpy-range 0 0 1 0 0 1 0 0 1 \
+ --additional-env-build-kwargs ${coke_can_option} &
+
+ eval_pids+=($!) # Track evaluation job PID
+ run_count=$((run_count + 1))
+ done
+ done
+done
+
+# Wait for all background jobs to finish
+stop_all_services
+echo "✅ All evaluations completed"
+
diff --git a/examples/SimplerEnv/eval_files/auto_eval_scripts/star_pick_coke_can_visual_matching.sh b/examples/SimplerEnv/eval_files/auto_eval_scripts/star_pick_coke_can_visual_matching.sh
new file mode 100644
index 0000000000000000000000000000000000000000..39e231f3edc97f7107692b949558d56b6a1dda1d
--- /dev/null
+++ b/examples/SimplerEnv/eval_files/auto_eval_scripts/star_pick_coke_can_visual_matching.sh
@@ -0,0 +1,137 @@
+# 4 (URDF variants) × 3 (coke_can options) × 1 (model path) = 12 runs
+
+
+# Environment setup
+cd /mnt/petrelfs/yejinhui/Projects/llavavla
+export starvla_python=/mnt/petrelfs/share/yejinhui/Envs/miniconda3/envs/starvlaSAM/bin/python
+export sim_python=/mnt/petrelfs/share/yejinhui/Envs/miniconda3/envs/dinoact/bin/python
+export SimplerEnv_PATH=/mnt/petrelfs/share/yejinhui/Projects/SimplerEnv
+export PYTHONPATH=$(pwd):${PYTHONPATH}
+base_port=5500
+
+MODEL_PATH=$1
+
+# Optional: allow overriding via argument
+if [ -z "$MODEL_PATH" ]; then
+ echo "❌ MODEL_PATH not provided as the first argument; falling back to default"
+ export MODEL_PATH="/mnt/petrelfs/yejinhui/Projects/llavavla/results/Checkpoints/1003_qwenfast/checkpoints/steps_10000_pytorch_model.pt"
+fi
+
+export ckpt_path=${MODEL_PATH}
+
+# Helper to launch policy servers
+policyserver_pids=()
+eval_pids=()
+
+
+task_name=pick_coke_vm
+
+
+start_service() {
+ local gpu_id=$1
+ local ckpt_path=$2
+ local port=$3
+ local server_log_dir="$(dirname "${ckpt_path}")/server_logs"
+ local svc_log="${server_log_dir}/$(basename "${ckpt_path%.*}")_${task_name}_${port}.log"
+ mkdir -p "${server_log_dir}"
+ echo "▶️ Starting service on GPU ${gpu_id}, port ${port}"
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${starvla_python} deployment/model_server/server_policy.py \
+ --ckpt_path ${ckpt_path} \
+ --port ${port} \
+ --use_bf16 \
+ > "${svc_log}" 2>&1 &
+
+ local pid=$! # capture PID immediately
+ policyserver_pids+=($pid)
+ sleep 20
+}
+
+# Helper to stop every service
+stop_all_services() {
+ # Wait for every evaluation job to complete
+ echo "⏳ Waiting for evaluation jobs to finish..."
+ for pid in "${eval_pids[@]}"; do
+ if ps -p "$pid" > /dev/null 2>&1; then
+ wait "$pid"
+ status=$?
+ if [ $status -ne 0 ]; then
+ echo "Warning: evaluation job $pid exited abnormally (status: $status)"
+ fi
+ fi
+ done
+
+ # Stop all services
+ echo "⏳ Stopping service processes..."
+ for pid in "${policyserver_pids[@]}"; do
+ if ps -p "$pid" > /dev/null 2>&1; then
+ kill "$pid" 2>/dev/null
+ wait "$pid" 2>/dev/null
+ else
+ echo "⚠️ Service process $pid no longer exists (might have exited early)"
+ fi
+ done
+
+
+ # Clear PID arrays
+ eval_pids=()
+ policyserver_pids=()
+ echo "✅ All services and tasks stopped"
+}
+
+
+# Retrieve CUDA_VISIBLE_DEVICES list on this host
+IFS=',' read -r -a CUDA_DEVICES <<< "$CUDA_VISIBLE_DEVICES" # convert comma-separated GPU list to an array
+NUM_GPUS=${#CUDA_DEVICES[@]} # count available GPUs
+
+
+
+policy_model=Qwenpi
+
+declare -a arr=(${MODEL_PATH})
+
+# lr_switch=laying horizontally but flipped left-right to match real eval; upright=standing; laid_vertically=laying vertically
+declare -a coke_can_options_arr=("lr_switch=True" "upright=True" "laid_vertically=True")
+
+# URDF variations
+declare -a urdf_version_arr=(None "recolor_tabletop_visual_matching_1" "recolor_tabletop_visual_matching_2" "recolor_cabinet_visual_matching_1")
+
+env_name=GraspSingleOpenedCokeCanInScene-v0
+scene_name=google_pick_coke_can_1_v4
+rgb_overlay_path=${SimplerEnv_PATH}/ManiSkill2_real2sim/data/real_inpainting/google_coke_can_real_eval_1.png
+
+# Variables for round-robin assignment
+total_gpus=8
+run_count=0
+
+for ckpt_path in "${arr[@]}"; do
+ echo "$ckpt_path"
+done
+
+for urdf_version in "${urdf_version_arr[@]}"; do
+ for coke_can_option in "${coke_can_options_arr[@]}"; do
+ for ckpt_path in "${arr[@]}"; do
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]} # map to GPU ID in CUDA_VISIBLE_DEVICES
+ # Launch service and capture the process ID
+ port=$((base_port + run_count))
+ start_service ${gpu_id} ${ckpt_path} ${port}
+
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/eval_files/start_simpler_env.py --ckpt-path ${ckpt_path} \
+ --robot google_robot_static \
+ --port $port \
+ --control-freq 3 --sim-freq 513 --max-episode-steps 80 \
+ --env-name ${env_name} --scene-name ${scene_name} \
+ --rgb-overlay-path ${rgb_overlay_path} \
+ --robot-init-x 0.35 0.35 1 --robot-init-y 0.20 0.20 1 --obj-init-x -0.35 -0.12 5 --obj-init-y -0.02 0.42 5 \
+ --robot-init-rot-quat-center 0 0 0 1 --robot-init-rot-rpy-range 0 0 1 0 0 1 0 0 1 \
+ --additional-env-build-kwargs ${coke_can_option} urdf_version=${urdf_version} &
+
+ eval_pids+=($!)
+ run_count=$((run_count + 1))
+ done
+ done
+done
+
+# Wait for all background jobs
+stop_all_services
+echo "✅ All evaluations finished"
+
diff --git a/examples/SimplerEnv/eval_files/auto_eval_scripts/star_put_in_drawer_variant_agg.sh b/examples/SimplerEnv/eval_files/auto_eval_scripts/star_put_in_drawer_variant_agg.sh
new file mode 100644
index 0000000000000000000000000000000000000000..fe38528bc8964e4080fbb6bade4ce107fd3f1209
--- /dev/null
+++ b/examples/SimplerEnv/eval_files/auto_eval_scripts/star_put_in_drawer_variant_agg.sh
@@ -0,0 +1,193 @@
+# Use all 8 GPUs and run tasks in the background
+# Total runs: 1 + 2 + 2 + 2 = 7 executions of main_inference.py.
+
+
+# Environment setup
+cd /mnt/petrelfs/yejinhui/Projects/llavavla
+export starvla_python=/mnt/petrelfs/share/yejinhui/Envs/miniconda3/envs/starvlaSAM/bin/python
+export sim_python=/mnt/petrelfs/share/yejinhui/Envs/miniconda3/envs/dinoact/bin/python
+export SimplerEnv_PATH=/mnt/petrelfs/share/yejinhui/Projects/SimplerEnv
+export PYTHONPATH=$(pwd):${PYTHONPATH}
+base_port=5500
+
+MODEL_PATH=$1
+
+# Optional: allow overriding via argument
+if [ -z "$MODEL_PATH" ]; then
+ echo "❌ MODEL_PATH not provided as the first argument; using default"
+ export MODEL_PATH="/mnt/petrelfs/yejinhui/Projects/llavavla/results/Checkpoints/1017_QwenOFT/checkpoints/steps_65000_pytorch_model.pt"
+fi
+
+export ckpt_path=${MODEL_PATH}
+
+# Helper to launch policy servers
+policyserver_pids=()
+eval_pids=()
+
+
+
+task_name=putin_va
+
+
+start_service() {
+ local gpu_id=$1
+ local ckpt_path=$2
+ local port=$3
+ local server_log_dir="$(dirname "${ckpt_path}")/server_logs"
+ local svc_log="${server_log_dir}/$(basename "${ckpt_path%.*}")_${task_name}_${port}.log"
+ mkdir -p "${server_log_dir}"
+
+ echo "▶️ Starting service on GPU ${gpu_id}, port ${port}"
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${starvla_python} deployment/model_server/server_policy.py \
+ --ckpt_path ${ckpt_path} \
+ --port ${port} \
+ --use_bf16 \
+ > "${svc_log}" 2>&1 &
+
+ local pid=$! # capture PID immediately
+ policyserver_pids+=($pid)
+ sleep 20
+}
+
+# Helper to stop every service
+stop_all_services() {
+ # Wait for every evaluation job to complete
+ echo "⏳ Waiting for evaluation jobs to finish..."
+ for pid in "${eval_pids[@]}"; do
+ if ps -p "$pid" > /dev/null 2>&1; then
+ wait "$pid"
+ status=$?
+ if [ $status -ne 0 ]; then
+ echo "Warning: evaluation job $pid exited abnormally (status: $status)"
+ fi
+ fi
+ done
+
+ # Stop all services
+ echo "⏳ Stopping service processes..."
+ for pid in "${policyserver_pids[@]}"; do
+ if ps -p "$pid" > /dev/null 2>&1; then
+ kill "$pid" 2>/dev/null
+ wait "$pid" 2>/dev/null
+ else
+ echo "⚠️ Service process $pid no longer exists (might have exited early)"
+ fi
+ done
+
+
+ # Clear PID arrays
+ eval_pids=()
+ policyserver_pids=()
+ echo "✅ All services and tasks stopped"
+}
+
+
+# Retrieve CUDA_VISIBLE_DEVICES list on this host
+IFS=',' read -r -a CUDA_DEVICES <<< "$CUDA_VISIBLE_DEVICES" # convert comma-separated GPU list to an array
+NUM_GPUS=${#CUDA_DEVICES[@]} # count available GPUs
+
+declare -a ckpt_paths=(
+ ${MODEL_PATH}
+)
+
+declare -a env_names=(
+ PlaceIntoClosedTopDrawerCustomInScene-v0
+)
+
+# Variables for round-robin assignment
+total_gpus=8
+run_count=0
+
+EXTRA_ARGS="--enable-raytracing --additional-env-build-kwargs model_ids=apple"
+
+# base setup
+scene_name=frl_apartment_stage_simple
+
+EvalSim() {
+ echo ${ckpt_path} ${env_name}
+ # Launch service and capture the process ID
+ port=$((base_port + run_count))
+ start_service ${gpu_id} ${ckpt_path} ${port}
+
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/eval_files/start_simpler_env.py --ckpt-path ${ckpt_path} \
+ --robot google_robot_static \
+ --port ${port} \
+ --control-freq 3 --sim-freq 513 --max-episode-steps 200 \
+ --env-name ${env_name} --scene-name ${scene_name} \
+ --robot-init-x 0.65 0.65 1 --robot-init-y -0.2 0.2 3 \
+ --robot-init-rot-quat-center 0 0 0 1 --robot-init-rot-rpy-range 0 0 1 0 0 1 0.0 0.0 1 \
+ --obj-init-x-range -0.08 -0.02 3 --obj-init-y-range -0.02 0.08 3 \
+ ${EXTRA_ARGS}
+
+}
+
+for ckpt_path in "${ckpt_paths[@]}"; do
+ for env_name in "${env_names[@]}"; do
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]}
+ EvalSim &
+ eval_pids+=($!)
+ run_count=$((run_count + 1))
+ done
+done
+
+# backgrounds
+declare -a scene_names=(
+ "modern_bedroom_no_roof"
+ "modern_office_no_roof"
+)
+
+for scene_name in "${scene_names[@]}"; do
+ for ckpt_path in "${ckpt_paths[@]}"; do
+ for env_name in "${env_names[@]}"; do
+ EXTRA_ARGS="--additional-env-build-kwargs shader_dir=rt model_ids=apple"
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]} # map to GPU ID in CUDA_VISIBLE_DEVICES
+ EvalSim &
+ eval_pids+=($!)
+ run_count=$((run_count + 1))
+ done
+ done
+done
+
+# lightings
+scene_name=frl_apartment_stage_simple
+
+for ckpt_path in "${ckpt_paths[@]}"; do
+ for env_name in "${env_names[@]}"; do
+ EXTRA_ARGS="--additional-env-build-kwargs shader_dir=rt light_mode=brighter model_ids=apple"
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]} # 映射到 CUDA_VISIBLE_DEVICES 中的 GPU ID
+ EvalSim &
+ eval_pids+=($!)
+ run_count=$((run_count + 1))
+
+ EXTRA_ARGS="--additional-env-build-kwargs shader_dir=rt light_mode=darker model_ids=apple"
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]} # 映射到 CUDA_VISIBLE_DEVICES 中的 GPU ID
+ EvalSim &
+ eval_pids+=($!)
+ run_count=$((run_count + 1))
+ done
+done
+
+# new cabinets
+scene_name=frl_apartment_stage_simple
+
+for ckpt_path in "${ckpt_paths[@]}"; do
+ for env_name in "${env_names[@]}"; do
+ EXTRA_ARGS="--additional-env-build-kwargs shader_dir=rt station_name=mk_station2 model_ids=apple"
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]} # 映射到 CUDA_VISIBLE_DEVICES 中的 GPU ID
+ EvalSim &
+ eval_pids+=($!)
+ run_count=$((run_count + 1))
+
+ EXTRA_ARGS="--additional-env-build-kwargs shader_dir=rt station_name=mk_station3 model_ids=apple"
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]} # 映射到 CUDA_VISIBLE_DEVICES 中的 GPU ID
+ EvalSim &
+ eval_pids+=($!)
+ run_count=$((run_count + 1))
+ done
+done
+
+# Wait for all background jobs
+stop_all_services
+echo "✅ All evaluations finished"
+
+
diff --git a/examples/SimplerEnv/eval_files/auto_eval_scripts/star_put_in_drawer_visual_matching.sh b/examples/SimplerEnv/eval_files/auto_eval_scripts/star_put_in_drawer_visual_matching.sh
new file mode 100644
index 0000000000000000000000000000000000000000..5f79b9e342b106c650818f195dc21a08b1317679
--- /dev/null
+++ b/examples/SimplerEnv/eval_files/auto_eval_scripts/star_put_in_drawer_visual_matching.sh
@@ -0,0 +1,165 @@
+# Use all 8 GPUs and run EvalOverlay tasks in the background
+# This results in 12 executions of main_inference.py.
+
+# Environment setup
+cd /mnt/petrelfs/yejinhui/Projects/llavavla
+export starvla_python=/mnt/petrelfs/share/yejinhui/Envs/miniconda3/envs/starvlaSAM/bin/python
+export sim_python=/mnt/petrelfs/share/yejinhui/Envs/miniconda3/envs/dinoact/bin/python
+export SimplerEnv_PATH=/mnt/petrelfs/share/yejinhui/Projects/SimplerEnv
+export PYTHONPATH=$(pwd):${PYTHONPATH}
+base_port=5500
+
+MODEL_PATH=$1
+
+# Optional: allow overriding via argument
+if [ -z "$MODEL_PATH" ]; then
+ echo "❌ MODEL_PATH not provided as the first argument; using default"
+ export MODEL_PATH="/mnt/petrelfs/yejinhui/Projects/llavavla/results/Checkpoints/1003_qwenfast/checkpoints/steps_10000_pytorch_model.pt"
+fi
+
+export ckpt_path=${MODEL_PATH}
+
+# Helper to launch policy servers
+policyserver_pids=()
+eval_pids=()
+
+
+task_name=putin_vm
+
+
+start_service() {
+ local gpu_id=$1
+ local ckpt_path=$2
+ local port=$3
+ local server_log_dir="$(dirname "${ckpt_path}")/server_logs"
+ local svc_log="${server_log_dir}/$(basename "${ckpt_path%.*}")_${task_name}_${port}.log"
+ mkdir -p "${server_log_dir}"
+
+ echo "▶️ Starting service on GPU ${gpu_id}, port ${port}"
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${starvla_python} deployment/model_server/server_policy.py \
+ --ckpt_path ${ckpt_path} \
+ --port ${port} \
+ --use_bf16 \
+ > "${svc_log}" 2>&1 &
+
+ local pid=$! # capture PID immediately
+ policyserver_pids+=($pid)
+ sleep 20
+}
+
+# Helper to stop every service
+stop_all_services() {
+ # Wait for every evaluation job to complete
+ echo "⏳ Waiting for evaluation jobs to finish..."
+ for pid in "${eval_pids[@]}"; do
+ if ps -p "$pid" > /dev/null 2>&1; then
+ wait "$pid"
+ status=$?
+ if [ $status -ne 0 ]; then
+ echo "Warning: evaluation job $pid exited abnormally (status: $status)"
+ fi
+ fi
+ done
+
+ # Stop all services
+ echo "⏳ Stopping service processes..."
+ for pid in "${policyserver_pids[@]}"; do
+ if ps -p "$pid" > /dev/null 2>&1; then
+ kill "$pid" 2>/dev/null
+ wait "$pid" 2>/dev/null
+ else
+ echo "⚠️ Service process $pid no longer exists (might have exited early)"
+ fi
+ done
+
+
+ # Clear PID arrays
+ eval_pids=()
+ policyserver_pids=()
+ echo "✅ All services and tasks stopped"
+}
+
+
+
+
+# Retrieve CUDA_VISIBLE_DEVICES list on this host
+IFS=',' read -r -a CUDA_DEVICES <<< "$CUDA_VISIBLE_DEVICES" # convert comma-separated GPU list to an array
+NUM_GPUS=${#CUDA_DEVICES[@]} # count available GPUs
+
+
+declare -a ckpt_paths=(
+ ${MODEL_PATH}
+)
+
+declare -a env_names=(
+ PlaceIntoClosedTopDrawerCustomInScene-v0
+)
+
+# URDF variations
+declare -a urdf_version_arr=("recolor_cabinet_visual_matching_1" "recolor_tabletop_visual_matching_1" "recolor_tabletop_visual_matching_2" None)
+
+# Variables for round-robin assignment
+total_gpus=8
+run_count=0
+
+# EvalOverlay runs main_inference three times (A0/B0/C0) on ${gpu_id}
+EvalOverlay() {
+ echo "${ckpt_path} ${env_name} (URDF=${urdf_version}) on GPU ${gpu_id}"
+ # Launch service and capture its PID
+ port=$((base_port + run_count))
+ start_service ${gpu_id} ${ckpt_path} ${port}
+
+
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/start_simpler_env.py --ckpt-path ${ckpt_path} \
+ --robot google_robot_static \
+ --port ${port} \
+ --control-freq 3 --sim-freq 513 --max-episode-steps 200 \
+ --env-name ${env_name} --scene-name dummy_drawer \
+ --robot-init-x 0.644 0.644 1 --robot-init-y -0.179 -0.179 1 \
+ --robot-init-rot-quat-center 0 0 0 1 --robot-init-rot-rpy-range 0 0 1 0 0 1 -0.03 -0.03 1 \
+ --obj-init-x-range -0.08 -0.02 3 --obj-init-y-range -0.02 0.08 3 \
+ --rgb-overlay-path ${SimplerEnv_PATH}/ManiSkill2_real2sim/data/real_inpainting/open_drawer_a0.png \
+ ${EXTRA_ARGS}
+
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/start_simpler_env.py --ckpt-path ${ckpt_path} \
+ --robot google_robot_static \
+ --port ${port} \
+ --control-freq 3 --sim-freq 513 --max-episode-steps 200 \
+ --env-name ${env_name} --scene-name dummy_drawer \
+ --robot-init-x 0.652 0.652 1 --robot-init-y 0.009 0.009 1 \
+ --robot-init-rot-quat-center 0 0 0 1 --robot-init-rot-rpy-range 0 0 1 0 0 1 0 0 1 \
+ --obj-init-x-range -0.08 -0.02 3 --obj-init-y-range -0.02 0.08 3 \
+ --rgb-overlay-path ${SimplerEnv_PATH}/ManiSkill2_real2sim/data/real_inpainting/open_drawer_b0.png \
+ ${EXTRA_ARGS}
+
+ CUDA_VISIBLE_DEVICES=${gpu_id} ${sim_python} examples/SimplerEnv/start_simpler_env.py --ckpt-path ${ckpt_path} \
+ --robot google_robot_static \
+ --port ${port} \
+ --control-freq 3 --sim-freq 513 --max-episode-steps 200 \
+ --env-name ${env_name} --scene-name dummy_drawer \
+ --robot-init-x 0.665 0.665 1 --robot-init-y 0.224 0.224 1 \
+ --robot-init-rot-quat-center 0 0 0 1 --robot-init-rot-rpy-range 0 0 1 0 0 1 0 0 1 \
+ --obj-init-x-range -0.08 -0.02 3 --obj-init-y-range -0.02 0.08 3 \
+ --rgb-overlay-path ${SimplerEnv_PATH}/ManiSkill2_real2sim/data/real_inpainting/open_drawer_c0.png \
+ ${EXTRA_ARGS}
+}
+
+for urdf_version in "${urdf_version_arr[@]}"; do
+ EXTRA_ARGS="--enable-raytracing --additional-env-build-kwargs station_name=mk_station_recolor light_mode=simple disable_bad_material=True urdf_version=${urdf_version} model_ids=baked_apple_v2"
+
+ for ckpt_path in "${ckpt_paths[@]}"; do
+ for env_name in "${env_names[@]}"; do
+ gpu_id=${CUDA_DEVICES[$((run_count % NUM_GPUS))]} # map to GPU ID in CUDA_VISIBLE_DEVICES
+
+ EvalOverlay &
+ eval_pids+=($!)
+ run_count=$((run_count + 1))
+ done
+ done
+done
+
+# Wait for all background jobs
+stop_all_services
+echo "✅ All evaluations finished"
+
+
diff --git a/examples/SimplerEnv/eval_files/custom_argparse.py b/examples/SimplerEnv/eval_files/custom_argparse.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d40e6fa45e2c921b03733fe64611e7c7db97308
--- /dev/null
+++ b/examples/SimplerEnv/eval_files/custom_argparse.py
@@ -0,0 +1,144 @@
+# copy from SimplerEnv/simpler_env/evaluation/argparse.py
+
+import argparse
+
+import numpy as np
+from sapien.core import Pose
+from transforms3d.euler import euler2quat
+
+from simpler_env.utils.io import DictAction
+
+
+def parse_range_tuple(t):
+ return np.linspace(t[0], t[1], int(t[2]))
+
+
+def get_args():
+ # parse command-line arguments
+ parser = argparse.ArgumentParser()
+ parser.add_argument(
+ "--policy-model",
+ type=str,
+ default="rt1",
+ help="Policy model type; e.g., 'rt1', 'octo-base', 'octo-small'",
+ )
+ parser.add_argument(
+ "--policy-setup",
+ type=str,
+ default="google_robot",
+ help="Policy model setup; e.g., 'google_robot', 'widowx_bridge'",
+ )
+ parser.add_argument("--ckpt-path", type=str, default=None)
+ parser.add_argument("--env-name", type=str, required=True)
+ parser.add_argument(
+ "--additional-env-save-tags",
+ type=str,
+ default=None,
+ help="Additional tags to save the environment eval results",
+ )
+ parser.add_argument("--scene-name", type=str, default="google_pick_coke_can_1_v4")
+ parser.add_argument("--enable-raytracing", action="store_true")
+ parser.add_argument("--robot", type=str, default="google_robot_static")
+ parser.add_argument(
+ "--obs-camera-name",
+ type=str,
+ default=None,
+ help="Obtain image observation from this camera for policy input. None = default",
+ )
+ parser.add_argument("--action-scale", type=float, default=1.0)
+
+ parser.add_argument("--control-freq", type=int, default=3)
+ parser.add_argument("--sim-freq", type=int, default=513)
+ parser.add_argument("--max-episode-steps", type=int, default=80)
+ parser.add_argument("--rgb-overlay-path", type=str, default=None)
+ parser.add_argument(
+ "--robot-init-x-range",
+ type=float,
+ nargs=3,
+ default=[0.35, 0.35, 1],
+ help="[xmin, xmax, num]",
+ )
+ parser.add_argument(
+ "--robot-init-y-range",
+ type=float,
+ nargs=3,
+ default=[0.20, 0.20, 1],
+ help="[ymin, ymax, num]",
+ )
+ parser.add_argument(
+ "--robot-init-rot-quat-center",
+ type=float,
+ nargs=4,
+ default=[1, 0, 0, 0],
+ help="[x, y, z, w]",
+ )
+ parser.add_argument(
+ "--robot-init-rot-rpy-range",
+ type=float,
+ nargs=9,
+ default=[0, 0, 1, 0, 0, 1, 0, 0, 1],
+ help="[rmin, rmax, rnum, pmin, pmax, pnum, ymin, ymax, ynum]",
+ )
+ parser.add_argument(
+ "--obj-variation-mode",
+ type=str,
+ default="xy",
+ choices=["xy", "episode"],
+ help="Whether to vary the xy position of a single object, or to vary predetermined episodes",
+ )
+ parser.add_argument("--obj-episode-range", type=int, nargs=2, default=[0, 60], help="[start, end]")
+ parser.add_argument(
+ "--obj-init-x-range",
+ type=float,
+ nargs=3,
+ default=[-0.35, -0.12, 5],
+ help="[xmin, xmax, num]",
+ )
+ parser.add_argument(
+ "--obj-init-y-range",
+ type=float,
+ nargs=3,
+ default=[-0.02, 0.42, 5],
+ help="[ymin, ymax, num]",
+ )
+
+ parser.add_argument(
+ "--additional-env-build-kwargs",
+ nargs="+",
+ action=DictAction,
+ help="Additional env build kwargs in xxx=yyy format. If the value "
+ 'is a list, it should be like key="[a,b]" or key=a,b '
+ 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" '
+ "Note that the quotation marks are necessary and that no white space "
+ "is allowed.",
+ )
+ parser.add_argument("--logging-dir", type=str, default="./results")
+ parser.add_argument("--tf-memory-limit", type=int, default=3072, help="Tensorflow memory limit")
+ parser.add_argument("--octo-init-rng", type=int, default=0, help="Octo init rng seed")
+ parser.add_argument("--async-freq", type=int, default=1)
+ parser.add_argument("--host", type=str, default="127.0.0.1", help="Octo init rng seed")
+ parser.add_argument("--port", type=int, default=10093)
+
+
+ args = parser.parse_args()
+
+ # env args: robot pose
+ args.robot_init_xs = parse_range_tuple(args.robot_init_x_range)
+ args.robot_init_ys = parse_range_tuple(args.robot_init_y_range)
+ args.robot_init_quats = []
+ for r in parse_range_tuple(args.robot_init_rot_rpy_range[:3]):
+ for p in parse_range_tuple(args.robot_init_rot_rpy_range[3:6]):
+ for y in parse_range_tuple(args.robot_init_rot_rpy_range[6:]):
+ args.robot_init_quats.append((Pose(q=euler2quat(r, p, y)) * Pose(q=args.robot_init_rot_quat_center)).q)
+ # env args: object position
+ if args.obj_variation_mode == "xy":
+ args.obj_init_xs = parse_range_tuple(args.obj_init_x_range)
+ args.obj_init_ys = parse_range_tuple(args.obj_init_y_range)
+ # update logging info (args.additional_env_save_tags) if using a different camera from default
+ if args.obs_camera_name is not None:
+ if args.additional_env_save_tags is None:
+ args.additional_env_save_tags = f"obs_camera_{args.obs_camera_name}"
+ else:
+ args.additional_env_save_tags = args.additional_env_save_tags + f"_obs_camera_{args.obs_camera_name}"
+
+ return args
diff --git a/examples/SimplerEnv/eval_files/model2simpler_interface.py b/examples/SimplerEnv/eval_files/model2simpler_interface.py
new file mode 100644
index 0000000000000000000000000000000000000000..34adb5e6f6e5cb81f2454f146c5bdf713fd6bf1f
--- /dev/null
+++ b/examples/SimplerEnv/eval_files/model2simpler_interface.py
@@ -0,0 +1,278 @@
+from collections import deque
+from typing import Optional, Sequence
+import os
+import cv2 as cv
+import matplotlib.pyplot as plt
+import numpy as np
+from transforms3d.euler import euler2axangle
+from typing import Dict
+import numpy as np
+from pathlib import Path
+
+
+from deployment.model_server.tools.websocket_policy_client import WebsocketClientPolicy
+from examples.SimplerEnv.eval_files.adaptive_ensemble import AdaptiveEnsembler
+from starVLA.model.tools import read_mode_config
+
+
+
+class ModelClient:
+ def __init__(
+ self,
+ policy_ckpt_path,
+ unnorm_key: Optional[str] = None,
+ policy_setup: str = "widowx_bridge",
+ horizon: int = 0,
+ action_ensemble_horizon: Optional[int] = None,
+ image_size: list[int] = [224, 224],
+ action_scale: float = 1.0,
+ cfg_scale: float = 1.5,
+ use_ddim: bool = True,
+ num_ddim_steps: int = 10,
+ action_ensemble = True,
+ adaptive_ensemble_alpha = 0.1,
+ host="0.0.0.0",
+ port=10093,
+ ) -> None:
+
+ # build client to connect server policy
+ self.client = WebsocketClientPolicy(host, port)
+
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
+ if policy_setup == "widowx_bridge":
+ unnorm_key = "oxe_bridge" if unnorm_key is None else unnorm_key
+ action_ensemble = action_ensemble
+ adaptive_ensemble_alpha = adaptive_ensemble_alpha
+ if action_ensemble_horizon is None:
+ # Set 7 for widowx_bridge to fix the window size of motion scale between each frame. see appendix in our paper for details
+ action_ensemble_horizon = 7
+ self.sticky_gripper_num_repeat = 1
+ elif policy_setup == "google_robot":
+ unnorm_key = "oxe_rt1" if unnorm_key is None else unnorm_key
+ action_ensemble = action_ensemble
+ adaptive_ensemble_alpha = adaptive_ensemble_alpha
+ if action_ensemble_horizon is None:
+ # Set 2 for google_robot to fix the window size of motion scale between each frame. see appendix in our paper for details
+ action_ensemble_horizon = 2
+ self.sticky_gripper_num_repeat = 10
+ else:
+ raise NotImplementedError(
+ f"Policy setup {policy_setup} not supported for octo models. The other datasets can be found in the huggingface config.json file."
+ )
+ self.policy_setup = policy_setup
+ self.unnorm_key = unnorm_key
+
+ print(f"*** policy_setup: {policy_setup}, unnorm_key: {unnorm_key} ***")
+ self.use_ddim = use_ddim
+ self.num_ddim_steps = num_ddim_steps
+
+
+ self.cfg_scale = cfg_scale # 1.5
+
+ self.image_size = image_size
+ self.action_scale = action_scale # 1.0
+ self.horizon = horizon #0
+ self.action_ensemble = action_ensemble
+ self.adaptive_ensemble_alpha = adaptive_ensemble_alpha
+ self.action_ensemble_horizon = action_ensemble_horizon
+ self.sticky_action_is_on = False
+ self.gripper_action_repeat = 0
+ self.sticky_gripper_action = 0.0
+ self.previous_gripper_action = None
+
+ self.task_description = None
+ self.image_history = deque(maxlen=self.horizon)
+ if self.action_ensemble:
+ self.action_ensembler = AdaptiveEnsembler(self.action_ensemble_horizon, self.adaptive_ensemble_alpha)
+ else:
+ self.action_ensembler = None
+ self.num_image_history = 0
+
+ self.action_norm_stats = self.get_action_stats(self.unnorm_key, policy_ckpt_path=policy_ckpt_path)
+
+
+ def _add_image_to_history(self, image: np.ndarray) -> None:
+ self.image_history.append(image)
+ self.num_image_history = min(self.num_image_history + 1, self.horizon)
+
+ def reset(self, task_description: str) -> None:
+ self.task_description = task_description
+ self.image_history.clear()
+ if self.action_ensemble:
+ self.action_ensembler.reset()
+ self.num_image_history = 0
+
+ self.sticky_action_is_on = False
+ self.gripper_action_repeat = 0
+ self.sticky_gripper_action = 0.0
+ self.previous_gripper_action = None
+
+ def step(
+ self, image: np.ndarray, task_description: Optional[str] = None, *args, **kwargs
+ ) -> tuple[dict[str, np.ndarray], dict[str, np.ndarray]]:
+ """
+ Input:
+ image: np.ndarray of shape (H, W, 3), uint8
+ task_description: Optional[str], task description; if different from previous task description, policy state is reset
+ Output:
+ raw_action: dict; raw policy action output
+ action: dict; processed action to be sent to the maniskill2 environment, with the following keys:
+ - 'world_vector': np.ndarray of shape (3,), xyz translation of robot end-effector
+ - 'rot_axangle': np.ndarray of shape (3,), axis-angle representation of end-effector rotation
+ - 'gripper': np.ndarray of shape (1,), gripper action
+ - 'terminate_episode': np.ndarray of shape (1,), 1 if episode should be terminated, 0 otherwise
+ """
+ if task_description is not None:
+ if task_description != self.task_description:
+ self.reset(task_description)
+
+ assert image.dtype == np.uint8
+ self._add_image_to_history(self._resize_image(image))
+ # image: Image.Image = Image.fromarray(image)
+
+ image = self._resize_image(image)
+ example = {
+ "image": [image],
+ "lang": self.task_description,
+ }
+
+ vla_input = {
+ "examples": [example],
+ "do_sample": False,
+ "cfg_scale": self.cfg_scale,
+ "use_ddim": self.use_ddim,
+ "num_ddim_steps": self.num_ddim_steps,
+ }
+
+ vla_input = {
+ "examples": [example],
+ "do_sample": False,
+ "use_ddim": self.use_ddim,
+ "num_ddim_steps": self.num_ddim_steps,
+ }
+
+
+ response = self.client.predict_action(vla_input)
+
+
+ # unnormalize the action
+ normalized_actions = response["data"]["normalized_actions"] # B, chunk, D
+ normalized_actions = normalized_actions[0]
+
+
+ raw_actions = self.unnormalize_actions(normalized_actions=normalized_actions, action_norm_stats=self.action_norm_stats)
+
+ if self.action_ensemble:
+ raw_actions = self.action_ensembler.ensemble_action(raw_actions)[None]
+
+ raw_action = {
+ "world_vector": np.array(raw_actions[0, :3]),
+ "rotation_delta": np.array(raw_actions[0, 3:6]),
+ "open_gripper": np.array(raw_actions[0, 6:7]), # range [0, 1]; 1 = open; 0 = close
+ }
+
+ # process raw_action to obtain the action to be sent to the maniskill2 environment
+ action = {}
+ action["world_vector"] = raw_action["world_vector"] * self.action_scale
+ action_rotation_delta = np.asarray(raw_action["rotation_delta"], dtype=np.float64)
+
+ roll, pitch, yaw = action_rotation_delta
+ axes, angles = euler2axangle(roll, pitch, yaw)
+ action_rotation_axangle = axes * angles
+ action["rot_axangle"] = action_rotation_axangle * self.action_scale
+
+ if self.policy_setup == "google_robot":
+ action["gripper"] = 0
+ current_gripper_action = raw_action["open_gripper"]
+ if self.previous_gripper_action is None:
+ relative_gripper_action = np.array([0])
+ self.previous_gripper_action = current_gripper_action
+ else:
+ relative_gripper_action = self.previous_gripper_action - current_gripper_action
+ # fix a bug in the SIMPLER code here
+ # self.previous_gripper_action = current_gripper_action
+
+ if np.abs(relative_gripper_action) > 0.5 and (not self.sticky_action_is_on):
+ self.sticky_action_is_on = True
+ self.sticky_gripper_action = relative_gripper_action
+ self.previous_gripper_action = current_gripper_action
+
+ if self.sticky_action_is_on:
+ self.gripper_action_repeat += 1
+ relative_gripper_action = self.sticky_gripper_action
+
+ if self.gripper_action_repeat == self.sticky_gripper_num_repeat:
+ self.sticky_action_is_on = False
+ self.gripper_action_repeat = 0
+ self.sticky_gripper_action = 0.0
+
+ action["gripper"] = relative_gripper_action
+
+ elif self.policy_setup == "widowx_bridge":
+ action["gripper"] = 2.0 * (raw_action["open_gripper"] > 0.5) - 1.0
+
+ action["terminate_episode"] = np.array([0.0])
+ return raw_action, action
+
+ @staticmethod
+ def unnormalize_actions(normalized_actions: np.ndarray, action_norm_stats: Dict[str, np.ndarray]) -> np.ndarray:
+ mask = action_norm_stats.get("mask", np.ones_like(action_norm_stats["q01"], dtype=bool))
+ action_high, action_low = np.array(action_norm_stats["q99"]), np.array(action_norm_stats["q01"])
+ normalized_actions = np.clip(normalized_actions, -1, 1)
+ normalized_actions[:, 6] = np.where(normalized_actions[:, 6] < 0.5, 0, 1)
+ actions = np.where(
+ mask,
+ 0.5 * (normalized_actions + 1) * (action_high - action_low) + action_low,
+ normalized_actions,
+ )
+
+ return actions
+
+ @staticmethod
+ def get_action_stats(unnorm_key: str, policy_ckpt_path) -> dict:
+ """
+ Duplicate stats accessor (retained for backward compatibility).
+ """
+ policy_ckpt_path = Path(policy_ckpt_path)
+ model_config, norm_stats = read_mode_config(policy_ckpt_path) # read config and norm_stats
+
+ # unnorm_key = baseframework._check_unnorm_key(norm_stats, unnorm_key) # 其实也是很环境 specific 的
+ return norm_stats[unnorm_key]["action"]
+
+
+
+ def _resize_image(self, image: np.ndarray) -> np.ndarray:
+ image = cv.resize(image, tuple(self.image_size), interpolation=cv.INTER_AREA)
+ return image
+
+ def visualize_epoch(
+ self, predicted_raw_actions: Sequence[np.ndarray], images: Sequence[np.ndarray], save_path: str
+ ) -> None:
+ images = [self._resize_image(image) for image in images]
+ ACTION_DIM_LABELS = ["x", "y", "z", "roll", "pitch", "yaw", "grasp"]
+
+ img_strip = np.concatenate(np.array(images[::3]), axis=1)
+
+ # set up plt figure
+ figure_layout = [["image"] * len(ACTION_DIM_LABELS), ACTION_DIM_LABELS]
+ plt.rcParams.update({"font.size": 12})
+ fig, axs = plt.subplot_mosaic(figure_layout)
+ fig.set_size_inches([45, 10])
+
+ # plot actions
+ pred_actions = np.array(
+ [
+ np.concatenate([a["world_vector"], a["rotation_delta"], a["open_gripper"]], axis=-1)
+ for a in predicted_raw_actions
+ ]
+ )
+ for action_dim, action_label in enumerate(ACTION_DIM_LABELS):
+ # actions have batch, horizon, dim, in this example we just take the first action for simplicity
+ axs[action_label].plot(pred_actions[:, action_dim], label="predicted action")
+ axs[action_label].set_title(action_label)
+ axs[action_label].set_xlabel("Time in one episode")
+
+ axs["image"].imshow(img_strip)
+ axs["image"].set_xlabel("Time in one episode (subsampled)")
+ plt.legend()
+ plt.savefig(save_path)
\ No newline at end of file
diff --git a/examples/SimplerEnv/eval_files/run_policy_server.sh b/examples/SimplerEnv/eval_files/run_policy_server.sh
new file mode 100644
index 0000000000000000000000000000000000000000..8cf63048c983a68d591cacff64ec0cccfb0b7848
--- /dev/null
+++ b/examples/SimplerEnv/eval_files/run_policy_server.sh
@@ -0,0 +1,27 @@
+
+
+cd /mnt/petrelfs/yejinhui/Projects/starVLA
+export PYTHONPATH=$(pwd):${PYTHONPATH}
+
+port=6678
+gpu_id=2
+# export DEBUG=true
+export star_vla_python=/mnt/petrelfs/share/yejinhui/Envs/miniconda3/envs/starVLA/bin/python
+
+your_ckpt=./results/Checkpoints/1208_bridge_rt_1_Qwen3PI/final_model/pytorch_model.pt
+
+#### build output directory #####
+ckpt_dir=$(dirname "${your_ckpt}")
+ckpt_base=$(basename "${your_ckpt}")
+ckpt_name="${ckpt_base%.*}"
+output_server_dir="${ckpt_dir}/output_server"
+mkdir -p "${output_server_dir}"
+log_file="${output_server_dir}/${ckpt_name}_policy_server_${port}.log"
+
+
+#### run server #####
+CUDA_VISIBLE_DEVICES=${gpu_id} ${star_vla_python} deployment/model_server/server_policy.py \
+ --ckpt_path ${your_ckpt} \
+ --port ${port} \
+ --use_bf16 \
+ 2>&1 | tee "${log_file}"
\ No newline at end of file
diff --git a/examples/SimplerEnv/eval_files/start_simpler_env.py b/examples/SimplerEnv/eval_files/start_simpler_env.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ce64d7702b24686a9e45ac236d93ffafe2d9d81
--- /dev/null
+++ b/examples/SimplerEnv/eval_files/start_simpler_env.py
@@ -0,0 +1,42 @@
+import os
+
+# from IPython import embed; embed()
+from examples.SimplerEnv.eval_files.custom_argparse import get_args
+from examples.SimplerEnv.eval_files.model2simpler_interface import ModelClient
+from simpler_env.evaluation.maniskill2_evaluator import maniskill2_evaluator
+
+import numpy as np
+
+
+def start_debugpy_once():
+ import debugpy
+ if getattr(start_debugpy_once, "_started", False):
+ return
+ debugpy.listen(("0.0.0.0", 10092))
+ print("🔍 Waiting for VSCode attach on 0.0.0.0:10092 ...")
+ debugpy.wait_for_client()
+ start_debugpy_once._started = True
+
+
+if __name__ == "__main__":
+ args = get_args()
+
+ os.environ["DISPLAY"] = ""
+ # prevent a single jax process from taking up all the GPU memory
+ os.environ["XLA_PYTHON_CLIENT_PREALLOCATE"] = "false"
+
+ if os.getenv("DEBUG", False):
+ start_debugpy_once()
+ model = ModelClient(
+ policy_ckpt_path=args.ckpt_path, # to get unnormalization stats
+ policy_setup=args.policy_setup,
+ port=args.port,
+ action_scale=args.action_scale,
+ cfg_scale=1.5 # cfg from 1.5 to 7 also performs well
+ )
+
+ # policy model creation; update this if you are using a new policy model
+ # run real-to-sim evaluation
+ success_arr = maniskill2_evaluator(model, args)
+ print(args)
+ print(" " * 10, "Average success", np.mean(success_arr))
diff --git a/examples/SimplerEnv/eval_files/start_simpler_env.sh b/examples/SimplerEnv/eval_files/start_simpler_env.sh
new file mode 100644
index 0000000000000000000000000000000000000000..eeb645de2807b134102430417cd453cf6c479341
--- /dev/null
+++ b/examples/SimplerEnv/eval_files/start_simpler_env.sh
@@ -0,0 +1,126 @@
+#!/bin/bash
+
+echo `which python`
+
+export sim_python=/mnt/petrelfs/share/yejinhui/Envs/miniconda3/envs/dinoact/bin/python
+export SimplerEnv_PATH=/mnt/petrelfs/share/yejinhui/Projects/SimplerEnv
+export PYTHONPATH=$(pwd):${PYTHONPATH}
+#### set environment variables #####
+
+#### get parameters #####
+if [ -n "$1" ]; then
+ MODEL_PATH="$1" # model path indict the output tree
+else
+ MODEL_PATH=./results/Checkpoints/1208_bridge_rt_1_Qwen3PI/final_model/pytorch_model.pt
+fi
+
+port=${2:-6678} # connect to your policy server port
+
+
+#### build output directory #####
+ckpt_path=${MODEL_PATH}
+ckpt_dir=$(dirname "${ckpt_path}")
+ckpt_base=$(basename "${ckpt_path}")
+ckpt_name="${ckpt_base%.*}"
+
+# Create output directories
+output_server_dir="${ckpt_dir}/output_server"
+output_eval_dir="${ckpt_dir}/output_eval"
+mkdir -p "${output_server_dir}"
+mkdir -p "${output_eval_dir}"
+#### build output directory #####
+
+TSET_NUM=1
+# export DEBUG=1
+
+IFS=',' read -r -a CUDA_DEVICES <<< "$CUDA_VISIBLE_DEVICES"
+NUM_GPUS=${#CUDA_DEVICES[@]}
+
+echo "CUDA_VISIBLE_DEVICES: $CUDA_VISIBLE_DEVICES"
+echo "CUDA_DEVICES: ${CUDA_DEVICES[@]}"
+echo "NUM_GPUS: $NUM_GPUS"
+
+scene_name=bridge_table_1_v1
+robot=widowx
+rgb_overlay_path=${SimplerEnv_PATH}/ManiSkill2_real2sim/data/real_inpainting/bridge_real_eval_1.png
+robot_init_x=0.147
+robot_init_y=0.028
+
+declare -a ENV_NAMES=(
+ # StackGreenCubeOnYellowCubeBakedTexInScene-v0
+ # PutCarrotOnPlateInScene-v0
+ # PutSpoonOnTableClothInScene-v0
+)
+
+for i in "${!ENV_NAMES[@]}"; do
+ env="${ENV_NAMES[i]}"
+ for ((run_idx=1; run_idx<=TSET_NUM; run_idx++)); do
+ # Path for log file
+ task_log="${output_eval_dir}/${ckpt_name}_${env}_run${run_idx}.log"
+ echo "▶️ Launching task [${env}] run#${run_idx}, log → ${task_log}"
+
+ ${sim_python} examples/SimplerEnv/eval_files/start_simpler_env.py \
+ --ckpt-path ${ckpt_path} \
+ --port ${port} \
+ --robot ${robot} \
+ --policy-setup widowx_bridge \
+ --control-freq 5 \
+ --sim-freq 500 \
+ --max-episode-steps 120 \
+ --env-name "${env}" \
+ --scene-name ${scene_name} \
+ --rgb-overlay-path ${rgb_overlay_path} \
+ --robot-init-x ${robot_init_x} ${robot_init_x} 1 \
+ --robot-init-y ${robot_init_y} ${robot_init_y} 1 \
+ --obj-variation-mode episode \
+ --obj-episode-range 0 24 \
+ --robot-init-rot-quat-center 0 0 0 1 \
+ --robot-init-rot-rpy-range 0 0 1 0 0 1 0 0 1 \
+ > "${task_log}" 2>&1 &
+
+ sleep 6
+
+ done
+done
+
+declare -a ENV_NAMES_V2=(
+ PutEggplantInBasketScene-v0
+)
+
+scene_name=bridge_table_1_v2
+robot=widowx_sink_camera_setup
+rgb_overlay_path=${SimplerEnv_PATH}/ManiSkill2_real2sim/data/real_inpainting/bridge_sink.png
+robot_init_x=0.127
+robot_init_y=0.06
+
+for i in "${!ENV_NAMES_V2[@]}"; do
+ env="${ENV_NAMES_V2[i]}"
+ for ((run_idx=1; run_idx<=TSET_NUM; run_idx++)); do
+ # Path for log file
+ task_log="${output_eval_dir}/${ckpt_name}_${env}_run${run_idx}.log"
+ echo "▶️ Launching V2 task [${env}] run#${run_idx}, log → ${task_log}"
+
+ ${sim_python} examples/SimplerEnv/eval_files/start_simpler_env.py\
+ --ckpt-path ${ckpt_path} \
+ --port ${port} \
+ --robot ${robot} \
+ --policy-setup widowx_bridge \
+ --control-freq 5 \
+ --sim-freq 500 \
+ --max-episode-steps 120 \
+ --env-name "${env}" \
+ --scene-name ${scene_name} \
+ --rgb-overlay-path ${rgb_overlay_path} \
+ --robot-init-x ${robot_init_x} ${robot_init_x} 1 \
+ --robot-init-y ${robot_init_y} ${robot_init_y} 1 \
+ --obj-variation-mode episode \
+ --obj-episode-range 0 24 \
+ --robot-init-rot-quat-center 0 0 0 1 \
+ --robot-init-rot-rpy-range 0 0 1 0 0 1 0 0 1 \
+ > "${task_log}" 2>&1 &
+
+ sleep 6
+ done
+done
+
+# echo "✅ Finished"
\ No newline at end of file
diff --git a/examples/SimplerEnv/eval_files/test_your_simplerEnv.py b/examples/SimplerEnv/eval_files/test_your_simplerEnv.py
new file mode 100644
index 0000000000000000000000000000000000000000..407cae0765bd5bcaad47f2b465580f8c90dfef9a
--- /dev/null
+++ b/examples/SimplerEnv/eval_files/test_your_simplerEnv.py
@@ -0,0 +1,40 @@
+
+# Optional: print more diagnostics for debugging
+# from sapien import disable_renderer
+# disable_renderer() # <-- Uncomment to skip the renderer
+
+
+
+from simpler_env.utils.env.env_builder import build_maniskill2_env, get_robot_control_mode
+from simpler_env.utils.env.observation_utils import get_image_from_maniskill2_obs_dict
+from simpler_env.utils.visualization import write_video
+import logging
+
+logging.basicConfig(level=logging.DEBUG)
+
+env_name = "PutEggplantInBasketScene-v0"
+
+kwargs = {
+ "obs_mode": "rgbd",
+ "robot": "widowx_sink_camera_setup",
+ "sim_freq": 500,
+ "control_mode": "arm_pd_ee_target_delta_pose_align2_gripper_pd_joint_pos",
+ "control_freq": 5,
+ "max_episode_steps": 120,
+ "scene_name": "bridge_table_1_v2",
+ "camera_cfgs": {"add_segmentation": True},
+ "rgb_overlay_path": "ManiSkill2_real2sim/data/real_inpainting/bridge_sink.png"
+}
+
+additional_env_build_kwargs = {}
+
+print("🔧 Start building ManiSkill2 env...")
+env = build_maniskill2_env(
+ env_name,
+ **additional_env_build_kwargs,
+ **kwargs,
+)
+print("✅ Env built successfully:", env)
+
+obs = env.reset()
+print("📷 First observation keys:", obs.keys() if isinstance(obs, dict) else type(obs))
diff --git a/examples/SimplerEnv/train_files/fractal_modality.json b/examples/SimplerEnv/train_files/fractal_modality.json
new file mode 100644
index 0000000000000000000000000000000000000000..07d8b5f9b9aa29340a32cd28d20e452098ea4c6d
--- /dev/null
+++ b/examples/SimplerEnv/train_files/fractal_modality.json
@@ -0,0 +1,74 @@
+{
+ "state": {
+ "x": {
+ "start": 0,
+ "end": 1
+ },
+ "y": {
+ "start": 1,
+ "end": 2
+ },
+ "z": {
+ "start": 2,
+ "end": 3
+ },
+ "rx": {
+ "start": 3,
+ "end": 4
+ },
+ "ry": {
+ "start": 4,
+ "end": 5
+ },
+ "rz": {
+ "start": 5,
+ "end": 6
+ },
+ "rw": {
+ "start": 6,
+ "end": 7
+ },
+ "gripper": {
+ "start": 7,
+ "end": 8
+ }
+ },
+ "action": {
+ "x": {
+ "start": 0,
+ "end": 1
+ },
+ "y": {
+ "start": 1,
+ "end": 2
+ },
+ "z": {
+ "start": 2,
+ "end": 3
+ },
+ "roll": {
+ "start": 3,
+ "end": 4
+ },
+ "pitch": {
+ "start": 4,
+ "end": 5
+ },
+ "yaw": {
+ "start": 5,
+ "end": 6
+ },
+ "gripper": {
+ "start": 6,
+ "end": 7
+ }
+ },
+ "video": {
+ "image": {
+ "original_key": "observation.images.image"
+ }
+ },
+ "annotation": {
+ "human.action.task_description": {"original_key": "task_index"}
+ }
+}
\ No newline at end of file
diff --git a/examples/SimplerEnv/train_files/modality.json b/examples/SimplerEnv/train_files/modality.json
new file mode 100644
index 0000000000000000000000000000000000000000..49324e2b47cdd9b31c703cf57796c819bff6898b
--- /dev/null
+++ b/examples/SimplerEnv/train_files/modality.json
@@ -0,0 +1,74 @@
+{
+ "state": {
+ "x": {
+ "start": 0,
+ "end": 1
+ },
+ "y": {
+ "start": 1,
+ "end": 2
+ },
+ "z": {
+ "start": 2,
+ "end": 3
+ },
+ "roll": {
+ "start": 3,
+ "end": 4
+ },
+ "pitch": {
+ "start": 4,
+ "end": 5
+ },
+ "yaw": {
+ "start": 5,
+ "end": 6
+ },
+ "pad": {
+ "start": 6,
+ "end": 7
+ },
+ "gripper": {
+ "start": 7,
+ "end": 8
+ }
+ },
+ "action": {
+ "x": {
+ "start": 0,
+ "end": 1
+ },
+ "y": {
+ "start": 1,
+ "end": 2
+ },
+ "z": {
+ "start": 2,
+ "end": 3
+ },
+ "roll": {
+ "start": 3,
+ "end": 4
+ },
+ "pitch": {
+ "start": 4,
+ "end": 5
+ },
+ "yaw": {
+ "start": 5,
+ "end": 6
+ },
+ "gripper": {
+ "start": 6,
+ "end": 7
+ }
+ },
+ "video": {
+ "image_0": {
+ "original_key": "observation.images.image_0"
+ }
+ },
+ "annotation": {
+ "human.action.task_description": {"original_key": "task_index"}
+ }
+}
\ No newline at end of file
diff --git a/examples/SimplerEnv/train_files/run_oxe_train.sh b/examples/SimplerEnv/train_files/run_oxe_train.sh
new file mode 100644
index 0000000000000000000000000000000000000000..38789e5729e78e34cbd46937a0ef75092e1d0a9f
--- /dev/null
+++ b/examples/SimplerEnv/train_files/run_oxe_train.sh
@@ -0,0 +1,73 @@
+
+
+export NCCL_SOCKET_IFNAME=bond0
+export NCCL_IB_HCA=mlx5_2,mlx5_3
+
+# used for check save when communication
+export NCCL_BLOCKING_WAIT=1
+export NCCL_ASYNC_ERROR_HANDLING=1
+export NCCL_TIMEOUT=1000 # timeout set to 1 hour (unit: seconds)
+
+###########################################################################################
+# === Please modify the following paths according to your environment ===
+Framework_name=QwenFast
+freeze_module_list=''
+base_vlm=playground/Pretrained_models/Qwen3-VL-4B-Instruct-Action
+config_yaml=./examples/SimplerEnv/train_files/starvla_cotrain_oxe.yaml
+oxe_data_root=playground/Datasets/OXE_LEROBOT
+data_mix=bridge_rt_1
+run_root_dir=./results/Checkpoints
+run_id=1221_${data_mix}_qwen3Fast
+# === End of environment variable configuration ===
+###########################################################################################
+
+
+# export WANDB_MODE=disabled
+
+output_dir=${run_root_dir}/${run_id}
+mkdir -p ${output_dir}
+# mv this script to the output dir
+cp $0 ${output_dir}/
+
+
+
+accelerate launch \
+ --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \
+ --num_processes 8 \
+ starVLA/training/train_starvla.py \
+ --config_yaml ${config_yaml} \
+ --framework.name ${Framework_name} \
+ --framework.qwenvl.base_vlm ${base_vlm} \
+ --datasets.vla_data.data_root_dir ${oxe_data_root}\
+ --datasets.vla_data.data_mix ${data_mix} \
+ --datasets.vla_data.per_device_batch_size 16 \
+ --trainer.freeze_modules ${freeze_module_list} \
+ --trainer.max_train_steps 100000 \
+ --trainer.save_interval 10000 \
+ --trainer.logging_frequency 100 \
+ --trainer.eval_interval 1000 \
+ --run_root_dir ${run_root_dir} \
+ --run_id ${run_id} \
+ --wandb_project starVLA_simplerEnv \
+ --wandb_entity jinhuiye \
+ # --is_debug True
+
+
+
+##### Multi-Server Multi-GPU training script #####
+ # accelerate launch \
+ # --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \
+ # --main_process_ip $MASTER_ADDR \
+ # --main_process_port $MASTER_PORT \
+ # --machine_rank $SLURM_PROCID \
+ # --num_machines $SLURM_NNODES \
+ # --num_processes=${TOTAL_GPUS} \
+ # starVLA/training/train_starvla.py \
+ # --config_yaml ${config_yaml} \
+ # --framework.name ${Framework_name} \
+ # --framework.qwenvl.base_vlm ${base_vlm} \
+ # --run_root_dir ${run_root_dir} \
+ # --run_id ${run_id} \
+ # --wandb_project your_project \
+ # --wandb_entity your_name
+##### Multi-Server Multi-GPU training script #####
diff --git a/examples/SimplerEnv/train_files/starvla_cotrain_oxe.yaml b/examples/SimplerEnv/train_files/starvla_cotrain_oxe.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..c0a19a514b3456b82fb174911f8c36596b82d0e4
--- /dev/null
+++ b/examples/SimplerEnv/train_files/starvla_cotrain_oxe.yaml
@@ -0,0 +1,114 @@
+run_id: qwenact
+run_root_dir: results/Checkpoints
+seed: 42
+trackers: [jsonl, wandb]
+wandb_entity: your_wandb_entity
+wandb_project: llavavla
+is_debug: false
+
+framework:
+ name: QwenGR00T
+ qwenvl:
+ base_vlm: ./playground/Pretrained_models/Qwen2.5-VL-3B-Instruct
+ attn_implementation: flash_attention_2
+ vl_hidden_dim: 2048
+ dino:
+ dino_backbone: dinov2_vits14
+
+ action_model:
+ action_model_type: DiT-B
+ hidden_size: 1024 # Matches the final DiT projection, used by the ActionDecoder
+ action_hidden_dim: 2560
+ add_pos_embed: True
+ max_seq_len: 1024
+ action_dim: 7
+ state_dim: 7
+ future_action_window_size: 15
+ action_horizon: 16
+ past_action_window_size: 0
+ repeated_diffusion_steps: 8
+ noise_beta_alpha: 1.5
+ noise_beta_beta: 1.0
+ noise_s: 0.999
+ num_timestep_buckets: 1000
+ num_inference_timesteps: 4
+ num_target_vision_tokens: 32
+ diffusion_model_cfg: # Parameters for the DiT transformer
+ cross_attention_dim: 2048 # Dimension of the VLM
+ dropout: 0.2
+ final_dropout: true
+ interleave_self_attention: true
+ norm_type: "ada_norm"
+ num_layers: 16
+ output_dim: 1024
+ positional_embeddings: null
+
+
+
+datasets:
+ vlm_data:
+ dataset_py: vlm_datasets
+ dataformat: llava_json
+ dataset_use: sharegpt4v_coco
+ eval_dataset: sharegpt4v_coco
+ data_flatten: false
+ base_interval: 2
+ max_pixels: 307200
+ min_pixels: 784
+ model_max_length: 2048
+ model_type: qwen2.5vl
+ per_device_batch_size: 4
+
+ vla_data:
+ dataset_py: lerobot_datasets
+ data_root_dir: playground/Datasets/OXE_LEROBOT_DATASET
+ data_mix: bridge_rt_1 # bridge_rt_1
+ action_type: delta_ee
+ CoT_prompt: "Your task is {instruction}. To identify the key objects for your task. Locate their bounding boxes in [x1,y1,x2,y2] format."
+ CoT_answer: bbox
+ default_image_resolution: [3, 224, 224]
+ per_device_batch_size: 16
+ load_all_data_for_training: true
+ obs: ["image_0"]
+ image_size: [224,224]
+ video_backend: torchvision_av
+
+trainer:
+ epochs: 100
+ max_train_steps: 100000
+ num_warmup_steps: 5000
+ save_interval: 5000
+ eval_interval: 100
+ learning_rate:
+ base: 1e-05
+ qwen_vl_interface: 1.0e-05
+ action_model: 1.0e-04
+ lr_scheduler_type: cosine_with_min_lr
+ scheduler_specific_kwargs:
+ min_lr: 5.0e-07
+ freeze_modules: ''
+ loss_scale:
+ vla: 1.0
+ vlm: 0.1
+ # pretrained_checkpoint: ./results/Checkpoints/1_need/0601_qwenact_fixqwen_32gpus_lr_1e-3_qformer_36_37/steps_100000/pytorch_model.pt
+ # reload_modules: 'action_model,layer_qformer' # warning: this may cause model to not converge
+ repeated_diffusion_steps: 4
+ max_grad_norm: 1.0
+ warmup_ratio: 0.1
+ weight_decay: 0.0
+ logging_frequency: 10
+ gradient_clipping: 1.0
+ gradient_accumulation_steps: 1
+
+ optimizer:
+ name: AdamW
+ betas: [0.9, 0.95]
+ eps: 1.0e-08
+ weight_decay: 1.0e-08
+
+ # parameters to be determined
+ is_resume: false
+ resume_epoch: null
+ resume_step: null
+ enable_gradient_checkpointing: true
+ enable_mixed_precision_training: true
diff --git a/examples/Suqian_agibot/README.md b/examples/Suqian_agibot/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..0009d95610b97e5f090a1af3fe1cf5f37f6b8a0b
--- /dev/null
+++ b/examples/Suqian_agibot/README.md
@@ -0,0 +1,136 @@
+# 🚀 Robocasa-GR1-Tabletop-Tasks Evaluation
+
+This document provides instructions for reproducing our **experimental results** with [robocasa-gr1-tabletop-tasks](https://github.com/robocasa/robocasa-gr1-tabletop-tasks).
+The evaluation process consists of two main parts:
+
+1. Setting up the `robocasa` environment and dependencies.
+2. Running the evaluation by launching services in both `starVLA` and `robocasa` environments.
+
+We have verified that this workflow runs successfully on **NVIDIA A100** GPUs.
+
+
+# Evaluation
+
+
+
+
+## ⬇️ 0. Download Checkpoints
+First, download the checkpoints from
+- [Qwen3VL-GR00T](https://huggingface.co/StarVLA/Qwen3-VL-GR00T-Robocasa-gr1)
+- [Qwen3VL-OFT](https://huggingface.co/StarVLA/Qwen3-VL-OFT-Robocasa)
+
+## 📦 1. Environment Setup
+
+To set up the environment, please first follow the [official RoboCasa installation guide](https://github.com/robocasa/robocasa-gr1-tabletop-tasks?tab=readme-ov-file#getting-started) to install the base `robocasa-gr1-tabletop-tasks` environment.
+
+than pip soceket support
+
+'''bash
+pip install tyro
+'''
+
+---
+
+## 🚀 2. Evaluation Workflow
+
+### Step 1. Start the server (starVLA environment)
+
+In the first terminal, activate the `starVLA` conda environment and run:
+
+```bash
+python deployment/model_server/server_policy.py \
+ --ckpt_path ${your_ckpt} \
+ --port 5678 \
+ --use_bf16
+```
+
+---
+
+### Step 2. Start the simulation (robocasa environment)
+
+In the second terminal, activate the `robocasa` conda environment and run:
+
+```bash
+export PYTHONPATH=$(pwd):${PYTHONPATH}
+your_ckpt=StarVLA/Qwen3-VL-OFT-Robocasa/checkpoints/steps_90000_pytorch_model.pt
+
+python examples/Robocasa_tabletop/eval_files/simulation_env.py\
+ --args.env_name ${env_name} \
+ --args.port 5678 \
+ --args.n_episodes 50 \
+ --args.n_envs 1 \
+ --args.max_episode_steps 720 \
+ --args.n_action_steps 12 \
+ --args.video_out_path ${video_out_path} \
+ --args.pretrained_path ${your_ckpt}
+```
+
+
+### Optional: Batch Evaluation
+
+If you have more GPU, you can use the batch evaluation script:
+```bash
+bash examples/Robocasa_tabletop/batch_eval_args.sh
+```
+⚠️ **Note:** Please ensure that you specify the correct checkpoint path in `batch_eval_args.sh`
+
+---
+## 📊 Experimental Results
+
+# RoboCasa GR1 Tabletop Tasks Evaluation Results
+
+| Task | GR00T-N1.6 | Qwen3GR00T | Qwen3PI | Qwen3OFT | Qwen3FAST |
+|------|------------|------------|---------|----------|-----------|
+| **PnP Bottle To Cabinet Close** | 51.5 | 46.0 | 26.0 | **30.0** | 38.0 |
+| **PnP Can To Drawer Close** | 13.0 | 80.0 | 62.0 | **76.0** | 44.0 |
+| **PnP Cup To Drawer Close** | 8.5 | 54.0 | 42.0 | **44.0** | 56.0 |
+| **PnP Milk To Microwave Close** | 14.0 | 48.0 | 50.0 | **44.0** | 44.0 |
+| **PnP Potato To Microwave Close** | 41.5 | 28.0 | 42.0 | **32.0** | 14.0 |
+| **PnP Wine To Cabinet Close** | 16.5 | 46.0 | 32.0 | **36.0** | 14.0 |
+| | | | | | |
+| **PnP Novel From Cuttingboard To Basket** | 58.0 | 48.0 | 40.0 | **50.0** | 54.0 |
+| **PnP Novel From Cuttingboard To Cardboardbox** | 46.5 | 40.0 | 46.0 | **40.0** | 42.0 |
+| **PnP Novel From Cuttingboard To Pan** | 68.5 | 68.0 | 60.0 | **70.0** | 58.0 |
+| **PnP Novel From Cuttingboard To Pot** | 65.0 | 52.0 | 40.0 | **54.0** | 58.0 |
+| **PnP Novel From Cuttingboard To Tieredbasket** | 46.5 | 56.0 | 44.0 | **38.0** | 40.0 |
+| | | | | | |
+| **PnP Novel From Placemat To Basket** | 58.5 | 42.0 | 44.0 | **32.0** | 36.0 |
+| **PnP Novel From Placemat To Bowl** | 57.5 | 44.0 | 52.0 | **58.0** | 38.0 |
+| **PnP Novel From Placemat To Plate** | 63.0 | 48.0 | 50.0 | **52.0** | 42.0 |
+| **PnP Novel From Placemat To Tieredshelf** | 28.5 | 18.0 | 28.0 | **24.0** | 18.0 |
+| | | | | | |
+| **PnP Novel From Plate To Bowl** | 57.0 | 60.0 | 52.0 | **60.0** | 52.0 |
+| **PnP Novel From Plate To Cardboardbox** | 43.5 | 50.0 | 40.0 | **50.0** | 30.0 |
+| **PnP Novel From Plate To Pan** | 51.0 | 54.0 | 36.0 | **66.0** | 48.0 |
+| **PnP Novel From Plate To Plate** | 78.7 | 70.0 | 48.0 | **68.0** | 50.0 |
+| | | | | | |
+| **PnP Novel From Tray To Cardboardbox** | 51.5 | 38.0 | 34.0 | **44.0** | 28.0 |
+| **PnP Novel From Tray To Plate** | 71.0 | 56.0 | 64.0 | **56.0** | 34.0 |
+| **PnP Novel From Tray To Pot** | 64.5 | 50.0 | 44.0 | **62.0** | 46.0 |
+| **PnP Novel From Tray To Tieredbasket** | 57.0 | 36.0 | 50.0 | **54.0** | 36.0 |
+| **PnP Novel From Tray To Tieredshelf** | 31.5 | 16.0 | 28.0 | **30.0** | 16.0 |
+| | | | | | |
+| **Average** | **47.6** | **47.8** | **43.9** | **48.8** | **39.0** |
+
+*Note: All values are success rates in percentage (%). A single model was trained for all 24 tasks. Results are reported over 50 rollouts per task.*
+
+---
+
+
+# 🚀 Reproduce Training Results
+## 📦 Step0: Download the training dataset
+Download the PhysicalAI-Robotics-GR00T-X-Embodiment-Sim directory datasets from [HuggingFace](https://huggingface.co/datasets/nvidia/PhysicalAI-Robotics-GR00T-X-Embodiment-Sim) to the playground/Datasets/nvidia/PhysicalAI-Robotics-GR00T-X-Embodiment-Sim directory
+
+To download only the relevant finetuning folders, you can refer [GR00T-N1.5](https://github.com/NVIDIA/Isaac-GR00T/tree/4af2b622892f7dcb5aae5a3fb70bcb02dc217b96/examples/RoboCasa#-1-dataset-preparation) repo's instruction.
+Or using the script download the *_1000 folders.
+
+```bash
+python examples/Robocasa_tabletop/download_gr00t_ft_data.py
+```
+
+## 🚀 Step1: Start Training
+Different datasets can be selected by modifying the parameter `data_mix`, and the following script can be used to fine-tune the `*_1000` datasets:
+```bash
+bash examples/Robocasa_tabletop/train_files/run_robocasa.sh
+```
+
diff --git a/examples/Suqian_agibot/eval_files/adaptive_ensemble.py b/examples/Suqian_agibot/eval_files/adaptive_ensemble.py
new file mode 100644
index 0000000000000000000000000000000000000000..520f85cc53c72aff24208476cc96a6042f4fb6c7
--- /dev/null
+++ b/examples/Suqian_agibot/eval_files/adaptive_ensemble.py
@@ -0,0 +1,44 @@
+"""
+adaptive_ensemble.py
+
+"""
+
+from collections import deque
+import numpy as np
+
+
+class AdaptiveEnsembler:
+ def __init__(self, pred_action_horizon, adaptive_ensemble_alpha=0.0):
+ self.pred_action_horizon = pred_action_horizon
+ self.action_history = deque(maxlen=self.pred_action_horizon)
+ self.adaptive_ensemble_alpha = adaptive_ensemble_alpha
+
+ def reset(self):
+ self.action_history.clear()
+
+ def ensemble_action(self, cur_action):
+ self.action_history.append(cur_action)
+ num_actions = len(self.action_history)
+ if cur_action.ndim == 1:
+ curr_act_preds = np.stack(self.action_history)
+ else:
+ curr_act_preds = np.stack(
+ [pred_actions[i] for (i, pred_actions) in zip(range(num_actions - 1, -1, -1), self.action_history)]
+ )
+
+ # calculate cosine similarity between the current prediction and all previous predictions
+ ref = curr_act_preds[num_actions-1, :]
+ previous_pred = curr_act_preds
+ dot_product = np.sum(previous_pred * ref, axis=1)
+ norm_previous_pred = np.linalg.norm(previous_pred, axis=1)
+ norm_ref = np.linalg.norm(ref)
+ cos_similarity = dot_product / (norm_previous_pred * norm_ref + 1e-7)
+
+ # compute the weights for each prediction
+ weights = np.exp(self.adaptive_ensemble_alpha * cos_similarity)
+ weights = weights / weights.sum()
+
+ # compute the weighted average across all predictions for this timestep
+ cur_action = np.sum(weights[:, None] * curr_act_preds, axis=0)
+
+ return cur_action
\ No newline at end of file
diff --git a/examples/Suqian_agibot/eval_files/base_config.py b/examples/Suqian_agibot/eval_files/base_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..020e071824a297cd11933583ae1967224dc17a0a
--- /dev/null
+++ b/examples/Suqian_agibot/eval_files/base_config.py
@@ -0,0 +1,33 @@
+from pydantic import BaseModel
+from abc import ABC, abstractmethod
+from typing import Dict, Any
+
+class ModalityConfig(BaseModel):
+ """Configuration for a modality."""
+
+ delta_indices: list[int]
+ """Delta indices to sample relative to the current index. The returned data will correspond to the original data at a sampled base index + delta indices."""
+ modality_keys: list[str]
+ """The keys to load for the modality in the dataset."""
+
+
+class BasePolicy(ABC):
+ @abstractmethod
+ def get_action(self, observations: Dict[str, Any]) -> Dict[str, Any]:
+ """
+ Abstract method to get the action for a given state.
+
+ Args:
+ observations: The observations from the environment.
+
+ Returns:
+ The action to take in the environment in dictionary format.
+ """
+ raise NotImplementedError
+
+ @abstractmethod
+ def get_modality_config(self) -> Dict[str, ModalityConfig]:
+ """
+ Return the modality config of the policy.
+ """
+ raise NotImplementedError
diff --git a/examples/Suqian_agibot/eval_files/batch_eval_args.sh b/examples/Suqian_agibot/eval_files/batch_eval_args.sh
new file mode 100644
index 0000000000000000000000000000000000000000..18d0d562047dab702fcfa7af14bbf7747992b5c6
--- /dev/null
+++ b/examples/Suqian_agibot/eval_files/batch_eval_args.sh
@@ -0,0 +1,197 @@
+#!/bin/bash
+
+# ============================================================
+# Argument Parsing
+# ============================================================
+###########################################################################################
+# === Please modify the paths to Python executables in conda environments ===
+
+export OMP_NUM_THREADS=1
+export MKL_NUM_THREADS=1
+export OPENBLAS_NUM_THREADS=1
+
+
+export LD_LIBRARY_PATH=/tmp/nvidia-gl-extract/usr/lib/x86_64-linux-gnu:$LD_LIBRARY_PATH
+export VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/nvidia_icd.json
+
+export PYOPENGL_PLATFORM=egl
+export MUJOCO_GL=egl
+
+starVLA_PYTHON=/mnt/workspace/envs/conda3/envs/starVLA_1/bin/python
+ROBOCASA_PYTHON=/mnt/workspace/envs/conda3/envs/robocasa/bin/python
+export PYTHONPATH=$(pwd):${PYTHONPATH}
+CKPT_DEFAULT="/mnt/workspace/users/yuanzhihao/code/starVLA/outputs/debug_starvla_qwen3fast_fourier_gr1_unified_1000/checkpoints/steps_10000_pytorch_model.pt"
+# CKPT_DEFAULT="/mnt/workspace/users/yuanzhihao/code/starVLA/outputs/StarVLA_Qwen3_VL_GR00T_Robocasa_gr1/checkpoints/steps_90000_pytorch_model.pt"
+
+# === End of environment variable configuration ===
+###########################################################################################
+
+N_ENVS_DEFAULT=1
+MAX_EPISODE_STEPS_DEFAULT=720
+N_ACTION_STEPS_DEFAULT=12
+
+BASE_PORT=6398
+NUM_GPUS=8
+
+# Parse command-line arguments
+CKPT_PATH=${1:-$CKPT_DEFAULT}
+N_ENVS=${2:-$N_ENVS_DEFAULT}
+MAX_EPISODE_STEPS=${3:-$MAX_EPISODE_STEPS_DEFAULT}
+N_ACTION_STEPS=${4:-$N_ACTION_STEPS_DEFAULT}
+
+
+echo "=== Evaluation Configuration ==="
+echo "Checkpoint Path : ${CKPT_PATH}"
+echo "Number of Envs : ${N_ENVS}"
+echo "Max Episode Steps : ${MAX_EPISODE_STEPS}"
+echo "Action Chunk Length : ${N_ACTION_STEPS}"
+echo "================================"
+
+# ============================================================
+# Evaluation Function
+# ============================================================
+
+EvalEnv() {
+ local GPU_ID=$1
+ local PORT=$2
+ local ENV_NAME=$3
+ local CKPT_PATH=$4
+ local LOG_DIR=$5
+ local ROBOCASA_PYTHON=$6
+ local N_ENVS=$7
+ local MAX_EPISODE_STEPS=$8
+ local N_ACTION_STEPS=$9
+ # save root CKPT_PATH 的 parent 文件夹
+ local SAVE_ROOT=$(dirname "$(dirname "$CKPT_PATH")")
+ local ckpt_name=$(basename "$CKPT_PATH" .pt)
+ local VIDEO_OUT_PATH="${SAVE_ROOT}/videos/${ckpt_name}/n_action_steps_${N_ACTION_STEPS}_max_episode_steps_${MAX_EPISODE_STEPS}_n_envs_${N_ENVS}_${ENV_NAME}"
+ mkdir -p "${VIDEO_OUT_PATH}"
+
+ echo "Launching evaluation | GPU ${GPU_ID} | Port ${PORT} | Env ${ENV_NAME}"
+
+ CUDA_VISIBLE_DEVICES=${GPU_ID} \
+ MUJOCO_GL=egl \
+ PYOPENGL_PLATFORM=egl \
+ EGL_VISIBLE_DEVICES=0 \
+ MUJOCO_EGL_DEVICE_ID=0 \
+ ${ROBOCASA_PYTHON} examples/Robocasa_tabletop/eval_files/simulation_env.py \
+ --args.env_name "${ENV_NAME}" \
+ --args.port "${PORT}" \
+ --args.n_episodes 100 \
+ --args.n_envs "${N_ENVS}" \
+ --args.max_episode_steps "${MAX_EPISODE_STEPS}" \
+ --args.n_action_steps "${N_ACTION_STEPS}" \
+ --args.video_out_path "${VIDEO_OUT_PATH}" \
+ --args.pretrained_path "${CKPT_PATH}" \
+ > "${LOG_DIR}/eval_env_${ENV_NAME//\//_}_gpu${GPU_ID}.log" 2>&1
+}
+
+# ============================================================
+# Environment List
+# ============================================================
+
+ENV_NAMES=(
+ gr1_unified/PnPCupToDrawerClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPPotatoToMicrowaveClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPMilkToMicrowaveClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPBottleToCabinetClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPWineToCabinetClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PnPCanToDrawerClose_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToBasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToPanSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToPotSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromCuttingboardToTieredbasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToBasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToBowlSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToPlateSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlacematToTieredshelfSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToBowlSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToPanSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromPlateToPlateSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToPlateSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToPotSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToTieredbasketSplitA_GR1ArmsAndWaistFourierHands_Env
+ gr1_unified/PosttrainPnPNovelFromTrayToTieredshelfSplitA_GR1ArmsAndWaistFourierHands_Env
+)
+
+# ============================================================
+# Runtime Configuration
+# ============================================================
+
+
+
+LOG_DIR="${CKPT_PATH}.log/eval_$(date +%Y%m%d_%H%M%S)"
+mkdir -p "${LOG_DIR}"
+
+echo "=== Launching Multi-GPU Evaluation ==="
+echo "GPUs : ${NUM_GPUS}"
+echo "Num Environments: ${#ENV_NAMES[@]}"
+echo "Log Directory : ${LOG_DIR}"
+
+# ============================================================
+# Step 1: Launch Policy Servers
+# ============================================================
+
+SERVER_PIDS=()
+
+for GPU_ID in $(seq 0 $((NUM_GPUS - 1))); do
+ PORT=$((BASE_PORT + GPU_ID))
+ echo "Starting policy server | GPU ${GPU_ID} | Port ${PORT}"
+
+ CUDA_VISIBLE_DEVICES=${GPU_ID} \
+ ${starVLA_PYTHON} deployment/model_server/server_policy.py \
+ --ckpt_path "${CKPT_PATH}" \
+ --port "${PORT}" \
+ --use_bf16 \
+ > "${LOG_DIR}/server_gpu${GPU_ID}_port${PORT}.log" 2>&1 &
+
+ SERVER_PIDS[$GPU_ID]=$!
+
+ sleep 10
+done
+
+sleep 30
+
+# ============================================================
+# Step 2: Dispatch Environments to GPUs
+# ============================================================
+
+COUNT=0
+for ENV_NAME in "${ENV_NAMES[@]}"; do
+ GPU_ID=$((COUNT % NUM_GPUS))
+ PORT=$((BASE_PORT + GPU_ID))
+
+ if (( (COUNT + 1) % NUM_GPUS == 0 )); then
+ EvalEnv "${GPU_ID}" "${PORT}" "${ENV_NAME}" "${CKPT_PATH}" "${LOG_DIR}" \
+ "${ROBOCASA_PYTHON}" "${N_ENVS}" "${MAX_EPISODE_STEPS}" "${N_ACTION_STEPS}"
+ else
+ EvalEnv "${GPU_ID}" "${PORT}" "${ENV_NAME}" "${CKPT_PATH}" "${LOG_DIR}" \
+ "${ROBOCASA_PYTHON}" "${N_ENVS}" "${MAX_EPISODE_STEPS}" "${N_ACTION_STEPS}" &
+ fi
+
+ COUNT=$((COUNT + 1))
+
+ sleep 2
+done
+
+# ============================================================
+# Step 3: Cleanup
+# ============================================================
+
+# 判断是否还有 examples/Robocasa_tabletop/eval_files/simulation_env.py
+while pgrep -f "examples/Robocasa_tabletop/eval_files/simulation_env.py" > /dev/null; do
+ echo "Waiting for all evaluation environments to finish..."
+ sleep 30
+done
+
+echo ""
+echo "Shutting down policy servers..."
+
+for PID in "${SERVER_PIDS[@]}"; do
+ kill "${PID}" 2>/dev/null && echo "Killed server PID ${PID}"
+done
+
+echo "=== Evaluation Finished ==="