Initial commit
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
# Keep docker build context small. mount/IsaacLab and mount/sru-navigation-sim
|
||||
# are needed by COPY in Dockerfile, so they MUST NOT be excluded.
|
||||
outputs/
|
||||
log*.txt
|
||||
auth_qrcode.png
|
||||
*.tar.gz
|
||||
*.tgz
|
||||
**/__pycache__/
|
||||
**/*.pyc
|
||||
**/.git/
|
||||
**/.gitignore
|
||||
.windsurf/
|
||||
.vscode/
|
||||
.idea/
|
||||
@@ -0,0 +1,3 @@
|
||||
# Copy to .env and fill in.
|
||||
WANDB_API_KEY=
|
||||
DISPLAY=:0
|
||||
@@ -0,0 +1,148 @@
|
||||
# =====================================================================
|
||||
# SRU Navigation Sim - Reproducible Training Image
|
||||
# Base: NVIDIA Isaac Sim 4.5.0 (matches IsaacLab v2.1.1 requirement)
|
||||
# =====================================================================
|
||||
ARG ISAAC_SIM_VERSION=4.5.0
|
||||
FROM nvcr.io/nvidia/isaac-sim:${ISAAC_SIM_VERSION}
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive \
|
||||
LANG=C.UTF-8 \
|
||||
ACCEPT_EULA=Y \
|
||||
PRIVACY_CONSENT=Y \
|
||||
OMNI_KIT_ALLOW_ROOT=1
|
||||
|
||||
# ---------- System deps ----------
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
git git-lfs curl wget vim ca-certificates build-essential \
|
||||
cmake ninja-build libgl1 libglib2.0-0 libsm6 libxext6 libxrender1 \
|
||||
libglu1-mesa libglib2.0-0 ncurses-term tmux htop \
|
||||
python3-pip && \
|
||||
git lfs install && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Avoid "dubious ownership" inside containers
|
||||
RUN git config --global --add safe.directory '*'
|
||||
|
||||
# ---------- Configure pip mirror (optional) ----------
|
||||
# Default behavior uses the official PyPI. The global pip config is written so
|
||||
# ALL python interpreters in the image (root, kit-bundled
|
||||
# `_isaac_sim/kit/python`, system python3) pick it up.
|
||||
#
|
||||
# Override pip index if needed: --build-arg PIP_INDEX_URL=https://your-mirror/simple --build-arg PIP_TRUSTED_HOST=your-mirror-host
|
||||
ARG PIP_INDEX_URL=
|
||||
ARG PIP_TRUSTED_HOST=
|
||||
RUN if [ -n "${PIP_INDEX_URL}" ]; then \
|
||||
mkdir -p /etc && printf "[global]\nindex-url = %s\ntrusted-host = %s\ntimeout = 120\nretries = 5\n" \
|
||||
"${PIP_INDEX_URL}" "${PIP_TRUSTED_HOST}" > /etc/pip.conf; \
|
||||
mkdir -p /root/.config/pip && cp /etc/pip.conf /root/.config/pip/pip.conf; \
|
||||
echo "[build] pip index -> ${PIP_INDEX_URL}"; \
|
||||
fi
|
||||
|
||||
# Workspace
|
||||
ARG ISAACLAB_VERSION=v2.1.1
|
||||
ENV ISAACLAB_PATH=/workspace/IsaacLab
|
||||
WORKDIR /workspace
|
||||
|
||||
# Optional build-time proxy (pass via: --build-arg HTTP_PROXY=... --build-arg HTTPS_PROXY=...)
|
||||
# Useful when the host is behind GFW / corporate firewall and bare `git clone github.com`
|
||||
# hits `GnuTLS recv error (-110)` / TLS resets. Leave empty to disable.
|
||||
ARG HTTP_PROXY=
|
||||
ARG HTTPS_PROXY=
|
||||
ARG NO_PROXY=
|
||||
ENV http_proxy=${HTTP_PROXY} \
|
||||
https_proxy=${HTTPS_PROXY} \
|
||||
no_proxy=${NO_PROXY}
|
||||
|
||||
# Optional GitHub mirror prefix (e.g. https://ghproxy.com/ or https://gh-proxy.com/).
|
||||
# When set, all subsequent github.com clones are rewritten through it via git insteadOf.
|
||||
ARG GITHUB_MIRROR=
|
||||
RUN if [ -n "${GITHUB_MIRROR}" ]; then \
|
||||
git config --global url."${GITHUB_MIRROR}https://github.com/".insteadOf "https://github.com/"; \
|
||||
echo "[build] github.com clones rewritten via ${GITHUB_MIRROR}"; \
|
||||
fi
|
||||
|
||||
# Harden git for flaky networks (large postBuffer, low-speed timeout, no compression,
|
||||
# disable smart-http v2 which is the layer that surfaces the GnuTLS reset on long clones).
|
||||
RUN git config --global http.postBuffer 1048576000 && \
|
||||
git config --global http.lowSpeedLimit 1000 && \
|
||||
git config --global http.lowSpeedTime 600 && \
|
||||
git config --global core.compression 0 && \
|
||||
git config --global http.version HTTP/1.1
|
||||
|
||||
# ---------- Bring IsaacLab v2.1.1 into the image ----------
|
||||
# We COPY from the local build context (./mount/IsaacLab) instead of `git clone`,
|
||||
# because on GFW-affected servers `git clone github.com` repeatedly fails with
|
||||
# GnuTLS resets / connection timeouts. To set this up on the host:
|
||||
#
|
||||
# # one-shot: clone IsaacLab anywhere reachable from your build context
|
||||
# git clone --depth 1 --branch v2.1.1 \
|
||||
# https://github.com/isaac-sim/IsaacLab.git <repo>/mount/IsaacLab
|
||||
#
|
||||
# If mount/IsaacLab is missing the build will abort here with a clear error.
|
||||
COPY mount/IsaacLab ${ISAACLAB_PATH}
|
||||
RUN test -d ${ISAACLAB_PATH}/source/isaaclab && \
|
||||
echo "[build] using local IsaacLab from mount/IsaacLab"
|
||||
|
||||
# Symlink Isaac Sim into IsaacLab as required by isaaclab.sh
|
||||
RUN ln -s /isaac-sim ${ISAACLAB_PATH}/_isaac_sim
|
||||
|
||||
# ---------- Install IsaacLab (uses bundled python from isaac-sim) ----------
|
||||
WORKDIR ${ISAACLAB_PATH}
|
||||
RUN ./isaaclab.sh --install
|
||||
|
||||
# Workaround: the official --install loop builds extensions in PEP-517 isolation,
|
||||
# which fails for source/isaaclab because the kit-python build env lacks pkg_resources.
|
||||
# Reinstall every source/* extension with --no-build-isolation to guarantee `import isaaclab` works.
|
||||
RUN for d in ${ISAACLAB_PATH}/source/*/; do \
|
||||
if [ -f "$d/setup.py" ]; then \
|
||||
${ISAACLAB_PATH}/_isaac_sim/python.sh -m pip install --no-build-isolation --timeout 180 --retries 5 -e "$d" || exit 1; \
|
||||
fi; \
|
||||
done && \
|
||||
${ISAACLAB_PATH}/_isaac_sim/python.sh -c "import isaaclab; print('isaaclab OK:', isaaclab.__file__)"
|
||||
|
||||
# ---------- Replace bundled rsl_rl with SRU-enhanced fork ----------
|
||||
# sru-navigation-learning provides ActorCriticSRU + MDPO/SPO/PPO required by sru-navigation-sim.
|
||||
# It installs under the package name `rsl_rl`, replacing any prior install.
|
||||
RUN ${ISAACLAB_PATH}/isaaclab.sh -p -m pip uninstall rsl-rl-lib -y || true
|
||||
RUN rm -rf ${ISAACLAB_PATH}/_isaac_sim/kit/python/lib/python3.10/site-packages/rsl_rl
|
||||
WORKDIR /workspace
|
||||
RUN for i in 1 2 3 4 5; do \
|
||||
git clone --depth 1 https://github.com/leggedrobotics/sru-navigation-learning.git /workspace/rsl_rl && break; \
|
||||
echo "[retry $i] sru-navigation-learning clone failed, retrying in 10s..."; \
|
||||
rm -rf /workspace/rsl_rl; \
|
||||
sleep 10; \
|
||||
done && test -d /workspace/rsl_rl/.git
|
||||
RUN ${ISAACLAB_PATH}/isaaclab.sh -p -m pip install --no-build-isolation --timeout 180 --retries 5 -e /workspace/rsl_rl
|
||||
RUN ${ISAACLAB_PATH}/_isaac_sim/python.sh -c "from rsl_rl.modules import ActorCriticSRU; print('SRU OK')"
|
||||
|
||||
# ---------- Clone & install sru-navigation-sim extension ----------
|
||||
ARG SRU_NAV_REPO=https://github.com/leggedrobotics/sru-navigation-sim.git
|
||||
ARG SRU_NAV_REF=main
|
||||
# Note: git network hardening already applied above (postBuffer / lowSpeedTime /
|
||||
# HTTP/1.1 / optional GITHUB_MIRROR), so this block only retries.
|
||||
RUN for i in 1 2 3 4 5; do \
|
||||
git clone --depth 1 --branch ${SRU_NAV_REF} \
|
||||
${SRU_NAV_REPO} ${ISAACLAB_PATH}/source/isaaclab_nav_task && break; \
|
||||
echo "[retry $i] sru-navigation-sim clone failed, cleaning up and retrying in 10s..."; \
|
||||
rm -rf ${ISAACLAB_PATH}/source/isaaclab_nav_task; \
|
||||
sleep 10; \
|
||||
done && \
|
||||
test -d ${ISAACLAB_PATH}/source/isaaclab_nav_task
|
||||
RUN ${ISAACLAB_PATH}/isaaclab.sh -p -m pip install -e \
|
||||
${ISAACLAB_PATH}/source/isaaclab_nav_task
|
||||
|
||||
# Useful Python packages for logging/visualization
|
||||
RUN ${ISAACLAB_PATH}/isaaclab.sh -p -m pip install \
|
||||
wandb tensorboard tensorboardX
|
||||
|
||||
# Common runtime envs
|
||||
ENV PYTHONUNBUFFERED=1 \
|
||||
NVIDIA_DRIVER_CAPABILITIES=all \
|
||||
NVIDIA_VISIBLE_DEVICES=all
|
||||
|
||||
WORKDIR ${ISAACLAB_PATH}
|
||||
|
||||
# Sanity check (non-fatal): list registered tasks
|
||||
RUN ${ISAACLAB_PATH}/isaaclab.sh -p -m pip show isaaclab_nav_task || true
|
||||
|
||||
CMD ["/bin/bash"]
|
||||
Submodule
+1
Submodule Train/IsaacLab added at 90b79bb2d4
+248
@@ -0,0 +1,248 @@
|
||||
# 🤖 SRU Navigation Training with Isaac Sim
|
||||
|
||||
**Reproducible training pipeline for SRU (Spatially-Enhanced Recurrent Units) navigation policy, ported from B2W (wheeled-legged + ZedX depth) to Unitree Go2 (quadruped + LiDAR-derived depth).**
|
||||
|
||||
Built on NVIDIA Isaac Sim 4.5.0 + IsaacLab v2.1.1, fully containerized with Docker.
|
||||
|
||||
[](https://developer.nvidia.com/isaac-sim)
|
||||
[](https://github.com/isaac-sim/IsaacLab)
|
||||
[](https://www.docker.com/)
|
||||
|
||||
---
|
||||
|
||||
## ✨ Highlights
|
||||
|
||||
- **Full B2W → Go2 port** — assets, cameras, terrain, rewards, termination conditions
|
||||
- **4-stage training pipeline** — Smoke → Cold-start (1024 envs, 30k iter) → Curriculum continuation → PureMaze refinement
|
||||
- **Evaluation toolchain** — termination rate stats, baseline comparison, collision analysis, depth ablation
|
||||
- **Env-var driven config** — difficulty, terrain, GPU selection, seed — no code edits needed
|
||||
- **Multi-GPU parallel training** — independent seeds across GPUs
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ Architecture
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ Docker Container (~30GB) │
|
||||
│ │
|
||||
│ ┌───────────────┐ ┌──────────────────────────────────┐ │
|
||||
│ │ Isaac Sim │ │ IsaacLab v2.1.1 │ │
|
||||
│ │ 4.5.0 │ │ ┌────────────┐ ┌─────────────┐ │ │
|
||||
│ └───────┬───────┘ │ │ Nav Task │ │ rsl_rl │ │ │
|
||||
│ │ │ │ (Go2 Port) │ │ (SRU Fork) │ │ │
|
||||
│ ▼ │ └─────┬──────┘ └──────┬──────┘ │ │
|
||||
│ ┌───────────────┐ │ │ │ │ │
|
||||
│ │ PhysX / GPU │ │ ▼ ▼ │ │
|
||||
│ │ Simulation │◄──┤ ┌──────────────────────────┐ │ │
|
||||
│ └───────────────┘ │ │ PPO + ActorCriticSRU │ │ │
|
||||
│ │ └──────────────────────────┘ │ │
|
||||
│ └──────────────────────────────────┘ │
|
||||
│ │
|
||||
│ Depth → VAE Encoder (64×5×8) → SRU Policy → SE2 cmd │
|
||||
│ ↓ │
|
||||
│ policy_go2_jit.pt → Joint Actions │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📋 Prerequisites
|
||||
|
||||
| Requirement | Minimum | Recommended |
|
||||
|---|---|---|
|
||||
| NVIDIA GPU | 12 GB VRAM | 24 GB+ |
|
||||
| NVIDIA Driver | ≥ 570 | ≥ 570 (⚠️ avoid 595.x) |
|
||||
| Docker | 24.0+ | Latest |
|
||||
| NVIDIA Container Toolkit | Installed | Latest |
|
||||
| Disk Space | 80 GB | 120 GB+ |
|
||||
| NGC Access | Required | For `nvcr.io/nvidia/isaac-sim:4.5.0` |
|
||||
|
||||
### VRAM Reference
|
||||
|
||||
| GPU | NUM_ENVS | GO2_CELL_SIZE |
|
||||
|---|---|---|
|
||||
| RTX 5070 12 GB | 768–1024 | 1.0 |
|
||||
| RTX 4090 24 GB | 2048–2820 | 1.0 / 2.0 |
|
||||
| A100 80 GB | 8000+ | 1.0 / 2.0 |
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
### 1. Clone & Configure
|
||||
|
||||
```bash
|
||||
git clone https://github.com/<your-org>/sru-nav-docker.git
|
||||
cd sru-nav-docker
|
||||
cp .env.example .env
|
||||
# Edit .env — set NGC credentials, GPU index, paths
|
||||
```
|
||||
|
||||
### 2. Build the Image
|
||||
|
||||
```bash
|
||||
docker compose build # ~30 GB, takes 20-40 min on first build
|
||||
```
|
||||
|
||||
### 3. Launch Container
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
docker compose exec sru-nav bash
|
||||
```
|
||||
|
||||
### 4. Smoke Test (~30 min)
|
||||
|
||||
```bash
|
||||
TASK=Isaac-Nav-PPO-Go2-Dev-v0 NUM_ENVS=24 MAX_ITER=300 \
|
||||
GO2_DIFFICULTY="0.0,0.4" GO2_INIT_LEVEL=0 \
|
||||
./scripts/train_go2_scratch.sh
|
||||
```
|
||||
|
||||
If training starts and loss decreases — you're good to go.
|
||||
|
||||
---
|
||||
|
||||
## 🏋️ Training Pipeline
|
||||
|
||||
### Stage 1 — Cold Start (36–48h)
|
||||
|
||||
```bash
|
||||
TASK=Isaac-Nav-PPO-Go2-v0 NUM_ENVS=1024 MAX_ITER=30000 \
|
||||
GO2_DIFFICULTY="0.0,0.4" GO2_INIT_LEVEL=0 GO2_CELL_SIZE=1.0 \
|
||||
SEED=42 RUN_NAME=mixed_scratch_v1 \
|
||||
./scripts/train_go2_scratch.sh
|
||||
```
|
||||
|
||||
### Stage 2 — Curriculum Continuation
|
||||
|
||||
```bash
|
||||
./scripts/continue_go2.sh --iters 10000 --from-iter 7400
|
||||
```
|
||||
|
||||
### Stage 3 — PureMaze Refinement
|
||||
|
||||
```bash
|
||||
TASK=Isaac-Nav-PPO-Go2-PureMaze-v0 NUM_ENVS=1024 MAX_ITER=10000 \
|
||||
./scripts/train_go2_scratch.sh
|
||||
```
|
||||
|
||||
### Evaluation
|
||||
|
||||
```bash
|
||||
# Termination rate analysis
|
||||
PLAY_DIFFICULTY="0.3,0.8" ./scripts/eval_terminations.sh --run-dir <run> --from-iter <iter>
|
||||
|
||||
# Baseline comparison
|
||||
./scripts/compare_baselines.sh
|
||||
|
||||
# Collision analysis
|
||||
./scripts/analyze_collisions.sh
|
||||
```
|
||||
|
||||
### Monitoring
|
||||
|
||||
```bash
|
||||
# TensorBoard
|
||||
docker compose exec sru-nav ./isaaclab.sh -p -m tensorboard.main --logdir logs --bind_all
|
||||
|
||||
# Or use Weights & Biases (configure WANDB_API_KEY in .env)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ⚙️ Configuration
|
||||
|
||||
All training behavior is controlled via environment variables — no code changes needed.
|
||||
|
||||
| Variable | Type | Default | Description |
|
||||
|---|---|---|---|
|
||||
| `TASK` | str | `Isaac-Nav-PPO-Go2-Dev-v0` | Gym task ID |
|
||||
| `NUM_ENVS` | int | `24` | Parallel environment count |
|
||||
| `MAX_ITER` | int | `1000` | Max PPO iterations |
|
||||
| `SEED` | int | `42` | Random seed |
|
||||
| `GPU` | str | — | GPU device index |
|
||||
| `RUN_NAME` | str | auto | Run directory name |
|
||||
| `GO2_DIFFICULTY` | `"lo,hi"` | cfg default | Difficulty range |
|
||||
| `GO2_INIT_LEVEL` | int | `5` | Initial max terrain row |
|
||||
| `GO2_CELL_SIZE` | float | `1.0` | Terrain tile cell size (m) |
|
||||
| `PLAY_DIFFICULTY` | `"lo,hi"` | — | Eval-time difficulty override |
|
||||
|
||||
### Gym Tasks
|
||||
|
||||
| Task ID | Purpose | Typical envs |
|
||||
|---|---|---|
|
||||
| `Isaac-Nav-PPO-Go2-v0` | Cold-start training (mixed terrain) | 1024–2048 |
|
||||
| `Isaac-Nav-PPO-Go2-Dev-v0` | Smoke test / debugging | 24–32 |
|
||||
| `Isaac-Nav-PPO-Go2-PureMaze-v0` | Stage-2 maze refinement | 1024 |
|
||||
| `Isaac-Nav-PPO-Go2-Play-v0` | Playback & evaluation | 20 |
|
||||
|
||||
---
|
||||
|
||||
## 📁 Project Structure
|
||||
|
||||
```
|
||||
sru-nav-docker/
|
||||
├── Dockerfile # Image build recipe
|
||||
├── docker-compose.yml # Container runtime config
|
||||
├── .env.example # Environment variable template
|
||||
├── scripts/ # Train / continue / play / eval / diagnostics
|
||||
│ ├── train_go2_scratch.sh
|
||||
│ ├── continue_go2.sh
|
||||
│ ├── eval_terminations.sh
|
||||
│ ├── compare_baselines.sh
|
||||
│ └── ...
|
||||
├── mount/
|
||||
│ ├── sru-navigation-sim/ # Task definitions + Go2 port
|
||||
│ │ ├── isaaclab_nav_task/ # Env, rewards, terrain, obs
|
||||
│ │ └── scripts/ # Entry points
|
||||
│ └── rsl_rl/ # rsl_rl SRU fork (ActorCriticSRU, PPO)
|
||||
├── IsaacLab/ # IsaacLab v2.1.1 source
|
||||
├── assets/baselines/ # Pre-trained baseline checkpoints
|
||||
├── outputs/logs/ # Training artifacts (TB + ckpt)
|
||||
└── docs/handover/ # Handover documentation
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔑 Key Dependencies
|
||||
|
||||
| Dependency | Source |
|
||||
|---|---|
|
||||
| Isaac Sim 4.5.0 | `nvcr.io/nvidia/isaac-sim:4.5.0` (NGC login required) |
|
||||
| IsaacLab v2.1.1 | [isaac-sim/IsaacLab](https://github.com/isaac-sim/IsaacLab) |
|
||||
| rsl_rl (SRU fork) | [leggedrobotics/sru-navigation-learning](https://github.com/leggedrobotics/sru-navigation-learning) |
|
||||
| Nav Task | [leggedrobotics/sru-navigation-sim](https://github.com/leggedrobotics/sru-navigation-sim) |
|
||||
|
||||
---
|
||||
|
||||
## 📖 Citation
|
||||
|
||||
If you use this work, please cite the original SRU navigation paper:
|
||||
|
||||
```bibtex
|
||||
@article{yang2025sru,
|
||||
author = {Yang, Fan and Frivik, Per and Hoeller, David and Wang, Chen and Cadena, Cesar and Hutter, Marco},
|
||||
title = {Spatially-enhanced recurrent memory for long-range mapless navigation via end-to-end reinforcement learning},
|
||||
journal = {The International Journal of Robotics Research},
|
||||
year = {2025},
|
||||
doi = {10.1177/02783649251401926},
|
||||
url = {https://doi.org/10.1177/02783649251401926}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🙏 Acknowledgments
|
||||
|
||||
- **[ETH Legged Robotics](https://rsl.ethz.ch/)** — SRU navigation (original paper & codebase)
|
||||
- **[NVIDIA Isaac Sim / IsaacLab](https://developer.nvidia.com/isaac-sim)** — Simulation platform
|
||||
- **[Unitree Robotics](https://www.unitree.com/)** — Go2 quadruped platform
|
||||
|
||||
---
|
||||
|
||||
## 📄 License
|
||||
|
||||
See [LICENSE](./LICENSE) in the repository root.
|
||||
Sub-components (IsaacLab, rsl_rl) retain their respective licenses.
|
||||
@@ -0,0 +1,75 @@
|
||||
services:
|
||||
sru-nav:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
args:
|
||||
ISAAC_SIM_VERSION: "4.5.0"
|
||||
ISAACLAB_VERSION: "v2.1.1"
|
||||
SRU_NAV_REPO: "https://github.com/leggedrobotics/sru-navigation-sim.git"
|
||||
SRU_NAV_REF: "main"
|
||||
# Optional, for CN servers behind GFW. Pass via env or shell:
|
||||
# GITHUB_MIRROR=https://ghproxy.com/ docker compose build
|
||||
# HTTP_PROXY=http://host:7890 HTTPS_PROXY=http://host:7890 docker compose build
|
||||
GITHUB_MIRROR: "${GITHUB_MIRROR:-}"
|
||||
HTTP_PROXY: "${HTTP_PROXY:-}"
|
||||
HTTPS_PROXY: "${HTTPS_PROXY:-}"
|
||||
NO_PROXY: "${NO_PROXY:-}"
|
||||
PIP_INDEX_URL: "${PIP_INDEX_URL:-}"
|
||||
PIP_TRUSTED_HOST: "${PIP_TRUSTED_HOST:-}"
|
||||
image: sru-nav:latest
|
||||
container_name: sru-nav
|
||||
runtime: nvidia
|
||||
stdin_open: true
|
||||
tty: true
|
||||
network_mode: host
|
||||
ipc: host
|
||||
shm_size: "16gb"
|
||||
ulimits:
|
||||
memlock: -1
|
||||
stack: 67108864
|
||||
environment:
|
||||
- ACCEPT_EULA=Y
|
||||
- PRIVACY_CONSENT=Y
|
||||
- DISPLAY=${DISPLAY:-:0}
|
||||
- NVIDIA_DRIVER_CAPABILITIES=all
|
||||
- NVIDIA_VISIBLE_DEVICES=all
|
||||
# Attempt to avoid RTX segfault on Blackwell (sm_120) by forcing true headless
|
||||
- OMNI_KIT_HEADLESS=1
|
||||
# Optional: put your wandb key in a .env file next to compose
|
||||
- WANDB_API_KEY=${WANDB_API_KEY:-}
|
||||
deploy:
|
||||
resources:
|
||||
reservations:
|
||||
devices:
|
||||
- driver: nvidia
|
||||
count: all
|
||||
capabilities: [gpu]
|
||||
volumes:
|
||||
# X11 for GUI (optional)
|
||||
- /tmp/.X11-unix:/tmp/.X11-unix:rw
|
||||
# Persist Isaac Sim caches across runs
|
||||
- isaac-cache-kit:/isaac-sim/kit/cache
|
||||
- isaac-cache-ov:/root/.cache/ov
|
||||
- isaac-cache-pip:/root/.cache/pip
|
||||
- isaac-cache-gl:/root/.cache/nvidia/GLCache
|
||||
- isaac-cache-compute:/root/.nv/ComputeCache
|
||||
- isaac-logs:/root/.nvidia-omniverse/logs
|
||||
- isaac-data:/root/.local/share/ov/data
|
||||
- isaac-docs:/root/Documents
|
||||
# Persist training outputs (logs/checkpoints)
|
||||
- ./outputs/logs:/workspace/IsaacLab/logs
|
||||
# Optional: live-mount the extension for development. Uncomment to use:
|
||||
# - ./sru-navigation-sim:/workspace/IsaacLab/source/isaaclab_nav_task
|
||||
working_dir: /workspace/IsaacLab
|
||||
command: /bin/bash
|
||||
|
||||
volumes:
|
||||
isaac-cache-kit:
|
||||
isaac-cache-ov:
|
||||
isaac-cache-pip:
|
||||
isaac-cache-gl:
|
||||
isaac-cache-compute:
|
||||
isaac-logs:
|
||||
isaac-data:
|
||||
isaac-docs:
|
||||
Submodule
+1
Submodule Train/mount/rsl_rl added at df600e8fd0
Submodule
+1
Submodule Train/mount/sru-navigation-sim added at 80f6c01c2d
Executable
+94
@@ -0,0 +1,94 @@
|
||||
#!/usr/bin/env bash
|
||||
# Depth-ablation diagnostic: does the trained Go2 policy actually USE the depth
|
||||
# camera, or has it learned to ignore it (perception-blind)?
|
||||
#
|
||||
# Runs headless inside the container, rolls out the policy, and compares the
|
||||
# action with vs without the depth slice zeroed. Prints a verdict.
|
||||
#
|
||||
# Examples:
|
||||
# # Latest run, latest checkpoint
|
||||
# ./scripts/ablate_depth.sh
|
||||
#
|
||||
# # Specific run + iter
|
||||
# ./scripts/ablate_depth.sh --run-dir 2026-06-16_09-24-44_phase2 --from-iter 6998
|
||||
#
|
||||
# # More steps / envs for tighter stats
|
||||
# ./scripts/ablate_depth.sh --from-iter 6998 --envs 32 --steps 400
|
||||
set -euo pipefail
|
||||
|
||||
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
|
||||
# ---- defaults ----
|
||||
TASK="Isaac-Nav-PPO-Go2-Play-v0"
|
||||
EXPERIMENT="go2_navigation_ppo_dev"
|
||||
NUM_ENVS=16
|
||||
STEPS=300
|
||||
FROM_ITER=""
|
||||
RUN_DIR=""
|
||||
CHECKPOINT=""
|
||||
SEED=42
|
||||
|
||||
usage() { sed -n '1,18p' "$0"; exit 0; }
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--from-iter) FROM_ITER="$2"; shift 2 ;;
|
||||
--run-dir) RUN_DIR="$2"; shift 2 ;;
|
||||
--checkpoint) CHECKPOINT="$2"; shift 2 ;;
|
||||
--task) TASK="$2"; shift 2 ;;
|
||||
--experiment) EXPERIMENT="$2"; shift 2 ;;
|
||||
--envs) NUM_ENVS="$2"; shift 2 ;;
|
||||
--steps) STEPS="$2"; shift 2 ;;
|
||||
--seed) SEED="$2"; shift 2 ;;
|
||||
-h|--help) usage ;;
|
||||
*) echo "[error] Unknown arg: $1" >&2; usage ;;
|
||||
esac
|
||||
done
|
||||
|
||||
HOST_LOG_ROOT="$REPO_ROOT/outputs/logs/rsl_rl/$EXPERIMENT"
|
||||
|
||||
# ---- resolve checkpoint (same scheme as play_go2.sh) ----
|
||||
if [[ -z "$CHECKPOINT" ]]; then
|
||||
if [[ -z "$RUN_DIR" ]]; then
|
||||
RUN_DIR="$(ls -1 "$HOST_LOG_ROOT" 2>/dev/null | sort | tail -n 1 || true)"
|
||||
[[ -z "$RUN_DIR" ]] && { echo "[error] No runs under $HOST_LOG_ROOT" >&2; exit 1; }
|
||||
fi
|
||||
RUN_PATH="$HOST_LOG_ROOT/$RUN_DIR"
|
||||
[[ -d "$RUN_PATH" ]] || { echo "[error] Run dir not found: $RUN_PATH" >&2; exit 1; }
|
||||
|
||||
if [[ -n "$FROM_ITER" ]]; then
|
||||
HOST_CKPT="$RUN_PATH/model_${FROM_ITER}.pt"
|
||||
[[ -f "$HOST_CKPT" ]] || { echo "[error] Checkpoint not found: $HOST_CKPT" >&2; exit 1; }
|
||||
else
|
||||
HOST_CKPT="$(ls -1 "$RUN_PATH"/model_*.pt 2>/dev/null | sort -V | tail -n 1)"
|
||||
[[ -z "$HOST_CKPT" ]] && { echo "[error] No model_*.pt in $RUN_PATH" >&2; exit 1; }
|
||||
fi
|
||||
CHECKPOINT="${HOST_CKPT/$REPO_ROOT\/outputs\/logs/\/workspace\/IsaacLab\/logs}"
|
||||
else
|
||||
HOST_CKPT="${CHECKPOINT/\/workspace\/IsaacLab\/logs/$REPO_ROOT\/outputs\/logs}"
|
||||
fi
|
||||
|
||||
cat <<EOF
|
||||
[ablate] task = $TASK
|
||||
[ablate] checkpoint = $CHECKPOINT
|
||||
[ablate] host file = $HOST_CKPT
|
||||
[ablate] envs = $NUM_ENVS
|
||||
[ablate] steps = $STEPS
|
||||
EOF
|
||||
|
||||
docker run --rm --gpus all \
|
||||
-e ACCEPT_EULA=Y -e PRIVACY_CONSENT=Y \
|
||||
-e PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
|
||||
--shm-size=16g --network host --ipc host \
|
||||
--ulimit memlock=-1 --ulimit stack=67108864 \
|
||||
-v "$REPO_ROOT/outputs/logs:/workspace/IsaacLab/logs" \
|
||||
-v "$REPO_ROOT/mount/sru-navigation-sim:/workspace/IsaacLab/source/isaaclab_nav_task" \
|
||||
-v "$REPO_ROOT/mount/rsl_rl:/workspace/rsl_rl" \
|
||||
--entrypoint bash sru-nav:latest -lc \
|
||||
"./isaaclab.sh -p source/isaaclab_nav_task/scripts/ablate_depth.py \
|
||||
--task $TASK \
|
||||
--num_envs $NUM_ENVS \
|
||||
--steps $STEPS \
|
||||
--seed $SEED \
|
||||
--checkpoint $CHECKPOINT \
|
||||
--headless"
|
||||
Executable
+99
@@ -0,0 +1,99 @@
|
||||
#!/usr/bin/env bash
|
||||
# Run instrumented collision analysis inside the Isaac container, then plot
|
||||
# figures on the host.
|
||||
#
|
||||
# Example:
|
||||
# PLAY_MAZE_ONLY=1 PLAY_CLASSIC_MAZE=1 PLAY_DIFFICULTY="0.8,1.0" PLAY_CELL_SIZE=1.0 \
|
||||
# ./scripts/analyze_collisions.sh \
|
||||
# --task Isaac-Nav-PPO-Go2-Play-v0 \
|
||||
# --experiment go2_navigation_ppo_puremaze \
|
||||
# --run-dir 2026-06-23_11-13-55_puremaze_tight_corridors \
|
||||
# --from-iter 32200 \
|
||||
# --envs 32 --steps 4000
|
||||
set -euo pipefail
|
||||
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
|
||||
TASK="Isaac-Nav-PPO-Go2-Play-v0"
|
||||
EXPERIMENT="go2_navigation_ppo_puremaze"
|
||||
RUN_DIR=""
|
||||
FROM_ITER=""
|
||||
CHECKPOINT=""
|
||||
NUM_ENVS=32
|
||||
STEPS=4000
|
||||
SEED=42
|
||||
|
||||
usage() {
|
||||
cat <<EOF
|
||||
Usage: $(basename "$0") [options]
|
||||
--task NAME (default: $TASK)
|
||||
--experiment NAME (default: $EXPERIMENT)
|
||||
--run-dir NAME run dir under outputs/logs/rsl_rl/<experiment>/
|
||||
--from-iter N model_<N>.pt
|
||||
--checkpoint PATH explicit in-container ckpt (overrides above)
|
||||
--envs N (default: $NUM_ENVS)
|
||||
--steps N (default: $STEPS)
|
||||
--seed N (default: $SEED)
|
||||
|
||||
Forwarded env vars: PLAY_DIFFICULTY PLAY_SUBTERRAIN_MIX PLAY_MAZE_ONLY
|
||||
PLAY_CELL_SIZE PLAY_CLASSIC_MAZE
|
||||
EOF
|
||||
exit 0
|
||||
}
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--task) TASK="$2"; shift 2 ;;
|
||||
--experiment) EXPERIMENT="$2"; shift 2 ;;
|
||||
--run-dir) RUN_DIR="$2"; shift 2 ;;
|
||||
--from-iter) FROM_ITER="$2"; shift 2 ;;
|
||||
--checkpoint) CHECKPOINT="$2"; shift 2 ;;
|
||||
--envs) NUM_ENVS="$2"; shift 2 ;;
|
||||
--steps) STEPS="$2"; shift 2 ;;
|
||||
--seed) SEED="$2"; shift 2 ;;
|
||||
-h|--help) usage ;;
|
||||
*) echo "[error] $1" >&2; usage ;;
|
||||
esac
|
||||
done
|
||||
|
||||
HOST_LOG_ROOT="$REPO_ROOT/outputs/logs/rsl_rl/$EXPERIMENT"
|
||||
if [[ -z "$CHECKPOINT" ]]; then
|
||||
[[ -z "$RUN_DIR" || -z "$FROM_ITER" ]] && { echo "[error] need --run-dir + --from-iter or --checkpoint" >&2; exit 1; }
|
||||
HOST_CKPT="$HOST_LOG_ROOT/$RUN_DIR/model_${FROM_ITER}.pt"
|
||||
[[ -f "$HOST_CKPT" ]] || { echo "[error] not found: $HOST_CKPT" >&2; exit 1; }
|
||||
CHECKPOINT="${HOST_CKPT/$REPO_ROOT\/outputs\/logs/\/workspace\/IsaacLab\/logs}"
|
||||
fi
|
||||
|
||||
TAG="${RUN_DIR:-$(basename "$(dirname "$CHECKPOINT")")}_iter${FROM_ITER:-unknown}"
|
||||
HOST_OUT="$REPO_ROOT/outputs/collisions/$TAG"
|
||||
CTR_OUT="/workspace/IsaacLab/logs/collisions/$TAG"
|
||||
mkdir -p "$HOST_OUT"
|
||||
|
||||
echo "[collisions] task=$TASK"
|
||||
echo "[collisions] ckpt(ctr)=$CHECKPOINT"
|
||||
echo "[collisions] out(host)=$HOST_OUT"
|
||||
|
||||
docker run --rm --gpus all \
|
||||
-e ACCEPT_EULA=Y -e PRIVACY_CONSENT=Y \
|
||||
-e PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
|
||||
-e PLAY_DIFFICULTY="${PLAY_DIFFICULTY:-}" \
|
||||
-e PLAY_SUBTERRAIN_MIX="${PLAY_SUBTERRAIN_MIX:-}" \
|
||||
-e PLAY_MAZE_ONLY="${PLAY_MAZE_ONLY:-}" \
|
||||
-e PLAY_CELL_SIZE="${PLAY_CELL_SIZE:-}" \
|
||||
-e PLAY_CLASSIC_MAZE="${PLAY_CLASSIC_MAZE:-}" \
|
||||
--shm-size=16g --network host --ipc host \
|
||||
--ulimit memlock=-1 --ulimit stack=67108864 \
|
||||
-v "$REPO_ROOT/outputs/logs:/workspace/IsaacLab/logs" \
|
||||
-v "$REPO_ROOT/mount/sru-navigation-sim:/workspace/IsaacLab/source/isaaclab_nav_task" \
|
||||
-v "$REPO_ROOT/mount/rsl_rl:/workspace/rsl_rl" \
|
||||
--entrypoint bash sru-nav:latest -lc \
|
||||
"./isaaclab.sh -p source/isaaclab_nav_task/scripts/analyze_collisions.py \
|
||||
--task $TASK \
|
||||
--num_envs $NUM_ENVS \
|
||||
--steps $STEPS \
|
||||
--seed $SEED \
|
||||
--checkpoint $CHECKPOINT \
|
||||
--out-dir $CTR_OUT \
|
||||
--headless && \
|
||||
./isaaclab.sh -p source/isaaclab_nav_task/scripts/plot_collisions.py $CTR_OUT/collisions.npz"
|
||||
echo "[collisions] done -> $HOST_OUT"
|
||||
ls -la "$HOST_OUT"
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Verify Go2 nav tasks are registered correctly. Must be launched via isaaclab.sh -p."""
|
||||
|
||||
from isaaclab.app import AppLauncher
|
||||
|
||||
# Headless minimal launcher
|
||||
app_launcher = AppLauncher(headless=True, enable_cameras=False)
|
||||
simulation_app = app_launcher.app
|
||||
|
||||
import gymnasium as gym # noqa: E402
|
||||
import isaaclab_nav_task # noqa: F401, E402
|
||||
|
||||
ids = sorted(s for s in gym.envs.registry.keys() if "Go2" in s or "B2W" in s)
|
||||
print("=" * 60)
|
||||
print("Registered Go2 + B2W tasks:")
|
||||
print("=" * 60)
|
||||
for i in ids:
|
||||
print(f" {i}")
|
||||
|
||||
simulation_app.close()
|
||||
Executable
+190
@@ -0,0 +1,190 @@
|
||||
#!/usr/bin/env bash
|
||||
# Apples-to-apples comparison: my-Go2-policy vs official-B2W-policy on the
|
||||
# SAME pure-maze scene (same seed, same PLAY_* env vars => same maze layouts).
|
||||
#
|
||||
# Bodies differ (Go2 quadruped vs B2W wheeled), but the terrain topology is
|
||||
# identical, so success-rate / failure-mode breakdowns are directly comparable
|
||||
# as a "policy + body" combo.
|
||||
#
|
||||
# Example:
|
||||
# ./scripts/compare_baselines.sh \
|
||||
# --go2-run 2026-06-23_11-13-55_puremaze_tight_corridors \
|
||||
# --go2-iter 32200 \
|
||||
# --b2w-jit assets/baselines/b2w_nav_policy_new.pt \
|
||||
# --cell-size 2.0 \
|
||||
# --difficulty "0.8,1.0" \
|
||||
# --envs 32 --steps 2000 --seed 42
|
||||
set -euo pipefail
|
||||
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
|
||||
# ---- defaults ----
|
||||
GO2_EXPERIMENT="go2_navigation_ppo_puremaze"
|
||||
GO2_RUN=""
|
||||
GO2_ITER=""
|
||||
B2W_JIT=""
|
||||
CELL_SIZE="2.0"
|
||||
DIFFICULTY="0.8,1.0"
|
||||
NUM_ENVS=32
|
||||
STEPS=2000
|
||||
SEED=42
|
||||
OUT_DIR="$REPO_ROOT/outputs/compare/$(date +%Y%m%d_%H%M%S)"
|
||||
|
||||
usage() {
|
||||
cat <<EOF
|
||||
Usage: $(basename "$0") --go2-run DIR --go2-iter N --b2w-jit PATH [options]
|
||||
|
||||
Required (Go2 side):
|
||||
--go2-run DIR Go2 run-dir name (under outputs/logs/rsl_rl/<experiment>/).
|
||||
--go2-iter N Go2 model_<N>.pt iter.
|
||||
|
||||
Required (B2W side):
|
||||
--b2w-jit PATH Host path to TorchScript B2W policy (e.g. nav_policy_new.pt).
|
||||
|
||||
Options:
|
||||
--go2-experiment N Go2 experiment subdir (default: $GO2_EXPERIMENT).
|
||||
--cell-size F PLAY_CELL_SIZE in meters (default: $CELL_SIZE).
|
||||
NOTE: B2W body is large; cell<1.5 usually impossible.
|
||||
--difficulty "l,h" PLAY_DIFFICULTY band (default: "$DIFFICULTY").
|
||||
--envs N Parallel envs (default: $NUM_ENVS).
|
||||
--steps N env.step() count (default: $STEPS).
|
||||
--seed N Shared seed for both runs (default: $SEED).
|
||||
--out-dir PATH Where to write logs+diff (default: outputs/compare/<ts>).
|
||||
-h, --help
|
||||
|
||||
Both runs share:
|
||||
PLAY_MAZE_ONLY=1 (100% maze sub-terrain)
|
||||
PLAY_CLASSIC_MAZE=1 (paper-style uniform walls)
|
||||
PLAY_DIFFICULTY=\$DIFFICULTY
|
||||
PLAY_CELL_SIZE=\$CELL_SIZE
|
||||
--seed \$SEED, --num_envs \$NUM_ENVS, --steps \$STEPS
|
||||
EOF
|
||||
exit 0
|
||||
}
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--go2-run) GO2_RUN="$2"; shift 2 ;;
|
||||
--go2-iter) GO2_ITER="$2"; shift 2 ;;
|
||||
--go2-experiment) GO2_EXPERIMENT="$2"; shift 2 ;;
|
||||
--b2w-jit) B2W_JIT="$2"; shift 2 ;;
|
||||
--cell-size) CELL_SIZE="$2"; shift 2 ;;
|
||||
--difficulty) DIFFICULTY="$2"; shift 2 ;;
|
||||
--envs) NUM_ENVS="$2"; shift 2 ;;
|
||||
--steps) STEPS="$2"; shift 2 ;;
|
||||
--seed) SEED="$2"; shift 2 ;;
|
||||
--out-dir) OUT_DIR="$2"; shift 2 ;;
|
||||
-h|--help) usage ;;
|
||||
*) echo "[error] Unknown arg: $1" >&2; usage ;;
|
||||
esac
|
||||
done
|
||||
|
||||
[[ -z "$GO2_RUN" || -z "$GO2_ITER" || -z "$B2W_JIT" ]] && \
|
||||
{ echo "[error] --go2-run, --go2-iter, --b2w-jit are required." >&2; usage; }
|
||||
|
||||
mkdir -p "$OUT_DIR"
|
||||
GO2_LOG="$OUT_DIR/go2_eval.log"
|
||||
B2W_LOG="$OUT_DIR/b2w_eval.log"
|
||||
DIFF_TABLE="$OUT_DIR/comparison.md"
|
||||
|
||||
# Shared env vars for both runs.
|
||||
export PLAY_MAZE_ONLY=1
|
||||
export PLAY_CLASSIC_MAZE=1
|
||||
export PLAY_DIFFICULTY="$DIFFICULTY"
|
||||
export PLAY_CELL_SIZE="$CELL_SIZE"
|
||||
|
||||
cat <<EOF | tee "$OUT_DIR/setup.txt"
|
||||
================ COMPARE SETUP ================
|
||||
out_dir = $OUT_DIR
|
||||
seed = $SEED
|
||||
envs = $NUM_ENVS
|
||||
steps = $STEPS
|
||||
PLAY_MAZE_ONLY = 1
|
||||
PLAY_CLASSIC_MAZE = 1
|
||||
PLAY_DIFFICULTY = $DIFFICULTY
|
||||
PLAY_CELL_SIZE = $CELL_SIZE
|
||||
----- GO2 -----
|
||||
experiment = $GO2_EXPERIMENT
|
||||
run-dir = $GO2_RUN
|
||||
iter = $GO2_ITER
|
||||
----- B2W -----
|
||||
jit policy = $B2W_JIT
|
||||
================================================
|
||||
EOF
|
||||
|
||||
# ---- 1. Go2 (my policy) on maze ----
|
||||
echo "[compare] >>> running Go2 eval ..."
|
||||
"$REPO_ROOT/scripts/eval_terminations.sh" \
|
||||
--task Isaac-Nav-PPO-Go2-Play-v0 \
|
||||
--experiment "$GO2_EXPERIMENT" \
|
||||
--run-dir "$GO2_RUN" \
|
||||
--from-iter "$GO2_ITER" \
|
||||
--envs "$NUM_ENVS" --steps "$STEPS" --seed "$SEED" \
|
||||
2>&1 | tee "$GO2_LOG"
|
||||
|
||||
# ---- 2. B2W (official JIT) on maze ----
|
||||
echo "[compare] >>> running B2W eval ..."
|
||||
"$REPO_ROOT/scripts/eval_jit_baseline.sh" \
|
||||
--task Isaac-Nav-PPO-B2W-Play-v0 \
|
||||
--jit-policy "$B2W_JIT" \
|
||||
--envs "$NUM_ENVS" --steps "$STEPS" --seed "$SEED" \
|
||||
2>&1 | tee "$B2W_LOG"
|
||||
|
||||
# ---- 3. Parse both logs and produce a side-by-side table ----
|
||||
python3 - "$GO2_LOG" "$B2W_LOG" "$DIFF_TABLE" <<'PY'
|
||||
import re, sys, pathlib
|
||||
go2_log, b2w_log, out_md = sys.argv[1], sys.argv[2], sys.argv[3]
|
||||
|
||||
def parse(path):
|
||||
"""Extract per-term counts from an eval-style log."""
|
||||
text = pathlib.Path(path).read_text()
|
||||
rows = {}
|
||||
# lines look like: " early_termination 1234 45.6% <- success"
|
||||
for m in re.finditer(r"^\s{2}([a-z_]+)\s+(\d+)\s+([\d.]+)%", text, re.M):
|
||||
rows[m.group(1)] = (int(m.group(2)), float(m.group(3)))
|
||||
return rows
|
||||
|
||||
g = parse(go2_log)
|
||||
b = parse(b2w_log)
|
||||
all_terms = sorted(set(g) | set(b))
|
||||
|
||||
# Ordering: success first, then collisions, then time_out, then rest.
|
||||
priority = {"early_termination": 0, "base_contact": 1, "large_pitch_angle": 2,
|
||||
"terrain_fall": 3, "time_out": 4}
|
||||
all_terms.sort(key=lambda n: (priority.get(n, 99), n))
|
||||
|
||||
lines = []
|
||||
lines.append("# Go2-policy vs official-B2W-policy on identical maze scenes\n")
|
||||
lines.append("| termination | Go2 count | Go2 % | B2W count | B2W % | meaning |")
|
||||
lines.append("|----------------------|-----------|--------|-----------|--------|---------|")
|
||||
meaning = {
|
||||
"early_termination": "**success** (reached goal)",
|
||||
"base_contact": "collision (body hit wall)",
|
||||
"large_pitch_angle": "tipped over",
|
||||
"terrain_fall": "fell into pit",
|
||||
"time_out": "ran out of time",
|
||||
}
|
||||
for t in all_terms:
|
||||
gc, gp = g.get(t, (0, 0.0))
|
||||
bc, bp = b.get(t, (0, 0.0))
|
||||
lines.append(f"| `{t:<20}` | {gc:>9} | {gp:>5.1f}% | {bc:>9} | {bp:>5.1f}% | {meaning.get(t,'')} |")
|
||||
|
||||
# Summary delta on success rate.
|
||||
g_succ = g.get("early_termination", (0, 0.0))[1]
|
||||
b_succ = b.get("early_termination", (0, 0.0))[1]
|
||||
lines.append("")
|
||||
lines.append(f"**Success rate:** Go2 = **{g_succ:.1f}%**, B2W = **{b_succ:.1f}%**, "
|
||||
f"Δ = **{g_succ - b_succ:+.1f}** pp (Go2 - B2W)")
|
||||
|
||||
out = "\n".join(lines) + "\n"
|
||||
pathlib.Path(out_md).write_text(out)
|
||||
print("\n" + "=" * 78)
|
||||
print(out)
|
||||
print(f"[compare] wrote {out_md}")
|
||||
PY
|
||||
|
||||
echo ""
|
||||
echo "[compare] all done."
|
||||
echo " setup: $OUT_DIR/setup.txt"
|
||||
echo " go2 log: $GO2_LOG"
|
||||
echo " b2w log: $B2W_LOG"
|
||||
echo " table: $DIFF_TABLE"
|
||||
Executable
+182
@@ -0,0 +1,182 @@
|
||||
#!/usr/bin/env bash
|
||||
# Continue training the Go2 SRU navigation policy with explicit CLI flags.
|
||||
#
|
||||
# Examples:
|
||||
# # Continue from the latest checkpoint of the latest run, train 1000 more iters.
|
||||
# ./scripts/continue_go2.sh --iters 1000
|
||||
#
|
||||
# # Resume from a specific iteration of the latest run.
|
||||
# ./scripts/continue_go2.sh --iters 2000 --from-iter 1000
|
||||
#
|
||||
# # Resume from a specific run directory + iteration.
|
||||
# ./scripts/continue_go2.sh --iters 500 \
|
||||
# --run-dir 2026-06-12_08-16-50_resume_from_33 --from-iter 600
|
||||
#
|
||||
# # Pin an exact checkpoint file (in-container path).
|
||||
# ./scripts/continue_go2.sh --iters 500 \
|
||||
# --checkpoint /workspace/IsaacLab/logs/rsl_rl/go2_navigation_ppo_dev/2026-06-12_08-16-50_resume_from_33/model_1000.pt
|
||||
#
|
||||
# # GUI mode, fewer envs.
|
||||
# ./scripts/continue_go2.sh --iters 200 --envs 8 --gui
|
||||
#
|
||||
# # Switch to the full-PPO task (different experiment_name dir).
|
||||
# ./scripts/continue_go2.sh --iters 2000 --task Isaac-Nav-PPO-Go2-v0 \
|
||||
# --experiment go2_navigation_ppo_ft_from_b2w
|
||||
#
|
||||
# Behavior:
|
||||
# - --load-optimizer is ON by default (true PPO resume); disable with --no-load-optimizer.
|
||||
# - A new timestamped run directory is created; old runs are preserved.
|
||||
# - The new run's --max_iterations is the *absolute* PPO iteration target,
|
||||
# so set it to (start_iter + extra_iters). For convenience you can pass
|
||||
# --extra-iters N which will be added to the resumed start_iter.
|
||||
#
|
||||
set -euo pipefail
|
||||
|
||||
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
|
||||
# ---- defaults ----
|
||||
TASK="Isaac-Nav-PPO-Go2-Dev-v0"
|
||||
EXPERIMENT="go2_navigation_ppo_dev" # log subdir under outputs/logs/rsl_rl/
|
||||
NUM_ENVS=1024
|
||||
ITERS="" # absolute target iteration count
|
||||
EXTRA_ITERS="" # alternative: N more iters past the resumed checkpoint
|
||||
FROM_ITER="" # specific iteration number to resume from
|
||||
RUN_DIR="" # specific run dir name under <experiment>/
|
||||
CHECKPOINT="" # explicit in-container checkpoint path (overrides everything)
|
||||
SEED=42
|
||||
RUN_NAME="" # auto-generated if empty
|
||||
GUI=0
|
||||
LOAD_OPTIMIZER=1
|
||||
|
||||
usage() {
|
||||
sed -n '1,30p' "$0"
|
||||
echo
|
||||
echo "Flags:"
|
||||
echo " --iters N Absolute target PPO iteration count (overrides max_iterations)."
|
||||
echo " --extra-iters N Iters to train past the resumed start (alternative to --iters)."
|
||||
echo " --from-iter N Resume from model_<N>.pt within the chosen run dir."
|
||||
echo " --run-dir NAME Run dir name under outputs/logs/rsl_rl/<experiment>/."
|
||||
echo " --checkpoint PATH Explicit in-container checkpoint path (overrides above)."
|
||||
echo " --task NAME Gym task id (default: $TASK)."
|
||||
echo " --experiment NAME Log subdir to scan (default: $EXPERIMENT)."
|
||||
echo " --envs N Parallel envs (default: $NUM_ENVS)."
|
||||
echo " --seed N Seed (default: $SEED)."
|
||||
echo " --run-name STR Suffix for the new run dir (default: resume_from_<iter>)."
|
||||
echo " --gui Show Isaac Sim GUI (X11)."
|
||||
echo " --no-load-optimizer Load model only (cold optimizer)."
|
||||
echo " -h, --help Show this help."
|
||||
exit 0
|
||||
}
|
||||
|
||||
# ---- arg parsing ----
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--iters) ITERS="$2"; shift 2 ;;
|
||||
--extra-iters) EXTRA_ITERS="$2"; shift 2 ;;
|
||||
--from-iter) FROM_ITER="$2"; shift 2 ;;
|
||||
--run-dir) RUN_DIR="$2"; shift 2 ;;
|
||||
--checkpoint) CHECKPOINT="$2"; shift 2 ;;
|
||||
--task) TASK="$2"; shift 2 ;;
|
||||
--experiment) EXPERIMENT="$2"; shift 2 ;;
|
||||
--envs) NUM_ENVS="$2"; shift 2 ;;
|
||||
--seed) SEED="$2"; shift 2 ;;
|
||||
--run-name) RUN_NAME="$2"; shift 2 ;;
|
||||
--gui) GUI=1; shift ;;
|
||||
--no-load-optimizer) LOAD_OPTIMIZER=0; shift ;;
|
||||
-h|--help) usage ;;
|
||||
*) echo "[error] Unknown arg: $1" >&2; usage ;;
|
||||
esac
|
||||
done
|
||||
|
||||
HOST_LOG_ROOT="$REPO_ROOT/outputs/logs/rsl_rl/$EXPERIMENT"
|
||||
|
||||
# ---- resolve checkpoint ----
|
||||
if [[ -z "$CHECKPOINT" ]]; then
|
||||
if [[ -z "$RUN_DIR" ]]; then
|
||||
RUN_DIR="$(ls -1 "$HOST_LOG_ROOT" 2>/dev/null | sort | tail -n 1 || true)"
|
||||
[[ -z "$RUN_DIR" ]] && { echo "[error] No runs under $HOST_LOG_ROOT" >&2; exit 1; }
|
||||
fi
|
||||
RUN_PATH="$HOST_LOG_ROOT/$RUN_DIR"
|
||||
[[ -d "$RUN_PATH" ]] || { echo "[error] Run dir not found: $RUN_PATH" >&2; exit 1; }
|
||||
|
||||
if [[ -n "$FROM_ITER" ]]; then
|
||||
HOST_CKPT="$RUN_PATH/model_${FROM_ITER}.pt"
|
||||
[[ -f "$HOST_CKPT" ]] || { echo "[error] Checkpoint not found: $HOST_CKPT" >&2; exit 1; }
|
||||
else
|
||||
HOST_CKPT="$(ls -1 "$RUN_PATH"/model_*.pt 2>/dev/null | sort -V | tail -n 1)"
|
||||
[[ -z "$HOST_CKPT" ]] && { echo "[error] No model_*.pt in $RUN_PATH" >&2; exit 1; }
|
||||
fi
|
||||
CHECKPOINT="${HOST_CKPT/$REPO_ROOT\/outputs\/logs/\/workspace\/IsaacLab\/logs}"
|
||||
else
|
||||
HOST_CKPT="${CHECKPOINT/\/workspace\/IsaacLab\/logs/$REPO_ROOT\/outputs\/logs}"
|
||||
fi
|
||||
|
||||
# ---- derive start iter from filename if possible ----
|
||||
START_ITER="$(basename "$HOST_CKPT" | sed -nE 's/model_([0-9]+)\.pt/\1/p')"
|
||||
[[ -z "$START_ITER" ]] && START_ITER=0
|
||||
|
||||
# ---- resolve target iteration count ----
|
||||
if [[ -z "$ITERS" && -n "$EXTRA_ITERS" ]]; then
|
||||
ITERS=$(( START_ITER + EXTRA_ITERS ))
|
||||
fi
|
||||
if [[ -z "$ITERS" ]]; then
|
||||
echo "[error] Must provide --iters N (absolute) or --extra-iters N (relative)." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
[[ -z "$RUN_NAME" ]] && RUN_NAME="resume_from_${START_ITER}"
|
||||
|
||||
# ---- GUI plumbing ----
|
||||
HEADLESS_FLAG="--headless"
|
||||
EXTRA_DOCKER_ARGS=()
|
||||
if [[ "$GUI" == "1" ]]; then
|
||||
HEADLESS_FLAG=""
|
||||
xhost +local:root >/dev/null 2>&1 || xhost +local:docker >/dev/null 2>&1 || true
|
||||
EXTRA_DOCKER_ARGS+=(-e "DISPLAY=${DISPLAY:-:1}"
|
||||
-v /tmp/.X11-unix:/tmp/.X11-unix:rw
|
||||
-v "$HOME/.Xauthority:/root/.Xauthority:ro")
|
||||
fi
|
||||
|
||||
OPT_FLAG=""
|
||||
[[ "$LOAD_OPTIMIZER" == "1" ]] && OPT_FLAG="--load_optimizer"
|
||||
|
||||
cat <<EOF
|
||||
[continue_go2] task = $TASK
|
||||
[continue_go2] experiment = $EXPERIMENT
|
||||
[continue_go2] checkpoint = $CHECKPOINT
|
||||
[continue_go2] start iter = $START_ITER
|
||||
[continue_go2] target iter = $ITERS (= $((ITERS - START_ITER)) more)
|
||||
[continue_go2] envs = $NUM_ENVS
|
||||
[continue_go2] seed = $SEED
|
||||
[continue_go2] run_name = $RUN_NAME
|
||||
[continue_go2] gui = $GUI
|
||||
[continue_go2] load_opt = $LOAD_OPTIMIZER
|
||||
EOF
|
||||
|
||||
docker run --rm --gpus all \
|
||||
-e ACCEPT_EULA=Y -e PRIVACY_CONSENT=Y \
|
||||
-e PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
|
||||
-e DEV_DIFFICULTY="${DEV_DIFFICULTY:-}" \
|
||||
-e GO2_DIFFICULTY="${GO2_DIFFICULTY:-}" \
|
||||
-e GO2_INIT_LEVEL="${GO2_INIT_LEVEL:-}" \
|
||||
-e GO2_CELL_SIZE="${GO2_CELL_SIZE:-}" \
|
||||
-e PUREMAZE_DIFFICULTY="${PUREMAZE_DIFFICULTY:-}" \
|
||||
-e PUREMAZE_CELL_SIZE="${PUREMAZE_CELL_SIZE:-}" \
|
||||
-e PUREMAZE_NUM_ROWS="${PUREMAZE_NUM_ROWS:-}" \
|
||||
-e PUREMAZE_NUM_COLS="${PUREMAZE_NUM_COLS:-}" \
|
||||
--shm-size=16g --network host --ipc host \
|
||||
--ulimit memlock=-1 --ulimit stack=67108864 \
|
||||
"${EXTRA_DOCKER_ARGS[@]}" \
|
||||
-v "$REPO_ROOT/outputs/logs:/workspace/IsaacLab/logs" \
|
||||
-v "$REPO_ROOT/mount/sru-navigation-sim:/workspace/IsaacLab/source/isaaclab_nav_task" \
|
||||
-v "$REPO_ROOT/mount/rsl_rl:/workspace/rsl_rl" \
|
||||
--entrypoint bash sru-nav:latest -lc \
|
||||
"./isaaclab.sh -p source/isaaclab_nav_task/scripts/train.py \
|
||||
--task $TASK \
|
||||
--num_envs $NUM_ENVS \
|
||||
--max_iterations $ITERS \
|
||||
--seed $SEED \
|
||||
--run_name $RUN_NAME \
|
||||
--checkpoint $CHECKPOINT \
|
||||
$OPT_FLAG \
|
||||
$HEADLESS_FLAG"
|
||||
@@ -0,0 +1,118 @@
|
||||
"""Convert an rsl_rl-style training checkpoint (torch.save dict) into a
|
||||
deployable TorchScript .pt usable by sru-navigation-sim's torch.jit.load().
|
||||
|
||||
Input: checkpoint with keys {model_state_dict, optimizer_state_dict, iter, infos}
|
||||
where model_state_dict has actor.0.weight / actor.2.weight / ...
|
||||
Output: TorchScript that does forward(obs) -> mean_actions
|
||||
|
||||
Usage:
|
||||
/workspace/IsaacLab/_isaac_sim/python.sh /tmp/convert_rsl_rl_ckpt_to_jit.py \
|
||||
<input_ckpt.pt> <output_jit.pt>
|
||||
"""
|
||||
|
||||
import sys
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
|
||||
def infer_actor_dims(state_dict):
|
||||
"""Walk actor.{0,2,4,...}.weight to recover layer sizes & activation slots."""
|
||||
layer_dims = []
|
||||
indices = sorted(
|
||||
int(k.split(".")[1])
|
||||
for k in state_dict
|
||||
if k.startswith("actor.") and k.endswith(".weight")
|
||||
)
|
||||
for idx in indices:
|
||||
w = state_dict[f"actor.{idx}.weight"]
|
||||
if w.ndim != 2:
|
||||
continue
|
||||
if not layer_dims:
|
||||
layer_dims.append(w.shape[1]) # in_features of first Linear
|
||||
layer_dims.append(w.shape[0]) # out_features
|
||||
return layer_dims, indices
|
||||
|
||||
|
||||
def build_actor_mlp(layer_dims, linear_indices, activation_name="elu"):
|
||||
"""Build an nn.Sequential mirroring rsl_rl's actor:
|
||||
Linear -> Activation -> Linear -> Activation -> ... -> Linear (no final activation)."""
|
||||
if activation_name.lower() == "elu":
|
||||
act_cls = nn.ELU
|
||||
elif activation_name.lower() == "relu":
|
||||
act_cls = nn.ReLU
|
||||
elif activation_name.lower() == "tanh":
|
||||
act_cls = nn.Tanh
|
||||
else:
|
||||
raise ValueError(f"unknown activation: {activation_name}")
|
||||
|
||||
# rsl_rl stores layers at indices 0, 2, 4, ... (activations live in odd slots).
|
||||
# We reconstruct that exact layout so load_state_dict by name works.
|
||||
layers = []
|
||||
n_linears = len(layer_dims) - 1
|
||||
for i in range(n_linears):
|
||||
layers.append(nn.Linear(layer_dims[i], layer_dims[i + 1]))
|
||||
if i < n_linears - 1:
|
||||
layers.append(act_cls())
|
||||
return nn.Sequential(*layers)
|
||||
|
||||
|
||||
class DeployableActor(nn.Module):
|
||||
"""Wraps the actor MLP and provides a clean forward(obs) -> mean_actions."""
|
||||
|
||||
def __init__(self, actor: nn.Module):
|
||||
super().__init__()
|
||||
self.actor = actor
|
||||
|
||||
def forward(self, obs: torch.Tensor) -> torch.Tensor:
|
||||
return self.actor(obs)
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) != 3:
|
||||
print("usage: convert_rsl_rl_ckpt_to_jit.py <input.pt> <output.pt>")
|
||||
sys.exit(1)
|
||||
src, dst = sys.argv[1], sys.argv[2]
|
||||
|
||||
print(f"[convert] loading checkpoint: {src}")
|
||||
ckpt = torch.load(src, map_location="cpu", weights_only=False)
|
||||
|
||||
sd_full = ckpt["model_state_dict"] if "model_state_dict" in ckpt else ckpt
|
||||
# Strip critic / std from state dict for the actor-only deployable model.
|
||||
actor_sd = {k: v for k, v in sd_full.items() if k.startswith("actor.")}
|
||||
print(f"[convert] actor weights: {len(actor_sd)} tensors")
|
||||
|
||||
layer_dims, linear_indices = infer_actor_dims(sd_full)
|
||||
print(f"[convert] actor MLP shape: {' -> '.join(map(str, layer_dims))}")
|
||||
print(f"[convert] action_dim = {layer_dims[-1]}, obs_dim = {layer_dims[0]}")
|
||||
|
||||
actor = build_actor_mlp(layer_dims, linear_indices, activation_name="elu")
|
||||
# Strip the "actor." prefix so the bare Sequential can load by index keys.
|
||||
stripped_sd = {k[len("actor."):]: v for k, v in actor_sd.items()}
|
||||
missing, unexpected = actor.load_state_dict(stripped_sd, strict=True)
|
||||
assert not missing and not unexpected, (missing, unexpected)
|
||||
print(f"[convert] state_dict loaded ✓")
|
||||
|
||||
deploy = DeployableActor(actor).eval()
|
||||
|
||||
# Sanity forward pass
|
||||
with torch.inference_mode():
|
||||
fake = torch.zeros(2, layer_dims[0])
|
||||
out = deploy(fake)
|
||||
print(f"[convert] forward sanity: in={tuple(fake.shape)} -> out={tuple(out.shape)}")
|
||||
print(f"[convert] zero-input output[0]: {out[0].numpy().round(3).tolist()}")
|
||||
|
||||
# Trace OR script. We use script since the MLP is straight-line code.
|
||||
scripted = torch.jit.script(deploy)
|
||||
scripted.save(dst)
|
||||
print(f"[convert] saved TorchScript model: {dst}")
|
||||
|
||||
# Verify round-trip
|
||||
reloaded = torch.jit.load(dst, map_location="cpu")
|
||||
with torch.inference_mode():
|
||||
out2 = reloaded(fake)
|
||||
assert torch.allclose(out, out2, atol=1e-6), "round-trip mismatch!"
|
||||
print(f"[convert] round-trip torch.jit.load() works ✓")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+102
@@ -0,0 +1,102 @@
|
||||
#!/usr/bin/env bash
|
||||
# Evaluate a TorchScript JIT navigation policy (e.g. the official B2W baseline
|
||||
# nav_policy_new.pt) on the IsaacLab navigation env, with the same PLAY_*
|
||||
# terrain env vars as eval_terminations.sh.
|
||||
#
|
||||
# Example: baseline on dense paper-style maze
|
||||
# PLAY_DIFFICULTY="0.8,1.0" \
|
||||
# PLAY_SUBTERRAIN_MIX="maze=1,non_maze=0,pits=0" \
|
||||
# PLAY_CLASSIC_MAZE=1 \
|
||||
# ./scripts/eval_jit_baseline.sh \
|
||||
# --task Isaac-Nav-PPO-B2W-Play-v0 \
|
||||
# --jit-policy assets/baselines/b2w_nav_policy_new.pt \
|
||||
# --envs 32 --steps 2000
|
||||
set -euo pipefail
|
||||
|
||||
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
|
||||
TASK="Isaac-Nav-PPO-B2W-Play-v0"
|
||||
JIT_HOST=""
|
||||
NUM_ENVS=32
|
||||
STEPS=2000
|
||||
SEED=42
|
||||
|
||||
usage() {
|
||||
cat <<EOF
|
||||
Usage: $(basename "$0") --jit-policy PATH [options]
|
||||
|
||||
Required:
|
||||
--jit-policy PATH Host path to a TorchScript .pt policy.
|
||||
(will be mounted into /workspace at /jit_policy.pt)
|
||||
|
||||
Options:
|
||||
--task NAME Gym task id (default: $TASK).
|
||||
--envs N Parallel envs (default: $NUM_ENVS).
|
||||
--steps N env.step() calls (default: $STEPS).
|
||||
--seed N (default: $SEED).
|
||||
-h, --help Show this help.
|
||||
|
||||
Forwarded env vars (set on host):
|
||||
PLAY_DIFFICULTY="lo,hi"
|
||||
PLAY_SUBTERRAIN_MIX="maze=1,non_maze=0,pits=0"
|
||||
PLAY_MAZE_ONLY=1
|
||||
PLAY_CELL_SIZE=2.0
|
||||
PLAY_CLASSIC_MAZE=1
|
||||
EOF
|
||||
exit 0
|
||||
}
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--jit-policy) JIT_HOST="$2"; shift 2 ;;
|
||||
--task) TASK="$2"; shift 2 ;;
|
||||
--envs) NUM_ENVS="$2"; shift 2 ;;
|
||||
--steps) STEPS="$2"; shift 2 ;;
|
||||
--seed) SEED="$2"; shift 2 ;;
|
||||
-h|--help) usage ;;
|
||||
*) echo "[error] Unknown arg: $1" >&2; usage ;;
|
||||
esac
|
||||
done
|
||||
|
||||
[[ -z "$JIT_HOST" ]] && { echo "[error] --jit-policy is required." >&2; exit 1; }
|
||||
# Resolve to absolute path
|
||||
if [[ "$JIT_HOST" != /* ]]; then JIT_HOST="$REPO_ROOT/$JIT_HOST"; fi
|
||||
[[ -f "$JIT_HOST" ]] || { echo "[error] JIT file not found: $JIT_HOST" >&2; exit 1; }
|
||||
|
||||
JIT_CTR="/workspace/baseline_policy.pt"
|
||||
|
||||
cat <<EOF
|
||||
[eval-jit] task = $TASK
|
||||
[eval-jit] jit (host) = $JIT_HOST
|
||||
[eval-jit] jit (ctr) = $JIT_CTR
|
||||
[eval-jit] envs = $NUM_ENVS
|
||||
[eval-jit] steps = $STEPS
|
||||
[eval-jit] PLAY_DIFFICULTY = ${PLAY_DIFFICULTY:-(default)}
|
||||
[eval-jit] PLAY_SUBTERRAIN_MIX = ${PLAY_SUBTERRAIN_MIX:-(default)}
|
||||
[eval-jit] PLAY_MAZE_ONLY = ${PLAY_MAZE_ONLY:-(default)}
|
||||
[eval-jit] PLAY_CELL_SIZE = ${PLAY_CELL_SIZE:-(default)}
|
||||
[eval-jit] PLAY_CLASSIC_MAZE = ${PLAY_CLASSIC_MAZE:-(default)}
|
||||
EOF
|
||||
|
||||
docker run --rm --gpus all \
|
||||
-e ACCEPT_EULA=Y -e PRIVACY_CONSENT=Y \
|
||||
-e PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
|
||||
-e PLAY_DIFFICULTY="${PLAY_DIFFICULTY:-}" \
|
||||
-e PLAY_SUBTERRAIN_MIX="${PLAY_SUBTERRAIN_MIX:-}" \
|
||||
-e PLAY_MAZE_ONLY="${PLAY_MAZE_ONLY:-}" \
|
||||
-e PLAY_CELL_SIZE="${PLAY_CELL_SIZE:-}" \
|
||||
-e PLAY_CLASSIC_MAZE="${PLAY_CLASSIC_MAZE:-}" \
|
||||
--shm-size=16g --network host --ipc host \
|
||||
--ulimit memlock=-1 --ulimit stack=67108864 \
|
||||
-v "$REPO_ROOT/outputs/logs:/workspace/IsaacLab/logs" \
|
||||
-v "$REPO_ROOT/mount/sru-navigation-sim:/workspace/IsaacLab/source/isaaclab_nav_task" \
|
||||
-v "$REPO_ROOT/mount/rsl_rl:/workspace/rsl_rl" \
|
||||
-v "$JIT_HOST:$JIT_CTR:ro" \
|
||||
--entrypoint bash sru-nav:latest -lc \
|
||||
"./isaaclab.sh -p source/isaaclab_nav_task/scripts/eval_jit_policy.py \
|
||||
--task $TASK \
|
||||
--num_envs $NUM_ENVS \
|
||||
--steps $STEPS \
|
||||
--seed $SEED \
|
||||
--jit_policy $JIT_CTR \
|
||||
--headless"
|
||||
Executable
+94
@@ -0,0 +1,94 @@
|
||||
#!/usr/bin/env bash
|
||||
# Headless termination breakdown evaluator. Counts per-term terminations over
|
||||
# N steps so we can read the *true* pit-fall rate (terrain_fall) now that the
|
||||
# Go2 cfg has tightened fall_height_threshold to -0.3m.
|
||||
#
|
||||
# Examples:
|
||||
# # Latest run, latest ckpt, 64 envs, 2000 steps
|
||||
# ./scripts/eval_terminations.sh
|
||||
#
|
||||
# # Specific run + iter + difficulty band
|
||||
# PLAY_DIFFICULTY="0.3,0.8" ./scripts/eval_terminations.sh \
|
||||
# --run-dir 2026-06-20_12-07-08_phase5_refine_0.3_0.8 --from-iter 27800
|
||||
set -euo pipefail
|
||||
|
||||
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
|
||||
TASK="Isaac-Nav-PPO-Go2-Play-v0"
|
||||
EXPERIMENT="go2_navigation_ppo_dev"
|
||||
NUM_ENVS=64
|
||||
STEPS=2000
|
||||
FROM_ITER=""
|
||||
RUN_DIR=""
|
||||
CHECKPOINT=""
|
||||
SEED=42
|
||||
|
||||
usage() { sed -n '1,15p' "$0"; exit 0; }
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--from-iter) FROM_ITER="$2"; shift 2 ;;
|
||||
--run-dir) RUN_DIR="$2"; shift 2 ;;
|
||||
--checkpoint) CHECKPOINT="$2"; shift 2 ;;
|
||||
--task) TASK="$2"; shift 2 ;;
|
||||
--experiment) EXPERIMENT="$2"; shift 2 ;;
|
||||
--envs) NUM_ENVS="$2"; shift 2 ;;
|
||||
--steps) STEPS="$2"; shift 2 ;;
|
||||
--seed) SEED="$2"; shift 2 ;;
|
||||
-h|--help) usage ;;
|
||||
*) echo "[error] Unknown arg: $1" >&2; usage ;;
|
||||
esac
|
||||
done
|
||||
|
||||
HOST_LOG_ROOT="$REPO_ROOT/outputs/logs/rsl_rl/$EXPERIMENT"
|
||||
|
||||
if [[ -z "$CHECKPOINT" ]]; then
|
||||
if [[ -z "$RUN_DIR" ]]; then
|
||||
RUN_DIR="$(ls -1 "$HOST_LOG_ROOT" 2>/dev/null | sort | tail -n 1 || true)"
|
||||
[[ -z "$RUN_DIR" ]] && { echo "[error] No runs under $HOST_LOG_ROOT" >&2; exit 1; }
|
||||
fi
|
||||
RUN_PATH="$HOST_LOG_ROOT/$RUN_DIR"
|
||||
[[ -d "$RUN_PATH" ]] || { echo "[error] Run dir not found: $RUN_PATH" >&2; exit 1; }
|
||||
|
||||
if [[ -n "$FROM_ITER" ]]; then
|
||||
HOST_CKPT="$RUN_PATH/model_${FROM_ITER}.pt"
|
||||
[[ -f "$HOST_CKPT" ]] || { echo "[error] Checkpoint not found: $HOST_CKPT" >&2; exit 1; }
|
||||
else
|
||||
HOST_CKPT="$(ls -1 "$RUN_PATH"/model_*.pt 2>/dev/null | sort -V | tail -n 1)"
|
||||
[[ -z "$HOST_CKPT" ]] && { echo "[error] No model_*.pt in $RUN_PATH" >&2; exit 1; }
|
||||
fi
|
||||
CHECKPOINT="${HOST_CKPT/$REPO_ROOT\/outputs\/logs/\/workspace\/IsaacLab\/logs}"
|
||||
else
|
||||
HOST_CKPT="${CHECKPOINT/\/workspace\/IsaacLab\/logs/$REPO_ROOT\/outputs\/logs}"
|
||||
fi
|
||||
|
||||
cat <<EOF
|
||||
[eval] task = $TASK
|
||||
[eval] checkpoint = $CHECKPOINT
|
||||
[eval] host file = $HOST_CKPT
|
||||
[eval] envs = $NUM_ENVS
|
||||
[eval] steps = $STEPS
|
||||
[eval] PLAY_DIFFICULTY = ${PLAY_DIFFICULTY:-(default)}
|
||||
EOF
|
||||
|
||||
docker run --rm --gpus all \
|
||||
-e ACCEPT_EULA=Y -e PRIVACY_CONSENT=Y \
|
||||
-e PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
|
||||
-e PLAY_DIFFICULTY="${PLAY_DIFFICULTY:-}" \
|
||||
-e PLAY_SUBTERRAIN_MIX="${PLAY_SUBTERRAIN_MIX:-}" \
|
||||
-e PLAY_MAZE_ONLY="${PLAY_MAZE_ONLY:-}" \
|
||||
-e PLAY_CELL_SIZE="${PLAY_CELL_SIZE:-}" \
|
||||
-e PLAY_CLASSIC_MAZE="${PLAY_CLASSIC_MAZE:-}" \
|
||||
--shm-size=16g --network host --ipc host \
|
||||
--ulimit memlock=-1 --ulimit stack=67108864 \
|
||||
-v "$REPO_ROOT/outputs/logs:/workspace/IsaacLab/logs" \
|
||||
-v "$REPO_ROOT/mount/sru-navigation-sim:/workspace/IsaacLab/source/isaaclab_nav_task" \
|
||||
-v "$REPO_ROOT/mount/rsl_rl:/workspace/rsl_rl" \
|
||||
--entrypoint bash sru-nav:latest -lc \
|
||||
"./isaaclab.sh -p source/isaaclab_nav_task/scripts/eval_terminations.py \
|
||||
--task $TASK \
|
||||
--num_envs $NUM_ENVS \
|
||||
--steps $STEPS \
|
||||
--seed $SEED \
|
||||
--checkpoint $CHECKPOINT \
|
||||
--headless"
|
||||
Executable
+251
@@ -0,0 +1,251 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Export a trained SRU navigation policy checkpoint to ONNX.
|
||||
|
||||
This script reconstructs the ActorCriticSRU model from the checkpoint's
|
||||
weight shapes (no Isaac Sim / IsaacLab needed), loads the weights, and
|
||||
calls the built-in export_onnx method.
|
||||
|
||||
Usage:
|
||||
# Export a specific checkpoint
|
||||
python scripts/export_onnx.py --checkpoint outputs/logs/rsl_rl/go2_navigation_ppo_mixed/<run>/model_4600.pt
|
||||
|
||||
# Export and also save JIT
|
||||
python scripts/export_onnx.py --checkpoint <path> --jit
|
||||
|
||||
# Override output location
|
||||
python scripts/export_onnx.py --checkpoint <path> --output-dir ./exported
|
||||
|
||||
Requirements:
|
||||
- torch
|
||||
- The rsl_rl fork must be importable (pip-installed or on PYTHONPATH)
|
||||
|
||||
ONNX model interface (ActorCriticSRU, single camera):
|
||||
Inputs:
|
||||
- obs: (1, num_actor_obs) — flattened observation vector
|
||||
- h_in: (num_layers, 1, hidden) — LSTM hidden state (zeros at episode start)
|
||||
- c_in: (num_layers, 1, hidden) — LSTM cell state (zeros at episode start)
|
||||
Outputs:
|
||||
- actions: (1, num_actions)
|
||||
- h_out: (num_layers, 1, hidden) — updated hidden state
|
||||
- c_out: (num_layers, 1, hidden) — updated cell state
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
def infer_config_from_state_dict(sd: dict) -> dict:
|
||||
"""Infer ActorCriticSRU constructor args from checkpoint weight shapes."""
|
||||
|
||||
# --- image_input_dims and num_cameras ---
|
||||
# attn_image_net cross-attention query projection weight: (Q, image_dim)
|
||||
# The first linear in CrossAttentionFuseModule is the query proj.
|
||||
# We look for attn_image_net.0.weight or similar.
|
||||
attn_keys = [k for k in sd if k.startswith("attn_image_net.") and "weight" in k]
|
||||
if not attn_keys:
|
||||
raise ValueError("Cannot find attn_image_net weights in checkpoint")
|
||||
# image_dim = out_features of the query projection
|
||||
# CrossAttentionFuseModule: q_proj weight shape = (image_dim, image_dim)
|
||||
# Find the first weight (query proj)
|
||||
attn_w = sd[attn_keys[0]]
|
||||
image_dim = attn_w.shape[0] # output features
|
||||
|
||||
# num_image_features = image_dim * H * W
|
||||
# We can get it from the actor input: actor_proprioceptive_input_dim + num_image_features = num_actor_obs
|
||||
# But we need H, W separately. Get from attn_image_net spatial reshape.
|
||||
# CrossAttentionFuseModule stores no spatial dims as parameters.
|
||||
# Instead, infer from total image features: look at the first linear of actor
|
||||
# which takes mlp_input_dim_actor = actor_proprioceptive_input_dim + image_dim
|
||||
# num_image_features = image_dim * H * W
|
||||
# We need H, W from image_input_dims=(C, H, W) where C=image_dim.
|
||||
# Check if there's a pattern in the attn weights that reveals spatial dims.
|
||||
# Fallback: use the known Go2 config defaults.
|
||||
# The Go2 config uses image_input_dims=(64, 5, 8), height_input_dims=(64, 7, 7).
|
||||
# image_dim=64, H=5, W=8 -> num_image_features = 64*5*8 = 2560
|
||||
# We can infer num_image_features from the observation dimension:
|
||||
# num_actor_obs = actor_proprioceptive_input_dim + num_image_features * num_cameras
|
||||
# actor_proprioceptive_input_dim = mlp_input_dim_actor - image_dim
|
||||
# mlp_input_dim_actor = memory_a input size = rnn input_size
|
||||
|
||||
# Get rnn input_size from memory_a.rnn weight
|
||||
rnn_keys = [k for k in sd if k.startswith("memory_a.") and "weight_ih" in k]
|
||||
if not rnn_keys:
|
||||
raise ValueError("Cannot find memory_a.rnn.weight_ih in checkpoint")
|
||||
rnn_input_size = sd[rnn_keys[0]].shape[1] # input size of LSTM
|
||||
rnn_hidden_size = sd[rnn_keys[0]].shape[0] // 4 # LSTM has 4 gates
|
||||
|
||||
# mlp_input_dim_actor = rnn_input_size
|
||||
# actor_proprioceptive_input_dim = mlp_input_dim_actor - image_dim
|
||||
actor_proprioceptive_input_dim = rnn_input_size - image_dim
|
||||
|
||||
# Get num_image_features from the linear_dropout_actor or actor first layer
|
||||
# linear_dropout_actor.linear weight: (actor_hidden_dims[0], rnn_hidden_size)
|
||||
ld_keys = [k for k in sd if k.startswith("linear_dropout_actor.") and "weight" in k]
|
||||
if ld_keys:
|
||||
actor_hidden_0 = sd[ld_keys[0]].shape[0]
|
||||
else:
|
||||
actor_hidden_0 = 512 # default
|
||||
|
||||
# Get num_actions from actor last layer
|
||||
actor_linear_keys = [k for k in sd if k.startswith("actor.") and "weight" in k]
|
||||
if not actor_linear_keys:
|
||||
raise ValueError("Cannot find actor weights in checkpoint")
|
||||
# Last actor layer weight: (num_actions, actor_hidden_dims[-1])
|
||||
last_actor_w = sd[actor_linear_keys[-1]]
|
||||
num_actions = last_actor_w.shape[0]
|
||||
|
||||
# Infer num_cameras: num_actor_obs = actor_proprioceptive_input_dim + num_image_features * num_cameras
|
||||
# We need num_actor_obs. We can get it from the attn_image_net input.
|
||||
# CrossAttentionFuseModule q_proj input = image_dim, k_proj input = info_dim = actor_proprioceptive_input_dim
|
||||
# But we still can't directly get num_image_features.
|
||||
# However, for Go2 with 1 camera: num_image_features = image_dim * H * W = 64 * 5 * 8 = 2560
|
||||
# For 2 cameras: num_actor_obs = actor_proprioceptive + 2 * num_image_features
|
||||
# We can try both and see which gives a "reasonable" obs dim.
|
||||
# Actually, we can get num_image_features from the attn_image_net more carefully.
|
||||
# CrossAttentionFuseModule reshapes image (B, C, H, W) -> (B, H*W, C) then projects.
|
||||
# The number of spatial tokens = H * W. This doesn't show up as a weight shape.
|
||||
#
|
||||
# Strategy: use known Go2 defaults (image_input_dims=(64,5,8), num_cameras=1)
|
||||
# and verify consistency.
|
||||
H, W = 5, 8 # Go2 default
|
||||
num_image_features = image_dim * H * W
|
||||
num_cameras = 1 # Go2 default
|
||||
|
||||
num_actor_obs = actor_proprioceptive_input_dim + num_image_features * num_cameras
|
||||
|
||||
# Infer height_input_dims for critic (not needed for actor export but for constructor)
|
||||
height_dim = image_dim # default 64
|
||||
hH, hW = 7, 7 # Go2 default
|
||||
num_height_features = height_dim * hH * hW
|
||||
|
||||
# critic_proprioceptive_input_dim = num_critic_obs - num_height_features - num_image_features * num_cameras - 1
|
||||
# We need num_critic_obs. Get from critic rnn input.
|
||||
critic_rnn_keys = [k for k in sd if k.startswith("memory_c.") and "weight_ih" in k]
|
||||
if critic_rnn_keys:
|
||||
critic_rnn_input = sd[critic_rnn_keys[0]].shape[1]
|
||||
critic_proprioceptive = critic_rnn_input - image_dim - height_dim
|
||||
num_critic_obs = critic_proprioceptive + num_height_features + num_image_features * num_cameras + 1
|
||||
else:
|
||||
num_critic_obs = num_actor_obs # fallback
|
||||
|
||||
# rnn_num_layers
|
||||
rnn_num_layers = len([k for k in sd if k.startswith("memory_a.") and "weight_ih_l" in k])
|
||||
if rnn_num_layers == 0:
|
||||
rnn_num_layers = 1
|
||||
|
||||
# actor_hidden_dims from actor weights
|
||||
actor_hidden_dims = []
|
||||
for k in sorted(actor_linear_keys):
|
||||
w = sd[k]
|
||||
actor_hidden_dims.append(w.shape[1])
|
||||
# Last layer's shape[0] is num_actions, not a hidden dim
|
||||
if actor_hidden_dims:
|
||||
actor_hidden_dims[-1] = actor_hidden_dims[-1] # keep last hidden
|
||||
# Actually actor weights: layer0 (h1, in), layer1 (h2, h1), ..., layerN (num_actions, hN)
|
||||
# So hidden_dims = [in_of_first] ... no, hidden_dims = [h1, h2, ..., hN]
|
||||
# weight shapes: (h1, in), (h2, h1), ..., (num_actions, hN)
|
||||
# hidden_dims = [out of each layer except last] = [h1, h2, ..., hN]
|
||||
actor_hidden_dims = []
|
||||
for i, k in enumerate(sorted(actor_linear_keys)):
|
||||
w = sd[k]
|
||||
if i < len(actor_linear_keys) - 1:
|
||||
actor_hidden_dims.append(w.shape[0]) # output dim = next hidden
|
||||
# last layer: shape[0] = num_actions
|
||||
|
||||
config = {
|
||||
"num_actor_obs": num_actor_obs,
|
||||
"num_critic_obs": num_critic_obs,
|
||||
"num_actions": num_actions,
|
||||
"actor_hidden_dims": actor_hidden_dims if actor_hidden_dims else [512, 256, 128],
|
||||
"critic_hidden_dims": actor_hidden_dims if actor_hidden_dims else [512, 256, 128],
|
||||
"activation": "elu",
|
||||
"init_noise_std": 1.0,
|
||||
"image_input_dims": (image_dim, H, W),
|
||||
"height_input_dims": (height_dim, hH, hW),
|
||||
"rnn_type": "lstm_sru",
|
||||
"dropout": 0.2,
|
||||
"rnn_hidden_size": rnn_hidden_size,
|
||||
"rnn_num_layers": rnn_num_layers,
|
||||
"time_embed_dim": 8,
|
||||
"num_cameras": num_cameras,
|
||||
}
|
||||
|
||||
return config
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Export SRU navigation policy checkpoint to ONNX.")
|
||||
parser.add_argument("--checkpoint", type=str, required=True,
|
||||
help="Path to model checkpoint (.pt file)")
|
||||
parser.add_argument("--output-dir", type=str, default=None,
|
||||
help="Output directory (default: <checkpoint_dir>/export)")
|
||||
parser.add_argument("--filename", type=str, default="policy.onnx",
|
||||
help="Output filename (default: policy.onnx)")
|
||||
parser.add_argument("--jit", action="store_true",
|
||||
help="Also export JIT (policy.pt)")
|
||||
parser.add_argument("--verbose", action="store_true",
|
||||
help="Print inferred config and model architecture")
|
||||
args = parser.parse_args()
|
||||
|
||||
checkpoint_path = Path(args.checkpoint).resolve()
|
||||
if not checkpoint_path.exists():
|
||||
print(f"[error] Checkpoint not found: {checkpoint_path}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
# Load checkpoint
|
||||
print(f"[export_onnx] Loading checkpoint: {checkpoint_path}")
|
||||
ckpt = torch.load(str(checkpoint_path), map_location="cpu", weights_only=False)
|
||||
sd = ckpt["model_state_dict"]
|
||||
print(f"[export_onnx] Checkpoint iteration: {ckpt.get('iter', 'unknown')}")
|
||||
|
||||
# Infer model config from weights
|
||||
config = infer_config_from_state_dict(sd)
|
||||
if args.verbose:
|
||||
print("\n[export_onnx] Inferred config:")
|
||||
for k, v in config.items():
|
||||
print(f" {k}: {v}")
|
||||
print()
|
||||
|
||||
# Build model
|
||||
from rsl_rl.modules import ActorCriticSRU
|
||||
|
||||
model = ActorCriticSRU(**config)
|
||||
model.load_state_dict(sd, strict=True)
|
||||
model.eval()
|
||||
model.to("cpu")
|
||||
|
||||
print(f"[export_onnx] Model loaded successfully")
|
||||
print(f" num_actor_obs: {config['num_actor_obs']}")
|
||||
print(f" num_actions: {config['num_actions']}")
|
||||
print(f" num_cameras: {config['num_cameras']}")
|
||||
print(f" image_dims: {config['image_input_dims']}")
|
||||
print(f" rnn_hidden: {config['rnn_hidden_size']}")
|
||||
|
||||
# Determine output directory
|
||||
if args.output_dir:
|
||||
output_dir = Path(args.output_dir)
|
||||
else:
|
||||
output_dir = checkpoint_path.parent / "export"
|
||||
|
||||
# Export ONNX
|
||||
print(f"\n[export_onnx] Exporting ONNX to: {output_dir}/{args.filename}")
|
||||
model.export_onnx(path=str(output_dir), filename=args.filename)
|
||||
|
||||
# Optionally export JIT
|
||||
if args.jit:
|
||||
jit_filename = args.filename.replace(".onnx", ".pt")
|
||||
if jit_filename == args.filename:
|
||||
jit_filename = "policy.pt"
|
||||
print(f"\n[export_onnx] Exporting JIT to: {output_dir}/{jit_filename}")
|
||||
model.export_jit(path=str(output_dir), filename=jit_filename)
|
||||
|
||||
print(f"\n[export_onnx] Done! Output: {output_dir}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+218
@@ -0,0 +1,218 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Inspect a SRU-Go2 training run: dump TensorBoard scalars + ckpt summary.
|
||||
|
||||
Usage:
|
||||
python scripts/inspect_run.py --run outputs/logs/rsl_rl/<exp>/<timestamp_runname>
|
||||
python scripts/inspect_run.py --latest # auto-pick newest run
|
||||
python scripts/inspect_run.py --latest --experiment go2_navigation_ppo_dev
|
||||
python scripts/inspect_run.py --run <path> --tags Train/mean_reward Loss/value_function
|
||||
|
||||
The script tries `tensorboard` first, falls back to `tbparse`, then to a
|
||||
minimal pure-protobuf reader. Prints a compact markdown-friendly summary
|
||||
that can be pasted directly into docs/RUN_LOG.md.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import glob
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Tuple
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
DEFAULT_LOG_ROOT = REPO_ROOT / "outputs" / "logs" / "rsl_rl"
|
||||
|
||||
# Tags worth surfacing by default (rsl_rl + custom). The script will keep only
|
||||
# the ones that actually appear in the events file.
|
||||
DEFAULT_TAGS = [
|
||||
"Train/mean_reward",
|
||||
"Train/mean_episode_length",
|
||||
"Train/learning_rate",
|
||||
"Loss/value_function",
|
||||
"Loss/surrogate",
|
||||
"Loss/entropy",
|
||||
"Policy/mean_noise_std",
|
||||
"Train/mean_success_rate",
|
||||
"Train/mean_collision_rate",
|
||||
]
|
||||
|
||||
|
||||
def _find_latest_run(experiment: str | None) -> Path:
|
||||
if experiment:
|
||||
roots = [DEFAULT_LOG_ROOT / experiment]
|
||||
else:
|
||||
roots = sorted([p for p in DEFAULT_LOG_ROOT.iterdir() if p.is_dir()])
|
||||
candidates: List[Path] = []
|
||||
for root in roots:
|
||||
if not root.exists():
|
||||
continue
|
||||
for entry in root.iterdir():
|
||||
if entry.is_dir() and re.match(r"\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}", entry.name):
|
||||
candidates.append(entry)
|
||||
if not candidates:
|
||||
raise SystemExit(f"[inspect_run] No runs under {DEFAULT_LOG_ROOT}")
|
||||
candidates.sort(key=lambda p: p.stat().st_mtime)
|
||||
return candidates[-1]
|
||||
|
||||
|
||||
def _read_scalars(run_dir: Path) -> Dict[str, List[Tuple[int, float]]]:
|
||||
"""Read all scalar tags from the run's tfevents files.
|
||||
|
||||
Returns mapping: tag -> list[(step, value)] sorted by step.
|
||||
Tries tensorboard.EventAccumulator; falls back to tbparse; then raw protobuf.
|
||||
"""
|
||||
files = sorted(glob.glob(str(run_dir / "events.out.tfevents.*")))
|
||||
if not files:
|
||||
raise SystemExit(f"[inspect_run] No tfevents in {run_dir}")
|
||||
|
||||
# --- attempt 1: tensorboard ---
|
||||
try:
|
||||
from tensorboard.backend.event_processing.event_accumulator import EventAccumulator
|
||||
acc = EventAccumulator(str(run_dir), size_guidance={"scalars": 0})
|
||||
acc.Reload()
|
||||
out: Dict[str, List[Tuple[int, float]]] = {}
|
||||
for tag in acc.Tags().get("scalars", []):
|
||||
out[tag] = [(e.step, e.value) for e in acc.Scalars(tag)]
|
||||
return out
|
||||
except Exception as e:
|
||||
print(f"[inspect_run] tensorboard path failed: {e}; trying tbparse", file=sys.stderr)
|
||||
|
||||
# --- attempt 2: tbparse ---
|
||||
try:
|
||||
from tbparse import SummaryReader # type: ignore
|
||||
reader = SummaryReader(str(run_dir), pivot=False)
|
||||
df = reader.scalars
|
||||
out2: Dict[str, List[Tuple[int, float]]] = {}
|
||||
for tag, group in df.groupby("tag"):
|
||||
group = group.sort_values("step")
|
||||
out2[tag] = list(zip(group["step"].astype(int), group["value"].astype(float)))
|
||||
return out2
|
||||
except Exception as e:
|
||||
print(f"[inspect_run] tbparse failed: {e}; trying raw protobuf", file=sys.stderr)
|
||||
|
||||
# --- attempt 3: raw protobuf via tensorflow ---
|
||||
try:
|
||||
import tensorflow as tf # type: ignore
|
||||
out3: Dict[str, List[Tuple[int, float]]] = {}
|
||||
for f in files:
|
||||
for raw in tf.data.TFRecordDataset(f):
|
||||
ev = tf.compat.v1.Event.FromString(raw.numpy())
|
||||
if not ev.summary:
|
||||
continue
|
||||
for v in ev.summary.value:
|
||||
if v.HasField("simple_value"):
|
||||
out3.setdefault(v.tag, []).append((int(ev.step), float(v.simple_value)))
|
||||
for k in out3:
|
||||
out3[k].sort()
|
||||
return out3
|
||||
except Exception as e:
|
||||
raise SystemExit(
|
||||
f"[inspect_run] All readers failed. Install one of:\n"
|
||||
f" pip install tensorboard\n pip install tbparse\n"
|
||||
f"Last error: {e}"
|
||||
)
|
||||
|
||||
|
||||
def _summarize(series: List[Tuple[int, float]]) -> dict:
|
||||
if not series:
|
||||
return {}
|
||||
steps = [s for s, _ in series]
|
||||
vals = [v for _, v in series]
|
||||
peak_idx = max(range(len(vals)), key=lambda i: vals[i])
|
||||
min_idx = min(range(len(vals)), key=lambda i: vals[i])
|
||||
# last-decile mean to smooth jitter
|
||||
tail = vals[max(0, len(vals) - max(1, len(vals) // 10)) :]
|
||||
return {
|
||||
"start_step": steps[0],
|
||||
"start_val": vals[0],
|
||||
"end_step": steps[-1],
|
||||
"end_val": vals[-1],
|
||||
"peak_step": steps[peak_idx],
|
||||
"peak_val": vals[peak_idx],
|
||||
"min_step": steps[min_idx],
|
||||
"min_val": vals[min_idx],
|
||||
"tail_mean": sum(tail) / len(tail),
|
||||
"n_points": len(series),
|
||||
}
|
||||
|
||||
|
||||
def _ckpt_summary(run_dir: Path) -> dict:
|
||||
ckpts = sorted(run_dir.glob("model_*.pt"), key=lambda p: int(re.findall(r"model_(\d+)\.pt", p.name)[0]))
|
||||
if not ckpts:
|
||||
return {}
|
||||
latest = ckpts[-1]
|
||||
iter_n = int(re.findall(r"model_(\d+)\.pt", latest.name)[0])
|
||||
return {
|
||||
"count": len(ckpts),
|
||||
"latest": latest.name,
|
||||
"latest_iter": iter_n,
|
||||
"size_mb": latest.stat().st_size / 1024 / 1024,
|
||||
"all_iters": [int(re.findall(r"model_(\d+)\.pt", p.name)[0]) for p in ckpts],
|
||||
}
|
||||
|
||||
|
||||
def _md_table(rows: List[List[str]], header: List[str]) -> str:
|
||||
out = ["| " + " | ".join(header) + " |", "| " + " | ".join(["---"] * len(header)) + " |"]
|
||||
for r in rows:
|
||||
out.append("| " + " | ".join(r) + " |")
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
g = ap.add_mutually_exclusive_group()
|
||||
g.add_argument("--run", type=str, help="Path to a run directory (host).")
|
||||
g.add_argument("--latest", action="store_true", help="Pick newest run under outputs/logs/rsl_rl/.")
|
||||
ap.add_argument("--experiment", type=str, default=None, help="Restrict --latest to this experiment subdir.")
|
||||
ap.add_argument("--tags", nargs="*", default=None, help="Override the tag whitelist; pass tag names.")
|
||||
ap.add_argument("--all-tags", action="store_true", help="Print every scalar tag found.")
|
||||
args = ap.parse_args()
|
||||
|
||||
if args.run:
|
||||
run_dir = Path(args.run).resolve()
|
||||
else:
|
||||
run_dir = _find_latest_run(args.experiment)
|
||||
if not run_dir.exists():
|
||||
raise SystemExit(f"[inspect_run] Not a dir: {run_dir}")
|
||||
|
||||
print(f"# Run inspection\n")
|
||||
print(f"- **dir**: `{run_dir}`")
|
||||
ck = _ckpt_summary(run_dir)
|
||||
if ck:
|
||||
print(f"- **checkpoints**: {ck['count']} files, latest `{ck['latest']}` "
|
||||
f"(iter {ck['latest_iter']}, {ck['size_mb']:.1f} MB)")
|
||||
print(f"- **all iters saved**: {ck['all_iters']}")
|
||||
print()
|
||||
|
||||
scalars = _read_scalars(run_dir)
|
||||
tags = args.tags or (list(scalars.keys()) if args.all_tags else DEFAULT_TAGS)
|
||||
rows = []
|
||||
for tag in tags:
|
||||
if tag not in scalars:
|
||||
continue
|
||||
s = _summarize(scalars[tag])
|
||||
if not s:
|
||||
continue
|
||||
rows.append([
|
||||
f"`{tag}`",
|
||||
f"{s['start_val']:.3g} @ {s['start_step']}",
|
||||
f"{s['end_val']:.3g} @ {s['end_step']}",
|
||||
f"{s['peak_val']:.3g} @ {s['peak_step']}",
|
||||
f"{s['min_val']:.3g} @ {s['min_step']}",
|
||||
f"{s['tail_mean']:.3g}",
|
||||
str(s["n_points"]),
|
||||
])
|
||||
|
||||
print("## Scalars\n")
|
||||
if rows:
|
||||
print(_md_table(rows, ["tag", "start", "end", "peak", "min", "tail-mean(10%)", "n"]))
|
||||
else:
|
||||
print("_no matching tags found_")
|
||||
print(f"\navailable tags: {sorted(scalars.keys())}")
|
||||
print()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+41
@@ -0,0 +1,41 @@
|
||||
#!/usr/bin/env bash
|
||||
# Launch the Isaac Sim full GUI (no task, no policy) in the project's docker.
|
||||
# Use this to manually inspect USDs (e.g. drag the Go2 USD into the stage,
|
||||
# expand link tree, view collision meshes).
|
||||
#
|
||||
# Usage:
|
||||
# ./scripts/open_isaacsim_gui.sh
|
||||
#
|
||||
# To open the Go2 USD inside the GUI:
|
||||
# 1. File -> Open -> paste the URL printed below into the file picker
|
||||
# 2. Or drag it from the Content browser (left panel):
|
||||
# Robots/Unitree/Go2/go2.usd
|
||||
set -e
|
||||
|
||||
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
|
||||
xhost +local:root >/dev/null 2>&1 || xhost +local:docker >/dev/null 2>&1 || true
|
||||
|
||||
cat <<EOF
|
||||
[host] DISPLAY=${DISPLAY:-:1}
|
||||
[host] Launching Isaac Sim GUI from sru-nav:latest ...
|
||||
|
||||
To inspect the Go2 USD once GUI is up, look under the Content browser:
|
||||
omniverse://localhost/NVIDIA/Assets/Isaac/<ver>/Isaac/Robots/Unitree/Go2/go2.usd
|
||||
or via the cloud asset path used by IsaacLab:
|
||||
\$ISAACLAB_NUCLEUS_DIR/Robots/Unitree/Go2/go2.usd
|
||||
|
||||
EOF
|
||||
|
||||
docker run --rm --gpus all \
|
||||
-e ACCEPT_EULA=Y -e PRIVACY_CONSENT=Y \
|
||||
-e DISPLAY="${DISPLAY:-:1}" \
|
||||
-e PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
|
||||
--shm-size=16g --network host --ipc host \
|
||||
--ulimit memlock=-1 --ulimit stack=67108864 \
|
||||
-v /tmp/.X11-unix:/tmp/.X11-unix:rw \
|
||||
-v "$HOME/.Xauthority:/root/.Xauthority:ro" \
|
||||
-v "$REPO_ROOT/outputs/logs:/workspace/IsaacLab/logs" \
|
||||
-v "$REPO_ROOT/mount/sru-navigation-sim:/workspace/IsaacLab/source/isaaclab_nav_task" \
|
||||
--entrypoint bash sru-nav:latest -lc \
|
||||
"/isaac-sim/isaac-sim.sh"
|
||||
Executable
+120
@@ -0,0 +1,120 @@
|
||||
#!/usr/bin/env bash
|
||||
# Visualize / evaluate a TorchScript JIT navigation policy (e.g. the official
|
||||
# upstream B2W baseline ``nav_policy_new.pt``) in the IsaacLab pure-maze env.
|
||||
#
|
||||
# Examples:
|
||||
# # GUI viewer, 4 envs, paper-style classic maze
|
||||
# PLAY_CLASSIC_MAZE=1 PLAY_DIFFICULTY="0.8,1.0" \
|
||||
# ./scripts/play_b2w_jit.sh --jit-policy assets/baselines/b2w_nav_policy_new.pt
|
||||
#
|
||||
# # Headless stats run (no GUI)
|
||||
# PLAY_CLASSIC_MAZE=1 PLAY_DIFFICULTY="0.8,1.0" \
|
||||
# ./scripts/play_b2w_jit.sh \
|
||||
# --jit-policy assets/baselines/b2w_nav_policy_new.pt \
|
||||
# --headless --envs 32 --steps 2000
|
||||
set -euo pipefail
|
||||
|
||||
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
|
||||
# ---- defaults (GUI-friendly) ----
|
||||
TASK="Isaac-Nav-PPO-B2W-Play-v0"
|
||||
JIT_HOST=""
|
||||
NUM_ENVS=4
|
||||
STEPS=100000 # huge so the viewer just keeps running until user closes it
|
||||
SEED=42
|
||||
HEADLESS=0
|
||||
|
||||
usage() {
|
||||
cat <<EOF
|
||||
Usage: $(basename "$0") --jit-policy PATH [options]
|
||||
|
||||
Required:
|
||||
--jit-policy PATH Host path to TorchScript .pt policy
|
||||
(mounted into /workspace/baseline_policy.pt).
|
||||
|
||||
Options:
|
||||
--task NAME Gym task id (default: $TASK).
|
||||
--envs N Parallel envs (default: $NUM_ENVS — GUI-friendly).
|
||||
--steps N env.step() calls (default: $STEPS).
|
||||
--seed N (default: $SEED).
|
||||
--headless Run without GUI (faster, no X11).
|
||||
-h, --help Show this help.
|
||||
|
||||
Forwarded env vars (set on host):
|
||||
PLAY_DIFFICULTY="lo,hi" terrain difficulty band
|
||||
PLAY_SUBTERRAIN_MIX=... e.g. "maze=1,non_maze=0,pits=0"
|
||||
PLAY_MAZE_ONLY=1 100% maze sub-terrain
|
||||
PLAY_CELL_SIZE=2.0 m per maze cell (B2W needs >= ~1.5)
|
||||
PLAY_CLASSIC_MAZE=1 paper-style uniform walls
|
||||
EOF
|
||||
exit 0
|
||||
}
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--jit-policy) JIT_HOST="$2"; shift 2 ;;
|
||||
--task) TASK="$2"; shift 2 ;;
|
||||
--envs) NUM_ENVS="$2"; shift 2 ;;
|
||||
--steps) STEPS="$2"; shift 2 ;;
|
||||
--seed) SEED="$2"; shift 2 ;;
|
||||
--headless) HEADLESS=1; shift ;;
|
||||
-h|--help) usage ;;
|
||||
*) echo "[error] Unknown arg: $1" >&2; usage ;;
|
||||
esac
|
||||
done
|
||||
|
||||
[[ -z "$JIT_HOST" ]] && { echo "[error] --jit-policy is required." >&2; exit 1; }
|
||||
if [[ "$JIT_HOST" != /* ]]; then JIT_HOST="$REPO_ROOT/$JIT_HOST"; fi
|
||||
[[ -f "$JIT_HOST" ]] || { echo "[error] JIT file not found: $JIT_HOST" >&2; exit 1; }
|
||||
|
||||
JIT_CTR="/workspace/baseline_policy.pt"
|
||||
|
||||
# ---- GUI plumbing (same as play_go2.sh) ----
|
||||
EXTRA_DOCKER_ARGS=()
|
||||
HEADLESS_FLAG=""
|
||||
if [[ "$HEADLESS" == "0" ]]; then
|
||||
xhost +local:root >/dev/null 2>&1 || xhost +local:docker >/dev/null 2>&1 || true
|
||||
EXTRA_DOCKER_ARGS+=(-e "DISPLAY=${DISPLAY:-:1}"
|
||||
-v /tmp/.X11-unix:/tmp/.X11-unix:rw
|
||||
-v "$HOME/.Xauthority:/root/.Xauthority:ro")
|
||||
else
|
||||
HEADLESS_FLAG="--headless"
|
||||
fi
|
||||
|
||||
cat <<EOF
|
||||
[play_b2w_jit] task = $TASK
|
||||
[play_b2w_jit] jit (host) = $JIT_HOST
|
||||
[play_b2w_jit] jit (ctr) = $JIT_CTR
|
||||
[play_b2w_jit] envs = $NUM_ENVS
|
||||
[play_b2w_jit] steps = $STEPS
|
||||
[play_b2w_jit] headless = $HEADLESS
|
||||
[play_b2w_jit] PLAY_DIFFICULTY = ${PLAY_DIFFICULTY:-(default)}
|
||||
[play_b2w_jit] PLAY_SUBTERRAIN_MIX = ${PLAY_SUBTERRAIN_MIX:-(default)}
|
||||
[play_b2w_jit] PLAY_MAZE_ONLY = ${PLAY_MAZE_ONLY:-(default)}
|
||||
[play_b2w_jit] PLAY_CELL_SIZE = ${PLAY_CELL_SIZE:-(default)}
|
||||
[play_b2w_jit] PLAY_CLASSIC_MAZE = ${PLAY_CLASSIC_MAZE:-(default)}
|
||||
EOF
|
||||
|
||||
docker run --rm --gpus all \
|
||||
-e ACCEPT_EULA=Y -e PRIVACY_CONSENT=Y \
|
||||
-e PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
|
||||
-e PLAY_DIFFICULTY="${PLAY_DIFFICULTY:-}" \
|
||||
-e PLAY_SUBTERRAIN_MIX="${PLAY_SUBTERRAIN_MIX:-}" \
|
||||
-e PLAY_MAZE_ONLY="${PLAY_MAZE_ONLY:-}" \
|
||||
-e PLAY_CELL_SIZE="${PLAY_CELL_SIZE:-}" \
|
||||
-e PLAY_CLASSIC_MAZE="${PLAY_CLASSIC_MAZE:-}" \
|
||||
--shm-size=16g --network host --ipc host \
|
||||
--ulimit memlock=-1 --ulimit stack=67108864 \
|
||||
"${EXTRA_DOCKER_ARGS[@]}" \
|
||||
-v "$REPO_ROOT/outputs/logs:/workspace/IsaacLab/logs" \
|
||||
-v "$REPO_ROOT/mount/sru-navigation-sim:/workspace/IsaacLab/source/isaaclab_nav_task" \
|
||||
-v "$REPO_ROOT/mount/rsl_rl:/workspace/rsl_rl" \
|
||||
-v "$JIT_HOST:$JIT_CTR:ro" \
|
||||
--entrypoint bash sru-nav:latest -lc \
|
||||
"./isaaclab.sh -p source/isaaclab_nav_task/scripts/eval_jit_policy.py \
|
||||
--task $TASK \
|
||||
--num_envs $NUM_ENVS \
|
||||
--steps $STEPS \
|
||||
--seed $SEED \
|
||||
--jit_policy $JIT_CTR \
|
||||
$HEADLESS_FLAG"
|
||||
Executable
+162
@@ -0,0 +1,162 @@
|
||||
#!/usr/bin/env bash
|
||||
# Replay a trained Go2 SRU navigation policy in the Isaac Sim GUI.
|
||||
#
|
||||
# Examples:
|
||||
# # Latest run, latest checkpoint, 4 envs (default)
|
||||
# ./scripts/play_go2.sh
|
||||
#
|
||||
# # Specific iter from latest run
|
||||
# ./scripts/play_go2.sh --from-iter 1000
|
||||
#
|
||||
# # Specific iter from a specific run dir
|
||||
# ./scripts/play_go2.sh \
|
||||
# --run-dir 2026-06-12_09-32-44_resume_from_1000 \
|
||||
# --from-iter 50999
|
||||
#
|
||||
# # Pin an exact in-container checkpoint path
|
||||
# ./scripts/play_go2.sh --checkpoint \
|
||||
# /workspace/IsaacLab/logs/rsl_rl/go2_navigation_ppo_dev/<run>/model_500.pt
|
||||
#
|
||||
# # Headless replay (no GUI), e.g. on a server
|
||||
# ./scripts/play_go2.sh --from-iter 800 --headless --envs 1
|
||||
#
|
||||
# # Browse a different experiment dir (e.g. full PPO)
|
||||
# ./scripts/play_go2.sh --experiment go2_navigation_ppo_ft_from_b2w --from-iter 5000
|
||||
#
|
||||
# Notes:
|
||||
# * --run-dir is the timestamped folder name under
|
||||
# outputs/logs/rsl_rl/<experiment>/.
|
||||
# * If neither --run-dir nor --checkpoint is given, the latest run is picked.
|
||||
# * If --from-iter is omitted, the latest model_*.pt in the run dir is used.
|
||||
# * The Play task disables corruption / pushes / large terrain to make the
|
||||
# viewer behave well; that is decided by --task (default: Play-v0).
|
||||
set -euo pipefail
|
||||
|
||||
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
|
||||
# ---- defaults ----
|
||||
TASK="Isaac-Nav-PPO-Go2-Play-v0"
|
||||
EXPERIMENT="go2_navigation_ppo_dev"
|
||||
NUM_ENVS=4
|
||||
FROM_ITER=""
|
||||
RUN_DIR=""
|
||||
CHECKPOINT=""
|
||||
HEADLESS=0
|
||||
SEED=42
|
||||
EXPORT_ONNX=0
|
||||
EXPORT_JIT=0
|
||||
|
||||
usage() {
|
||||
sed -n '1,30p' "$0"
|
||||
echo
|
||||
echo "Flags:"
|
||||
echo " --from-iter N Replay model_<N>.pt within the chosen run dir."
|
||||
echo " --run-dir NAME Run dir name under outputs/logs/rsl_rl/<experiment>/."
|
||||
echo " --checkpoint PATH Explicit IN-CONTAINER path (overrides --run-dir/--from-iter)."
|
||||
echo " --task NAME Gym task id (default: $TASK)."
|
||||
echo " --experiment NAME Log subdir (default: $EXPERIMENT)."
|
||||
echo " --envs N Parallel envs (default: $NUM_ENVS)."
|
||||
echo " --seed N Seed (default: $SEED)."
|
||||
echo " --headless Run without GUI (faster, no X11)."
|
||||
echo " --export-onnx Also export policy to <run-dir>/export/policy.onnx."
|
||||
echo " --export-jit Also export policy to <run-dir>/export/policy.pt (TorchScript)."
|
||||
echo " -h, --help Show this help."
|
||||
exit 0
|
||||
}
|
||||
|
||||
# ---- arg parsing ----
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--from-iter) FROM_ITER="$2"; shift 2 ;;
|
||||
--run-dir) RUN_DIR="$2"; shift 2 ;;
|
||||
--checkpoint) CHECKPOINT="$2"; shift 2 ;;
|
||||
--task) TASK="$2"; shift 2 ;;
|
||||
--experiment) EXPERIMENT="$2"; shift 2 ;;
|
||||
--envs) NUM_ENVS="$2"; shift 2 ;;
|
||||
--seed) SEED="$2"; shift 2 ;;
|
||||
--headless) HEADLESS=1; shift ;;
|
||||
--export-onnx) EXPORT_ONNX=1; shift ;;
|
||||
--export-jit) EXPORT_JIT=1; shift ;;
|
||||
-h|--help) usage ;;
|
||||
*) echo "[error] Unknown arg: $1" >&2; usage ;;
|
||||
esac
|
||||
done
|
||||
|
||||
HOST_LOG_ROOT="$REPO_ROOT/outputs/logs/rsl_rl/$EXPERIMENT"
|
||||
|
||||
# ---- resolve checkpoint ----
|
||||
if [[ -z "$CHECKPOINT" ]]; then
|
||||
if [[ -z "$RUN_DIR" ]]; then
|
||||
RUN_DIR="$(ls -1 "$HOST_LOG_ROOT" 2>/dev/null | sort | tail -n 1 || true)"
|
||||
[[ -z "$RUN_DIR" ]] && { echo "[error] No runs under $HOST_LOG_ROOT" >&2; exit 1; }
|
||||
fi
|
||||
RUN_PATH="$HOST_LOG_ROOT/$RUN_DIR"
|
||||
[[ -d "$RUN_PATH" ]] || { echo "[error] Run dir not found: $RUN_PATH" >&2; exit 1; }
|
||||
|
||||
if [[ -n "$FROM_ITER" ]]; then
|
||||
HOST_CKPT="$RUN_PATH/model_${FROM_ITER}.pt"
|
||||
if [[ ! -f "$HOST_CKPT" ]]; then
|
||||
echo "[error] Checkpoint not found: $HOST_CKPT" >&2
|
||||
echo "[hint] Available iters in $RUN_DIR:" >&2
|
||||
ls -1 "$RUN_PATH"/model_*.pt 2>/dev/null \
|
||||
| sed -nE 's/.*model_([0-9]+)\.pt/ \1/p' \
|
||||
| paste -sd ' ' >&2
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
HOST_CKPT="$(ls -1 "$RUN_PATH"/model_*.pt 2>/dev/null | sort -V | tail -n 1)"
|
||||
[[ -z "$HOST_CKPT" ]] && { echo "[error] No model_*.pt in $RUN_PATH" >&2; exit 1; }
|
||||
fi
|
||||
CHECKPOINT="${HOST_CKPT/$REPO_ROOT\/outputs\/logs/\/workspace\/IsaacLab\/logs}"
|
||||
else
|
||||
HOST_CKPT="${CHECKPOINT/\/workspace\/IsaacLab\/logs/$REPO_ROOT\/outputs\/logs}"
|
||||
fi
|
||||
|
||||
# ---- GUI plumbing ----
|
||||
EXTRA_DOCKER_ARGS=()
|
||||
HEADLESS_FLAG=""
|
||||
if [[ "$HEADLESS" == "0" ]]; then
|
||||
xhost +local:root >/dev/null 2>&1 || xhost +local:docker >/dev/null 2>&1 || true
|
||||
EXTRA_DOCKER_ARGS+=(-e "DISPLAY=${DISPLAY:-:1}"
|
||||
-v /tmp/.X11-unix:/tmp/.X11-unix:rw
|
||||
-v "$HOME/.Xauthority:/root/.Xauthority:ro")
|
||||
else
|
||||
HEADLESS_FLAG="--headless"
|
||||
fi
|
||||
|
||||
cat <<EOF
|
||||
[play_go2] task = $TASK
|
||||
[play_go2] experiment = $EXPERIMENT
|
||||
[play_go2] checkpoint = $CHECKPOINT
|
||||
[play_go2] host file = $HOST_CKPT
|
||||
[play_go2] envs = $NUM_ENVS
|
||||
[play_go2] headless = $HEADLESS
|
||||
EOF
|
||||
|
||||
docker run --rm --gpus all \
|
||||
-e ACCEPT_EULA=Y -e PRIVACY_CONSENT=Y \
|
||||
-e PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
|
||||
-e PLAY_DIFFICULTY="${PLAY_DIFFICULTY:-}" \
|
||||
-e PLAY_SUBTERRAIN_MIX="${PLAY_SUBTERRAIN_MIX:-}" \
|
||||
-e PLAY_MAZE_ONLY="${PLAY_MAZE_ONLY:-}" \
|
||||
-e PLAY_CELL_SIZE="${PLAY_CELL_SIZE:-}" \
|
||||
-e PLAY_CLASSIC_MAZE="${PLAY_CLASSIC_MAZE:-}" \
|
||||
-e PUREMAZE_DIFFICULTY="${PUREMAZE_DIFFICULTY:-}" \
|
||||
-e PUREMAZE_CELL_SIZE="${PUREMAZE_CELL_SIZE:-}" \
|
||||
-e PUREMAZE_NUM_ROWS="${PUREMAZE_NUM_ROWS:-}" \
|
||||
-e PUREMAZE_NUM_COLS="${PUREMAZE_NUM_COLS:-}" \
|
||||
--shm-size=16g --network host --ipc host \
|
||||
--ulimit memlock=-1 --ulimit stack=67108864 \
|
||||
"${EXTRA_DOCKER_ARGS[@]}" \
|
||||
-v "$REPO_ROOT/outputs/logs:/workspace/IsaacLab/logs" \
|
||||
-v "$REPO_ROOT/mount/sru-navigation-sim:/workspace/IsaacLab/source/isaaclab_nav_task" \
|
||||
-v "$REPO_ROOT/mount/rsl_rl:/workspace/rsl_rl" \
|
||||
--entrypoint bash sru-nav:latest -lc \
|
||||
"./isaaclab.sh -p source/isaaclab_nav_task/scripts/play.py \
|
||||
--task $TASK \
|
||||
--num_envs $NUM_ENVS \
|
||||
--seed $SEED \
|
||||
--checkpoint $CHECKPOINT \
|
||||
$HEADLESS_FLAG \
|
||||
$([[ $EXPORT_ONNX == 1 ]] && echo --export_onnx) \
|
||||
$([[ $EXPORT_JIT == 1 ]] && echo --export_jit)"
|
||||
Executable
+64
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env bash
|
||||
# Replay a trained Go2 navigation policy in the Isaac Sim GUI (X11 forwarded).
|
||||
#
|
||||
# Usage:
|
||||
# ./scripts/play_go2_gui.sh # latest dev run, 4 envs
|
||||
# NUM_ENVS=8 ./scripts/play_go2_gui.sh
|
||||
# CHECKPOINT=/workspace/IsaacLab/logs/rsl_rl/go2_navigation_ppo_dev/2026-06-12_06-25-41/model_33.pt \
|
||||
# ./scripts/play_go2_gui.sh
|
||||
#
|
||||
# The CHECKPOINT path must be the IN-CONTAINER path (under /workspace/IsaacLab/logs/...).
|
||||
set -e
|
||||
|
||||
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
|
||||
NUM_ENVS="${NUM_ENVS:-4}"
|
||||
TASK="${TASK:-Isaac-Nav-PPO-Go2-Play-v0}"
|
||||
# Which experiment subdir to scan when CHECKPOINT not given. Override with
|
||||
# EXPERIMENT=go2_navigation_ppo_puremaze for P0 / maze runs.
|
||||
EXPERIMENT="${EXPERIMENT:-go2_navigation_ppo_dev}"
|
||||
|
||||
# Auto-pick the latest checkpoint under <EXPERIMENT> if none was provided.
|
||||
if [[ -z "${CHECKPOINT:-}" ]]; then
|
||||
HOST_LOG_ROOT="$REPO_ROOT/outputs/logs/rsl_rl/$EXPERIMENT"
|
||||
LATEST_RUN="$(ls -1 "$HOST_LOG_ROOT" 2>/dev/null | sort | tail -n 1 || true)"
|
||||
if [[ -z "$LATEST_RUN" ]]; then
|
||||
echo "[error] No runs found under $HOST_LOG_ROOT and no CHECKPOINT given." >&2
|
||||
exit 1
|
||||
fi
|
||||
LATEST_CKPT="$(ls -1 "$HOST_LOG_ROOT/$LATEST_RUN"/model_*.pt 2>/dev/null | sort -V | tail -n 1)"
|
||||
if [[ -z "$LATEST_CKPT" ]]; then
|
||||
echo "[error] No model_*.pt found in $HOST_LOG_ROOT/$LATEST_RUN" >&2
|
||||
exit 1
|
||||
fi
|
||||
# Map host path -> in-container path.
|
||||
CHECKPOINT="${LATEST_CKPT/$REPO_ROOT\/outputs\/logs/\/workspace\/IsaacLab\/logs}"
|
||||
fi
|
||||
|
||||
xhost +local:root >/dev/null 2>&1 || xhost +local:docker >/dev/null 2>&1 || true
|
||||
|
||||
echo "[host] DISPLAY=${DISPLAY:-:1}"
|
||||
echo "[host] task=$TASK num_envs=$NUM_ENVS"
|
||||
echo "[host] checkpoint (in container) = $CHECKPOINT"
|
||||
|
||||
docker run --rm --gpus all \
|
||||
-e ACCEPT_EULA=Y -e PRIVACY_CONSENT=Y \
|
||||
-e DISPLAY="${DISPLAY:-:1}" \
|
||||
-e PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
|
||||
-e PLAY_DIFFICULTY="${PLAY_DIFFICULTY:-}" \
|
||||
-e PLAY_CELL_SIZE="${PLAY_CELL_SIZE:-}" \
|
||||
-e PLAY_MAZE_ONLY="${PLAY_MAZE_ONLY:-}" \
|
||||
-e PLAY_CLASSIC_MAZE="${PLAY_CLASSIC_MAZE:-}" \
|
||||
-e PLAY_SUBTERRAIN_MIX="${PLAY_SUBTERRAIN_MIX:-}" \
|
||||
--shm-size=16g --network host --ipc host \
|
||||
--ulimit memlock=-1 --ulimit stack=67108864 \
|
||||
-v /tmp/.X11-unix:/tmp/.X11-unix:rw \
|
||||
-v "$HOME/.Xauthority:/root/.Xauthority:ro" \
|
||||
-v "$REPO_ROOT/outputs/logs:/workspace/IsaacLab/logs" \
|
||||
-v "$REPO_ROOT/mount/sru-navigation-sim:/workspace/IsaacLab/source/isaaclab_nav_task" \
|
||||
-v "$REPO_ROOT/mount/rsl_rl:/workspace/rsl_rl" \
|
||||
--entrypoint bash sru-nav:latest -lc \
|
||||
"./isaaclab.sh -p source/isaaclab_nav_task/scripts/play.py \
|
||||
--task $TASK \
|
||||
--num_envs $NUM_ENVS \
|
||||
--checkpoint $CHECKPOINT"
|
||||
@@ -0,0 +1,224 @@
|
||||
"""Diagnose a TorchScript locomotion .pt file's interface.
|
||||
|
||||
Run inside the sru-nav container; mount this script at /tmp/probe_pt.py.
|
||||
|
||||
Reports:
|
||||
1. TorchScript graph code (top-level forward signature)
|
||||
2. State-dict key names + shapes (gives clues about layer order / obs slicing)
|
||||
3. Tries common observation dimensions to find the input width
|
||||
4. Output dimension (= number of joint targets the policy emits)
|
||||
5. A quick "what zero input produces" check (sanity for output range)
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import torch
|
||||
|
||||
DEFAULT_PT = (
|
||||
"/workspace/IsaacLab/source/isaaclab_nav_task/isaaclab_nav_task/"
|
||||
"navigation/assets/data/Policies/locomotion/go2/policy_go2.pt"
|
||||
)
|
||||
PT_PATH = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_PT
|
||||
|
||||
assert os.path.isfile(PT_PATH), f"File not found: {PT_PATH}"
|
||||
print(f"[probe] loading: {PT_PATH}")
|
||||
print(f"[probe] file size: {os.path.getsize(PT_PATH) / 1e6:.2f} MB")
|
||||
|
||||
device = "cuda" if torch.cuda.is_available() else "cpu"
|
||||
print(f"[probe] device: {device}")
|
||||
|
||||
is_torchscript = False
|
||||
model = None
|
||||
raw_obj = None
|
||||
try:
|
||||
model = torch.jit.load(PT_PATH, map_location=device)
|
||||
model.eval()
|
||||
is_torchscript = True
|
||||
print(f"[probe] format: TorchScript ✓")
|
||||
print(f"[probe] type: {type(model).__name__}")
|
||||
except Exception as e:
|
||||
print(f"[probe] torch.jit.load FAILED: {str(e).splitlines()[0][:120]}")
|
||||
print(f"[probe] → falling back to torch.load() (pickle)")
|
||||
try:
|
||||
raw_obj = torch.load(PT_PATH, map_location=device, weights_only=False)
|
||||
print(f"[probe] format: pickle (torch.save) — NOT TorchScript")
|
||||
print(f"[probe] top-level type: {type(raw_obj).__name__}")
|
||||
except Exception as e2:
|
||||
print(f"[probe] torch.load ALSO failed: {e2}")
|
||||
sys.exit(1)
|
||||
|
||||
if not is_torchscript:
|
||||
print("\n=========================================================")
|
||||
print(" ⚠ This file is NOT a TorchScript model.")
|
||||
print(" sru-navigation-sim calls `torch.jit.load(.pt)` which will fail.")
|
||||
print(" You need to either:")
|
||||
print(" (a) Re-export your policy with torch.jit.script(model).save(...)")
|
||||
print(" (b) Provide the original nn.Module class so we wrap+script it")
|
||||
print("=========================================================\n")
|
||||
|
||||
# Inspect the loaded object
|
||||
print("=========================================================")
|
||||
print(" Contents of torch.load() output")
|
||||
print("=========================================================")
|
||||
if isinstance(raw_obj, dict):
|
||||
print(f" dict with {len(raw_obj)} top-level keys:")
|
||||
for k, v in raw_obj.items():
|
||||
t = type(v).__name__
|
||||
extra = ""
|
||||
if isinstance(v, torch.Tensor):
|
||||
extra = f" shape={tuple(v.shape)} dtype={v.dtype}"
|
||||
elif isinstance(v, dict):
|
||||
extra = f" ({len(v)} sub-keys)"
|
||||
print(f" [{k!r}] {t}{extra}")
|
||||
# If it has 'model_state_dict' or 'state_dict' or is itself a state_dict, dump shapes
|
||||
sd = None
|
||||
for key in ["model_state_dict", "state_dict", "model", "policy"]:
|
||||
if key in raw_obj and isinstance(raw_obj[key], dict):
|
||||
sd = raw_obj[key]
|
||||
print(f"\n → Found state-dict under key {key!r}")
|
||||
break
|
||||
if sd is None and all(isinstance(v, torch.Tensor) for v in raw_obj.values()):
|
||||
sd = raw_obj
|
||||
print(f"\n → Top-level dict appears to be a state_dict itself")
|
||||
if sd is not None:
|
||||
print(f"\n State-dict keys & shapes ({len(sd)} entries):")
|
||||
for i, (k, v) in enumerate(sd.items()):
|
||||
shape = tuple(v.shape) if isinstance(v, torch.Tensor) else type(v).__name__
|
||||
print(f" [{i:2d}] {k:60s} {shape}")
|
||||
if i >= 50:
|
||||
print(f" ... ({len(sd) - 51} more)")
|
||||
break
|
||||
# First Linear's in_features
|
||||
first_linear_in = None
|
||||
for k, v in sd.items():
|
||||
if isinstance(v, torch.Tensor) and v.ndim == 2 and "weight" in k.lower():
|
||||
first_linear_in = v.shape[1]
|
||||
print(f"\n → first 2D-weight key {k!r} has in_features = {first_linear_in}")
|
||||
print(f" most likely D_obs = {first_linear_in}")
|
||||
break
|
||||
# Last Linear's out_features
|
||||
last_linear_out = None
|
||||
last_linear_key = None
|
||||
for k, v in sd.items():
|
||||
if isinstance(v, torch.Tensor) and v.ndim == 2 and "weight" in k.lower():
|
||||
last_linear_out = v.shape[0]
|
||||
last_linear_key = k
|
||||
if last_linear_out is not None:
|
||||
print(f" → last 2D-weight key {last_linear_key!r} has out_features = {last_linear_out}")
|
||||
print(f" most likely action_dim = {last_linear_out}")
|
||||
elif isinstance(raw_obj, torch.nn.Module):
|
||||
print(f" → It's a raw nn.Module instance (untraced). Class: {type(raw_obj).__name__}")
|
||||
print(f" → We can try to forward it directly without TorchScript.")
|
||||
model = raw_obj
|
||||
model.eval()
|
||||
is_torchscript = False
|
||||
else:
|
||||
print(f" (unsupported type: {type(raw_obj)})")
|
||||
print("\n[probe] done — see message above for next steps.")
|
||||
sys.exit(0)
|
||||
|
||||
print("\n=========================================================")
|
||||
print("1. TorchScript .code (forward signature & top-level graph)")
|
||||
print("=========================================================")
|
||||
try:
|
||||
code = getattr(model, "code", None)
|
||||
if code is None:
|
||||
print("(no .code attribute -- model may be a ScriptFunction)")
|
||||
else:
|
||||
print(code[:4000])
|
||||
except Exception as e:
|
||||
print(f"(error reading .code: {e})")
|
||||
|
||||
print("\n=========================================================")
|
||||
print("2. State dict keys & shapes")
|
||||
print("=========================================================")
|
||||
sd = model.state_dict()
|
||||
print(f"total params: {sum(v.numel() for v in sd.values()):,}")
|
||||
for i, (k, v) in enumerate(sd.items()):
|
||||
print(f" [{i:2d}] {k:60s} {tuple(v.shape)}")
|
||||
if i >= 40:
|
||||
print(f" ... ({len(sd) - 41} more)")
|
||||
break
|
||||
|
||||
# First Linear layer's input dim is a strong hint for D_obs
|
||||
first_weight = next(
|
||||
(v for k, v in sd.items() if v.ndim == 2 and ("weight" in k or k.endswith(".weight"))),
|
||||
None,
|
||||
)
|
||||
hint_obs = first_weight.shape[1] if first_weight is not None else None
|
||||
if hint_obs is not None:
|
||||
print(f"\n[probe] first Linear weight has in_features = {hint_obs}")
|
||||
print(f" → most likely D_obs = {hint_obs}")
|
||||
|
||||
print("\n=========================================================")
|
||||
print("3. Trying input dimensions (looking for the one that works)")
|
||||
print("=========================================================")
|
||||
# Common Go2 obs dims:
|
||||
# 33 = 3+3+3+3+12+12 (no last_action)
|
||||
# 45 = 3+3+3+3+12+12+12 (with last_action of joint dim)
|
||||
# 48 = 3+3+3+3+12+12+12+3 (with last_action including vel cmd)
|
||||
# 52 = 3+3+3+3+12+12+16 (sru-nav-sim LowLevelPolicyCfg, with B2W-style last_action=16)
|
||||
# 60 = 3+3+3+3+12+12+12+12 (joint pos+vel+pos+vel duplicated)
|
||||
# 235 = with height_scan (legged_gym style)
|
||||
candidate_dims = [33, 36, 39, 42, 45, 48, 51, 52, 60, 96, 235]
|
||||
if hint_obs is not None and hint_obs not in candidate_dims:
|
||||
candidate_dims.insert(0, hint_obs)
|
||||
|
||||
working_dims = []
|
||||
for d in candidate_dims:
|
||||
try:
|
||||
with torch.inference_mode():
|
||||
out = model(torch.zeros(2, d, device=device))
|
||||
if isinstance(out, tuple):
|
||||
shapes = [tuple(o.shape) for o in out if isinstance(o, torch.Tensor)]
|
||||
print(f" D_obs = {d:3d} ✓ (tuple output, shapes={shapes})")
|
||||
else:
|
||||
print(f" D_obs = {d:3d} ✓ output shape = {tuple(out.shape)}")
|
||||
working_dims.append((d, tuple(out.shape)))
|
||||
except Exception as e:
|
||||
msg = str(e).split("\n")[0][:90]
|
||||
print(f" D_obs = {d:3d} ✗ {msg}")
|
||||
|
||||
print("\n=========================================================")
|
||||
print("4. Summary")
|
||||
print("=========================================================")
|
||||
if not working_dims:
|
||||
print(" ⚠ NO standard input dim worked.")
|
||||
print(" → Inspect step-2 first-Linear in_features and try that exact size.")
|
||||
print(f" → Expected: D_obs = {hint_obs}")
|
||||
else:
|
||||
for d, out_shape in working_dims:
|
||||
n_out = out_shape[1] if len(out_shape) >= 2 else None
|
||||
print(f" D_obs = {d}, output_dim = {n_out}")
|
||||
if n_out == 12:
|
||||
print(" → 12 outputs = pure leg joint targets (Go2 has 12 leg joints).")
|
||||
print(" You'll use `low_level_velocity_action = None` (the patched action term).")
|
||||
elif n_out == 16:
|
||||
print(" → 16 outputs matches B2W layout (12 legs + 4 wheels).")
|
||||
print(" Adapter must zero-pad if your Go2 only emits 12.")
|
||||
elif n_out == 18:
|
||||
print(" → 18 outputs = 12 legs + something extra (maybe 6 dummy?).")
|
||||
else:
|
||||
print(f" → {n_out} outputs is unusual; verify against your training task.")
|
||||
|
||||
print("\n=========================================================")
|
||||
print("5. Probing zero-input output magnitude (sanity)")
|
||||
print("=========================================================")
|
||||
if working_dims:
|
||||
d, _ = working_dims[0]
|
||||
with torch.inference_mode():
|
||||
out = model(torch.zeros(1, d, device=device))
|
||||
if isinstance(out, torch.Tensor):
|
||||
print(f" output[0] (first 12 dims): "
|
||||
f"{out[0, :12].cpu().numpy().round(3).tolist()}")
|
||||
print(f" output stats: mean={out.mean().item():.3f}, "
|
||||
f"std={out.std().item():.3f}, "
|
||||
f"min={out.min().item():.3f}, max={out.max().item():.3f}")
|
||||
if out.abs().max() > 5.0:
|
||||
print(" ⚠ Output magnitude > 5; policy likely emits raw joint angles or torques.")
|
||||
print(" Standard IsaacLab convention: tanh-bounded ∈ [-1, 1].")
|
||||
elif out.abs().max() < 0.05:
|
||||
print(" ⚠ Output extremely small; may be a state_dict-only file (not a working policy).")
|
||||
else:
|
||||
print(" ✓ Output magnitude looks reasonable.")
|
||||
print("\n[probe] done")
|
||||
Executable
+38
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env bash
|
||||
# Run probe_pt.py inside the sru-nav container against the Go2 locomotion .pt.
|
||||
# Usage:
|
||||
# ./scripts/probe_pt.sh # uses default path under mount/
|
||||
# ./scripts/probe_pt.sh /custom/path/in/host # absolute host path
|
||||
set -e
|
||||
|
||||
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
HOST_PT="${1:-$REPO_ROOT/mount/sru-navigation-sim/isaaclab_nav_task/navigation/assets/data/Policies/locomotion/go2/policy_go2.pt}"
|
||||
|
||||
if [[ ! -f "$HOST_PT" ]]; then
|
||||
echo "ERROR: .pt not found at: $HOST_PT"
|
||||
echo " Copy your Go2 locomotion .pt there first."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "[host] probing: $HOST_PT"
|
||||
echo "[host] file size: $(du -h "$HOST_PT" | cut -f1)"
|
||||
|
||||
# Translate the host path to the corresponding container path (the mount).
|
||||
HOST_NAV_SIM="$REPO_ROOT/mount/sru-navigation-sim"
|
||||
CONTAINER_NAV_SIM="/workspace/IsaacLab/source/isaaclab_nav_task"
|
||||
if [[ "$HOST_PT" == "$HOST_NAV_SIM"/* ]]; then
|
||||
CONTAINER_PT="${HOST_PT/$HOST_NAV_SIM/$CONTAINER_NAV_SIM}"
|
||||
else
|
||||
echo "ERROR: .pt must live under $HOST_NAV_SIM (the live-mounted folder)."
|
||||
echo " Got: $HOST_PT"
|
||||
exit 1
|
||||
fi
|
||||
echo "[host] container path: $CONTAINER_PT"
|
||||
|
||||
docker run --rm --gpus all \
|
||||
-e ACCEPT_EULA=Y -e PRIVACY_CONSENT=Y \
|
||||
--shm-size=4g --ipc host \
|
||||
-v "$REPO_ROOT/scripts/probe_pt.py:/tmp/probe_pt.py:ro" \
|
||||
-v "$REPO_ROOT/mount/sru-navigation-sim:/workspace/IsaacLab/source/isaaclab_nav_task" \
|
||||
--entrypoint bash sru-nav:latest -lc \
|
||||
"/workspace/IsaacLab/_isaac_sim/python.sh /tmp/probe_pt.py '$CONTAINER_PT'"
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/usr/bin/env bash
|
||||
set -e
|
||||
cd /workspace/IsaacLab
|
||||
./isaaclab.sh -p source/isaaclab_nav_task/scripts/train.py \
|
||||
--task Isaac-Nav-MDPO-AoW-D-v0 \
|
||||
--num_envs ${NUM_ENVS:-2048} \
|
||||
--max_iterations ${MAX_ITERS:-10000} \
|
||||
--headless \
|
||||
"$@"
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/usr/bin/env bash
|
||||
# Quick dev/smoke-test (300 iters, tensorboard).
|
||||
set -e
|
||||
cd /workspace/IsaacLab
|
||||
./isaaclab.sh -p source/isaaclab_nav_task/scripts/train.py \
|
||||
--task Isaac-Nav-PPO-B2W-Dev-v0 \
|
||||
--num_envs ${NUM_ENVS:-32} \
|
||||
--headless \
|
||||
"$@"
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/usr/bin/env bash
|
||||
# Run inside the container.
|
||||
set -e
|
||||
cd /workspace/IsaacLab
|
||||
./isaaclab.sh -p source/isaaclab_nav_task/scripts/train.py \
|
||||
--task Isaac-Nav-PPO-B2W-v0 \
|
||||
--num_envs ${NUM_ENVS:-4096} \
|
||||
--headless \
|
||||
"$@"
|
||||
Executable
+78
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env bash
|
||||
# Continue training the Go2 SRU navigation policy from the latest dev checkpoint.
|
||||
#
|
||||
# Defaults: headless (no GUI for speed), Dev task (same cfg as the previous
|
||||
# 33-iter run), warm-start with optimizer state so PPO truly resumes.
|
||||
#
|
||||
# Usage:
|
||||
# ./scripts/train_go2_continue.sh # 1000 iter, 24 envs
|
||||
# NUM_ENVS=32 MAX_ITER=2000 ./scripts/train_go2_continue.sh
|
||||
# CHECKPOINT=/workspace/IsaacLab/logs/.../model_33.pt ./scripts/train_go2_continue.sh
|
||||
# GUI=1 ./scripts/train_go2_continue.sh # show Isaac Sim GUI
|
||||
# TASK=Isaac-Nav-PPO-Go2-v0 ./scripts/train_go2_continue.sh # full PPO task (5000 iter cap)
|
||||
#
|
||||
# Notes:
|
||||
# * CHECKPOINT must be the IN-CONTAINER path under /workspace/IsaacLab/logs/...
|
||||
# * --load_optimizer keeps PPO momentum / adaptive-LR state, so loss curves
|
||||
# look continuous instead of restarting cold.
|
||||
# * RTX 5070 has 12 GB VRAM. 24 envs headless is conservative; tune up if free.
|
||||
set -e
|
||||
|
||||
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
|
||||
NUM_ENVS="${NUM_ENVS:-24}"
|
||||
MAX_ITER="${MAX_ITER:-1000}"
|
||||
TASK="${TASK:-Isaac-Nav-PPO-Go2-Dev-v0}"
|
||||
GUI="${GUI:-0}"
|
||||
SEED="${SEED:-42}"
|
||||
RUN_NAME="${RUN_NAME:-resume_from_33}"
|
||||
|
||||
# Auto-pick the latest dev checkpoint if none provided.
|
||||
if [[ -z "${CHECKPOINT:-}" ]]; then
|
||||
HOST_LOG_ROOT="$REPO_ROOT/outputs/logs/rsl_rl/go2_navigation_ppo_dev"
|
||||
LATEST_RUN="$(ls -1 "$HOST_LOG_ROOT" 2>/dev/null | sort | tail -n 1 || true)"
|
||||
if [[ -z "$LATEST_RUN" ]]; then
|
||||
echo "[error] No previous runs under $HOST_LOG_ROOT and no CHECKPOINT given." >&2
|
||||
exit 1
|
||||
fi
|
||||
LATEST_CKPT="$(ls -1 "$HOST_LOG_ROOT/$LATEST_RUN"/model_*.pt 2>/dev/null | sort -V | tail -n 1)"
|
||||
if [[ -z "$LATEST_CKPT" ]]; then
|
||||
echo "[error] No model_*.pt found in $HOST_LOG_ROOT/$LATEST_RUN" >&2
|
||||
exit 1
|
||||
fi
|
||||
CHECKPOINT="${LATEST_CKPT/$REPO_ROOT\/outputs\/logs/\/workspace\/IsaacLab\/logs}"
|
||||
fi
|
||||
|
||||
HEADLESS_FLAG="--headless"
|
||||
EXTRA_DOCKER_ARGS=()
|
||||
if [[ "$GUI" == "1" ]]; then
|
||||
HEADLESS_FLAG=""
|
||||
xhost +local:root >/dev/null 2>&1 || xhost +local:docker >/dev/null 2>&1 || true
|
||||
EXTRA_DOCKER_ARGS+=(-e "DISPLAY=${DISPLAY:-:1}"
|
||||
-v /tmp/.X11-unix:/tmp/.X11-unix:rw
|
||||
-v "$HOME/.Xauthority:/root/.Xauthority:ro")
|
||||
fi
|
||||
|
||||
echo "[host] task=$TASK num_envs=$NUM_ENVS max_iter=$MAX_ITER gui=$GUI"
|
||||
echo "[host] checkpoint (in container) = $CHECKPOINT"
|
||||
echo "[host] run_name=$RUN_NAME seed=$SEED"
|
||||
|
||||
docker run --rm --gpus all \
|
||||
-e ACCEPT_EULA=Y -e PRIVACY_CONSENT=Y \
|
||||
-e PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
|
||||
--shm-size=16g --network host --ipc host \
|
||||
--ulimit memlock=-1 --ulimit stack=67108864 \
|
||||
"${EXTRA_DOCKER_ARGS[@]}" \
|
||||
-v "$REPO_ROOT/outputs/logs:/workspace/IsaacLab/logs" \
|
||||
-v "$REPO_ROOT/mount/sru-navigation-sim:/workspace/IsaacLab/source/isaaclab_nav_task" \
|
||||
-v "$REPO_ROOT/mount/rsl_rl:/workspace/rsl_rl" \
|
||||
--entrypoint bash sru-nav:latest -lc \
|
||||
"./isaaclab.sh -p source/isaaclab_nav_task/scripts/train.py \
|
||||
--task $TASK \
|
||||
--num_envs $NUM_ENVS \
|
||||
--max_iterations $MAX_ITER \
|
||||
--seed $SEED \
|
||||
--run_name $RUN_NAME \
|
||||
--checkpoint $CHECKPOINT \
|
||||
--load_optimizer \
|
||||
$HEADLESS_FLAG"
|
||||
Executable
+39
@@ -0,0 +1,39 @@
|
||||
#!/usr/bin/env bash
|
||||
# Train Go2 nav with the Isaac Sim GUI visible (X11 forwarded from host).
|
||||
# Default: 30 iterations, small env count, so you can watch the dogs walking.
|
||||
#
|
||||
# Usage:
|
||||
# ./scripts/train_go2_gui.sh # 30 iter, 32 envs, GUI
|
||||
# NUM_ENVS=16 MAX_ITER=100 ./scripts/train_go2_gui.sh
|
||||
#
|
||||
set -e
|
||||
|
||||
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
|
||||
NUM_ENVS="${NUM_ENVS:-32}"
|
||||
MAX_ITER="${MAX_ITER:-30}"
|
||||
TASK="${TASK:-Isaac-Nav-PPO-Go2-Dev-v0}"
|
||||
|
||||
# Allow the docker user (any UID) to talk to the host X server.
|
||||
# This affects only the local user's X server.
|
||||
xhost +local:root >/dev/null 2>&1 || xhost +local:docker >/dev/null 2>&1 || true
|
||||
|
||||
echo "[host] DISPLAY=${DISPLAY:-:1}"
|
||||
echo "[host] task=$TASK num_envs=$NUM_ENVS max_iterations=$MAX_ITER"
|
||||
|
||||
docker run --rm --gpus all \
|
||||
-e ACCEPT_EULA=Y -e PRIVACY_CONSENT=Y \
|
||||
-e DISPLAY="${DISPLAY:-:1}" \
|
||||
-e PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
|
||||
--shm-size=16g --network host --ipc host \
|
||||
--ulimit memlock=-1 --ulimit stack=67108864 \
|
||||
-v /tmp/.X11-unix:/tmp/.X11-unix:rw \
|
||||
-v "$HOME/.Xauthority:/root/.Xauthority:ro" \
|
||||
-v "$REPO_ROOT/outputs/logs:/workspace/IsaacLab/logs" \
|
||||
-v "$REPO_ROOT/mount/sru-navigation-sim:/workspace/IsaacLab/source/isaaclab_nav_task" \
|
||||
-v "$REPO_ROOT/mount/rsl_rl:/workspace/rsl_rl" \
|
||||
--entrypoint bash sru-nav:latest -lc \
|
||||
"./isaaclab.sh -p source/isaaclab_nav_task/scripts/train.py \
|
||||
--task $TASK \
|
||||
--num_envs $NUM_ENVS \
|
||||
--max_iterations $MAX_ITER"
|
||||
Executable
+86
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env bash
|
||||
# Train the Go2 SRU navigation policy FROM SCRATCH (no checkpoint).
|
||||
#
|
||||
# Defaults: headless, 24 envs, 1000 iter, Dev task, seed=42.
|
||||
# Use this when you intentionally want a cold start (e.g. after sweeping
|
||||
# reward / action / terrain shaping where the previous policy mean has
|
||||
# collapsed into a degenerate solution and resuming would just re-learn it).
|
||||
#
|
||||
# Usage:
|
||||
# ./scripts/train_go2_scratch.sh # 1000 iter, 24 envs, headless
|
||||
# NUM_ENVS=16 MAX_ITER=500 ./scripts/train_go2_scratch.sh
|
||||
# GUI=1 NUM_ENVS=4 MAX_ITER=200 ./scripts/train_go2_scratch.sh
|
||||
# TASK=Isaac-Nav-PPO-Go2-v0 RUN_NAME=scratch_full ./scripts/train_go2_scratch.sh
|
||||
#
|
||||
# Notes:
|
||||
# * No --checkpoint flag is passed, so the agent + critic are re-initialised.
|
||||
# * RTX 5070 (12 GB VRAM): 24 envs headless is the safe default. GUI + 32
|
||||
# envs OOMs (G0.0 lesson).
|
||||
# * Output goes to outputs/logs/rsl_rl/<EXPERIMENT>/<timestamp>_<RUN_NAME>/.
|
||||
set -e
|
||||
|
||||
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
|
||||
NUM_ENVS="${NUM_ENVS:-24}"
|
||||
MAX_ITER="${MAX_ITER:-1000}"
|
||||
TASK="${TASK:-Isaac-Nav-PPO-Go2-Dev-v0}"
|
||||
GUI="${GUI:-0}"
|
||||
SEED="${SEED:-42}"
|
||||
RUN_NAME="${RUN_NAME:-scratch_reward_fix_v1}"
|
||||
# GPU selection. Set GPU=0 / GPU=1 / GPU=0,1 to pin specific cards.
|
||||
# Empty (default) = all visible GPUs (--gpus all). The container sees the selected
|
||||
# GPU(s) as cuda:0,cuda:1,... so the training process always uses cuda:0 inside.
|
||||
GPU="${GPU:-}"
|
||||
|
||||
GPU_FLAG="--gpus all"
|
||||
if [[ -n "$GPU" ]]; then
|
||||
GPU_FLAG="--gpus device=${GPU}"
|
||||
fi
|
||||
|
||||
HEADLESS_FLAG="--headless"
|
||||
EXTRA_DOCKER_ARGS=()
|
||||
if [[ "$GUI" == "1" ]]; then
|
||||
HEADLESS_FLAG=""
|
||||
xhost +local:root >/dev/null 2>&1 || xhost +local:docker >/dev/null 2>&1 || true
|
||||
EXTRA_DOCKER_ARGS+=(-e "DISPLAY=${DISPLAY:-:1}"
|
||||
-v /tmp/.X11-unix:/tmp/.X11-unix:rw
|
||||
-v "$HOME/.Xauthority:/root/.Xauthority:ro")
|
||||
fi
|
||||
|
||||
cat <<EOF
|
||||
[train_go2_scratch] task = $TASK
|
||||
[train_go2_scratch] num_envs = $NUM_ENVS
|
||||
[train_go2_scratch] max_iter = $MAX_ITER
|
||||
[train_go2_scratch] seed = $SEED
|
||||
[train_go2_scratch] run_name = $RUN_NAME
|
||||
[train_go2_scratch] gui = $GUI
|
||||
[train_go2_scratch] gpu = ${GPU:-all}
|
||||
[train_go2_scratch] (no --checkpoint: cold start)
|
||||
EOF
|
||||
|
||||
docker run --rm $GPU_FLAG \
|
||||
--name "go2_train_gpu${GPU:-all}_${RUN_NAME}_$$" \
|
||||
-e ACCEPT_EULA=Y -e PRIVACY_CONSENT=Y \
|
||||
-e PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
|
||||
-e DEV_DIFFICULTY="${DEV_DIFFICULTY:-}" \
|
||||
-e GO2_DIFFICULTY="${GO2_DIFFICULTY:-}" \
|
||||
-e GO2_INIT_LEVEL="${GO2_INIT_LEVEL:-}" \
|
||||
-e GO2_CELL_SIZE="${GO2_CELL_SIZE:-}" \
|
||||
-e PUREMAZE_DIFFICULTY="${PUREMAZE_DIFFICULTY:-}" \
|
||||
-e PUREMAZE_CELL_SIZE="${PUREMAZE_CELL_SIZE:-}" \
|
||||
-e PUREMAZE_NUM_ROWS="${PUREMAZE_NUM_ROWS:-}" \
|
||||
-e PUREMAZE_NUM_COLS="${PUREMAZE_NUM_COLS:-}" \
|
||||
--shm-size=16g --network host --ipc host \
|
||||
--ulimit memlock=-1 --ulimit stack=67108864 \
|
||||
"${EXTRA_DOCKER_ARGS[@]}" \
|
||||
-v "$REPO_ROOT/outputs/logs:/workspace/IsaacLab/logs" \
|
||||
-v "$REPO_ROOT/mount/sru-navigation-sim:/workspace/IsaacLab/source/isaaclab_nav_task" \
|
||||
-v "$REPO_ROOT/mount/rsl_rl:/workspace/rsl_rl" \
|
||||
--entrypoint bash sru-nav:latest -lc \
|
||||
"./isaaclab.sh -p source/isaaclab_nav_task/scripts/train.py \
|
||||
--task $TASK \
|
||||
--num_envs $NUM_ENVS \
|
||||
--max_iterations $MAX_ITER \
|
||||
--seed $SEED \
|
||||
--run_name $RUN_NAME \
|
||||
$HEADLESS_FLAG"
|
||||
@@ -0,0 +1,167 @@
|
||||
"""Validate that policy_go2_jit.pt produces correct Go2 locomotion inside the
|
||||
sru-navigation-sim environment, without any high-level navigation policy.
|
||||
|
||||
We feed hard-coded SE2 commands (vx, vy, omega) directly into env.step() and
|
||||
measure the actual base motion that results. This isolates the low-level
|
||||
locomotion contract from any navigation training.
|
||||
|
||||
Test sequence (each phase ~3 seconds):
|
||||
1. Stand still (0.0, 0.0, 0.0) -> expect: stays upright, ~0 velocity
|
||||
2. Forward walk (0.5, 0.0, 0.0) -> expect: moves +X, vx ~ 0.3 m/s
|
||||
3. Backward walk (-0.5, 0.0, 0.0) -> expect: moves -X, vx ~ -0.3 m/s
|
||||
4. Lateral right (0.0, 0.5, 0.0) -> expect: moves +Y (limited)
|
||||
5. Rotate (yaw) (0.0, 0.0, 0.5) -> expect: omega ~ 0.35 rad/s
|
||||
|
||||
Run:
|
||||
./isaaclab.sh -p /tmp/validate_go2_locomotion.py --num_envs 4 --headless
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
|
||||
from isaaclab.app import AppLauncher
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--task", default="Isaac-Nav-PPO-Go2-Dev-v0")
|
||||
parser.add_argument("--num_envs", type=int, default=4)
|
||||
parser.add_argument("--phase_seconds", type=float, default=3.0)
|
||||
AppLauncher.add_app_launcher_args(parser)
|
||||
args = parser.parse_args()
|
||||
args.headless = True
|
||||
args.enable_cameras = True # depth camera obs needed by env
|
||||
|
||||
app_launcher = AppLauncher(args)
|
||||
simulation_app = app_launcher.app
|
||||
|
||||
import torch # noqa: E402
|
||||
import gymnasium as gym # noqa: E402
|
||||
|
||||
import isaaclab_nav_task # noqa: F401, E402
|
||||
from isaaclab_tasks.utils.parse_cfg import parse_env_cfg # noqa: E402
|
||||
|
||||
|
||||
def main():
|
||||
env_cfg = parse_env_cfg(
|
||||
args.task, device="cuda:0", num_envs=args.num_envs, use_fabric=True
|
||||
)
|
||||
env = gym.make(args.task, cfg=env_cfg)
|
||||
print(f"[validate] action_space = {env.action_space}")
|
||||
print(f"[validate] observation_space (policy group) = "
|
||||
f"{env.observation_space['policy'].shape}")
|
||||
|
||||
obs, _ = env.reset()
|
||||
device = env.unwrapped.device
|
||||
|
||||
# Phase definitions: (label, command, num_steps)
|
||||
# The env decimation is 4 (low-level @ 50 Hz), and the high-level step is
|
||||
# called at 10 Hz (env.step). So phase_seconds * 10 = num steps.
|
||||
phase_steps = int(args.phase_seconds * 10)
|
||||
phases = [
|
||||
("stand_still", torch.tensor([ 0.0, 0.0, 0.0])),
|
||||
("forward", torch.tensor([ 0.7, 0.0, 0.0])),
|
||||
("backward", torch.tensor([-0.7, 0.0, 0.0])),
|
||||
("lateral_right", torch.tensor([ 0.0, 0.7, 0.0])),
|
||||
("yaw_rotate", torch.tensor([ 0.0, 0.0, 0.7])),
|
||||
]
|
||||
|
||||
# Probe sensors
|
||||
robot = env.unwrapped.scene["robot"]
|
||||
|
||||
print("\n" + "=" * 78)
|
||||
print(f"{'phase':<16} {'cmd (vx,vy,ω)':<22} "
|
||||
f"{'measured (vx,vy,ω)':<22} "
|
||||
f"{'h(m)':>6} {'pitch':>7} {'falls':>6}")
|
||||
print("=" * 78)
|
||||
|
||||
fails = []
|
||||
for label, cmd in phases:
|
||||
# Fresh reset per phase so prior falls / terrain placement don't bias
|
||||
# the next phase's height measurement.
|
||||
env.reset()
|
||||
cmd_batch = cmd.to(device).unsqueeze(0).expand(args.num_envs, -1).contiguous()
|
||||
# Reset stats for this phase
|
||||
v_lin_sum = torch.zeros(3, device=device)
|
||||
omega_sum = torch.zeros(1, device=device)
|
||||
height_sum = torch.zeros(1, device=device)
|
||||
pitch_max = 0.0
|
||||
n_steps = 0
|
||||
falls = 0
|
||||
|
||||
for _ in range(phase_steps):
|
||||
obs, _, terminated, truncated, _ = env.step(cmd_batch)
|
||||
n_steps += 1
|
||||
base_lin_vel = robot.data.root_lin_vel_b # body frame, (N, 3)
|
||||
base_ang_vel = robot.data.root_ang_vel_b
|
||||
root_pos = robot.data.root_pos_w # (N, 3)
|
||||
grav_b = robot.data.projected_gravity_b # (N, 3)
|
||||
v_lin_sum += base_lin_vel.mean(dim=0)
|
||||
omega_sum += base_ang_vel[:, 2].mean().unsqueeze(0)
|
||||
height_sum += root_pos[:, 2].mean().unsqueeze(0)
|
||||
# pitch = angle between projected_gravity_b and (-Z body) = (0,0,-1)
|
||||
pitch_now = (
|
||||
torch.acos(torch.clamp(-grav_b[:, 2], -1.0, 1.0))
|
||||
.max().item()
|
||||
)
|
||||
pitch_max = max(pitch_max, pitch_now)
|
||||
falls += int(terminated.any().item() or truncated.any().item())
|
||||
|
||||
v_lin = (v_lin_sum / n_steps).cpu().numpy().round(3).tolist()
|
||||
omega = (omega_sum / n_steps).item()
|
||||
h_avg = (height_sum / n_steps).item()
|
||||
|
||||
# Height threshold uses world-frame Z; the rough terrain in the dev env
|
||||
# can place the robot on top of features up to ~0.25 m, so allow up
|
||||
# to 0.65 m total for a healthy Go2 body (~0.40 m default standing).
|
||||
ok_height = 0.20 < h_avg < 0.70
|
||||
ok_pitch = pitch_max < 0.6
|
||||
ok_overall = ok_height and ok_pitch
|
||||
flag = "✓" if ok_overall else "✗"
|
||||
|
||||
cmd_str = f"({cmd[0]:+.1f},{cmd[1]:+.1f},{cmd[2]:+.1f})"
|
||||
meas_str = f"({v_lin[0]:+.2f},{v_lin[1]:+.2f},{omega:+.2f})"
|
||||
print(f"{flag} {label:<14} {cmd_str:<22} {meas_str:<22} "
|
||||
f"{h_avg:>6.3f} {pitch_max:>6.2f}r {falls:>6d}")
|
||||
|
||||
# Per-phase pass criteria
|
||||
if label == "stand_still":
|
||||
if abs(v_lin[0]) > 0.15 or abs(v_lin[1]) > 0.15:
|
||||
fails.append(f"{label}: drifting at zero command "
|
||||
f"(v_lin={v_lin})")
|
||||
elif label == "forward":
|
||||
if v_lin[0] < 0.10:
|
||||
fails.append(f"{label}: not moving forward "
|
||||
f"(vx={v_lin[0]:.2f})")
|
||||
elif label == "backward":
|
||||
if v_lin[0] > -0.10:
|
||||
fails.append(f"{label}: not moving backward "
|
||||
f"(vx={v_lin[0]:.2f})")
|
||||
elif label == "yaw_rotate":
|
||||
if abs(omega) < 0.10:
|
||||
fails.append(f"{label}: not rotating (ω={omega:.2f})")
|
||||
|
||||
if not ok_height:
|
||||
fails.append(f"{label}: body too low/high (h={h_avg:.2f})")
|
||||
if not ok_pitch:
|
||||
fails.append(f"{label}: tilted over (max pitch={pitch_max:.2f} rad)")
|
||||
|
||||
print("=" * 78)
|
||||
if fails:
|
||||
print("\n⚠ FAILED CHECKS:")
|
||||
for f in fails:
|
||||
print(f" - {f}")
|
||||
print("\nLikely causes:")
|
||||
print(" • Action scale mismatch (training used different scale)")
|
||||
print(" • Joint order mismatch between policy output and IsaacLab USD")
|
||||
print(" • Observation order mismatch")
|
||||
else:
|
||||
print("\n✅ ALL LOCOMOTION CHECKS PASSED")
|
||||
print(" Go2 stands, walks forward/back, and rotates as commanded.")
|
||||
print(" Locomotion contract with sru-navigation-sim is correct.")
|
||||
|
||||
env.close()
|
||||
simulation_app.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user