Cosmos 영상 생성과 Alpamayo 주행 모델 직접 실행하기

Cosmos의 카메라 조건 영상 생성에 이어 Alpamayo 예측 경로를 Isaac Sim에서 재생합니다. 직접 만든 장면으로 각각 실행한 모델 실험입니다.

  • Cosmos3-Edge
  • Alpamayo2-Edge
  • Isaac Sim
  • OpenUSD
월드 모델 생성과 주행 모델의 출력
실행 영상실행 영상과 기록

Isaac Sim 이미지 한 장으로 짧은 영상을 만들고, 별도로 직접 구성한 교차로의 카메라 영상을 주행 모델에 넣어 봅니다. 저장된 출력은 GPU 없이도 검사할 수 있습니다. 두 실험은 서로 독립적이며, Cosmos가 만든 영상을 Alpamayo에 연결하는 구성은 아닙니다.

동작 원리

데이터는 어떻게 흐를까요?
  1. 입력두 모델에 각각 입력 준비Cosmos: RGB와 카메라 동작 / Alpamayo: RGB 22장과 과거 자세

    직접 만든 장면을 사용합니다. 서로 다른 모델의 입출력을 확인하는 두 실험입니다.

  2. 처리공개 가중치로 추론Cosmos3-Edge · Alpamayo2-Edge

    Cosmos는 영상 픽셀을 생성하고, Alpamayo는 차량의 미래 위치와 회전을 예측합니다.

  3. 출력각 결과 확인MP4 61프레임 · 미래 자세 64개

    영상과 저장된 텐서를 검사합니다. Isaac Sim 속 차량은 예측 경로를 재생합니다.

이미지 한 장으로 이어지는 장면을 만들면?

Cosmos3-Edge는 RGB 이미지와 장면 설명을 받아 잠재 공간에서 영상의 노이즈를 제거한 뒤, 결과를 RGB 프레임으로 복원합니다. 이 실습의 첫 이미지에는 작업대 위의 노란 큐브, 초록 큐브, 검은 블록이 있습니다.

텍스트
Isaac Sim 카메라 → RGB 이미지 한 장 + 움직임 설명 → Cosmos3-Edge → 생성 영상
                  이미지와 시드는 고정하고 left / right만 변경

요청하는 출력은 24 FPS, 49프레임으로 약 2.04초입니다. 모델이 USD 장면이나 접촉력, 충돌 판정을 내놓는 것은 아닙니다. 영상 파일이 정상적으로 만들어졌는지와, 우리가 요청한 움직임이 나왔는지는 따로 확인해야 합니다. 공식 추론 입출력 안내

카메라 동작을 숫자로 직접 지정하면?

동작 조건을 주는 예제에서는 같은 이미지에 float32 [60, 9] 배열을 추가합니다. 한 행은 모델용으로 정규화된 이동 채널 3개와 6차원 회전 표현으로 구성됩니다. 미터 단위 이동량을 그대로 넣은 값이 아니며, 다시 정규화해서도 안 됩니다. NVIDIA가 공개한 카메라 동작 예제를 그대로 받아 SHA-256(547b977c…83c5595)을 확인합니다. Framework는 이 9개 채널에 패딩을 붙여 모델의 동작 입력 너비에 맞춥니다. 고정 리비전의 공식 카메라 예제

텍스트
직접 만든 RGB 이미지 + NVIDIA의 카메라 동작 60×9 → forward_dynamics → RGB 61프레임
                                                                     30 FPS

첫 프레임은 관측 이미지이고, 이후 60프레임은 모델이 예측한 시점입니다. 촬영한 실행에서는 480 해상도 등급의 패딩·크롭을 거쳐 832×464 영상이 나왔습니다. 카메라 시점이 달라지는 모습은 확인할 수 있지만, 출력은 생성된 RGB 영상입니다. 새로운 3D 장면을 복원하거나 물리 계산으로 카메라 경로의 정확성을 보장하는 과정은 아닙니다.

카메라와 차량의 과거 움직임을 어떻게 경로로 바꿀까?

Alpamayo2-Edge는 카메라 영상, 최근 차량 움직임, 내비게이션 지시를 함께 읽습니다. 시각·언어 모델이 주행 상황에 관한 설명을 만들고, 행동 예측 모듈이 움직임을 예측합니다. 공식 디코더는 예측한 가속도와 곡률을 적분해 미래 위치와 자세를 구합니다. 이 실습의 교차로는 직접 만든 기본 도형으로 구성하며, 접근 제한이 있는 실제 주행 영상은 사용하지 않습니다. 공식 모델 카드

텍스트
카메라 6대 / RGB 22프레임 ─┐
과거 차량 자세 20개 ────────┼→ Alpamayo2-Edge → 상황 설명 + 미래 자세 64개
"교차로에서 직진하세요" ───┘                 → 저장된 숫자 배열 검사
실습에서 주고받는 데이터 형태와 의미
카메라 이미지 CPU uint8 [22, 1, 3, 360, 640]. 이미지 22장, 항목당 1프레임, RGB 채널, 높이, 너비 순서입니다.
카메라 ID·촬영 시각 int64 [22]. ID 0/1/2/3/5/6에 각각 3/5/3/3/3/5프레임이 대응합니다. 전방 카메라 두 대는 현재 기준 −2, −1, −0.5, −0.1, 0초, 나머지는 −1, −0.1, 0초를 담습니다.
과거 위치 float32 [1, 20, 3]. 차량 기준 XYZ 위치를 0.1초 간격으로 담습니다. 회전 행렬 [1, 20, 3, 3]도 함께 줍니다. 실습에서는 카메라 리그를 5 m/s로 이동시킵니다.
예측 위치 [1, 1, 1, 64, 3]. 배치 1개, 경로 묶음 1개, 후보 1개, 64개의 XYZ 위치입니다. 현재 이후 0.1~6.4초를 0.1초 간격으로 예측하며, 회전 출력은 [1, 1, 1, 64, 3, 3]입니다.

