# 5. RL 학습 (Isaac Lab — Advanced)

이 섹션은 **선택 사항**입니다. VLA fine-tuning(4장)과 독립적으로 진행할 수 있으며, Isaac Lab을 사용한 강화학습(RL) 파이프라인을 HyperPod에서 실행합니다.

***

## RL vs VLA: 언제 어떤 접근을 사용하나?

|       | VLA (GR00T Fine-tuning) | RL (Isaac Lab)         |
| ----- | ----------------------- | ---------------------- |
| 학습 방식 | 사전학습 모델 + 데모 데이터 추가 학습  | 시뮬레이션에서 시행착오로 학습       |
| 입력    | 카메라 이미지 + 언어 지시         | 관절 센서 (proprioception) |
| 출력    | End-effector 상대 변위      | Joint position targets |
| 장점    | 적은 데이터로 빠르게 특화          | 정밀 제어, 시뮬레이션 데이터 무한    |
| 단점    | 시뮬레이션 검증 어려움            | Sim-to-Real gap        |
| 대표 사례 | 가정용 물건 집기               | 사족보행, 정밀 조립            |

두 접근을 **결합**하는 것이 이상적입니다:

1. RL로 기본 동작 학습 → 시뮬레이션 데이터 수집
2. VLA로 시각+언어 이해력 추가 fine-tuning

***

## 4.5.1 Isaac Lab 환경 준비

Isaac Lab은 NVIDIA Isaac Sim 위에 구축된 RL 프레임워크로, GPU 병렬 시뮬레이션을 통해 수천 개의 환경을 동시에 실행합니다.

### 환경 설치 (최초 1회)

```bash
# Isaac Lab 환경 설치 (컨테이너 import + 워크샵 태스크 준비, ~15분)
bash /fsx/scratch/aws-physical-ai-recipes/training/hyperpod/scripts/setup_isaaclab_env.sh
```

이 스크립트는 다음을 수행합니다:

* Isaac Sim 컨테이너를 NGC에서 가져와 Enroot 이미지로 변환 (`/fsx/enroot/data/isaaclab+latest.sqsh`, \~20GB)
* SO-101 워크샵 태스크 패키지를 `/fsx/scratch/isaaclab-workshop/`에 복사
* 체크포인트/로그 디렉토리 생성

수동으로 컨테이너만 가져오려면:

```bash
mkdir -p /fsx/enroot/data /fsx/enroot/tmp
export ENROOT_CACHE_PATH=/fsx/enroot
export ENROOT_DATA_PATH=/fsx/enroot/data
export TMPDIR=/fsx/enroot/tmp

sudo enroot import --output /fsx/enroot/data/isaaclab+latest.sqsh \
  docker://nvcr.io#nvidia/isaac-sim:4.5.0
```

{% hint style="info" %}
Isaac Sim 컨테이너는 \~20GB입니다. FSx에 저장하면 모든 compute node에서 공유 사용 가능합니다.
{% endhint %}

### 워크샵 태스크 확인

SO-101 5-DOF 로봇 팔을 사용한 두 가지 RL 태스크가 준비되어 있습니다:

| 태스크 ID                    | 설명                 | 난이도 | 학습 시간 |
| ------------------------- | ------------------ | --- | ----- |
| `Workshop-SO101-Reach-v0` | 랜덤 타겟 위치로 엔드이펙터 이동 | 쉬움  | \~15분 |
| `Workshop-SO101-Lift-v0`  | 테이블 위 물체를 집어 올리기   | 중간  | \~25분 |

***

## 4.5.2 RL 학습 실행

### SLURM 작업 제출

```bash
# Reach 태스크 학습 (기본, ~15분)
sbatch /fsx/scratch/aws-physical-ai-recipes/training/hyperpod/slurm-templates/rl/finetune_isaaclab.sbatch

# Lift 태스크 학습
TASK=Workshop-SO101-Lift-v0 MAX_ITERATIONS=500 \
  sbatch /fsx/scratch/aws-physical-ai-recipes/training/hyperpod/slurm-templates/rl/finetune_isaaclab.sbatch
```

### 래퍼 스크립트 사용

```bash
/fsx/scratch/aws-physical-ai-recipes/training/hyperpod/slurm-templates/rl/run_rl.sh \
  --task Workshop-SO101-Reach-v0 --iterations 300
```

### 학습 파라미터

| 변수               | 기본값                     | 설명                    |
| ---------------- | ----------------------- | --------------------- |
| `TASK`           | Workshop-SO101-Reach-v0 | Isaac Lab 태스크 ID      |
| `NUM_ENVS`       | 2048                    | 병렬 시뮬레이션 수 (VRAM에 비례) |
| `MAX_ITERATIONS` | 300                     | PPO 학습 이터레이션          |
| `LOG_DIR`        | /fsx/checkpoints/rl     | 체크포인트 저장              |
| `CHECKPOINT`     | (없음)                    | 이어하기 체크포인트 경로         |

***

## 4.5.3 학습 모니터링

```bash
# 로그 확인
tail -f /fsx/scratch/logs/isaaclab-<JOB_ID>.out

# 정상 진행 시 출력 예시:
# Training: Workshop-SO101-Reach-v0
#   Envs: 2048
#   Iterations: 300
#   Log dir: /fsx/checkpoints/rl/reach/SO101_Reach
#   Device: cuda:0
# [INFO] Iteration 10/300 — reward: 2.34, episode_length: 450
# [INFO] Iteration 50/300 — reward: 8.67, episode_length: 380
# ...
# Training complete!
```

