kabilanKB commited on
Commit
28ff0ee
·
verified ·
1 Parent(s): 4a60044

Add Jetson Thor hardware-in-the-loop deployment (thor_deploy/)

Browse files

Thor setup/serve scripts, Isaac Lab 3.0 so101_bench client patch, HIL web UI, and README; model card links it.

README.md CHANGED
@@ -26,15 +26,17 @@ as consolidated safetensors.
26
  | Folder | Iteration | Epoch (approx.) | Benchmark |
27
  | --- | ---: | ---: | --- |
28
  | `iter_6000/` | 6000 | 3.5 | not evaluated yet |
29
- | `iter_6500/` | 6500 | 3.8 | evaluation in progress |
30
- | `iter_7000/` | 7000 (final) | 4.0 | not evaluated yet |
31
 
32
- **No full benchmark result yet.** Earlier checkpoints of the same run scored 0 / 50 (iteration
33
- 1500) and 0 / 100 (iteration 2500) on the benchmark below. An evaluation of iteration 6500 is in
34
- progress and has recorded its first success. For comparison, the
35
  [Cosmos3-Nano SO-101 policy](https://huggingface.co/kabilanKB/cosmos_nano_policy_so101) scores
36
  3.1% on the same benchmark.
37
 
 
 
 
38
  ## Training
39
 
40
  | Setting | Value |
@@ -91,6 +93,24 @@ The pipeline for training, merge, export, serving and evaluation is in
91
 
92
  **Response:** `action`, 32 × 6 absolute joint targets in raw `.pos` units.
93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  ## Limitations
95
 
96
  - Trained and evaluated only in simulation. It has not been tested on a physical SO-101.
 
26
  | Folder | Iteration | Epoch (approx.) | Benchmark |
27
  | --- | ---: | ---: | --- |
28
  | `iter_6000/` | 6000 | 3.5 | not evaluated yet |
29
+ | `iter_6500/` | 6500 | 3.8 | **5 / 98 (5.1%)**, the best checkpoint |
30
+ | `iter_7000/` | 7000 (final) | 4.0 | 1 / 100 (1.0%) |
31
 
32
+ Scores are on the benchmark below with a 25 s episode limit. Earlier checkpoints of the same run
33
+ scored 0 / 50 (iteration 1500) and 0 / 100 (iteration 2500). For comparison, the
 
34
  [Cosmos3-Nano SO-101 policy](https://huggingface.co/kabilanKB/cosmos_nano_policy_so101) scores
35
  3.1% on the same benchmark.
36
 
37
+ **Runs on a Jetson Thor:** see [`thor_deploy/`](thor_deploy/README.md) for serving `iter_6500`
38
+ natively on a Thor and driving the Isaac Lab benchmark from a PC through a hardware-in-the-loop web UI.
39
+
40
  ## Training
41
 
42
  | Setting | Value |
 
93
 
94
  **Response:** `action`, 32 × 6 absolute joint targets in raw `.pos` units.
95
 
96
+ ## Run on a Jetson Thor
97
+
98
+ The policy server runs natively on an NVIDIA Jetson Thor (JetPack 7, CUDA 13); the ~9 GB of BF16
99
+ weights fit in the Thor's memory. [`thor_deploy/`](thor_deploy/README.md) has one-command setup and
100
+ serve scripts for the Thor, a setup script for the PC that runs the `so101_bench` simulation
101
+ (ported to Isaac Lab 3.0 / Isaac Sim 6.0), and a hardware-in-the-loop web UI that takes the Thor's IP
102
+ address, launches the policy server on the Thor over SSH, runs the benchmark and shows each camera
103
+ frame and action chunk.
104
+
105
+ ```bash
106
+ # Thor
107
+ uvx hf@latest download kabilanKB/cosmos_edge_policy_so101 --include "thor_deploy/*" --local-dir ~/so101_deploy
108
+ bash ~/so101_deploy/thor_deploy/thor/setup_thor.sh && bash ~/so101-edge-thor/serve_thor.sh
109
+ ```
110
+
111
+ On the Thor a 32-step chunk takes ~2.1 s with cuDNN attention and `torch.compile` (details and the
112
+ two fixes that make this possible are in the deploy README), versus 0.42 s on an RTX PRO 6000.
113
+
114
  ## Limitations
115
 
116
  - Trained and evaluated only in simulation. It has not been tested on a physical SO-101.
thor_deploy/README.md ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Run `cosmos_edge_policy_so101` on a Jetson Thor
2
+
3
+ Hardware-in-the-loop test of the SO-101 Cosmos3-Edge policy (`iter_6500/`): the policy runs
4
+ **natively on an NVIDIA Jetson Thor**, and the `so101_bench` Isaac Lab digital twin runs on a PC/laptop
5
+ as its client. A web page on the PC takes the Thor's IP address, **launches the Cosmos Edge policy
6
+ server on the Thor over SSH**, warms it up, runs the benchmark and shows every camera frame sent to
7
+ the Thor and every action chunk it returns.
8
+
9
+ ```
10
+ PC / laptop (RTX GPU) Jetson Thor
11
+ ┌──────────────────────────────────────────┐ ┌──────────────────────────────────┐
12
+ │ Isaac Lab 3.0 + Isaac Sim 6.0 │ │ cosmos-framework policy server │
13
+ │ so101_bench (So101Bench-Bin-v0) │ │ Cosmos3-Edge SO-101, iter 6500 │
14
+ │ wrist + overhead cameras, joint state ──┼── ws ───► │ OpenPI WebSocket, port 8000 │
15
+ │ ◄── 32 × 6 joint targets per request │ (LAN) │ ~2.1 s per chunk (BF16, ~9 GB) │
16
+ │ web UI http://127.0.0.1:8765 (relay) │ │ │
17
+ └──────────────────────────────────────────┘ └──────────────────────────────────┘
18
+ ```
19
+
20
+ | Folder | What it is |
21
+ | --- | --- |
22
+ | `thor/setup_thor.sh` | One-time Thor setup: cosmos-framework `5e67049` + SO-101 patch, uv venv, cuDNN upgrade, `iter_6500` download |
23
+ | `thor/serve_thor.sh` | Starts the policy server with the full SO-101 serving contract |
24
+ | `thor/so101-support.patch` | SO-101 support for cosmos-framework `5e67049` (domain, normalizer stats, server flags) |
25
+ | `laptop/setup_laptop.sh` | One-time PC setup: `so101_bench` + Isaac Lab 3 port + USD assets + web UI |
26
+ | `laptop/so101_bench_isaaclab3.patch` | Cosmos3 client, task suites and the Isaac Lab 3.0 port, against `5hadytru/so101_bench@205d4f9` |
27
+ | `laptop/webui/` | The runner page (`so101_thor_ui.py`, `index.html`) |
28
+
29
+ ## Verified configuration
30
+
31
+ | | |
32
+ | --- | --- |
33
+ | Thor | Jetson AGX Thor, JetPack 7 (L4T R38.1), CUDA 13.0, Ubuntu 24.04, MAXN power mode |
34
+ | Thor Python stack | uv venv, Python 3.13, torch 2.10.0+cu130 (aarch64), cuDNN 9.26 |
35
+ | PC | RTX PRO 5000 Blackwell Laptop GPU (24 GB), driver 595, Ubuntu |
36
+ | PC simulation | Isaac Sim 6.0.1, Isaac Lab 3.0 (conda env, Python 3.12) |
37
+ | Network | Same LAN (Wi-Fi works; each request is one ~1.8 MB frame pair) |
38
+
39
+ ## 0. SSH key (once)
40
+
41
+ The web page starts and stops the server on the Thor with key-based SSH, so it never asks for a
42
+ password. On the PC:
43
+
44
+ ```bash
45
+ ls ~/.ssh/id_ed25519.pub || ssh-keygen -t ed25519 # create a key if the PC has none
46
+ ssh-copy-id <thor-user>@<thor-ip> # asks for the Thor password this one time
47
+ ssh -o BatchMode=yes <thor-user>@<thor-ip> true && echo key login works
48
+ ```
49
+
50
+ (Without `ssh-copy-id`: append the contents of the PC's `~/.ssh/id_ed25519.pub` to
51
+ `~/.ssh/authorized_keys` on the Thor.)
52
+
53
+ ## 1. Thor: install the policy server
54
+
55
+ Needs ~20 GB free disk, internet, no sudo.
56
+
57
+ ```bash
58
+ # on the Thor
59
+ uvx hf@latest download kabilanKB/cosmos_edge_policy_so101 --include "thor_deploy/*" --local-dir ~/so101_deploy
60
+ bash ~/so101_deploy/thor_deploy/thor/setup_thor.sh # installs into ~/so101-edge-thor (20-40 min)
61
+ ```
62
+
63
+ That is all the Thor needs; the web page starts the server. To run it by hand instead:
64
+
65
+ ```bash
66
+ bash ~/so101-edge-thor/serve_thor.sh # foreground
67
+ bash ~/so101-edge-thor/serve_thor.sh --tmux # tmux session so101serve, log ~/so101-edge-thor/logs/serve_latest.log
68
+ bash ~/so101-edge-thor/serve_thor.sh --stop
69
+ curl http://<thor-ip>:8000/healthz # -> OK once the log prints "ready domain='so101' ..."
70
+ ```
71
+
72
+ ## 2. PC: install the simulation client and the web UI
73
+
74
+ Needs an environment that already has **Isaac Sim 6.0 + Isaac Lab 3.0**
75
+ ([Isaac Lab installation](https://isaac-sim.github.io/IsaacLab/main/source/setup/installation/index.html)).
76
+ Nothing is installed into that environment; the client's two extra packages go into a side folder.
77
+
78
+ ```bash
79
+ uvx hf@latest download kabilanKB/cosmos_edge_policy_so101 --include "thor_deploy/*" --local-dir ~/so101_deploy
80
+ bash ~/so101_deploy/thor_deploy/laptop/setup_laptop.sh --python ~/miniconda3/envs/env_isaaclab/bin/python
81
+ ~/so101-thor-client/run_ui.sh --thor <thor-ip> --thor-user <thor-user> # then open http://127.0.0.1:8765/
82
+ ```
83
+
84
+ `setup_laptop.sh` clones `5hadytru/so101_bench` at `205d4f9`, applies `so101_bench_isaaclab3.patch`,
85
+ downloads the USD scene assets (~430 MB) from `5hadytru/so101_bench_assets`, and installs
86
+ `openpi-client` and `pyzmq` into `~/so101-thor-client/vendor_py`.
87
+
88
+ ## 3. Use the web UI
89
+
90
+ 1. **Cosmos Edge policy server on the Jetson Thor:** enter the Thor IP and SSH user →
91
+ **Launch server on Thor**. The page runs `serve_thor.sh --tmux` over SSH, follows the Thor's server
92
+ log until the model is loaded (~15 s), then sends two warm-up inferences (the first compiles
93
+ kernels, ~20 s; later ones take ~2.1 s) and reports the chunk shape, value range and Thor inference
94
+ time. The status pill shows *not running / loading model / ready*, and the Thor's log is one click
95
+ away. A warning appears if the actions look un-normalized (inside [-1, 1]), which means a server
96
+ flag is missing. **Stop server** stops it on the Thor; **Test connection** re-checks a running one.
97
+ 2. **Benchmark:** pick a suite, optionally limit the episode count or fix the instruction, tick
98
+ **Isaac Sim window** to watch the arm, then **Start run**. With *Launch Thor server if needed*
99
+ ticked, Start run does step 1 by itself first. Isaac Sim needs 1–2 minutes to load.
100
+ 3. While it runs: the frame sent to the Thor, the returned 32-step chunk per joint, the episode so far,
101
+ per-episode results with the success rate, Thor inference and round-trip medians, and the client
102
+ log. **Pause / Resume / Skip episode / Stop** control the running benchmark.
103
+
104
+ | Suite | Episodes | What it tests |
105
+ | --- | ---: | --- |
106
+ | `focus5` | 100 | The 5 training objects, 20 fixed layouts each (the reference benchmark) |
107
+ | `unseen` | 52 | 26 objects never seen in training, 2 layouts each |
108
+ | `wins` | 12 | Layouts where a checkpoint succeeded before (quick demo) |
109
+ | `clutter` | 100 | focus5 targets with 3 distractors on the table |
110
+ | `mix` | 75 | Training-distribution instruction mix |
111
+
112
+ Each run is saved in `~/so101-thor-client/runs/<suite>_<time>/`: `eval.log` (the benchmark log with
113
+ per-episode results), `records.jsonl` (every request/response) and `obs/` (every frame sent).
114
+ Episodes time out at 60 s of simulated time.
115
+
116
+ ## Speed
117
+
118
+ | Thor server | Time per chunk (32 actions = 1.07 s of motion) |
119
+ | --- | ---: |
120
+ | Eager (NVIDIA's documented `TORCHDYNAMO_DISABLE=1`), stock cuDNN 9.15 | 4.3 s |
121
+ | Eager + cuDNN 9.26 attention | 3.15 s |
122
+ | **`torch.compile` + cuDNN 9.26 attention (default)** | **2.1 s** |
123
+ | Reference: 1× RTX PRO 6000 workstation | 0.42 s |
124
+
125
+ The benchmark waits for each chunk before stepping the simulation, so a slower server makes runs take
126
+ longer but does not change the policy's behaviour. With the Isaac Sim window open, a 60 s episode
127
+ takes about 5 minutes of wall time.
128
+
129
+ Two things make the Thor fast:
130
+
131
+ - **cuDNN attention.** cosmos-framework enables its cuDNN attention backend only for cuDNN ≥ 9.22;
132
+ torch 2.10 ships 9.15, so attention otherwise falls back to a path ~5× slower on Thor (flash-attn
133
+ has no aarch64 build and NATTEN's fused kernels target sm_90/100/103, not Thor's sm_110).
134
+ `setup_thor.sh` upgrades `nvidia-cudnn-cu13` in the venv. **A later `uv sync` downgrades it; re-run
135
+ the `uv pip install "nvidia-cudnn-cu13>=9.22"` line after one.**
136
+ - **`torch.compile`.** The Triton in the venv bundles a `ptxas` that does not know `sm_110a`, which
137
+ is why NVIDIA's instructions disable compilation on Thor. JetPack's CUDA 13.0 `ptxas` does, so
138
+ `serve_thor.sh` points Triton at `/usr/local/cuda/bin/ptxas`. `SO101_COMPILE=0` runs eager instead.
139
+
140
+ ## Isaac Lab 3.0 port of `so101_bench`
141
+
142
+ `so101_bench` was written for Isaac Lab 2.3 / Isaac Sim 5.1. Isaac Sim 5.1 did not start on the
143
+ verified PC (it segfaults in the RTX renderer on this GPU and driver, even with an empty scene), so the
144
+ client was ported to Isaac Lab 3.0 / Isaac Sim 6.0. The port keeps the scene, poses and camera
145
+ images as close as possible to the 2.3 version the policy was trained and benchmarked on:
146
+
147
+ - **Quaternions:** Isaac Lab 3.0 uses (x, y, z, w). The benchmark's own pose math stays in the 2.3
148
+ (w, x, y, z) convention, using Isaac Lab 2.3's quaternion functions copied into
149
+ `so101_bench/utils/quat_wxyz.py`. Conversion happens only at the Isaac Lab boundary: configured
150
+ rotations, `root_quat_w`, `FrameView` poses and root-pose writes.
151
+ - **Data and writes:** asset and sensor data are `ProxyArray` (read with `.torch`); root-pose writes use
152
+ `write_root_pose_to_sim_index` / `write_root_velocity_to_sim_index`; the PhysX rigid-body views used
153
+ to teleport multi-body objects take warp arrays; `isaacsim.core.*` imports were replaced by
154
+ Isaac Lab 3 equivalents.
155
+ - **Lighting:** the room scan USD carries its own near-black dome light. Isaac Sim 5.1 added it to the
156
+ benchmark's dome light; Isaac Sim 6's Real-Time 2.0 renderer used it alone, and every camera frame
157
+ came out ~3× darker than the frames the policy was trained on. The port deactivates the room's dome
158
+ light and scales the benchmark's dome light by 1.2 (`SO101_DOME_INTENSITY_SCALE`).
159
+
160
+ Checked against the Isaac Sim 5.1 workstation on the same layout (`focus5` episode 1): identical
161
+ initial joint state, identical camera poses and object placement, and a mean absolute pixel
162
+ difference of 4.9 / 255 (overhead camera) and 3.2 / 255 (wrist camera) in the first frame sent to the
163
+ policy (72 / 255 and 38 / 255 before the lighting fix). Physics and
164
+ rendering are still different engine versions, so success rates measured with this client are not
165
+ strictly comparable with the Isaac Sim 5.1 numbers in the model card.
166
+
167
+ ## Troubleshooting
168
+
169
+ | Symptom | Cause / fix |
170
+ | --- | --- |
171
+ | `ModuleNotFoundError: iopath` or `... OpenPI's WebsocketPolicyServer` on the Thor | The venv is missing a group: `uv sync --group cu130 --group policy-server --extra train`, then re-run the cuDNN upgrade |
172
+ | `ptxas ... Value 'sm_110a' is not defined` | Triton's bundled ptxas; `serve_thor.sh` sets `TRITON_PTXAS_PATH=/usr/local/cuda/bin/ptxas`. Without JetPack's CUDA it falls back to eager |
173
+ | Chunks take ~4 s instead of ~2 s | cuDNN < 9.22 in the venv (check `torch.backends.cudnn.version()`), or `SO101_COMPILE=0` |
174
+ | `uv sync` hangs with no output | A dropped network connection; stop it and re-run with `UV_HTTP_TIMEOUT=120` |
175
+ | `SSH key login to <user>@<ip> failed` | Do step 0 (key-based SSH) for that user |
176
+ | Launch: `no ~/so101-edge-thor/serve_thor.sh on the Thor` | Run `setup_thor.sh` on the Thor first (step 1), or start the page with `--thor-dir <folder>` |
177
+ | Test connection: `cannot reach <ip>:8000` | Server not started, a different port, or a firewall on the Thor |
178
+ | Actions inside [-1, 1] | The server was started without `--action-normalization minmax` / the SO-101 stats file |
179
+ | Isaac Sim window does not open | Run the page from a desktop session (the client inherits `DISPLAY`), or untick the window for a headless run |
180
+
181
+ ## License
182
+
183
+ The policy weights are under the OpenMDW License 1.1 (see the model card). The cosmos-framework patch
184
+ applies to [NVIDIA/cosmos-framework](https://github.com/NVIDIA/cosmos-framework); the `so101_bench`
185
+ patch applies to [5hadytru/so101_bench](https://github.com/5hadytru/so101_bench) (BSD-3-Clause) and
186
+ includes Isaac Lab 2.3 quaternion functions (BSD-3-Clause).
thor_deploy/laptop/setup_laptop.sh ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # One-time setup of the SO-101 Isaac Lab client + web UI on the machine that runs the simulation.
3
+ #
4
+ # bash setup_laptop.sh --python /path/to/isaaclab-env/bin/python [install dir]
5
+ #
6
+ # --python: the Python of an environment that already has Isaac Sim 6.0 + Isaac Lab 3.0
7
+ # (e.g. ~/miniconda3/envs/env_isaaclab/bin/python). Nothing is installed into it.
8
+ # Install dir defaults to ~/so101-thor-client. Result:
9
+ # so101_bench/ upstream 5hadytru/so101_bench @ 205d4f9 + so101_bench_isaaclab3.patch + USD assets
10
+ # vendor_py/ openpi-client + pyzmq for the client (kept out of the Isaac Lab env)
11
+ # webui/ the runner page (python webui/so101_thor_ui.py --thor <thor-ip>)
12
+ set -euo pipefail
13
+
14
+ PY=""; DIR=""
15
+ while [ $# -gt 0 ]; do
16
+ case "$1" in
17
+ --python) PY=$2; shift 2;;
18
+ -h|--help) sed -n 2,12p "$0"; exit 0;;
19
+ *) DIR=$1; shift;;
20
+ esac
21
+ done
22
+ DIR=${DIR:-$HOME/so101-thor-client}
23
+ PY=${PY:-$(command -v python || true)}
24
+ HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
25
+ BENCH_COMMIT=205d4f9
26
+ log() { echo "[setup-laptop] $*"; }
27
+
28
+ [ -x "$PY" ] || { log "pass --python <isaaclab env python>"; exit 1; }
29
+ "$PY" - <<'PYEOF' || { echo "[setup-laptop] that python has no Isaac Lab 3 / Isaac Sim 6"; exit 1; }
30
+ import importlib.metadata as m
31
+ v = m.version("isaacsim"); print(f"[setup-laptop] isaacsim {v}, isaaclab {m.version('isaaclab')}")
32
+ assert int(v.split(".")[0]) >= 6, "Isaac Sim 6.x required (this client is ported to Isaac Lab 3.0)"
33
+ PYEOF
34
+
35
+ mkdir -p "$DIR"
36
+ # 1. so101_bench at the upstream commit, plus the SO-101 Cosmos client and the Isaac Lab 3 port
37
+ if [ ! -d "$DIR/so101_bench/.git" ]; then
38
+ log "cloning 5hadytru/so101_bench"
39
+ git clone -q https://github.com/5hadytru/so101_bench.git "$DIR/so101_bench"
40
+ fi
41
+ cd "$DIR/so101_bench"
42
+ git checkout -q "$BENCH_COMMIT"
43
+ if git apply --check "$HERE/so101_bench_isaaclab3.patch" 2>/dev/null; then
44
+ git apply "$HERE/so101_bench_isaaclab3.patch"; log "applied so101_bench_isaaclab3.patch"
45
+ elif git apply --reverse --check "$HERE/so101_bench_isaaclab3.patch" 2>/dev/null; then
46
+ log "patch already applied"
47
+ else
48
+ log "error: so101_bench_isaaclab3.patch does not apply"; exit 1
49
+ fi
50
+
51
+ # 2. USD assets (~430 MB, gitignored upstream)
52
+ ASSETS=source/so101_bench/so101_bench/assets
53
+ if [ ! -f "$ASSETS/usd/room_scan.usdc" ]; then
54
+ log "downloading USD assets from 5hadytru/so101_bench_assets"
55
+ TMP=$(mktemp -d)
56
+ "$PY" -c "from huggingface_hub import hf_hub_download as d; print(d('5hadytru/so101_bench_assets', 'so101_bench_usd_assets.tar.gz', repo_type='dataset', local_dir='$TMP'))" >/dev/null
57
+ tar -xzf "$TMP/so101_bench_usd_assets.tar.gz" -C "$ASSETS/"
58
+ rm -rf "$TMP"
59
+ fi
60
+
61
+ # 3. Client-only packages, installed next to (not into) the Isaac Lab environment
62
+ log "installing openpi-client + pyzmq into $DIR/vendor_py"
63
+ "$PY" -m pip install -q --target "$DIR/vendor_py" --no-deps --upgrade openpi-client==0.1.2 pyzmq
64
+
65
+ # 4. Web UI
66
+ mkdir -p "$DIR/webui"
67
+ cp "$HERE/webui/so101_thor_ui.py" "$HERE/webui/index.html" "$DIR/webui/"
68
+ cat > "$DIR/run_ui.sh" <<RUN
69
+ #!/usr/bin/env bash
70
+ # Open http://127.0.0.1:8765/ after starting. --thor <ip> --thor-user <user> pre-fill the Thor fields.
71
+ exec "$PY" "$DIR/webui/so101_thor_ui.py" --bench "$DIR/so101_bench" "\$@"
72
+ RUN
73
+ chmod +x "$DIR/run_ui.sh"
74
+ log "done. Start the page with: $DIR/run_ui.sh --thor <thor-ip> --thor-user <thor-user> then open http://127.0.0.1:8765/"
thor_deploy/laptop/so101_bench_isaaclab3.patch ADDED
The diff for this file is too large to render. See raw diff
 
thor_deploy/laptop/webui/index.html ADDED
@@ -0,0 +1,509 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <title>SO-101 Thor HIL</title>
2
+ <meta charset="utf-8">
3
+ <meta name="viewport" content="width=device-width, initial-scale=1">
4
+ <style>
5
+ :root {
6
+ --bg: #0f1115; --panel: #171a21; --line: #262b36; --text: #e6e8ee; --dim: #8b93a7;
7
+ --accent: #76b900; --warn: #e0a340; --bad: #e0605a;
8
+ --j0: #5aa9e6; --j1: #f28f3b; --j2: #7bd389; --j3: #c792ea; --j4: #f6d55c; --j5: #ef6f8a;
9
+ }
10
+ * { box-sizing: border-box; }
11
+ body { margin: 0; background: var(--bg); color: var(--text);
12
+ font: 13px/1.4 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; }
13
+ .wrap { padding: 14px 16px 40px; max-width: 1500px; margin: 0 auto; }
14
+ header { display: flex; flex-wrap: wrap; gap: 10px 22px; align-items: baseline; margin-bottom: 12px; }
15
+ h1 { font-size: 16px; margin: 0; font-weight: 600; }
16
+ h1 b { color: var(--accent); }
17
+ .prompt { font-size: 15px; font-weight: 500; }
18
+ .stat { color: var(--dim); font-variant-numeric: tabular-nums; }
19
+ .stat b { color: var(--text); font-weight: 600; }
20
+ .live { display: inline-flex; align-items: center; gap: 6px; cursor: pointer; user-select: none;
21
+ border: 1px solid var(--line); border-radius: 999px; padding: 2px 10px; }
22
+ .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--accent); }
23
+ .paused .dot { background: var(--warn); }
24
+ .grid { display: grid; grid-template-columns: minmax(280px, 420px) 1fr; gap: 14px; }
25
+ @media (max-width: 900px) { .grid { grid-template-columns: 1fr; } }
26
+ .panel { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 10px 12px; }
27
+ .panel h2 { font-size: 12px; text-transform: uppercase; letter-spacing: .06em; color: var(--dim);
28
+ margin: 0 0 8px; font-weight: 600; }
29
+ .obs { position: relative; }
30
+ .obs img { width: 100%; display: block; border-radius: 4px; background: #000; min-height: 120px; }
31
+ .obs .tag { position: absolute; left: 6px; background: rgba(0,0,0,.6); padding: 1px 6px;
32
+ border-radius: 4px; font-size: 11px; }
33
+ .charts { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; }
34
+ @media (max-width: 700px) { .charts { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
35
+ canvas { width: 100%; display: block; }
36
+ .state { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 6px; margin-top: 8px; }
37
+ .state div { background: #11141a; border-radius: 4px; padding: 4px 6px; }
38
+ .state span { display: block; color: var(--dim); font-size: 10px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
39
+ .scrub { display: flex; gap: 10px; align-items: center; margin: 12px 0; flex-wrap: wrap; }
40
+ .scrub input[type=range] { flex: 1; min-width: 200px; accent-color: var(--accent); }
41
+ button { background: #222734; color: var(--text); border: 1px solid var(--line); border-radius: 6px;
42
+ padding: 3px 10px; cursor: pointer; font: inherit; }
43
+ button:hover { border-color: var(--dim); }
44
+ .row2 { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; margin-top: 14px; }
45
+ @media (max-width: 900px) { .row2 { grid-template-columns: 1fr; } }
46
+ .tbl { overflow: auto; max-height: 340px; }
47
+ table { border-collapse: collapse; width: 100%; font-variant-numeric: tabular-nums; }
48
+ th, td { padding: 2px 6px; text-align: right; border-bottom: 1px solid var(--line); white-space: nowrap; }
49
+ th { color: var(--dim); font-weight: 500; position: sticky; top: 0; background: var(--panel); }
50
+ td.l, th.l { text-align: left; }
51
+ .ok { color: var(--accent); } .fail { color: var(--dim); } .skip { color: var(--warn); }
52
+ .legend { color: var(--dim); font-size: 11px; margin-top: 6px; }
53
+ .legend i { display: inline-block; width: 14px; height: 2px; vertical-align: middle; margin: 0 4px 0 10px; }
54
+ .empty { color: var(--dim); padding: 30px 0; text-align: center; }
55
+
56
+ .ctl { display: grid; grid-template-columns: 1.1fr 1fr; gap: 14px; margin-bottom: 14px; }
57
+ @media (max-width: 900px) { .ctl { grid-template-columns: 1fr; } }
58
+ .form { display: flex; flex-wrap: wrap; gap: 8px 12px; align-items: end; }
59
+ .form label { display: flex; flex-direction: column; gap: 3px; color: var(--dim); font-size: 11px; }
60
+ input[type=text], input[type=number], select { background: #11141a; color: var(--text); border: 1px solid var(--line);
61
+ border-radius: 6px; padding: 5px 8px; font: inherit; min-width: 0; }
62
+ input:focus, select:focus { outline: none; border-color: var(--accent); }
63
+ button.primary { background: var(--accent); color: #111; border-color: var(--accent); font-weight: 600; }
64
+ button.danger { border-color: var(--bad); color: var(--bad); }
65
+ button:disabled { opacity: .45; cursor: default; }
66
+ .msg { margin-top: 8px; font-size: 12px; color: var(--dim); min-height: 18px; white-space: pre-wrap; }
67
+ .msg.good { color: var(--accent); } .msg.bad { color: var(--bad); }
68
+ .pill { display: inline-block; border-radius: 999px; padding: 1px 9px; border: 1px solid var(--line); font-size: 12px; }
69
+ .pill.run { border-color: var(--accent); color: var(--accent); } .pill.idle { color: var(--dim); }
70
+ pre.log { margin: 0; max-height: 260px; overflow: auto; font: 11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace;
71
+ color: #b9c0cf; white-space: pre-wrap; word-break: break-all; }
72
+ .big { font-size: 22px; font-weight: 600; font-variant-numeric: tabular-nums; }
73
+ .kpis { display: flex; gap: 22px; flex-wrap: wrap; margin-top: 8px; }
74
+ .kpis div span { display: block; color: var(--dim); font-size: 11px; }
75
+ @media (max-width: 600px) { .wrap { padding: 12px 16px 40px; } .form label { flex: 1 1 100%; } }
76
+ </style>
77
+
78
+ <div class="wrap">
79
+
80
+ <header>
81
+ <h1>SO-101 <b>hardware-in-the-loop</b></h1>
82
+ <span class="stat">Cosmos3-Edge policy on the Jetson Thor · Isaac Lab So101Bench on this machine</span>
83
+ <span class="pill idle" id="runPill">idle</span>
84
+ </header>
85
+
86
+ <div class="ctl">
87
+ <div class="panel">
88
+ <h2>1 · Cosmos Edge policy server on the Jetson Thor</h2>
89
+ <div class="form">
90
+ <label>Thor IP address<input type="text" id="host" placeholder="Thor IP" size="15" autocomplete="off"></label>
91
+ <label>SSH user<input type="text" id="user" placeholder="user" size="11" autocomplete="off"></label>
92
+ <label>Port<input type="number" id="port" value="8000" style="width:76px"></label>
93
+ </div>
94
+ <div class="form" style="margin-top:10px">
95
+ <button class="primary" id="launchBtn">Launch server on Thor</button>
96
+ <button id="checkBtn">Test connection</button>
97
+ <button class="danger" id="stopSrvBtn">Stop server</button>
98
+ <span class="pill idle" id="srvPill">not checked</span>
99
+ </div>
100
+ <div class="msg" id="checkMsg">Enter the Thor's IP and SSH user, then launch the server. It loads in ~15 s; the first inference compiles kernels (~20 s).</div>
101
+ <details style="margin-top:8px"><summary class="stat" style="cursor:pointer">Thor server log</summary>
102
+ <pre class="log" id="srvLog" style="max-height:200px;margin-top:6px">–</pre></details>
103
+ </div>
104
+ <div class="panel">
105
+ <h2>2 · Benchmark (runs here)</h2>
106
+ <div class="form">
107
+ <label>Suite<select id="suite"></select></label>
108
+ <label>Episodes (blank = all)<input type="number" id="numEp" min="1" placeholder="all" style="width:90px"></label>
109
+ <label style="flex-direction:row;align-items:center;gap:6px;color:var(--text)"><input type="checkbox" id="gui" checked> Isaac Sim window</label>
110
+ <label style="flex-direction:row;align-items:center;gap:6px;color:var(--text)"><input type="checkbox" id="autoLaunch" checked> Launch Thor server if needed</label>
111
+ </div>
112
+ <div class="form" style="margin-top:8px">
113
+ <label style="flex:1">Fixed instruction (optional, overrides the suite's)<input type="text" id="instr" placeholder="e.g. Place the cooking spoon in the plastic bin"></label>
114
+ </div>
115
+ <div class="form" style="margin-top:10px">
116
+ <button class="primary" id="startBtn">Start run</button>
117
+ <button id="pauseBtn">Pause</button>
118
+ <button id="resumeBtn">Resume</button>
119
+ <button id="skipBtn">Skip episode</button>
120
+ <button class="danger" id="stopBtn">Stop</button>
121
+ </div>
122
+ <div class="msg" id="suiteMsg"></div>
123
+ <div class="msg" id="runMsg"></div>
124
+ </div>
125
+ </div>
126
+
127
+ <div class="panel" style="margin-bottom:14px">
128
+ <h2>Results</h2>
129
+ <div class="kpis">
130
+ <div><span>successes</span><b class="big ok" id="kOk">–</b></div>
131
+ <div><span>episodes finished</span><b class="big" id="kRun">–</b></div>
132
+ <div><span>success rate</span><b class="big" id="kRate">–</b></div>
133
+ <div><span>Thor inference (median)</span><b class="big" id="kInfer">–</b></div>
134
+ <div><span>round-trip (median)</span><b class="big" id="kRt">–</b></div>
135
+ <div><span>elapsed</span><b class="big" id="kTime">–</b></div>
136
+ </div>
137
+ </div>
138
+ <header>
139
+ <span class="prompt" id="prompt">waiting for the first request…</span>
140
+ <span class="live" id="live" title="pause to inspect"><span class="dot"></span><span id="liveTxt">live</span></span>
141
+ </header>
142
+ <header style="margin-top:-4px">
143
+ <span class="stat">episode <b id="ep">–</b></span>
144
+ <span class="stat">chunk <b id="chunkInEp">–</b> in episode</span>
145
+ <span class="stat">request <b id="req">–</b></span>
146
+ <span class="stat">at <b id="wall">–</b></span>
147
+ <span class="stat">inference <b id="infer">–</b> ms</span>
148
+ <span class="stat">round-trip <b id="rt">–</b> ms</span>
149
+ <span class="stat">since previous <b id="gap">–</b> s</span>
150
+ <span class="stat">rate <b id="rate">–</b> chunks/min</span>
151
+ </header>
152
+
153
+ <div class="grid">
154
+ <div class="panel">
155
+ <h2>Observation sent to the policy</h2>
156
+ <div class="obs">
157
+ <img id="img" alt="observation">
158
+ <span class="tag" style="top:6px">wrist camera</span>
159
+ <span class="tag" style="top:calc(50% + 6px)">overhead camera</span>
160
+ </div>
161
+ <div class="state" id="state"></div>
162
+ <div class="legend">State = joint positions in LeRobot units (joints ±100, gripper 0–100), the row the chunk is conditioned on.</div>
163
+ </div>
164
+ <div class="panel">
165
+ <h2>Action chunk returned (32 steps × 6 joints, 1.07 s at 30 Hz)</h2>
166
+ <div class="charts" id="chunkCharts"></div>
167
+ <div class="legend">
168
+ <i style="background:var(--dim)"></i>previous chunk
169
+ <i style="background:var(--j0)"></i>this chunk
170
+ ● current state (step 0)
171
+ </div>
172
+ </div>
173
+ </div>
174
+
175
+ <div class="scrub">
176
+ <button id="prev">◀</button>
177
+ <input type="range" id="slider" min="0" max="0" value="0">
178
+ <button id="next">▶</button>
179
+ <span class="stat" id="pos">–</span>
180
+ </div>
181
+
182
+ <div class="panel">
183
+ <h2>Episode so far: every chunk laid end to end, dots are the observed state at each request</h2>
184
+ <div class="charts" id="epCharts"></div>
185
+ </div>
186
+
187
+ <div class="row2">
188
+ <div class="panel">
189
+ <h2>Chunk values</h2>
190
+ <div class="tbl" id="chunkTbl"></div>
191
+ </div>
192
+ <div class="panel">
193
+ <h2>Benchmark episodes</h2>
194
+ <div class="tbl" id="epTbl"><div class="empty">no finished episodes yet</div></div>
195
+ </div>
196
+ </div>
197
+
198
+ <div class="panel" style="margin-top:14px">
199
+ <h2>Isaac Lab client log</h2>
200
+ <pre class="log" id="log">no run yet</pre>
201
+ </div>
202
+ </div>
203
+ <script>
204
+ const JOINT_COLORS = ["--j0","--j1","--j2","--j3","--j4","--j5"].map(v => getComputedStyle(document.documentElement).getPropertyValue(v).trim());
205
+ const DIM = getComputedStyle(document.documentElement).getPropertyValue("--dim").trim();
206
+ const LINE = getComputedStyle(document.documentElement).getPropertyValue("--line").trim();
207
+ const CHUNK_S = 32 / 30;
208
+ let joints = ["shoulder_pan","shoulder_lift","elbow_flex","wrist_flex","wrist_roll","gripper"];
209
+ let records = []; // all records the page has seen, ordered by i
210
+ let last = -1;
211
+ let live = true;
212
+ let cursor = -1; // index into records
213
+
214
+ const $ = id => document.getElementById(id);
215
+
216
+ function makeCanvases(host, n, h) {
217
+ host.innerHTML = "";
218
+ return Array.from({length: n}, () => { const c = document.createElement("canvas"); c.dataset.h = h; host.appendChild(c); return c; });
219
+ }
220
+ const chunkCanvases = makeCanvases($("chunkCharts"), 6, 150);
221
+ const epCanvases = makeCanvases($("epCharts"), 6, 150);
222
+
223
+ function fit(c) {
224
+ const dpr = window.devicePixelRatio || 1, w = c.clientWidth, h = +c.dataset.h;
225
+ c.width = w * dpr; c.height = h * dpr; c.style.height = h + "px";
226
+ const ctx = c.getContext("2d"); ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
227
+ return [ctx, w, h];
228
+ }
229
+
230
+ function plot(c, title, color, series, xmax, points) {
231
+ // series: [{xs, ys, color, width, alpha}], points: [{x, y, color}]
232
+ const [ctx, w, h] = fit(c);
233
+ const pad = {l: 36, r: 6, t: 16, b: 16};
234
+ let lo = Infinity, hi = -Infinity;
235
+ for (const s of series) for (const y of s.ys) { lo = Math.min(lo, y); hi = Math.max(hi, y); }
236
+ for (const p of points) { lo = Math.min(lo, p.y); hi = Math.max(hi, p.y); }
237
+ if (!isFinite(lo)) { lo = 0; hi = 1; }
238
+ if (hi - lo < 2) { const m = (hi + lo) / 2; lo = m - 1; hi = m + 1; }
239
+ const span = hi - lo; lo -= span * .08; hi += span * .08;
240
+ const X = x => pad.l + (x / xmax) * (w - pad.l - pad.r);
241
+ const Y = y => pad.t + (1 - (y - lo) / (hi - lo)) * (h - pad.t - pad.b);
242
+ ctx.clearRect(0, 0, w, h);
243
+ ctx.fillStyle = color; ctx.font = "600 11px system-ui"; ctx.fillText(title, pad.l, 11);
244
+ ctx.strokeStyle = LINE; ctx.lineWidth = 1; ctx.fillStyle = DIM; ctx.font = "10px system-ui";
245
+ for (const f of [0, .5, 1]) {
246
+ const v = lo + f * (hi - lo), y = Y(v);
247
+ ctx.beginPath(); ctx.moveTo(pad.l, y); ctx.lineTo(w - pad.r, y); ctx.stroke();
248
+ ctx.fillText(v.toFixed(1), 2, y + 3);
249
+ }
250
+ ctx.fillText("0", pad.l, h - 3);
251
+ const xl = xmax.toFixed(xmax < 5 ? 2 : 0) + " s"; ctx.fillText(xl, w - pad.r - ctx.measureText(xl).width, h - 3);
252
+ for (const s of series) {
253
+ ctx.globalAlpha = s.alpha ?? 1; ctx.strokeStyle = s.color; ctx.lineWidth = s.width ?? 1.6;
254
+ ctx.beginPath(); s.xs.forEach((x, k) => k ? ctx.lineTo(X(x), Y(s.ys[k])) : ctx.moveTo(X(x), Y(s.ys[k]))); ctx.stroke();
255
+ }
256
+ ctx.globalAlpha = 1;
257
+ for (const p of points) { ctx.fillStyle = p.color; ctx.beginPath(); ctx.arc(X(p.x), Y(p.y), p.r ?? 3, 0, 7); ctx.fill(); }
258
+ }
259
+
260
+ function render() {
261
+ if (!records.length) return;
262
+ const r = records[cursor];
263
+ $("prompt").textContent = r.prompt;
264
+ $("ep").textContent = r.episode;
265
+ const epRecs = records.filter(x => x.episode === r.episode && x.i <= r.i);
266
+ $("chunkInEp").textContent = epRecs.length;
267
+ $("req").textContent = r.i;
268
+ $("wall").textContent = r.wall;
269
+ $("infer").textContent = r.infer_ms.toFixed(0);
270
+ $("rt").textContent = r.roundtrip_ms.toFixed(0);
271
+ $("gap").textContent = r.since_prev_s == null ? "–" : r.since_prev_s.toFixed(1);
272
+ const recent = records.slice(Math.max(0, cursor - 20), cursor + 1).filter(x => x.since_prev_s != null && x.since_prev_s < 15);
273
+ const meanGap = recent.reduce((a, x) => a + x.since_prev_s, 0) / (recent.length || 1);
274
+ $("rate").textContent = recent.length ? (60 / meanGap).toFixed(1) : "–";
275
+
276
+ const img = $("img"), src = `/obs/${r.i}.jpg`;
277
+ if (img.getAttribute("src") !== src) img.setAttribute("src", src);
278
+
279
+ $("state").innerHTML = r.state.map((v, j) => `<div><span>${joints[j]}</span><b style="color:${JOINT_COLORS[j]}">${v.toFixed(1)}</b></div>`).join("");
280
+
281
+ const prev = records[cursor - 1] && records[cursor - 1].episode === r.episode ? records[cursor - 1] : null;
282
+ const steps = r.action.map((_, k) => (k + 1) / 30);
283
+ chunkCanvases.forEach((c, j) => {
284
+ const series = [];
285
+ if (prev) series.push({xs: prev.action.map((_, k) => (k + 1) / 30 - CHUNK_S), ys: prev.action.map(a => a[j]), color: DIM, alpha: .5, width: 1});
286
+ series.push({xs: [0, ...steps], ys: [r.state[j], ...r.action.map(a => a[j])], color: JOINT_COLORS[j], width: 2});
287
+ const vis = series.map(s => ({...s, xs: s.xs.map(x => x + (prev ? CHUNK_S : 0))}));
288
+ plot(c, joints[j], JOINT_COLORS[j], vis, CHUNK_S * (prev ? 2 : 1), [{x: prev ? CHUNK_S : 0, y: r.state[j], color: "#fff"}]);
289
+ });
290
+
291
+ const t0 = epRecs.length ? epRecs[0].t : r.t;
292
+ const epEnd = Math.max(CHUNK_S * epRecs.length, 1);
293
+ epCanvases.forEach((c, j) => {
294
+ const series = epRecs.map((x, k) => ({
295
+ xs: [k * CHUNK_S, ...x.action.map((_, s) => k * CHUNK_S + (s + 1) / 30)],
296
+ ys: [x.state[j], ...x.action.map(a => a[j])],
297
+ color: JOINT_COLORS[j], width: x.i === r.i ? 2.2 : 1.2, alpha: x.i === r.i ? 1 : .65,
298
+ }));
299
+ const points = epRecs.map((x, k) => ({x: k * CHUNK_S, y: x.state[j], color: "#fff", r: 2}));
300
+ plot(c, joints[j], JOINT_COLORS[j], series, epEnd, points);
301
+ });
302
+
303
+ $("chunkTbl").innerHTML = "<table><tr><th>step</th><th>t (s)</th>" + joints.map((n, j) => `<th style="color:${JOINT_COLORS[j]}">${n}</th>`).join("") + "</tr>"
304
+ + `<tr><td>state</td><td>0.000</td>${r.state.map(v => `<td>${v.toFixed(2)}</td>`).join("")}</tr>`
305
+ + r.action.map((a, k) => `<tr><td>${k + 1}</td><td>${((k + 1) / 30).toFixed(3)}</td>${a.map(v => `<td>${v.toFixed(2)}</td>`).join("")}</tr>`).join("") + "</table>";
306
+
307
+ const slider = $("slider"); slider.max = records.length - 1; slider.value = cursor;
308
+ $("pos").textContent = `${cursor + 1} / ${records.length} loaded`;
309
+ }
310
+
311
+ async function poll() {
312
+ try {
313
+ const res = await fetch(`/api/records?after=${last}&limit=500`);
314
+ const data = await res.json();
315
+ joints = data.joints || joints;
316
+ if (data.records.length) {
317
+ records.push(...data.records);
318
+ last = records[records.length - 1].i;
319
+ if (records.length > 3000) { const drop = records.length - 3000; records.splice(0, drop); cursor = Math.max(0, cursor - drop); }
320
+ if (live) cursor = records.length - 1;
321
+ render();
322
+ }
323
+ } catch (e) { /* server restarting; try again */ }
324
+ setTimeout(poll, 1000);
325
+ }
326
+
327
+ async function pollEpisodes() {
328
+ try {
329
+ const eps = await (await fetch("/api/episodes")).json();
330
+ const ok0 = eps.filter(e => e.result === "success").length, run0 = eps.filter(e => e.result !== "skipped").length;
331
+ $("kOk").textContent = eps.length ? ok0 : "–"; $("kRun").textContent = eps.length ? run0 : "–";
332
+ $("kRate").textContent = run0 ? (100 * ok0 / run0).toFixed(1) + " %" : "–";
333
+ if (!eps.length) $("epTbl").innerHTML = '<div class="empty">no finished episodes yet</div>';
334
+ if (eps.length) {
335
+ const ok = eps.filter(e => e.result === "success").length, run = eps.filter(e => e.result !== "skipped").length;
336
+ $("epTbl").innerHTML = `<div class="stat" style="margin-bottom:6px"><b>${ok}</b> successes / <b>${run}</b> episodes</div>`
337
+ + "<table><tr><th>#</th><th class=l>object</th><th class=l>group</th><th class=l>result</th><th>s</th></tr>"
338
+ + eps.slice().reverse().map(e => `<tr><td>${e.n}</td><td class=l>${e.object}</td><td class=l>${e.group.replace(/_/g, " ")}</td>`
339
+ + `<td class="l ${e.result === "success" ? "ok" : e.result === "skipped" ? "skip" : "fail"}">${e.result}</td><td>${e.seconds == null ? "" : e.seconds.toFixed(1)}</td></tr>`).join("")
340
+ + "</table>";
341
+ }
342
+ } catch (e) {}
343
+ setTimeout(pollEpisodes, 4000);
344
+ }
345
+
346
+ function setLive(v) { live = v; $("live").classList.toggle("paused", !v); $("liveTxt").textContent = v ? "live" : "paused"; if (v && records.length) { cursor = records.length - 1; render(); } }
347
+ $("live").onclick = () => setLive(!live);
348
+ $("slider").oninput = e => { setLive(false); cursor = +e.target.value; render(); };
349
+ $("prev").onclick = () => { setLive(false); cursor = Math.max(0, cursor - 1); render(); };
350
+ $("next").onclick = () => { cursor = Math.min(records.length - 1, cursor + 1); render(); };
351
+ document.addEventListener("keydown", e => {
352
+ if (e.key === "ArrowLeft") $("prev").click();
353
+ if (e.key === "ArrowRight") $("next").click();
354
+ if (e.key === " ") { e.preventDefault(); setLive(!live); }
355
+ });
356
+ window.addEventListener("resize", render);
357
+
358
+ const median = a => { if (!a.length) return null; const s = [...a].sort((x, y) => x - y); return s[Math.floor(s.length / 2)]; };
359
+ function kpis() {
360
+ const tail = records.slice(-60);
361
+ const inf = median(tail.map(r => r.infer_ms).filter(v => v > 0)), rt = median(tail.map(r => r.roundtrip_ms));
362
+ $("kInfer").textContent = inf == null ? "–" : inf.toFixed(0) + " ms";
363
+ $("kRt").textContent = rt == null ? "–" : rt.toFixed(0) + " ms";
364
+ }
365
+ setInterval(kpis, 2000);
366
+
367
+ function msg(id, text, cls) { const el = $(id); el.textContent = text; el.className = "msg" + (cls ? " " + cls : ""); }
368
+ async function post(url, body) {
369
+ const res = await fetch(url, {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify(body || {})});
370
+ return res.json();
371
+ }
372
+ function saveForm() {
373
+ try { localStorage.setItem("so101thor", JSON.stringify({host: $("host").value, user: $("user").value, port: $("port").value, suite: $("suite").value,
374
+ numEp: $("numEp").value, gui: $("gui").checked, autoLaunch: $("autoLaunch").checked, instr: $("instr").value})); } catch (e) {}
375
+ }
376
+ function loadForm(cfg) {
377
+ let s = {};
378
+ try { s = JSON.parse(localStorage.getItem("so101thor") || "{}"); } catch (e) {}
379
+ $("host").value = s.host || cfg.default_host || "";
380
+ $("user").value = s.user || cfg.default_user || "";
381
+ $("autoLaunch").checked = s.autoLaunch !== false;
382
+ $("port").value = s.port || cfg.default_port || 8000;
383
+ if (s.suite && cfg.suites[s.suite]) $("suite").value = s.suite;
384
+ $("numEp").value = s.numEp || ""; $("gui").checked = s.gui !== false; $("instr").value = s.instr || "";
385
+ }
386
+ let suiteInfo = {}, suiteSizes = {};
387
+ function showSuite() { const k = $("suite").value; msg("suiteMsg", suiteInfo[k] || ""); }
388
+
389
+ const thorCfg = () => ({host: $("host").value.trim(), user: $("user").value.trim(), port: +$("port").value || 8000});
390
+ const sleep = ms => new Promise(r => setTimeout(r, ms));
391
+ let srvState = "unknown";
392
+ function setSrv(state, text) {
393
+ srvState = state;
394
+ const pill = $("srvPill");
395
+ pill.textContent = text || state;
396
+ pill.className = "pill " + (state === "ready" ? "run" : "idle");
397
+ pill.style.borderColor = state === "error" || state === "unreachable" ? "var(--bad)" : state === "starting" ? "var(--warn)" : "";
398
+ pill.style.color = state === "error" || state === "unreachable" ? "var(--bad)" : state === "starting" ? "var(--warn)" : "";
399
+ }
400
+ async function thorStatus() {
401
+ const c = thorCfg();
402
+ if (!c.host || !c.user) return null;
403
+ try {
404
+ const r = await post("/api/thor/status", c);
405
+ if (r.log !== undefined) { const el = $("srvLog"); el.textContent = r.log || "(no log yet)"; el.scrollTop = el.scrollHeight; }
406
+ if (!r.ok) { setSrv(r.state || "error", r.state === "unreachable" ? "Thor unreachable" : "error"); msg("checkMsg", "✗ " + r.error, "bad"); return r; }
407
+ setSrv(r.state, {ready: `ready · ${c.host}:${c.port}`, starting: "loading model…", stopped: "not running", error: "server error"}[r.state] || r.state);
408
+ return r;
409
+ } catch (e) { return null; }
410
+ }
411
+ async function testConnection(quiet) {
412
+ const c = thorCfg();
413
+ if (!c.host) { msg("checkMsg", "Enter the Thor's IP address.", "bad"); return false; }
414
+ msg("checkMsg", `Sending two test inferences to ${c.host}:${c.port} (the first after a server start compiles kernels, ~20 s)…`);
415
+ const r = await post("/api/check", c);
416
+ if (!r.ok) { msg("checkMsg", `✗ ${r.error}`, "bad"); return false; }
417
+ const units = r.units_ok ? "" : "\n⚠ actions are inside [-1, 1]: the server is probably missing its normalization flags.";
418
+ msg("checkMsg", `✓ Policy server ready at ${c.host}:${c.port}\nchunk ${r.action_shape.join(" × ")}, values ${r.action_min} … ${r.action_max}\n`
419
+ + `Thor inference ${r.infer_ms} ms · round-trip ${r.roundtrip_ms.join(" / ")} ms${units}`, r.units_ok ? "good" : "bad");
420
+ return r.units_ok;
421
+ }
422
+ // Launch (if needed) -> wait for "ready" -> warm up. Returns true when the Thor is serving.
423
+ async function ensureServer() {
424
+ const c = thorCfg();
425
+ if (!c.host || !c.user) { msg("checkMsg", "Enter the Thor's IP address and SSH user.", "bad"); return false; }
426
+ msg("checkMsg", `Launching the policy server on ${c.user}@${c.host}…`);
427
+ const r = await post("/api/thor/launch", c);
428
+ if (!r.ok) { msg("checkMsg", "✗ " + r.error, "bad"); setSrv("error", "launch failed"); return false; }
429
+ if (!r.already_running) {
430
+ setSrv("starting", "loading model…");
431
+ const t0 = Date.now();
432
+ while (Date.now() - t0 < 300000) {
433
+ await sleep(3000);
434
+ const st = await thorStatus();
435
+ if (st && st.healthy) break;
436
+ if (st && (st.state === "error" || (st.state === "stopped" && Date.now() - t0 > 15000))) {
437
+ msg("checkMsg", "✗ The server stopped while loading; see the Thor server log below.", "bad");
438
+ $("srvLog").closest("details").open = true; return false;
439
+ }
440
+ msg("checkMsg", `Loading the model on the Thor… ${Math.round((Date.now() - t0) / 1000)} s`);
441
+ }
442
+ }
443
+ await thorStatus();
444
+ return await testConnection();
445
+ }
446
+ $("launchBtn").onclick = async () => { saveForm(); $("launchBtn").disabled = true; await ensureServer(); $("launchBtn").disabled = false; };
447
+ $("checkBtn").onclick = async () => { saveForm(); $("checkBtn").disabled = true; await thorStatus(); await testConnection(); $("checkBtn").disabled = false; };
448
+ $("stopSrvBtn").onclick = async () => {
449
+ if (st.running && !confirm("A benchmark run is using this server. Stop the server anyway?")) return;
450
+ const r = await post("/api/thor/stop", thorCfg());
451
+ msg("checkMsg", r.ok ? "Policy server stopped on the Thor." : "✗ " + r.error, r.ok ? "" : "bad");
452
+ await thorStatus();
453
+ };
454
+ setInterval(() => { if (!document.hidden) thorStatus(); }, 6000);
455
+
456
+ $("startBtn").onclick = async () => {
457
+ saveForm();
458
+ const body = {host: $("host").value.trim(), port: +$("port").value || 8000, suite: $("suite").value,
459
+ gui: $("gui").checked, instruction: $("instr").value.trim() || null,
460
+ num_episodes: $("numEp").value ? +$("numEp").value : null};
461
+ if (!body.host) return msg("runMsg", "Enter the Thor's IP address.", "bad");
462
+ $("startBtn").disabled = true;
463
+ if ($("autoLaunch").checked && srvState !== "ready") {
464
+ msg("runMsg", "Getting the Thor policy server ready first…");
465
+ if (!(await ensureServer())) { msg("runMsg", "✗ The Thor policy server is not ready; see step 1.", "bad"); $("startBtn").disabled = false; return; }
466
+ }
467
+ const r = await post("/api/start", body);
468
+ if (!r.ok) { msg("runMsg", "✗ " + r.error, "bad"); $("startBtn").disabled = false; return; }
469
+ records = []; last = -1; cursor = -1;
470
+ msg("runMsg", `Started (pid ${r.pid}). Isaac Sim takes about 1–2 minutes to load before the first request reaches the Thor.\nRun folder: ${r.run_dir}`, "good");
471
+ status();
472
+ };
473
+ $("stopBtn").onclick = async () => { const r = await post("/api/stop"); msg("runMsg", r.ok ? "Stopped." : "✗ " + r.error, r.ok ? "" : "bad"); status(); };
474
+ for (const [id, command] of [["pauseBtn", "pause"], ["resumeBtn", "resume"], ["skipBtn", "skip"]])
475
+ $(id).onclick = async () => { const r = await post("/api/control", {command}); msg("runMsg", r.ok ? `Sent “${command}”.` : "✗ " + r.error, r.ok ? "" : "bad"); };
476
+ $("suite").onchange = () => { showSuite(); saveForm(); };
477
+
478
+ function fmtDur(s) { s = Math.max(0, Math.round(s)); const h = Math.floor(s / 3600), m = Math.floor(s % 3600 / 60); return (h ? h + " h " : "") + m + " min " + (s % 60) + " s"; }
479
+ let st = {};
480
+ async function status() {
481
+ try {
482
+ st = await (await fetch("/api/status")).json();
483
+ const pill = $("runPill");
484
+ pill.textContent = st.running ? `running · ${st.suite} → ${st.host}:${st.port}` : (st.exit_code == null ? "idle" : `finished (exit ${st.exit_code})`);
485
+ pill.className = "pill " + (st.running ? "run" : "idle");
486
+ $("startBtn").disabled = !!st.running;
487
+ for (const id of ["stopBtn", "pauseBtn", "resumeBtn", "skipBtn"]) $(id).disabled = !st.running;
488
+ $("kTime").textContent = st.started_t ? fmtDur((st.running ? Date.now() / 1000 : (records.length ? records[records.length - 1].t : Date.now() / 1000)) - st.started_t) : "–";
489
+ } catch (e) {}
490
+ }
491
+ async function pollLog() {
492
+ try {
493
+ const t = await (await fetch("/api/log?lines=80")).text();
494
+ const el = $("log"), atEnd = el.scrollTop + el.clientHeight >= el.scrollHeight - 20;
495
+ if (t) { el.textContent = t; if (atEnd) el.scrollTop = el.scrollHeight; }
496
+ } catch (e) {}
497
+ setTimeout(pollLog, 3000);
498
+ }
499
+
500
+ (async () => {
501
+ const cfg = await (await fetch("/api/config")).json();
502
+ suiteInfo = cfg.suites; suiteSizes = cfg.suite_sizes || {};
503
+ joints = cfg.joints || joints;
504
+ $("suite").innerHTML = Object.keys(cfg.suites).map(k => `<option value="${k}">${k}${suiteSizes[k] ? " (" + suiteSizes[k] + ")" : ""}</option>`).join("");
505
+ loadForm(cfg); showSuite(); status(); thorStatus();
506
+ setInterval(status, 3000);
507
+ })();
508
+ poll(); pollEpisodes(); pollLog();
509
+ </script>
thor_deploy/laptop/webui/so101_thor_ui.py ADDED
@@ -0,0 +1,589 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Web UI for running the SO-101 Isaac Lab benchmark on this machine against a policy
2
+ server on a Jetson Thor (or any host running the Cosmos3-Edge policy server).
3
+
4
+ python so101_thor_ui.py [--port 8765] # then open http://127.0.0.1:8765/
5
+
6
+ The page takes the Thor address, checks the server (metadata + one timed inference),
7
+ then starts ``so101_bench/scripts/cosmos3_eval.py`` here. The Isaac Sim window opens on
8
+ this machine; the page shows every observation sent to Thor and every action chunk it
9
+ returns, per-episode results, and the client log.
10
+
11
+ Traffic path: Isaac Lab client -> ws://127.0.0.1:<relay> (this process) -> ws://<thor>:<port>
12
+ Frames are relayed byte-for-byte; a copy of each request/response pair is decoded off the
13
+ relay path for the page, so the client and server see exactly what they would without it.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import asyncio
20
+ import json
21
+ import os
22
+ import re
23
+ import signal
24
+ import subprocess
25
+ import sys
26
+ import threading
27
+ import time
28
+ from collections import deque
29
+ from http import HTTPStatus
30
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
31
+ from pathlib import Path
32
+
33
+ _VENDOR = Path(__file__).resolve().parent.parent / "vendor_py" # openpi-client, pyzmq (see setup_laptop.sh)
34
+ if _VENDOR.is_dir():
35
+ sys.path.insert(0, str(_VENDOR))
36
+
37
+ import numpy as np
38
+ import websockets
39
+ from openpi_client import msgpack_numpy
40
+ from PIL import Image
41
+
42
+ HERE = Path(__file__).resolve().parent
43
+ ROOT = HERE.parent # the client folder: so101_bench/, webui/, runs/
44
+ JOINTS = ["shoulder_pan", "shoulder_lift", "elbow_flex", "wrist_flex", "wrist_roll", "gripper"]
45
+ EPISODE_GAP_S = 15.0 # a pause this long between requests means the bench reset the scene
46
+ _EPISODE = re.compile(r"Episode (\d+)/(\d+): (?:success=(\w+), reason=(\w+), length=([\d.]+)s|skipped)")
47
+
48
+ #: Benchmark suites: task file and layout-file glob, both relative to so101_bench/.
49
+ SUITES = {
50
+ "focus5": ("tasks/focus5.jsonl", "tasks/layouts/focus5_layouts_*.jsonl",
51
+ "5 training objects, 20 fixed layouts each (100 episodes)"),
52
+ "unseen": ("tasks/focus5_unseen.jsonl", "tasks/layouts/focus5_unseen_layouts_*.jsonl",
53
+ "26 objects never seen in training, 2 layouts each (52 episodes)"),
54
+ "wins": ("tasks/focus5_wins.jsonl", "tasks/layouts/focus5_layouts_*.jsonl",
55
+ "12 layouts where a checkpoint has succeeded before (quick demo)"),
56
+ "clutter": ("tasks/focus5_clutter.jsonl", "tasks/layouts/focus5_clutter_layouts_*.jsonl",
57
+ "focus5 targets with 3 distractors on the table (100 episodes)"),
58
+ "mix": ("tasks/edge_train_mix.jsonl", "tasks/layouts/edge_train_mix_layouts_*.jsonl",
59
+ "training-distribution mix (75 episodes)"),
60
+ }
61
+
62
+
63
+ # ------------------------------------------------------------------ recording
64
+ class Recorder:
65
+ """Decoded request/response pairs: the newest in memory, all of them on disk."""
66
+
67
+ def __init__(self, keep: int = 2000) -> None:
68
+ self.keep = keep
69
+ self.lock = threading.Lock()
70
+ self.reset(None)
71
+
72
+ def reset(self, out: Path | None) -> None:
73
+ with getattr(self, "lock", threading.Lock()):
74
+ self.out = out
75
+ self.records: deque[dict] = deque(maxlen=self.keep)
76
+ self.count = 0
77
+ self.episode = 0
78
+ self.last_t: float | None = None
79
+ self.last_prompt: str | None = None
80
+ self.jsonl = None
81
+ if out is not None:
82
+ (out / "obs").mkdir(parents=True, exist_ok=True)
83
+ self.jsonl = (out / "records.jsonl").open("a")
84
+
85
+ def add(self, request: bytes, response: bytes, t_sent: float, t_recv: float) -> None:
86
+ obs = msgpack_numpy.unpackb(request)
87
+ reply = msgpack_numpy.unpackb(response)
88
+ if not isinstance(obs, dict) or not isinstance(reply, dict) or "action" not in reply:
89
+ return
90
+ prompt = str(obs.get("prompt", ""))
91
+ gap = None if self.last_t is None else t_sent - self.last_t
92
+ if self.last_t is None or gap > EPISODE_GAP_S or prompt != self.last_prompt:
93
+ self.episode += 1
94
+ self.last_t, self.last_prompt = t_sent, prompt
95
+
96
+ index = self.count
97
+ self.count += 1
98
+ image = np.asarray(obs.get("observation/image"))
99
+ if image.ndim == 3 and self.out is not None:
100
+ Image.fromarray(image.astype(np.uint8)).save(self.out / "obs" / f"{index:06d}.jpg", quality=85)
101
+ joints = np.asarray(obs.get("observation/joint_position", np.zeros((1, 5)))).reshape(-1, 5)[-1]
102
+ gripper = np.asarray(obs.get("observation/gripper_position", np.zeros((1, 1)))).reshape(-1)[-1]
103
+ action = np.asarray(reply["action"], dtype=np.float64)
104
+ timing = reply.get("server_timing", {}) or {}
105
+ rec = {
106
+ "i": index,
107
+ "episode": self.episode,
108
+ "wall": time.strftime("%H:%M:%S", time.localtime(t_sent)),
109
+ "t": t_sent,
110
+ "prompt": prompt.split(". This video")[0],
111
+ "state": [round(float(v), 3) for v in [*joints, gripper]],
112
+ "action": [[round(float(v), 3) for v in row] for row in action],
113
+ "infer_ms": round(float(timing.get("infer_ms", 0.0)), 1),
114
+ "roundtrip_ms": round((t_recv - t_sent) * 1000, 1),
115
+ "since_prev_s": None if gap is None else round(gap, 2),
116
+ }
117
+ with self.lock:
118
+ self.records.append(rec)
119
+ if self.jsonl is not None:
120
+ self.jsonl.write(json.dumps(rec) + "\n")
121
+ self.jsonl.flush()
122
+
123
+ def since(self, after: int, limit: int) -> list[dict]:
124
+ with self.lock:
125
+ return [r for r in self.records if r["i"] > after][:limit]
126
+
127
+
128
+ # ---------------------------------------------------------------------- relay
129
+ class Relay:
130
+ """WebSocket relay to the policy server. The upstream is set when a run starts."""
131
+
132
+ def __init__(self, recorder: Recorder, host: str, port: int) -> None:
133
+ self.recorder = recorder
134
+ self.host, self.port = host, port
135
+ self.upstream: tuple[str, int] | None = None
136
+ self.decode_q: asyncio.Queue | None = None
137
+ self.loop: asyncio.AbstractEventLoop | None = None
138
+
139
+ async def health(self, path, request_headers):
140
+ # websockets<=12 (the version openpi-client runs with under Isaac Sim) legacy API
141
+ if path == "/healthz":
142
+ return HTTPStatus.OK, [], b"OK\n"
143
+ return None
144
+
145
+ async def handler(self, client, path: str | None = None) -> None:
146
+ if self.upstream is None:
147
+ await client.close(1011, "no policy server selected")
148
+ return
149
+ url = f"ws://{self.upstream[0]}:{self.upstream[1]}"
150
+ async with websockets.connect(url, compression=None, max_size=None, open_timeout=30,
151
+ ping_interval=None) as upstream:
152
+ await client.send(await upstream.recv()) # server metadata
153
+ try:
154
+ while True:
155
+ request = await client.recv()
156
+ t_sent = time.time()
157
+ await upstream.send(request)
158
+ response = await upstream.recv()
159
+ t_recv = time.time()
160
+ await client.send(response)
161
+ if isinstance(request, bytes) and isinstance(response, bytes):
162
+ try:
163
+ self.decode_q.put_nowait((request, response, t_sent, t_recv))
164
+ except asyncio.QueueFull:
165
+ pass # never slow the relay down for the page
166
+ except websockets.ConnectionClosed:
167
+ pass
168
+
169
+ async def decoder(self) -> None:
170
+ while True:
171
+ item = await self.decode_q.get()
172
+ try:
173
+ await asyncio.to_thread(self.recorder.add, *item)
174
+ except Exception as exc: # a bad record must not stop the relay
175
+ print(f"[ui] decode failed: {exc!r}", flush=True)
176
+
177
+ async def run(self) -> None:
178
+ self.loop = asyncio.get_running_loop()
179
+ self.decode_q = asyncio.Queue(maxsize=64)
180
+ asyncio.create_task(self.decoder())
181
+ async with websockets.serve(self.handler, self.host, self.port, compression=None, max_size=None,
182
+ ping_interval=None, process_request=self.health):
183
+ await asyncio.Future()
184
+
185
+
186
+ def check_server(host: str, port: int, prompt: str) -> dict:
187
+ """Connect to the policy server, read its metadata and time one synthetic inference."""
188
+ from openpi_client import websocket_client_policy
189
+
190
+ out: dict = {"host": host, "port": port}
191
+ t0 = time.time()
192
+ try:
193
+ import socket
194
+ with socket.create_connection((host, port), timeout=5):
195
+ pass
196
+ except OSError as exc:
197
+ return {**out, "ok": False, "error": f"cannot reach {host}:{port} ({exc.strerror or exc})"}
198
+ try:
199
+ client = websocket_client_policy.WebsocketClientPolicy(host, port)
200
+ out["connect_ms"] = round((time.time() - t0) * 1000)
201
+ meta = client.get_server_metadata() or {}
202
+ out["metadata"] = {k: (v if isinstance(v, (str, int, float, bool)) else str(v)) for k, v in meta.items()}
203
+ rng = np.random.default_rng(0)
204
+ req = {
205
+ "observation/image": rng.integers(0, 255, size=(960, 640, 3), dtype=np.uint8),
206
+ "observation/joint_position": np.zeros((1, 5), dtype=np.float32),
207
+ "observation/gripper_position": np.full((1, 1), 20.0, dtype=np.float32),
208
+ "prompt": prompt,
209
+ }
210
+ times = []
211
+ for _ in range(2): # the first call after a server start compiles kernels
212
+ t = time.time()
213
+ reply = client.infer(req)
214
+ times.append(round((time.time() - t) * 1000))
215
+ a = np.asarray(reply["action"])
216
+ timing = reply.get("server_timing", {}) or {}
217
+ out.update(ok=True, action_shape=list(a.shape), action_min=round(float(a.min()), 2),
218
+ action_max=round(float(a.max()), 2), roundtrip_ms=times,
219
+ infer_ms=round(float(timing.get("infer_ms", 0.0))))
220
+ # A healthy SO-101 chunk is in LeRobot .pos units (joints roughly +-100). Values
221
+ # stuck inside [-1, 1] mean the server is missing its normalization flags.
222
+ out["units_ok"] = bool(np.abs(a).max() > 1.5)
223
+ except Exception as exc:
224
+ out.update(ok=False, error=f"{type(exc).__name__}: {exc}")
225
+ return out
226
+
227
+
228
+ # ------------------------------------------------------------- the Thor side
229
+ _SAFE_HOST = re.compile(r"^[A-Za-z0-9._-]{1,253}$")
230
+ _SAFE_USER = re.compile(r"^[A-Za-z0-9._-]{1,64}$")
231
+ _SAFE_DIR = re.compile(r"^[A-Za-z0-9._/~-]{1,256}$")
232
+
233
+
234
+ class ThorControl:
235
+ """Start, watch and stop the policy server on the Thor over SSH (key-based, never prompts).
236
+
237
+ Uses the scripts installed by ``setup_thor.sh``: ``<dir>/serve_thor.sh --tmux`` starts the server
238
+ in the tmux session ``so101serve`` and links its log to ``<dir>/logs/serve_latest.log``.
239
+ """
240
+
241
+ def __init__(self, default_user: str, default_dir: str) -> None:
242
+ self.default_user = default_user
243
+ self.default_dir = default_dir
244
+
245
+ def _target(self, cfg: dict) -> tuple[str, str, str, int]:
246
+ host = str(cfg.get("host", "")).strip()
247
+ user = str(cfg.get("user") or self.default_user).strip()
248
+ tdir = str(cfg.get("dir") or self.default_dir).strip()
249
+ port = int(cfg.get("port", 8000))
250
+ if not _SAFE_HOST.match(host):
251
+ raise ValueError("enter the Thor's IP address")
252
+ if not _SAFE_USER.match(user):
253
+ raise ValueError("enter the SSH user on the Thor")
254
+ if not _SAFE_DIR.match(tdir):
255
+ raise ValueError("invalid install folder")
256
+ return host, user, tdir, port
257
+
258
+ @staticmethod
259
+ def _ssh(user: str, host: str, command: str, timeout: float = 20) -> tuple[int, str]:
260
+ argv = ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=8", "-o", "StrictHostKeyChecking=accept-new",
261
+ f"{user}@{host}", command]
262
+ try:
263
+ r = subprocess.run(argv, capture_output=True, text=True, timeout=timeout)
264
+ except subprocess.TimeoutExpired:
265
+ return 124, "ssh timed out"
266
+ return r.returncode, (r.stdout + r.stderr).strip()
267
+
268
+ @staticmethod
269
+ def _healthy(host: str, port: int) -> bool:
270
+ import urllib.request
271
+ try:
272
+ with urllib.request.urlopen(f"http://{host}:{port}/healthz", timeout=3) as resp:
273
+ return resp.status == 200
274
+ except Exception:
275
+ return False
276
+
277
+ def _ssh_error(self, user: str, host: str, out: str) -> str:
278
+ if "Permission denied" in out or "publickey" in out:
279
+ return (f"SSH key login to {user}@{host} failed. Add this PC's key to the Thor once "
280
+ f"(see the README, 'SSH key'), then try again.")
281
+ if "Could not resolve" in out or "No route" in out or "timed out" in out or "refused" in out:
282
+ return f"cannot reach {host} over SSH ({out.splitlines()[-1] if out else 'no answer'})"
283
+ return out.splitlines()[-1] if out else "ssh failed"
284
+
285
+ def launch(self, cfg: dict) -> dict:
286
+ host, user, tdir, port = self._target(cfg)
287
+ if self._healthy(host, port):
288
+ return {"ok": True, "already_running": True}
289
+ code, out = self._ssh(user, host, f"test -f {tdir}/serve_thor.sh && echo HAS_SERVE")
290
+ if code != 0:
291
+ return {"ok": False, "error": self._ssh_error(user, host, out)}
292
+ if "HAS_SERVE" not in out:
293
+ return {"ok": False, "error": f"no {tdir}/serve_thor.sh on the Thor; run setup_thor.sh there first"}
294
+ code, out = self._ssh(user, host, f"SO101_PORT={port} bash {tdir}/serve_thor.sh --tmux", timeout=30)
295
+ if code != 0:
296
+ return {"ok": False, "error": out.splitlines()[-1] if out else "launch failed"}
297
+ return {"ok": True, "message": out.splitlines()[-1] if out else "starting"}
298
+
299
+ def stop(self, cfg: dict) -> dict:
300
+ host, user, tdir, port = self._target(cfg)
301
+ code, out = self._ssh(user, host, f"SO101_PORT={port} bash {tdir}/serve_thor.sh --stop")
302
+ if code != 0 and not out:
303
+ return {"ok": False, "error": self._ssh_error(user, host, out)}
304
+ return {"ok": True, "message": out or "stopped"}
305
+
306
+ def status(self, cfg: dict) -> dict:
307
+ host, user, tdir, port = self._target(cfg)
308
+ healthy = self._healthy(host, port)
309
+ code, out = self._ssh(
310
+ user, host,
311
+ f"tmux has-session -t so101serve 2>/dev/null && echo __SESSION__; "
312
+ f"grep -q 'ready domain=' {tdir}/logs/serve_latest.log 2>/dev/null && echo __READY__; "
313
+ f"tail -c 20000 {tdir}/logs/serve_latest.log 2>/dev/null | tr '\\r' '\\n' | "
314
+ f"grep -vE 'OmniMoTModel: config|^\\s*$' | tail -n 40",
315
+ )
316
+ if code == 255:
317
+ return {"ok": False, "healthy": healthy, "state": "unreachable", "error": self._ssh_error(user, host, out)}
318
+ session = "__SESSION__" in out
319
+ ready = "__READY__" in out
320
+ log_text = out.replace("__SESSION__", "").replace("__READY__", "").strip()
321
+ if healthy:
322
+ state = "ready" # answering health checks (also when started by hand)
323
+ elif session:
324
+ # A busy server cannot answer /healthz during an inference, so trust the log once it
325
+ # has said "ready".
326
+ state = "ready" if ready else "starting"
327
+ elif "Traceback" in log_text and not ready:
328
+ state = "error" # died while loading; the log shows why
329
+ else:
330
+ state = "stopped"
331
+ return {"ok": True, "healthy": healthy, "session": session, "state": state, "log": log_text}
332
+
333
+
334
+ # ------------------------------------------------------------------- the run
335
+ class Runner:
336
+ """One Isaac Lab client process at a time."""
337
+
338
+ def __init__(self, args: argparse.Namespace, relay: Relay, recorder: Recorder) -> None:
339
+ self.args = args
340
+ self.relay = relay
341
+ self.recorder = recorder
342
+ self.proc: subprocess.Popen | None = None
343
+ self.run_dir: Path | None = None
344
+ self.log_path: Path | None = None
345
+ self.info: dict = {}
346
+ self.lock = threading.Lock()
347
+
348
+ def running(self) -> bool:
349
+ return self.proc is not None and self.proc.poll() is None
350
+
351
+ def command(self, cfg: dict) -> tuple[list[str], dict]:
352
+ bench = self.args.bench
353
+ suite = cfg.get("suite", "focus5")
354
+ if suite not in SUITES:
355
+ raise ValueError(f"unknown suite {suite!r}")
356
+ tasks, layouts_glob, _ = SUITES[suite]
357
+ argv = [
358
+ str(self.args.python), "-u", "scripts/cosmos3_eval.py",
359
+ "--task", "So101Bench-Bin-v0",
360
+ "--episodes_jsonl", tasks,
361
+ "--policy_host", "127.0.0.1",
362
+ "--policy_port", str(self.args.relay_port),
363
+ "--action_horizon", str(int(cfg.get("action_horizon", 32))),
364
+ "--camera_snapshot_stdin", "false",
365
+ ]
366
+ layouts = sorted(bench.glob(layouts_glob), key=lambda p: p.stat().st_mtime)
367
+ if layouts:
368
+ argv += ["--episode_layouts_jsonl", str(layouts[-1].relative_to(bench))]
369
+ if cfg.get("num_episodes"):
370
+ argv += ["--num_episodes", str(int(cfg["num_episodes"]))]
371
+ if cfg.get("instruction"):
372
+ argv += ["--lang_instruction", str(cfg["instruction"])]
373
+ if not cfg.get("gui", True):
374
+ argv.append("--headless")
375
+ env = os.environ.copy()
376
+ env["PYTHONPATH"] = os.pathsep.join([str(bench / "source/so101_bench"), *map(str, self.args.pythonpath)])
377
+ env["PYTHONUNBUFFERED"] = "1"
378
+ env.setdefault("OMNI_KIT_ACCEPT_EULA", "YES")
379
+ if cfg.get("gui", True) and not env.get("DISPLAY"):
380
+ env["DISPLAY"] = ":0"
381
+ return argv, env
382
+
383
+ def start(self, cfg: dict) -> dict:
384
+ with self.lock:
385
+ if self.running():
386
+ return {"ok": False, "error": "a run is already in progress"}
387
+ host = str(cfg.get("host", "")).strip()
388
+ port = int(cfg.get("port", 8000))
389
+ if not host:
390
+ return {"ok": False, "error": "enter the Thor address first"}
391
+ argv, env = self.command(cfg)
392
+ stamp = time.strftime("%Y%m%d_%H%M%S")
393
+ self.run_dir = self.args.runs / f"{cfg.get('suite', 'focus5')}_{stamp}"
394
+ self.run_dir.mkdir(parents=True, exist_ok=True)
395
+ self.log_path = self.run_dir / "eval.log"
396
+ self.recorder.reset(self.run_dir)
397
+ self.relay.upstream = (host, port)
398
+ self.info = {"host": host, "port": port, "suite": cfg.get("suite", "focus5"),
399
+ "gui": bool(cfg.get("gui", True)), "started": time.strftime("%H:%M:%S"),
400
+ "started_t": time.time(), "run_dir": str(self.run_dir), "argv": argv}
401
+ (self.run_dir / "run.json").write_text(json.dumps(self.info, indent=2))
402
+ log = self.log_path.open("w")
403
+ self.proc = subprocess.Popen(argv, cwd=self.args.bench, env=env, stdout=log,
404
+ stderr=subprocess.STDOUT, stdin=subprocess.PIPE,
405
+ start_new_session=True, text=True)
406
+ self.info["pid"] = self.proc.pid
407
+ return {"ok": True, **self.info}
408
+
409
+ def send(self, command: str) -> dict:
410
+ """pause / resume / skip, through the eval script's terminal-control stdin."""
411
+ if not self.running() or self.proc.stdin is None:
412
+ return {"ok": False, "error": "no run in progress"}
413
+ try:
414
+ self.proc.stdin.write(command + "\n")
415
+ self.proc.stdin.flush()
416
+ except OSError as exc:
417
+ return {"ok": False, "error": str(exc)}
418
+ return {"ok": True}
419
+
420
+ def stop(self) -> dict:
421
+ if not self.running():
422
+ return {"ok": False, "error": "no run in progress"}
423
+ try:
424
+ os.killpg(self.proc.pid, signal.SIGINT)
425
+ for _ in range(40):
426
+ if self.proc.poll() is not None:
427
+ break
428
+ time.sleep(0.25)
429
+ if self.proc.poll() is None:
430
+ os.killpg(self.proc.pid, signal.SIGKILL)
431
+ except ProcessLookupError:
432
+ pass
433
+ return {"ok": True}
434
+
435
+ def status(self) -> dict:
436
+ return {"running": self.running(), "exit_code": None if self.proc is None else self.proc.poll(),
437
+ **{k: v for k, v in self.info.items() if k != "argv"}}
438
+
439
+ def episodes(self) -> list[dict]:
440
+ if self.log_path is None or not self.log_path.exists():
441
+ return []
442
+ tasks_file = self.args.bench / SUITES.get(self.info.get("suite", "focus5"), SUITES["focus5"])[0]
443
+ rows = [json.loads(line) for line in tasks_file.read_text().splitlines() if line.strip()]
444
+ out = {}
445
+ for m in _EPISODE.finditer(self.log_path.read_text(errors="ignore")):
446
+ n = int(m.group(1))
447
+ row = rows[n - 1] if 0 < n <= len(rows) else {}
448
+ out[n] = {
449
+ "n": n, "of": int(m.group(2)),
450
+ "object": row.get("target") or ", ".join(row.get("objects", [])),
451
+ "group": row.get("ood_key", ""),
452
+ "result": "skipped" if m.group(3) is None else ("success" if m.group(3) == "True" else m.group(4)),
453
+ "seconds": None if m.group(5) is None else float(m.group(5)),
454
+ }
455
+ return [out[k] for k in sorted(out)]
456
+
457
+ def log_tail(self, lines: int) -> str:
458
+ if self.log_path is None or not self.log_path.exists():
459
+ return ""
460
+ with self.log_path.open("rb") as f:
461
+ f.seek(0, os.SEEK_END)
462
+ f.seek(max(0, f.tell() - 200_000))
463
+ text = f.read().decode(errors="ignore")
464
+ return "\n".join(text.splitlines()[-lines:])
465
+
466
+
467
+ # ----------------------------------------------------------------------- http
468
+ def make_http(args: argparse.Namespace, recorder: Recorder, runner: Runner, thor: ThorControl) -> ThreadingHTTPServer:
469
+ page = HERE / "index.html"
470
+
471
+ class Handler(BaseHTTPRequestHandler):
472
+ def log_message(self, *a) -> None: # quiet
473
+ pass
474
+
475
+ def _send(self, body: bytes, ctype: str, status: int = 200) -> None:
476
+ self.send_response(status)
477
+ self.send_header("Content-Type", ctype)
478
+ self.send_header("Cache-Control", "no-store")
479
+ self.send_header("Content-Length", str(len(body)))
480
+ self.end_headers()
481
+ self.wfile.write(body)
482
+
483
+ def _json(self, obj, status: int = 200) -> None:
484
+ self._send(json.dumps(obj).encode(), "application/json", status)
485
+
486
+ def _body(self) -> dict:
487
+ n = int(self.headers.get("Content-Length") or 0)
488
+ return json.loads(self.rfile.read(n) or b"{}") if n else {}
489
+
490
+ def do_GET(self) -> None:
491
+ path, _, query = self.path.partition("?")
492
+ params = dict(p.split("=", 1) for p in query.split("&") if "=" in p)
493
+ if path == "/":
494
+ return self._send(page.read_bytes(), "text/html; charset=utf-8")
495
+ if path == "/api/config":
496
+ return self._json({"default_host": args.thor, "default_port": args.thor_port,
497
+ "default_user": args.thor_user, "default_dir": args.thor_dir,
498
+ "suites": {k: v[2] for k, v in SUITES.items()},
499
+ "suite_sizes": {k: sum(1 for line in (args.bench / v[0]).read_text().splitlines() if line.strip())
500
+ for k, v in SUITES.items() if (args.bench / v[0]).exists()},
501
+ "joints": JOINTS})
502
+ if path == "/api/status":
503
+ return self._json(runner.status())
504
+ if path == "/api/records":
505
+ after = int(params.get("after", -1))
506
+ return self._json({"records": recorder.since(after, int(params.get("limit", 200))),
507
+ "count": recorder.count})
508
+ if path == "/api/episodes":
509
+ return self._json(runner.episodes())
510
+ if path == "/api/log":
511
+ return self._send(runner.log_tail(int(params.get("lines", 80))).encode(), "text/plain; charset=utf-8")
512
+ m = re.fullmatch(r"/obs/(\d+)\.jpg", path)
513
+ if m and recorder.out is not None:
514
+ f = recorder.out / "obs" / f"{int(m.group(1)):06d}.jpg"
515
+ if f.exists():
516
+ return self._send(f.read_bytes(), "image/jpeg")
517
+ self._send(b"not found", "text/plain", 404)
518
+
519
+ def do_POST(self) -> None:
520
+ try:
521
+ body = self._body()
522
+ if self.path == "/api/check":
523
+ return self._json(check_server(str(body.get("host", "")).strip(), int(body.get("port", 8000)),
524
+ str(body.get("prompt") or "Place the cooking spoon in the plastic bin")))
525
+ if self.path == "/api/thor/launch":
526
+ return self._json(thor.launch(body))
527
+ if self.path == "/api/thor/stop":
528
+ return self._json(thor.stop(body))
529
+ if self.path == "/api/thor/status":
530
+ return self._json(thor.status(body))
531
+ if self.path == "/api/start":
532
+ return self._json(runner.start(body))
533
+ if self.path == "/api/stop":
534
+ return self._json(runner.stop())
535
+ if self.path == "/api/control":
536
+ command = str(body.get("command", ""))
537
+ if command not in {"pause", "resume", "skip"}:
538
+ return self._json({"ok": False, "error": "unknown command"}, 400)
539
+ return self._json(runner.send(command))
540
+ except ValueError as exc:
541
+ return self._json({"ok": False, "error": str(exc)}, 400)
542
+ except Exception as exc:
543
+ return self._json({"ok": False, "error": f"{type(exc).__name__}: {exc}"}, 500)
544
+ self._send(b"not found", "text/plain", 404)
545
+
546
+ return ThreadingHTTPServer((args.host, args.port), Handler)
547
+
548
+
549
+ def main() -> None:
550
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
551
+ p.add_argument("--host", default="127.0.0.1", help="address the page listens on")
552
+ p.add_argument("--port", type=int, default=8765, help="page port")
553
+ p.add_argument("--relay-port", type=int, default=8001, help="local port the Isaac Lab client connects to")
554
+ p.add_argument("--thor", default=os.environ.get("SO101_THOR_HOST", ""), help="pre-filled Thor address")
555
+ p.add_argument("--thor-port", type=int, default=int(os.environ.get("SO101_THOR_PORT", 8000)))
556
+ p.add_argument("--thor-user", default=os.environ.get("SO101_THOR_USER", ""), help="pre-filled SSH user on the Thor")
557
+ p.add_argument("--thor-dir", default=os.environ.get("SO101_THOR_DIR", "~/so101-edge-thor"),
558
+ help="install folder of setup_thor.sh on the Thor")
559
+ p.add_argument("--bench", type=Path, default=ROOT / "so101_bench", help="so101_bench checkout")
560
+ p.add_argument("--python", type=Path, default=Path(sys.executable),
561
+ help="python with Isaac Sim 5.1 + Isaac Lab 2.3 (defaults to this interpreter)")
562
+ p.add_argument("--runs", type=Path, default=ROOT / "runs", help="where run logs and frames are kept")
563
+ p.add_argument("--pythonpath", type=Path, action="append", default=None,
564
+ help="extra PYTHONPATH entries for the client (default: <client>/vendor_py if present)")
565
+ args = p.parse_args()
566
+ args.bench = args.bench.resolve()
567
+ if args.pythonpath is None:
568
+ args.pythonpath = [ROOT / "vendor_py"] if (ROOT / "vendor_py").is_dir() else []
569
+ args.runs.mkdir(parents=True, exist_ok=True)
570
+
571
+ recorder = Recorder()
572
+ relay = Relay(recorder, "127.0.0.1", args.relay_port)
573
+ runner = Runner(args, relay, recorder)
574
+ thor = ThorControl(args.thor_user, args.thor_dir)
575
+ httpd = make_http(args, recorder, runner, thor)
576
+ threading.Thread(target=httpd.serve_forever, daemon=True).start()
577
+ print(f"[ui] open http://{args.host}:{args.port}/ (relay ws://127.0.0.1:{args.relay_port}, runs {args.runs})",
578
+ flush=True)
579
+ try:
580
+ asyncio.run(relay.run())
581
+ except KeyboardInterrupt:
582
+ pass
583
+ finally:
584
+ if runner.running():
585
+ runner.stop()
586
+
587
+
588
+ if __name__ == "__main__":
589
+ main()
thor_deploy/thor/serve_thor.sh ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Start the SO-101 Cosmos3-Edge policy server on the Jetson Thor (OpenPI WebSocket, port 8000).
3
+ #
4
+ # bash serve_thor.sh # foreground
5
+ # bash serve_thor.sh --detach # background; log in <dir>/logs/serve_<stamp>.log
6
+ # bash serve_thor.sh --tmux # tmux session "so101serve"; log in <dir>/logs/serve_latest.log
7
+ # # (what the PC web UI's "Launch server" button runs over SSH)
8
+ # bash serve_thor.sh --stop # stop the tmux / detached server
9
+ #
10
+ # Health: curl localhost:8000/healthz -> OK (from another machine: curl <thor-ip>:8000/healthz)
11
+ set -euo pipefail
12
+
13
+ DIR=${SO101_THOR_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}
14
+ [ -d "$DIR/cosmos-framework" ] || DIR=$HOME/so101-edge-thor
15
+ FW=$DIR/cosmos-framework
16
+ ITER=${SO101_ITER:-6500}
17
+ CKPT=${SO101_CHECKPOINT:-$DIR/checkpoints/iter_$ITER}
18
+ PORT=${SO101_PORT:-8000}
19
+
20
+ [ -f "$CKPT/checkpoint.json" ] || { echo "no checkpoint at $CKPT (run setup_thor.sh)"; exit 1; }
21
+
22
+ export PATH="$FW/.venv/bin:$HOME/.local/bin:$PATH" # uvx resolves the cached VAE
23
+ export VIRTUAL_ENV=$FW/.venv
24
+ export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
25
+ # torch.compile: the venv's Triton ships a ptxas without sm_110a (Thor), so point Triton at
26
+ # JetPack's CUDA 13 ptxas. SO101_COMPILE=0 falls back to eager (NVIDIA's documented Thor
27
+ # setting, TORCHDYNAMO_DISABLE=1): same actions, ~10x slower per chunk.
28
+ if [ "${SO101_COMPILE:-1}" = "1" ] && [ -x /usr/local/cuda/bin/ptxas ]; then
29
+ export TRITON_PTXAS_PATH=/usr/local/cuda/bin/ptxas TRITON_PTXAS_BLACKWELL_PATH=/usr/local/cuda/bin/ptxas
30
+ else
31
+ export TORCHDYNAMO_DISABLE=1
32
+ fi
33
+ export HF_HUB_DISABLE_IMPLICIT_TOKEN=1
34
+ # The venv's own CUDA 13 libraries first, so a system CUDA cannot shadow libcublasLt.
35
+ CU13=$(ls -d "$FW"/.venv/lib/python3.*/site-packages/nvidia/cu13/lib 2>/dev/null | tail -1 || true)
36
+ [ -n "$CU13" ] && export LD_LIBRARY_PATH="$CU13${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
37
+
38
+ # Every flag below is part of the SO-101 serving contract and fails silently if dropped:
39
+ # 5 arm joints (DROID has 7), gripper on [0, 100] (no flip), min-max normalization with the
40
+ # SO-101 stats (else joints are commanded to ~0), 30 fps conditioning, and the two-view layout
41
+ # the model was trained on (wrist on top, overhead below).
42
+ ARGS=(
43
+ -u -m cosmos_framework.scripts.action_policy_server_robolab
44
+ --checkpoint-path "$CKPT"
45
+ --port "$PORT"
46
+ --domain-name so101
47
+ --action-dim 6
48
+ --arm-joint-dim 5
49
+ --action-space joint_pos
50
+ --conditioning-fps 30
51
+ --no-flip-gripper
52
+ --action-normalization minmax
53
+ --normalizer-stats-path cosmos_framework/data/generator/action/normalizer_stats/so101_lerobot_stats.json
54
+ --view-description "The top half is from the front-facing wrist camera. The bottom half is from the fixed overhead camera."
55
+ --no-guardrails
56
+ )
57
+
58
+ cd "$FW"
59
+ SESSION=${SO101_TMUX_SESSION:-so101serve}
60
+ if [ "${1:-}" = "--stop" ]; then
61
+ tmux kill-session -t "$SESSION" 2>/dev/null && echo "stopped tmux session $SESSION"
62
+ pkill -f "[a]ction_policy_server_robolab.*--port $PORT" && echo "stopped server on port $PORT"
63
+ exit 0
64
+ fi
65
+ if [ "${1:-}" = "--tmux" ]; then
66
+ if tmux has-session -t "$SESSION" 2>/dev/null; then echo "already running in tmux session $SESSION"; exit 0; fi
67
+ mkdir -p "$DIR/logs"; LOG=$DIR/logs/serve_$(date +%Y%m%d_%H%M%S).log
68
+ ln -sfn "$LOG" "$DIR/logs/serve_latest.log"
69
+ # tmux sessions take their environment from the tmux server, so pass the settings explicitly.
70
+ tmux new-session -d -s "$SESSION" "SO101_THOR_DIR='$DIR' SO101_CHECKPOINT='$CKPT' SO101_PORT=$PORT SO101_COMPILE=${SO101_COMPILE:-1} bash '$DIR/serve_thor.sh' 2>&1 | tee '$LOG'"
71
+ echo "policy server starting in tmux session $SESSION, log $LOG"
72
+ exit 0
73
+ fi
74
+ if [ "${1:-}" = "--detach" ]; then
75
+ mkdir -p "$DIR/logs"; LOG=$DIR/logs/serve_$(date +%Y%m%d_%H%M%S).log
76
+ setsid nohup python "${ARGS[@]}" > "$LOG" 2>&1 < /dev/null &
77
+ echo "policy server pid $! log $LOG"
78
+ echo "ready when: grep -q 'ready domain' $LOG or curl -s localhost:$PORT/healthz"
79
+ else
80
+ exec python "${ARGS[@]}"
81
+ fi
thor_deploy/thor/setup_thor.sh ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # One-time setup of the SO-101 Cosmos3-Edge policy server on a Jetson Thor (JetPack 7, CUDA 13).
3
+ #
4
+ # bash setup_thor.sh [install dir] # default: ~/so101-edge-thor
5
+ #
6
+ # Needs: git, internet, ~20 GB free disk. No sudo. Installs uv into ~/.local/bin if missing.
7
+ # Result: <dir>/cosmos-framework (commit 5e67049 + SO-101 patch, uv venv with the cu130 group)
8
+ # <dir>/checkpoints/iter_6500 (the released Edge 6500 export, ~7.3 GB)
9
+ set -euo pipefail
10
+
11
+ DIR=${1:-$HOME/so101-edge-thor}
12
+ HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
13
+ FRAMEWORK_COMMIT=5e67049
14
+ HF_REPO=${SO101_HF_REPO:-kabilanKB/cosmos_edge_policy_so101}
15
+ ITER=${SO101_ITER:-6500}
16
+
17
+ log() { echo "[setup-thor] $*"; }
18
+ [ "$(uname -m)" = aarch64 ] || log "warning: this script is written for the aarch64 Jetson Thor"
19
+
20
+ mkdir -p "$DIR/logs"
21
+ export PATH="$HOME/.local/bin:$PATH"
22
+ if ! command -v uv >/dev/null; then
23
+ log "installing uv"
24
+ curl -LsSf https://astral.sh/uv/install.sh | sh
25
+ fi
26
+
27
+ free_gb=$(df -BG --output=avail "$DIR" | tail -1 | tr -dc 0-9)
28
+ if [ ! -f "$DIR/checkpoints/iter_$ITER/checkpoint.json" ] && [ "$free_gb" -lt 20 ]; then
29
+ log "warning: only ${free_gb} GB free; the venv, checkpoint and VAE need ~20 GB"
30
+ fi
31
+
32
+ # 1. cosmos-framework at the commit the policy was trained and exported with, plus SO-101 support
33
+ if [ ! -d "$DIR/cosmos-framework/.git" ]; then
34
+ log "cloning cosmos-framework"
35
+ git clone -q https://github.com/NVIDIA/cosmos-framework.git "$DIR/cosmos-framework"
36
+ fi
37
+ cd "$DIR/cosmos-framework"
38
+ git checkout -q "$FRAMEWORK_COMMIT"
39
+ if git apply --check "$HERE/so101-support.patch" 2>/dev/null; then
40
+ git apply "$HERE/so101-support.patch"; log "applied SO-101 patch"
41
+ elif git apply --reverse --check "$HERE/so101-support.patch" 2>/dev/null; then
42
+ log "SO-101 patch already applied"
43
+ else
44
+ log "error: the SO-101 patch does not apply to $(git log --oneline -1)"; exit 1
45
+ fi
46
+
47
+ # 2. Python environment. The cu130 group has aarch64 builds of torch 2.10+cu130; flash-attn
48
+ # is x86-only and is not needed for serving.
49
+ log "uv sync (10-30 min the first time)"
50
+ export UV_HTTP_TIMEOUT=${UV_HTTP_TIMEOUT:-120}
51
+ # cu130: aarch64 torch 2.10+cu130. policy-server: OpenPI's WebSocket server. train extra: modules
52
+ # the server imports (iopath, ...); no training runs here.
53
+ uv sync --group cu130 --group policy-server --extra train
54
+ # cuDNN >= 9.22 enables the framework's cuDNN attention backend on Thor (sm_110): attention is
55
+ # ~5x faster than the fallback and a chunk drops from ~4.3 s to ~2.1 s (with torch.compile).
56
+ # torch 2.10 ships 9.15; cuDNN 9 minor releases are ABI compatible. Re-run after any `uv sync`.
57
+ uv pip install --python .venv/bin/python "nvidia-cudnn-cu13>=9.22"
58
+
59
+ # 3. The policy checkpoint (public repo, no token needed)
60
+ if [ ! -f "$DIR/checkpoints/iter_$ITER/checkpoint.json" ]; then
61
+ log "downloading $HF_REPO iter_$ITER"
62
+ HF_HUB_DISABLE_IMPLICIT_TOKEN=1 uvx hf@latest download "$HF_REPO" --include "iter_$ITER/*" \
63
+ --local-dir "$DIR/checkpoints"
64
+ fi
65
+
66
+ # 4. Pre-fetch the Wan2.2 VAE the server loads at start (so the first start is not a download)
67
+ log "pre-fetching the Wan2.2 VAE"
68
+ HF_HUB_DISABLE_IMPLICIT_TOKEN=1 uvx hf@latest download Wan-AI/Wan2.2-TI2V-5B Wan2.2_VAE.pth \
69
+ --revision 921dbaf3f1674a56f47e83fb80a34bac8a8f203e >/dev/null
70
+
71
+ cp "$HERE/serve_thor.sh" "$DIR/serve_thor.sh" 2>/dev/null || true
72
+ log "done. Launch the server from the PC web UI, or here with: bash $DIR/serve_thor.sh --tmux"
thor_deploy/thor/so101-support.patch ADDED
The diff for this file is too large to render. See raw diff