예를 들어 [5.0, 0.4, 0.0]은 기준 시점의 차량에서 앞으로 5 m, 왼쪽으로 0.4 m 떨어진 위치를 뜻합니다. 이 숫자는 좌표 설명용 예시이며 실제 예측값은 아닙니다. 직접 만든 도로는 모델이 평가받은 실제 주행 데이터와 다릅니다. 합성 입력으로 모델 연결을 확인하는 실험이므로, 가중치가 실제로 로드되고 올바른 형태의 출력이 나오는지 확인합니다. 차량을 폐루프로 주행시키는 성능 평가는 아닙니다.

처음이면 실습 파일부터 받기

GPU 실습은 Isaac Sim을 실행할 머신에서 터미널을 엽니다. CPU 실습은 지금 쓰는 컴퓨터에서 해도 됩니다. 아래 명령은 한 줄씩 입력하고 Enter를 누르세요. 여러 줄짜리 명령 블록은 통째로 복사해도 됩니다.

Shell
cd "$HOME"
git clone https://github.com/james-joobs/awesome-nvidia-physical-ai.git
cd awesome-nvidia-physical-ai
pwd

홈 폴더에 받는 예입니다. 이미 내려받았다면 git clone은 건너뛰고 내 실습 폴더로 이동합니다. 새 터미널을 열 때마다 pwd의 출력 끝이 awesome-nvidia-physical-ai인지 확인하세요. 그래야 labs/로 시작하는 파일을 찾을 수 있습니다.

실행하기

1. Linux GPU 머신에서 전용 폴더 준비하기

GPU 머신에서 터미널을 열고 이 저장소 폴더로 이동합니다. GPU·드라이버 준비를 확인한 뒤, 가중치와 가상환경을 저장할 빈 폴더를 저장소 바깥에 지정하세요. 촬영에 사용한 GPU는 RTX 5090 32 GiB입니다. 소스와 모델 버전은 model-pins.json에 고정했습니다.

Shell
export WORLD_DRIVING_ROOT="$HOME/physical-ai-experiments/world-driving"
bash labs/world-driving/setup.sh

Cosmos와 Alpamayo는 서로 다른 가상환경에 설치됩니다. Cosmos는 CUDA 13.0 추론용 잠금 파일을, Alpamayo는 Python 3.12용 잠금 파일을 사용합니다. 공개 가중치가 약 13.5 GiB, 촬영 환경의 가상환경 두 개가 약 16 GiB였으며 캐시와 별도로 받는 VAE에도 공간이 필요합니다. 이 실습에는 여유 공간을 최소 60 GiB 확보하고, 사용할 체크포인트의 조건을 확인하세요. Cosmos 설치 안내 · Alpamayo 설치 안내

2. 같은 이미지로 두 영상 만들기

같은 터미널에서 아래 두 줄을 차례로 실행합니다. 직접 제작한 시뮬레이터 이미지와 시드 19는 그대로 두고, 큐브의 이동 방향만 바꿉니다. 스크립트는 공동 GPU 잠금을 기다리므로, 다른 실습과 동시에 GPU 메모리를 차지하지 않습니다.

Shell
bash labs/world-driving/run_cosmos.sh right
bash labs/world-driving/run_cosmos.sh left

WORLD_DRIVING_ROOT 아래의 outputs/cosmos-right/workbench-right/vision.mp4를 열어 보세요. 지시한 대로 움직이지 않더라도 두 결과를 모두 남겨 비교합니다. 이 스크립트는 정해진 합성 입력을 처리할 때 추가 가드레일 모델을 끕니다. 서비스로 배포할 때는 별도의 가드레일 구성을 정해야 합니다.

숫자로 지정한 카메라 동작도 넣어 보려면 아래 명령을 실행하세요. 고정한 12 KB 동작 파일을 받아 해시와 배열 형태를 확인하고, 같은 공개 Edge 체크포인트로 추론합니다.

Shell
bash labs/world-driving/run_camera_action.sh

3. Isaac Sim에서 주행 모델에 넣을 이미지 촬영하기

ISAAC_LAB_PYTHON에 Isaac Lab과 Isaac Sim이 설치된 Python 실행 파일 경로를 넣습니다. 촬영 환경은 Isaac Sim 6.1.0.0 / Isaac Lab 17.0.2이며, AppLauncher --viz kit를 사용합니다. 사이트의 Isaac Sim 6.2 작업대 실습과는 별개 환경입니다. 처음 실행할 때는 시뮬레이터의 라이선스 안내를 확인하세요.

Shell
export ISAAC_LAB_PYTHON="/path/to/IsaacLab/.venv/bin/python"
flock /tmp/physical-ai-four-domains.gpu.lock \
  "$ISAAC_LAB_PYTHON" labs/world-driving/make_driving_scene.py \
  --viz kit --output "$WORLD_DRIVING_ROOT/inputs/synthetic-intersection"

GUI에 도로 장면이 열리고, 표에 있는 카메라 위치와 시각에 맞춰 이미지 22장을 촬영합니다. 같은 폴더에 input.json과 synthetic-intersection.usda도 저장됩니다. Linux X11에서 실제 시뮬레이터 창을 녹화하려면 --record-window /absolute/path/to/ffmpeg를 추가하세요. 그래픽 데스크톱의 터미널에서 실행하면 해당 세션의 DISPLAY와 XAUTHORITY를 사용할 수 있습니다.

4. 공개된 주행 모델 가중치로 추론하기

앞에서 촬영한 카메라 이미지와 과거 위치를 읽고, 고정한 BF16 체크포인트를 불러와 설명과 경로를 저장합니다. 가속 추론용 컴파일 없이 기본 PyTorch SDPA 어텐션을 사용합니다.

Shell
python3 labs/cli.py --json run alpamayo-synthetic \
  --python "$WORLD_DRIVING_ROOT/alpamayo2-edge/.venv/bin/python" \
  --input "$WORLD_DRIVING_ROOT/inputs/synthetic-intersection" \
  --model "$WORLD_DRIVING_ROOT/checkpoints/Alpamayo2-Edge" \
  --seed 19 --output "$WORLD_DRIVING_ROOT/outputs/alpamayo-cli"

outputs/alpamayo-cli/output.json에는 설명, output.safetensors에는 예측한 숫자 배열이 저장됩니다. 별도 기록에는 GPU, 패키지 버전, 메모리 사용량, 입출력 배열의 형태를 남깁니다. 모델을 불러오기 전에 가중치 파일 두 개의 SHA-256도 대조합니다. 촬영한 실행의 적응형 추론 출력은 긴 설명 대신 <NOMINAL> 토큰이었습니다. 실제 폐루프 주행 평가는 장면 접근 권한을 준비한 뒤 AlpaSim 실습에서 진행합니다.