### TensorBoard로 학습 곡선 확인

```bash
# Head node에서 TensorBoard 시작
pip install tensorboard
tensorboard --logdir /fsx/checkpoints/rl --host 0.0.0.0 --port 6006

# SSH 터널링으로 로컬 접속
# (로컬 PC에서 실행)
ssh -L 6006:localhost:6006 hyperpod
# 브라우저에서 http://localhost:6006 접속
```

***

## 4.5.4 학습 결과 확인

### 체크포인트 구조

```bash
ls /fsx/checkpoints/rl/reach/SO101_Reach/
# model_0.pt  model_50.pt  model_100.pt  ...  model_300.pt
```

### 시뮬레이션에서 학습된 정책 실행 (검증)

학습된 RL 정책이 실제로 태스크를 수행하는지 시뮬레이션에서 확인합니다:

```bash
# 컨테이너 내부에서 실행 (렌더링 포함, DCV 연결 시)
python /fsx/scratch/aws-physical-ai-recipes/isaac-lab-workshop/exp/workshop/src/workshop/scripts/train_rl.py \
  --task Workshop-SO101-Reach-v0 \
  --checkpoint /fsx/checkpoints/rl/reach/SO101_Reach/model_300.pt \
  --num_envs 50 \
  --max_iterations 0

# Headless로 성공률만 측정
python /fsx/scratch/aws-physical-ai-recipes/isaac-lab-workshop/exp/workshop/src/workshop/scripts/train_rl.py \
  --task Workshop-SO101-Reach-v0 \
  --checkpoint /fsx/checkpoints/rl/reach/SO101_Reach/model_300.pt \
  --num_envs 256 \
  --max_iterations 0 \
  --headless
```

***

## 4.5.5 GR00T + Isaac Lab 연동 (Closed-loop VLA 검증)

학습된 GR00T VLA 정책을 Isaac Sim 시뮬레이션에서 closed-loop으로 평가할 수 있습니다. 이 경우 GR00T가 카메라 이미지 + 관절 상태를 받아 action을 출력하고, 시뮬레이션에서 로봇을 직접 제어합니다.

### 아키텍처

```
┌──────────────────┐     ZMQ      ┌─────────────────────┐
│  GR00T Policy    │◀────────────▶│  Isaac Sim          │
│  (Inference GPU) │  obs/action  │  (Simulation GPU)   │
│                  │              │  - Camera images    │
│  checkpoint-2000 │              │  - Joint states     │
└──────────────────┘              │  - Robot control    │
                                  └─────────────────────┘
```

### GR00T 추론 서버 시작

```bash
source /fsx/envs/gr00t/bin/activate
cd /fsx/scratch/Isaac-GR00T

# ZMQ 기반 추론 서버 시작
python -m gr00t.eval.run_gr00t_server \
  --model-path /fsx/checkpoints/vla/groot-demo_data/checkpoint-2000 \
  --embodiment-tag OXE_DROID_RELATIVE_EEF_RELATIVE_JOINT \
  --port 5555
```

### Closed-loop 시뮬레이션 클라이언트

```bash
# 별도 터미널 또는 노드에서 (Isaac Sim 컨테이너 내부)
python /fsx/scratch/aws-physical-ai-recipes/isaac-lab-workshop/exp/workshop/src/workshop/scripts/run_closed_loop.py \
  --policy_host <GR00T_SERVER_IP> \
  --policy_port 5555 \
  --instruction "pick up the cube" \
  --num_steps 5000 \
  --headless
```

{% hint style="warning" %}
GR00T closed-loop 연동은 두 개의 GPU가 필요합니다 (하나는 추론, 하나는 시뮬레이션). `ml.g5.12xlarge` (4x A10G) 노드를 사용하세요.
{% endhint %}

***

## 4.5.6 트러블슈팅

| 증상                              | 원인               | 해결 방법                          |
| ------------------------------- | ---------------- | ------------------------------ |
| Container image not found       | Enroot 이미지 미생성   | `enroot import` 재실행            |
| CUDA OOM with 2048 envs         | A10G VRAM 부족     | `NUM_ENVS=1024` 또는 `512`로 줄이기  |
| `ModuleNotFoundError: workshop` | 태스크 패키지 미등록      | `sys.path`에 워크샵 경로 추가 필요       |
| `--headless` flag 무시됨           | Isaac Sim 버전 차이  | `DISPLAY=""` 환경변수로 강제 headless |
| 학습이 수렴하지 않음                     | iteration 부족     | `MAX_ITERATIONS=1000` 이상으로 늘리기 |
| ZMQ connection refused          | 서버 미시작 또는 포트 불일치 | 서버 로그 확인, 포트 번호 일치 확인          |

***

## References

* [NVIDIA Isaac Lab Documentation](https://isaac-sim.github.io/IsaacLab/)
* [rsl\_rl PPO Implementation](https://github.com/leggedrobotics/rsl_rl)
* [Isaac-GR00T Evaluation](https://github.com/NVIDIA/Isaac-GR00T/tree/main/gr00t/eval)
* [Isaac Sim NGC Container](https://catalog.ngc.nvidia.com/orgs/nvidia/containers/isaac-sim)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hi-space.gitbook.io/physical-ai-on-aws/physical-ai-on-aws-guide/hyperpod-distributed-training/5.-rl-training.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