결과 확인하기

GPU 없이 저장된 파일 검사하기

검사에는 Python과 FFmpeg·FFprobe만 있으면 됩니다. 생성 폴더와 Alpamayo 출력 폴더를 지정하면 영상을 끝까지 디코딩해 프레임 수와 FPS를 확인합니다. 저장된 경로 배열도 직접 읽어 잘못된 형태나 유효하지 않은 숫자가 없는지 검사합니다.

Shell
python3 labs/world-driving/check.py \
  --cosmos labs/world-driving/evidence/cosmos-camera-actions \
  --alpamayo labs/world-driving/evidence/alpamayo-synthetic

위 경로는 저장소에 동봉한 공개 결과를 사용하므로 모델 실행 환경을 설치하지 않아도 됩니다. GPU에서 직접 돌린 뒤에는 내 출력 폴더로 바꿔 검사하세요. 촬영한 CLI 실행은 입력 처리까지 13.37초, PyTorch 최대 할당 메모리는 5.76 GiB였습니다. RTX 5090 한 대에서 합성 입력 하나를 처리한 기록이며, 일반적인 성능 수치로 해석하지 않습니다.

evidence/prediction-scene/alpamayo-trajectory.usda에는 모델이 예측한 위치 64개를 도로 위에 그려 두었습니다. 저장된 위치·회전 배열에 맞춰 차량 모형도 움직입니다. 이 장면의 Isaac Sim 영상은 예측 경로 재생이며, 재생 중에 모델이 새 주행 결정을 하거나 차량 물리를 계산하지 않습니다. 재생 장면 생성 코드 · 실행·검사 기록

무엇을 비교해야 할까?

  • Cosmos: 첫 프레임과 마지막 프레임을 나란히 보고, 큐브 방향·카메라 움직임·물체 형태를 확인하세요. sample_outputs.json이 success여도 지시한 동작이 나오지 않았다면 별도로 기록합니다.
  • Alpamayo: 빠진 가중치 없이 모델이 로드됐는지, 저장된 좌표가 유효한지, 차량 기준 좌표를 올바르게 읽었는지 확인합니다. 그럴듯한 설명과 경로만으로 안전한 주행을 입증할 수는 없습니다.
  • 접근 권한: 11월 19일 촬영 머신에서 NuRec 장면 접근은 확인됐지만, 별도 PhysicalAI-AV 원본 데이터셋 요청은 HTTP 403으로 거절됐습니다. 공개된 합성 입력 실험에는 두 데이터셋 모두 필요하지 않습니다. 승인과 사용 조건은 각각 다르며, 해당 데이터에서 파생된 영상·지표는 로컬에 보관합니다.

소스·모델 버전 · Cosmos · Alpamayo · AlpaSim 폐루프 실습

실행 영상과 기록

실습 소스 코드

setup.shGitHub에서 파일 보기
Shell
#!/usr/bin/env bash
set -euo pipefail

task_root="${WORLD_DRIVING_ROOT:?Choose an isolated folder with at least 60 GiB free for weights, runtimes and caches}"
uv_bin="${UV_BIN:-$HOME/.local/bin/uv}"
mkdir -p "$task_root"
cd "$task_root"
clone_pin() {
  local directory="$1" url="$2" revision="$3"
  if [[ ! -d "$directory/.git" ]]; then
    git clone "$url" "$directory"
  fi
  if [[ -n "$(git -C "$directory" status --porcelain)" ]]; then
    printf 'Stop: %s has local changes. Choose an empty task folder.\n' "$directory" >&2
    return 1
  fi
  git -C "$directory" fetch origin "$revision"
  git -C "$directory" checkout --detach "$revision"
}
clone_pin cosmos-framework https://github.com/NVIDIA/cosmos-framework.git afd7d4c4087a8929c84523ff60172642fd11690b
clone_pin alpamayo2-edge https://github.com/NVlabs/alpamayo2-edge.git 02f55a7aeabc1a2b9f7a80445c08e40bddc89f5e
(
  cd cosmos-framework
  "$uv_bin" tool run --from uv==0.11.29 uv sync --locked --group cu130 --extra guardrail --no-default-groups --python 3.13
)
(
  cd alpamayo2-edge
  "$uv_bin" sync --locked --extra dataset --no-default-groups
)
cosmos-framework/.venv/bin/hf download nvidia/Cosmos3-Edge \
  --revision 6afc1256321c3a8e623d89be3bc5117a1e90f96b \
  --local-dir checkpoints/Cosmos3-Edge
alpamayo2-edge/.venv/bin/hf download nvidia/Alpamayo2-Edge \
  --revision b92b6aa326bd3e2235db28f248ad5a30b5890e64 \
  --local-dir checkpoints/Alpamayo2-Edge
model-pins.jsonGitHub에서 파일 보기
JSON
{
  "checked_at": "2026-11-19",
  "camera_action_sidecar": {
    "url": "https://media.githubusercontent.com/media/nvidia-cosmos/cosmos-dependencies/2b17a2413bd86b2cf9b03823637108851e4ddf2d/inputs/action/camera_action_44.json",
    "sha256": "547b977ccd6d435d579ba83e82e58618d0bebf2e8e7d8d577bf2e9c8883c5595",
    "shape": [60, 9],
    "semantics": "Published native normalized camera-pose sequence: three translation channels and six rotation channels. Preserve unchanged; do not assume translation is raw meters."
  },
  "cosmos": {
    "source": "https://github.com/NVIDIA/cosmos-framework",
    "source_revision": "afd7d4c4087a8929c84523ff60172642fd11690b",
    "model": "nvidia/Cosmos3-Edge",
    "model_revision": "6afc1256321c3a8e623d89be3bc5117a1e90f96b",
    "gated": false,
    "weights_gib": 8.5,
    "terms": "OpenMDW-1.1; the Hugging Face metadata license field is other, with a linked license",
    "weights_license_url": "https://openmdw.ai/license/1-1/",
    "code_license_url": "https://github.com/NVIDIA/cosmos-framework/blob/afd7d4c4087a8929c84523ff60172642fd11690b/LICENSE",
    "requirements": "Dedicated Python 3.13, locked cu130 inference group. Driver must support CUDA 13.0."
  },
  "alpamayo": {
    "source": "https://github.com/NVlabs/alpamayo2-edge",
    "source_revision": "02f55a7aeabc1a2b9f7a80445c08e40bddc89f5e",
    "model": "nvidia/Alpamayo2-Edge",
    "model_revision": "b92b6aa326bd3e2235db28f248ad5a30b5890e64",
    "gated": false,
    "weights_gib": 4.94,
    "code_license": "Apache-2.0",
    "weights_license": "OpenMDW-1.1",
    "weights_license_url": "https://huggingface.co/nvidia/Alpamayo2-Edge/blob/b92b6aa326bd3e2235db28f248ad5a30b5890e64/LICENSE",
    "code_license_url": "https://github.com/NVlabs/alpamayo2-edge/blob/02f55a7aeabc1a2b9f7a80445c08e40bddc89f5e/LICENSE",
    "weight_sha256": {
      "00000.safetensors": "d13c1a427218baf7b7d365098c0f5496c0e5e6a6bf662836b8eebbe7eb7cfe7f",
      "00001.safetensors": "cfe424a7320ce729cd927b5ceaab4323a62443b50f461a2f5c0dd0b10634e0b5"
    },
    "requirements": "Python 3.12, locked torch 2.8.0 and Transformers 5.17.0; upstream recommends >=16 GiB for BF16 example, validated there on H100."
  },
  "large_models_deferred": {
    "nvidia/Cosmos3-Nano-Sim-Bimanual": {
      "model_revision": "da4d2c09175e2a6dd5b237265318066d5134312e",
      "weights_gib": 29.57,
      "reason": "Weights alone almost fill a 32 GiB GPU; runtime memory was not validated."
    },
    "nvidia/Cosmos3-Nano-Sim-Transfer": {
      "model_revision": "45510d5b8cefa338b7abc01eb702cf1e9cdf6742",
      "weights_gib": 29.54,
      "reason": "Weights alone almost fill a 32 GiB GPU; runtime memory was not validated."
    }
  }
}
make_cosmos_input.pyGitHub에서 파일 보기
Python
"""Prepare a short, explicitly generative Cosmos test from our own simulator image."""

import argparse
import hashlib
import json
from pathlib import Path

parser = argparse.ArgumentParser()
parser.add_argument("--image", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--direction", choices=["left", "right"], default="right")
args = parser.parse_args()
args.output.parent.mkdir(parents=True, exist_ok=True)
manifest = {
    "model_mode": "image2video",
    "prompt": (
        "A fixed camera watches a wooden workbench in a clean robotics simulation. "
        "A yellow cube is in the center, a mint green cube at the rear left and a tall dark block on the right. "
        f"The yellow cube slides slowly to the {args.direction} across the table. "
        "The green cube and the dark block remain stationary. "
        "Keep the camera fixed, preserve the tabletop, lighting, object colors and sizes. "
        "Continuous motion, no cuts, no added objects."
    ),
    "vision_path": str(args.image.resolve()),
    "format_prompt_as_json": False,
    "prompt_upsampling": False,
    "num_frames": 49,
    "fps": 24,
    "resolution": "480",
    "num_steps": 16,
}
args.output.write_text(json.dumps(manifest, indent=2) + "\n")
receipt = {
    "kind": "image-conditioned video generation; not a physics simulation or robot policy",
    "input_sha256": hashlib.sha256(args.image.read_bytes()).hexdigest(),
    "input_origin": "Our self-authored Isaac Sim Replicator workbench scene, frame 05",
    "manifest": manifest,
}
args.output.with_suffix(".provenance.json").write_text(json.dumps(receipt, indent=2) + "\n")
make_camera_action_input.pyGitHub에서 파일 보기
Python
"""Pair our simulator image with NVIDIA's pinned native camera-action example.

Use the published normalized sequence unchanged: inventing metric units or
normalizing this sequence a second time would change the input contract.
"""

import argparse
import hashlib
import json
import math
from pathlib import Path
import subprocess

parser = argparse.ArgumentParser()
parser.add_argument("--image", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
args.output.parent.mkdir(parents=True, exist_ok=True)
revision = "2b17a2413bd86b2cf9b03823637108851e4ddf2d"
url = f"https://media.githubusercontent.com/media/nvidia-cosmos/cosmos-dependencies/{revision}/inputs/action/camera_action_44.json"
payload = subprocess.check_output(["curl", "-fsSL", "--max-time", "60", url])
digest = hashlib.sha256(payload).hexdigest()
assert digest == "547b977ccd6d435d579ba83e82e58618d0bebf2e8e7d8d577bf2e9c8883c5595", digest
actions = json.loads(payload)
assert len(actions) == 60 and all(len(row) == 9 for row in actions)
assert all(math.isfinite(value) for row in actions for value in row)
action_path = args.output.with_name("camera-action-60x9.json")
action_path.write_bytes(payload)
spec = {
    "name": "workbench-camera-actions",
    "action_chunk_size": 60,
    "action_path": str(action_path.resolve()),
    "domain_name": "camera_pose",
    "fps": 30,
    "view_point": "ego_view",
    "guidance": 1.0,
    "image_size": 480,
    "resolution": "480",
    "model_mode": "forward_dynamics",
    "num_frames": 61,
    "num_steps": 30,
    "prompt": "A wooden workbench holds a yellow cube, a mint green cube and a tall dark block. The camera moves around the stationary objects.",
    "shift": 5.0,
    "vision_path": str(args.image.resolve()),
}
args.output.write_text(json.dumps(spec, indent=2) + "\n")
args.output.with_suffix(".provenance.json").write_text(json.dumps({
    "input_origin": "Our self-authored Isaac Sim Replicator workbench scene, frame 05",
    "action_origin": url,
    "action_sha256": digest,
    "action_shape": [60, 9],
    "action_columns": "native normalized camera-pose channels: 3 translation + 6D rotation; not raw metric displacements",
    "normalization": "Preserve NVIDIA's published values unchanged. Framework pads the native channels to its model action width.",
    "output": "Initial observation plus 60 predicted RGB frames; not a physics solver or a new 3D reconstruction",
}, indent=2) + "\n")
make_driving_scene.pyGitHub에서 파일 보기
Python
"""Render our own six-camera, 22-frame input in Isaac Sim; no driving dataset needed."""

import argparse
import hashlib
import json
from importlib.metadata import version
import math
import os
from pathlib import Path
import signal
import subprocess

from isaaclab.app import AppLauncher

parser = argparse.ArgumentParser()
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--record-window", type=Path, help="FFmpeg executable for native Isaac Sim GUI recording")
AppLauncher.add_app_launcher_args(parser)
args = parser.parse_args()
args.enable_cameras = True
launcher = AppLauncher(args)
app = launcher.app

import numpy as np
from PIL import Image
import omni.replicator.core as rep
import omni.usd
from omni.kit.viewport.utility import get_active_viewport
from pxr import Gf, Sdf, UsdGeom, UsdLux, UsdShade

args.output.mkdir(parents=True, exist_ok=True)
omni.usd.get_context().new_stage()
stage = omni.usd.get_context().get_stage()
UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z)
UsdGeom.SetStageMetersPerUnit(stage, 1.0)
world = UsdGeom.Xform.Define(stage, "/World")
stage.SetDefaultPrim(world.GetPrim())


def material(name, rgb):
    mat = UsdShade.Material.Define(stage, "/World/Looks/" + name)
    shader = UsdShade.Shader.Define(stage, mat.GetPath().AppendChild("Shader"))
    shader.CreateIdAttr("UsdPreviewSurface")
    shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set(Gf.Vec3f(*rgb))
    shader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(.7)
    mat.CreateSurfaceOutput().ConnectToSource(shader.ConnectableAPI(), "surface")
    return mat


def block(name, center, size, mat):
    shape = UsdGeom.Cube.Define(stage, "/World/" + name)
    shape.CreateSizeAttr(1)
    shape.AddTranslateOp().Set(Gf.Vec3d(*center))
    shape.AddScaleOp().Set(Gf.Vec3d(*size))
    UsdShade.MaterialBindingAPI.Apply(shape.GetPrim()).Bind(mat)
    return shape


asphalt = material("Asphalt", (.12, .14, .16))
grass = material("Grass", (.13, .24, .13))
white = material("White", (.9, .91, .88))
yellow = material("Yellow", (.96, .7, .05))
red = material("RedCar", (.62, .045, .035))
blue = material("BlueCar", (.02, .18, .4))
glass = material("Glass", (.05, .12, .16))
concrete = material("Concrete", (.42, .45, .43))
block("Ground", (20, 0, -.12), (160, 160, .2), grass)
block("MainRoad", (20, 0, .005), (150, 8, .05), asphalt)
block("CrossRoad", (28, 0, .02), (8, 100, .05), asphalt)
for index, x in enumerate(range(-45, 96, 6)):
    if 22 < x < 34:
        continue
    block(f"CenterLine{index}", (x, 0, .04), (3, .12, .015), yellow)
for index, y in enumerate((-3.65, 3.65)):
    for side, x in enumerate((-12, 65)):
        block(f"Edge{index}_{side}", (x, y, .04), (68, .1, .015), white)
for index, y in enumerate(np.arange(-3.1, 3.2, .75)):
    block(f"Crosswalk{index}", (22.8, float(y), .06), (.8, .42, .015), white)
for index, (x, y, h) in enumerate(((42, -15, 12), (56, -14, 8), (40, 17, 10), (-18, 16, 6), (-25, -14, 7))):
    block(f"Building{index}", (x, y, h / 2), (9, 9, h), concrete)
for index, (x, y, body) in enumerate(((17, 2.05, blue), (28, -12, red))):
    block(f"Car{index}Body", (x, y, .65), (4.2, 1.8, .9), body)
    block(f"Car{index}Cabin", (x - .2, y, 1.2), (2, 1.6, .7), glass)
light = UsdLux.DomeLight.Define(stage, "/World/Sky")
light.CreateIntensityAttr(1400)
sun = UsdLux.DistantLight.Define(stage, "/World/Sun")
sun.CreateIntensityAttr(2600)
sun.AddRotateXYZOp().Set(Gf.Vec3f(315, 15, 20))

width, height = 640, 360
camera = UsdGeom.Camera.Define(stage, "/World/Camera")
camera.CreateHorizontalApertureAttr(20.955)
camera.CreateClippingRangeAttr(Gf.Vec2f(.1, 250))
camera_op = camera.AddTransformOp()
product = rep.create.render_product(str(camera.GetPath()), (width, height))
annotator = rep.AnnotatorRegistry.get_annotator("rgb")
annotator.attach([product])
get_active_viewport().camera_path = str(camera.GetPath())
profiles = {0: (55, (-1, -.1, 0), 12), 1: (0, (-2, -1, -.5, -.1, 0), 14),
            2: (-55, (-1, -.1, 0), 12), 3: (145, (-1, -.1, 0), 12),
            5: (-145, (-1, -.1, 0), 12), 6: (0, (-2, -1, -.5, -.1, 0), 30)}
shots = []
recorder = None
record_log = None
if args.record_window:
    camera_op.Set(Gf.Matrix4d(1).SetLookAt(Gf.Vec3d(0, -1.8, 1.6), Gf.Vec3d(30, -1.8, 1.4), Gf.Vec3d(0, 0, 1)).GetInverse())
    for _ in range(35):
        app.update()
    windows = subprocess.check_output(["xwininfo", "-root", "-tree"], text=True)
    rows = [row for row in windows.splitlines() if '"Isaac Lab ' in row and "mutter-x11-frames" not in row]
    if not rows:
        raise RuntimeError("Native Isaac Sim window was not found; use --viz kit")
    identifier = str(int(rows[0].split()[0], 16))
    record_log = (args.output / "record-window.log").open("w")
    recorder = subprocess.Popen([
        str(args.record_window), "-nostdin", "-hide_banner", "-loglevel", "warning", "-y",
        "-f", "x11grab", "-draw_mouse", "0", "-framerate", "24", "-window_id", identifier,
        "-i", f"{os.environ['DISPLAY']}.0", "-an", "-c:v", "libx264", "-preset", "fast", "-crf", "22",
        "-pix_fmt", "yuv420p", "-movflags", "+faststart", str(args.output / "six-camera-isaac-gui.mp4"),
    ], stdout=record_log, stderr=subprocess.STDOUT)
for camera_id, (degrees, times, focal) in profiles.items():
    for offset in times:
        eye = Gf.Vec3d(offset * 5, -1.8, 1.6)
        yaw = math.radians(degrees)
        target = eye + Gf.Vec3d(math.cos(yaw) * 30, math.sin(yaw) * 30, -.2)
        camera_op.Set(Gf.Matrix4d(1).SetLookAt(eye, target, Gf.Vec3d(0, 0, 1)).GetInverse())
        camera.GetFocalLengthAttr().Set(focal)
        for _ in range(14):
            app.update()
        rgb = np.asarray(annotator.get_data())[:, :, :3].copy()
        assert rgb.shape == (height, width, 3) and rgb.mean() > 3, (camera_id, offset, rgb.shape)
        name = f"camera-{camera_id}-t{round((offset + 2) * 1000000):07d}.png"
        Image.fromarray(rgb).save(args.output / name)
        shots.append({"camera_id": camera_id, "timestamp_us": round((offset + 2) * 1000000),
                      "relative_time_s": offset, "image": name,
                      "sha256": hashlib.sha256((args.output / name).read_bytes()).hexdigest()})
        print(f"RENDER camera={camera_id} t={offset:+.1f}s file={name}", flush=True)
stage.GetRootLayer().Export(str(args.output / "synthetic-intersection.usda"))
(args.output / "input.json").write_text(json.dumps({
    "kind": "self-authored synthetic interface smoke; not a driving benchmark",
    "isaac_sim_version": version("isaacsim"),
    "isaac_lab_version": version("isaaclab"),
    "coordinate_frame": "ego x forward, y left, z up; ego reference at query time",
    "width": width, "height": height, "ego_speed_m_s": 5, "shots": shots,
    "history_times_s": [round(-1.9 + .1 * i, 3) for i in range(20)],
    "history_xyz_m": [[round((-1.9 + .1 * i) * 5, 3), 0, 0] for i in range(20)],
}, indent=2) + "\n")
annotator.detach([product])
if recorder:
    recorder.send_signal(signal.SIGINT)
    recorder.wait(timeout=20)
    record_log.close()
app.close()
run_cosmos.shGitHub에서 파일 보기
Shell
#!/usr/bin/env bash
set -euo pipefail

task_root="${WORLD_DRIVING_ROOT:?Set WORLD_DRIVING_ROOT to the isolated GPU-machine folder}"
lab_root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
direction="${1:-right}"
input_image="${2:-$lab_root/input/workbench.png}"
mkdir -p "$task_root/inputs" "$task_root/logs"
python3 "$lab_root/make_cosmos_input.py" --image "$input_image" \
  --output "$task_root/inputs/workbench-$direction.json" --direction "$direction"
export COSMOS_TRAINING=0
export PATH="$task_root/cosmos-framework/.venv/bin:$PATH"
cd "$task_root/cosmos-framework"
# Use the same lock for every other GPU job in this recording session.
flock /tmp/physical-ai-four-domains.gpu.lock \
  .venv/bin/python -m cosmos_framework.scripts.inference \
  -i "$task_root/inputs/workbench-$direction.json" \
  -o "$task_root/outputs/cosmos-$direction" \
  --checkpoint-path "$task_root/checkpoints/Cosmos3-Edge" \
  --parallelism-preset=latency --seed=19 \
  --no-use-torch-compile --no-guardrails
run_camera_action.shGitHub에서 파일 보기
Shell
#!/usr/bin/env bash
set -euo pipefail
task_root="${WORLD_DRIVING_ROOT:?Set WORLD_DRIVING_ROOT to the isolated GPU-machine folder}"
lab_root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
python3 "$lab_root/make_camera_action_input.py" --image "$lab_root/input/workbench.png" \
  --output "$task_root/inputs/workbench-camera-actions.json"
export COSMOS_TRAINING=0
export PATH="$task_root/cosmos-framework/.venv/bin:$PATH"
cd "$task_root/cosmos-framework"
flock /tmp/physical-ai-four-domains.gpu.lock \
  .venv/bin/python -m cosmos_framework.scripts.inference \
  -i "$task_root/inputs/workbench-camera-actions.json" \
  -o "$task_root/outputs/cosmos-camera-actions" \
  --checkpoint-path "$task_root/checkpoints/Cosmos3-Edge" \
  --parallelism-preset=latency --seed=19 \
  --no-use-torch-compile --no-guardrails
run_alpamayo_synthetic.pyGitHub에서 파일 보기
Python
"""Use released Alpamayo2-Edge weights on self-authored Isaac Sim camera frames.

This checks the model interface and output shapes, not driving quality or safety.
"""

import argparse
import hashlib
import json
from importlib.metadata import version
from pathlib import Path
import subprocess
import time

import numpy as np
from PIL import Image
import torch

from alpamayo2_edge.checkpoint import load_model
from alpamayo2_edge.inference import run_data

parser = argparse.ArgumentParser()
parser.add_argument("--input", type=Path, required=True)
parser.add_argument("--model", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--nav-text", default="Continue straight through the intersection.")
parser.add_argument("--seed", type=int, default=43)
args = parser.parse_args()
pins = json.loads(Path(__file__).with_name("model-pins.json").read_text())["alpamayo"]
weight_digests = {}
for filename, expected in pins["weight_sha256"].items():
    digest = hashlib.sha256()
    with (args.model / filename).open("rb") as stream:
        for block in iter(lambda: stream.read(1024 * 1024), b""):
            digest.update(block)
    weight_digests[filename] = digest.hexdigest()
    if digest.hexdigest() != expected:
        raise ValueError(f"Checkpoint shard {filename} differs from the documented model revision")
manifest = json.loads((args.input / "input.json").read_text())
images = np.stack([np.asarray(Image.open(args.input / row["image"]).convert("RGB"))
                   for row in manifest["shots"]])
data = {
    "image_frames": torch.from_numpy(images).permute(0, 3, 1, 2).unsqueeze(1).contiguous(),
    "camera_indices": torch.tensor([row["camera_id"] for row in manifest["shots"]], dtype=torch.int64),
    "absolute_timestamps": torch.tensor([row["timestamp_us"] for row in manifest["shots"]], dtype=torch.int64),
    "ego_history_xyz": torch.tensor([manifest["history_xyz_m"]], dtype=torch.float32),
    "ego_history_rot": torch.eye(3).reshape(1, 1, 3, 3).repeat(1, 20, 1, 1),
    "nav_text": [args.nav_text],
}
args.output.mkdir(parents=True, exist_ok=True)
began = time.perf_counter()
torch.cuda.reset_peak_memory_stats()
model, loading_info = load_model(str(args.model.resolve()), device="cuda", dtype="bfloat16",
                                attn_implementation="sdpa", local_files_only=True)
settings = dict(seed=args.seed, top_p=.98, top_k=None, temperature=.6, num_traj_sets=1,
                num_traj_samples=1, max_generation_length=192,
                diffusion_kwargs={"inference_step": 10})
result = run_data(model, data, "isaac-synthetic-intersection", args.output, settings, "cuda")
receipt = {
    "scope": "actual Alpamayo2-Edge model inference on a self-authored synthetic interface test; not driving evaluation",
    "upstream_source": "https://github.com/NVlabs/alpamayo2-edge",
    "upstream_revision": "02f55a7aeabc1a2b9f7a80445c08e40bddc89f5e",
    "model_id": "nvidia/Alpamayo2-Edge",
    "model_revision": "b92b6aa326bd3e2235db28f248ad5a30b5890e64",
    "verified_weight_sha256": weight_digests,
    "gpu": torch.cuda.get_device_name(0),
    "peak_allocated_gib": torch.cuda.max_memory_allocated() / 2**30,
    "total_elapsed_s": time.perf_counter() - began,
    "versions": {key: version(key) for key in ("torch", "torchvision", "transformers", "safetensors")},
    "input_shapes": {key: list(value.shape) for key, value in data.items() if isinstance(value, torch.Tensor)},
    "navigation": args.nav_text,
    "seed": args.seed,
    "result": result,
}
(args.output / "receipt.json").write_text(json.dumps(receipt, indent=2) + "\n")
print(json.dumps(receipt), flush=True)
run_alpamayo.shGitHub에서 파일 보기
Shell
#!/usr/bin/env bash
set -euo pipefail
task_root="${WORLD_DRIVING_ROOT:?Set WORLD_DRIVING_ROOT to the isolated GPU-machine folder}"
lab_root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
test -f "$task_root/inputs/synthetic-intersection/input.json"
mkdir -p "$task_root/outputs/alpamayo-synthetic"
flock /tmp/physical-ai-four-domains.gpu.lock \
  "$task_root/alpamayo2-edge/.venv/bin/python" "$lab_root/run_alpamayo_synthetic.py" \
  --input "$task_root/inputs/synthetic-intersection" \
  --model "$task_root/checkpoints/Alpamayo2-Edge" \
  --output "$task_root/outputs/alpamayo-synthetic"
make_prediction_scene.pyGitHub에서 파일 보기
Python
"""Show saved Alpamayo predictions as an animated USD proxy, without a model or GPU.

This is a replay of predicted poses. No vehicle physics or closed-loop policy
execution is added. Requires numpy and the USD Python bindings (usd-core).
"""

import argparse
import csv
import hashlib
import json
import math
from pathlib import Path
import struct

import numpy as np
from pxr import Gf, Sdf, Usd, UsdGeom, UsdShade

parser = argparse.ArgumentParser()
parser.add_argument("--scene", type=Path, required=True)
parser.add_argument("--prediction", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
args.output.mkdir(parents=True, exist_ok=True)
content = args.prediction.read_bytes()
header_size = struct.unpack("<Q", content[:8])[0]
header = json.loads(content[8:8 + header_size])
numeric = content[8 + header_size:]


def tensor(name):
    spec = header[name]
    assert spec["dtype"] == "F32", (name, spec)
    begin, end = spec["data_offsets"]
    return np.frombuffer(numeric[begin:end], dtype="<f4").reshape(spec["shape"])


xyz = tensor("pred_xyz")[0, 0, 0]
rot = tensor("pred_rot")[0, 0, 0]
assert xyz.shape == (64, 3) and rot.shape == (64, 3, 3)
assert np.isfinite(xyz).all() and np.isfinite(rot).all()
stage = Usd.Stage.Open(str(args.scene))
stage.SetStartTimeCode(0)
stage.SetEndTimeCode(192)
stage.SetTimeCodesPerSecond(30)
stage.SetFramesPerSecond(30)


def material(name, color, emissive=False):
    mat = UsdShade.Material.Define(stage, "/World/Looks/" + name)
    shader = UsdShade.Shader.Define(stage, mat.GetPath().AppendChild("Shader"))
    shader.CreateIdAttr("UsdPreviewSurface")
    shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set(Gf.Vec3f(*color))
    shader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(.55)
    if emissive:
        shader.CreateInput("emissiveColor", Sdf.ValueTypeNames.Color3f).Set(Gf.Vec3f(*color))
    mat.CreateSurfaceOutput().ConnectToSource(shader.ConnectableAPI(), "surface")
    return mat


orange = material("PredictedRoute", (1, .36, .015), True)
lime = material("PredictedCar", (.3, .8, .045))
glass = material("PredictedGlass", (.02, .09, .12))
points = [Gf.Vec3f(0, -1.8, .13)] + [Gf.Vec3f(float(x), float(y - 1.8), float(z + .13)) for x, y, z in xyz]
path = UsdGeom.BasisCurves.Define(stage, "/World/PredictedRoute")
path.CreateTypeAttr("linear")
path.CreateCurveVertexCountsAttr([len(points)])
path.CreatePointsAttr(points)
path.CreateWidthsAttr([.15])
path.SetWidthsInterpolation(UsdGeom.Tokens.constant)
UsdShade.MaterialBindingAPI.Apply(path.GetPrim()).Bind(orange)
proxy = UsdGeom.Xform.Define(stage, "/World/PredictedVehicleProxy")
position = proxy.AddTranslateOp()
orientation = proxy.AddOrientOp()
for name, location, scale, look in (("Body", (.3, 0, .65), (4.2, 1.8, .9), lime),
                                    ("Cabin", (-.1, 0, 1.22), (2.0, 1.6, .65), glass)):
    block = UsdGeom.Cube.Define(stage, proxy.GetPath().AppendChild(name))
    block.CreateSizeAttr(1)
    block.AddTranslateOp().Set(Gf.Vec3d(*location))
    block.AddScaleOp().Set(Gf.Vec3d(*scale))
    UsdShade.MaterialBindingAPI.Apply(block.GetPrim()).Bind(look)
position.Set(Gf.Vec3d(0, -1.8, 0), 0)
orientation.Set(Gf.Quatf(1), 0)
rows = []
for index, (point, rotation) in enumerate(zip(xyz, rot, strict=True)):
    seconds = (index + 1) / 10
    yaw = math.atan2(float(rotation[1, 0]), float(rotation[0, 0]))
    position.Set(Gf.Vec3d(float(point[0]), float(point[1] - 1.8), float(point[2])), seconds * 30)
    orientation.Set(Gf.Quatf(math.cos(yaw / 2), Gf.Vec3f(0, 0, math.sin(yaw / 2))), seconds * 30)
    rows.append([seconds, *map(float, point), yaw])
center_x = float((xyz[:, 0].min() + xyz[:, 0].max()) / 2)
center_y = float((xyz[:, 1].min() + xyz[:, 1].max()) / 2) - 1.8
span = max(float(np.ptp(xyz[:, 0])), float(np.ptp(xyz[:, 1])), 20)
target = Gf.Vec3d(center_x, center_y, .6)
eye = target + Gf.Vec3d(-span * .8, -span * .9, span)
camera = UsdGeom.Camera.Define(stage, "/World/FilmCamera")
camera.CreateFocalLengthAttr(24)
camera.CreateHorizontalApertureAttr(20.955)
camera.CreateClippingRangeAttr(Gf.Vec2f(.1, 300))
camera.AddTransformOp().Set(Gf.Matrix4d(1).SetLookAt(eye, target, Gf.Vec3d(0, 0, 1)).GetInverse())
stage.Export(str(args.output / "alpamayo-trajectory.usda"))
(args.output / "takes.json").write_text(json.dumps([
    ["alpamayo-trajectory", "alpamayo-trajectory", "FilmCamera", 0.0, 1.0, 7.5]
], indent=2) + "\n")
with (args.output / "prediction.csv").open("w") as stream:
    writer = csv.writer(stream, lineterminator="\n")
    writer.writerow(["time_s", "ego_x_m", "ego_y_m", "ego_z_m", "body_yaw_rad"])
    writer.writerows(rows)
metadata = {
    "mode": "model-trajectory-replay; no closed-loop driving or dynamics",
    "prediction_sha256": hashlib.sha256(content).hexdigest(),
    "points": 64,
    "time_step_s": .1,
    "ego_origin_in_usd_m": [0, -1.8, 0],
    "proxy": "Cosmetic car dimensions; transforms replay model positions and yaw-only body rotations",
    "first_predicted_xyz_m": xyz[0].tolist(),
    "last_predicted_xyz_m": xyz[-1].tolist(),
    "scene": "alpamayo-trajectory.usda",
}
(args.output / "prediction-scene.json").write_text(json.dumps(metadata, indent=2) + "\n")
print(json.dumps(metadata), flush=True)
check.pyGitHub에서 파일 보기
Python
"""Check saved model products on a CPU, without importing either model runtime."""

import argparse
import json
import math
from pathlib import Path
import struct
import subprocess

parser = argparse.ArgumentParser()
parser.add_argument("--cosmos", type=Path, help="Folder containing sample_outputs.json and vision.mp4")
parser.add_argument("--alpamayo", type=Path, help="Folder containing output.json and output.safetensors")
parser.add_argument("--ffmpeg", default="ffmpeg")
parser.add_argument("--ffprobe", default="ffprobe")
args = parser.parse_args()
if not args.cosmos and not args.alpamayo:
    parser.error("Choose --cosmos, --alpamayo, or both")
checks = {}
if args.cosmos:
    receipt = json.loads((args.cosmos / "sample_outputs.json").read_text())
    assert receipt["status"] == "success", receipt.get("message")
    probe = json.loads(subprocess.check_output([
        args.ffprobe, "-v", "error", "-select_streams", "v:0", "-count_frames",
        "-show_entries", "stream=width,height,r_frame_rate,nb_read_frames", "-of", "json",
        str(args.cosmos / "vision.mp4"),
    ], text=True))["streams"][0]
    assert int(probe["nb_read_frames"]) == receipt["args"]["num_frames"], probe
    numerator, denominator = map(int, probe["r_frame_rate"].split("/"))
    assert abs(numerator / denominator - receipt["args"]["fps"]) < 1e-6, probe
    subprocess.run([args.ffmpeg, "-v", "error", "-xerror", "-i", str(args.cosmos / "vision.mp4"),
                    "-f", "null", "-"], check=True)
    checks["cosmos"] = {"decoded_video": probe,
                        "scope": "generation completed; prompt adherence still requires visual review"}
if args.alpamayo:
    record = json.loads((args.alpamayo / "output.json").read_text())
    expected_shapes = {"pred_xyz": [1, 1, 1, 64, 3], "pred_rot": [1, 1, 1, 64, 3, 3]}
    content = (args.alpamayo / "output.safetensors").read_bytes()
    header_length = struct.unpack("<Q", content[:8])[0]
    header = json.loads(content[8:8 + header_length])
    numeric = content[8 + header_length:]
    for name, shape in expected_shapes.items():
        tensor = header[name]
        assert tensor["shape"] == shape and tensor["dtype"] == "F32", (name, tensor)
        begin, end = tensor["data_offsets"]
        values = [entry[0] for entry in struct.iter_unpack("<f", numeric[begin:end])]
        assert len(values) == math.prod(shape) and all(map(math.isfinite, values)), name
    assert record["finite"] is True
    assert record["pred_xyz_shape"] == expected_shapes["pred_xyz"]
    assert record["pred_rot_shape"] == expected_shapes["pred_rot"]
    checks["alpamayo"] = {"finite_saved_trajectories": True, "shapes": expected_shapes,
                          "scope": "model interface smoke on synthetic observations; not driving evaluation"}
print(json.dumps(checks, indent=2))