직접 만든 도로 위로 카메라를 올려 봅니다. NuRec으로 그 시점의 화면을 복원하고, Harmonizer 적용 전후를 비교한 뒤, Alpamayo 2 Edge가 예측한 경로를 표시합니다. 먼저 GPU 없이 저장된 결과를 확인하고, GPU 실습에서 같은 과정을 직접 실행해 보세요. 정적인 장면 복원과 주행 모델의 단일 예측을 연결하는 실습입니다.
동작 원리
- 입력직접 만든 도로 촬영
RGB·깊이 120장 · K · 카메라 자세학습용 깊이만 초기화에 쓰고, 높이를 올린 카메라 40곳은 비교용으로 남깁니다.
- 처리장면 복원 후 프레임 보정
NuRec 새 시점 RGB → Harmonizer RGB원래 USD와 비교합니다. 생성 모델의 보정이 픽셀 정확도를 낮출 수도 있습니다.
- 출력주행 모델의 예측 표시
원본 여섯 카메라 + 과거 자세 → 미래 자세 64개실제 Alpamayo 출력을 화면에 투영합니다. 차량에 제어 명령을 적용하는 단계는 포함하지 않습니다.
1. 사진뿐 아니라 깊이와 카메라 위치도 필요한 이유
사진에는 색이 담겨 있지만, 그것만으로 카메라나 도로의 정확한 3D 위치를 알 수는 없습니다. 이 실습에서는 기본 도형으로 만든 USD 도로 장면을 사용합니다. 시뮬레이터가 정확한 기하 정보를 알고 있으므로, 세 개의 나란한 촬영 경로에서 RGB와 z-depth를 120장씩 얻습니다.
RGB 한 장은 576 × 1024 × 3 크기의 uint8 배열입니다. 각 채널의 값은 0~255입니다. 깊이는 576 × 1024 크기의 실수 배열이며, 카메라의 광축 방향 거리를 미터로 나타냅니다. 카메라 내부 파라미터는 다음과 같습니다.
K = [[512, 0, 512],
[ 0, 512, 288],
[ 0, 0, 1]]
앞의 512는 픽셀 단위 초점거리이고, (512, 288)은 주점입니다. 4 × 4 카메라 자세 행렬은 이 카메라가 장면의 어디에 있고 어느 쪽을 보는지 나타냅니다. OpenCV·NCore 카메라는 오른쪽·아래·앞을 각각 +X·+Y·+Z로 씁니다. USD 카메라는 -Z 방향을 바라보고 +Y가 위쪽이므로, 촬영 코드에서 좌표축을 바꿉니다.
깊이가 Z인 픽셀 (u,v)는 X = (u-cx)·Z/fx, Y = (v-cy)·Z/fy로 카메라 기준 3D 점이 됩니다. 이를 카메라 자세로 변환하면 세계 좌표의 점을 얻습니다. 학습용 촬영의 깊이만 사용해 Gaussian 90,028개를 초기화합니다. 시뮬레이터의 정답 깊이를 쓰는 조건이므로, 일반 영상만으로 깊이를 알아내는 실험과는 조건이 다릅니다.
변환 코드는 RGB·카메라 정보·자세·촬영 시각을 NCore V4로 묶습니다. 움직이는 물체는 없는 정적 장면이어서 물체 트랙은 비워 둡니다. NCore 좌표계 설명
2. NuRec은 무엇을 학습하고, 새 시점은 어떻게 그릴까?
NuRec은 촬영된 모습에 맞춰 Gaussian의 위치·크기·회전·불투명도·색을 조정합니다. 학습한 장면에 다른 카메라 위치와 내부 파라미터를 넣으면 그 시점의 RGB를 렌더링할 수 있습니다.
이번 실행은 NuRec 26.04, 학습 2,400스텝, gsplat 렌더러를 사용했습니다. 검사용 카메라는 촬영 경로 사이에서 높이를 1m 올린 위치 40곳을 지나갑니다. 이 시점의 RGB와 깊이는 학습이나 초기화에 넣지 않았습니다. 원래 USD도 똑같은 카메라에서 렌더링해 비교할 정답 영상을 확보했습니다.
Gaussian 장면이 표현하는 것은 카메라에서 본 모습입니다. 차량의 물리 움직임·충돌체·제어기는 따로 필요합니다. NuRec 소스와 배포 구분
3. Harmonizer는 화면을 어떻게 바꿀까?
공개된 harmonizer_nontemporal.pt에 float[1,3,1,576,1024] 형태의 RGB를 넣습니다. 픽셀 값은 [-1,1]로 정규화합니다. Cosmos 기반의 단일 스텝 모델이 같은 크기의 이미지를 출력하면 다시 RGB PNG로 저장합니다. 이번 코드에는 별도의 색 전이 처리를 더하지 않았습니다.
이 체크포인트는 프레임별 보정입니다. 이전 프레임을 참고하지 않습니다. 이전 보정 결과를 함께 쓰는 temporal 모드는 별도 체크포인트와 Cosmos 기본 모델이 필요합니다. 이번 계정에서는 그 기본 모델이 403 응답이어서, temporal 결과는 포함하지 않았습니다. Harmonizer 모델 카드 · 공식 연결 방법
Built on NVIDIA Cosmos. 화면이 매끈해져도 차선이나 물체의 경계가 달라질 수 있습니다. 원래 USD와 비교해서 바뀐 픽셀이 실제 정답에 가까워졌는지 확인합니다.
4. 초록색 경로는 누가 계산했을까?
Alpamayo에는 Harmonizer의 출력 대신 Isaac Sim에서 촬영한 원본 영상을 넣습니다. 여섯 카메라의 이미지 22장과 카메라 ID·촬영 시각, 차량의 과거 위치·회전 20개, Continue straight through the intersection.이라는 주행 지시를 전달합니다. 화면을 만드는 흐름과 경로를 예측하는 흐름이 같은 도로 장면을 공유하는 구성입니다.
image_frames: uint8[22,1,3,360,640]
ego_history_xyz: float[1,20,3]
ego_history_rot: float[1,20,3,3]
↓ Alpamayo 2 Edge
pred_xyz: float[1,1,1,64,3]
pred_rot: float[1,1,1,64,3,3]
출력은 0.1초 간격의 미래 자세 64개, 즉 6.4초 구간입니다. 실제 첫 예측 위치는 약 [0.5010, 0.000064, 0.0]m이고, 마지막은 [30.2868, -0.08339, 0.0]m였습니다. 추론 시점의 차량을 기준으로 x는 앞, y는 왼쪽, z는 위를 뜻합니다.
영상 합성 코드는 차량의 원점을 USD의 [0,-1.8,0]에 놓고, 예측 위치를 표시용 카메라 좌표로 바꾼 뒤 K로 화면에 투영합니다. 카메라 밖에 있는 점도 볼 수 있도록 작은 BEV를 함께 표시합니다.
영상에서는 한 번 저장한 예측 경로를 순서대로 드러냅니다. 조향 명령을 실행하거나 이동 후 다시 추론하는 단계는 포함하지 않았습니다. 모델의 추론 텍스트는 <NOMINAL>이었으며, 그 밖의 설명을 만들어 붙이지 않았습니다. Alpamayo 2 Edge 공식 소스
처음이면 실습 파일부터 받기
GPU 실습은 필요한 NVIDIA GPU가 있는 머신에서 터미널을 엽니다. CPU 실습은 지금 쓰는 컴퓨터에서 해도 됩니다. 아래 명령은 한 줄씩 입력하고 Enter를 누르세요. 여러 줄짜리 명령 블록은 통째로 복사해도 됩니다.
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. GPU 없이 저장된 결과부터 확인하기
한국어 비교 영상을 열어 보세요. NuRec 단독 영상, Harmonizer 단독 영상, 경로 표시 영상도 따로 준비했습니다. evidence 폴더에는 손실 없이 저장한 이미지 세 묶음과 예측 경로 JSON이 있습니다.
수치도 확인하려면 저장소 폴더에서 터미널을 엽니다. 아래 명령은 검사에 필요한 작은 Python 환경을 만들고, NumPy와 Pillow를 설치한 뒤 저장된 결과를 검사합니다.
python3 -m venv .venv-reality-check
source .venv-reality-check/bin/activate
python -m pip install numpy Pillow
python labs/reality-view/check.py
파일 해시, 미래 자세 64개의 유한값과 회전 행렬, 저장된 비교 이미지의 PSNR을 확인합니다. FFmpeg를 설치한 환경에서는 마지막 명령에 --decode-video를 붙이면 모든 MP4를 실제 디코딩해 손상된 프레임도 검사합니다.
2. GPU 머신과 모델 환경 준비하기
직접 생성할 때는 NVIDIA GPU가 있는 Linux 머신, GPU를 사용할 수 있는 Docker, Isaac Lab의 Python 실행 환경, 여유 디스크 40GB 이상이 필요합니다. 이번 작은 예제는 RTX 5090 32GB, 시스템 메모리 약 32GB, Isaac Sim 6.1.0.0 / Isaac Lab 17.0.2에서 실행했습니다. NuRec의 일반적인 재구성 작업에는 더 많은 시스템 메모리가 권장됩니다. 여기서는 작은 정적 장면과 적은 데이터 로더 프로세스를 사용했습니다. 기존 환경을 바로 업그레이드하지 말고, 검증된 버전을 별도로 유지하세요.
Linux GPU 환경 준비 · Isaac Sim 설치·사용 안내 · NuRec 공식 하드웨어 요구사항
GPU 머신에서 저장소 폴더의 터미널을 열고 아래 변수를 설정합니다. Python 경로는 자신이 설치한 Isaac Lab 환경의 실행 파일로 바꿔 주세요.
export REALITY_VIEW_ROOT="$HOME/physical-ai-labs/road-view"
export ALPAMAYO_ROOT="$HOME/physical-ai-labs/road-models"
export ISAAC_PYTHON="/absolute/path/to/isaaclab/.venv/bin/python"
mkdir -p "$REALITY_VIEW_ROOT" "$ALPAMAYO_ROOT"
nvidia-smi
앞의 변수는 결과와 모델을 어디에 저장할지 정합니다. 서버 주소나 인증 정보를 넣는 자리가 아닙니다. GPU에 다른 작업이 없는지 확인한 뒤 진행하세요. uv를 설치하고 계정에 따라 필요한 Hugging Face 인증을 마쳤다면 다음을 실행합니다.
bash labs/reality-view/setup_models.sh
docker pull nvcr.io/nvidia/nre/nre-ga:26.04
실행기는 run.sh에 확인한 컨테이너 digest를 고정했습니다. NuRec 런타임의 약관, Harmonizer의 NVIDIA Open Model License, Alpamayo 가중치의 OpenMDW-1.1은 이 저장소의 MIT 코드 라이선스와 각각 구분됩니다. 사전 학습 가중치는 저장소에 포함하지 않았습니다. 고정 버전과 공식 라이선스
3. 도로를 촬영하고 NCore로 변환하기
Omniverse 약관을 확인한 후 동의 변수를 설정합니다. capture는 자체 제작 USD를 열어 이미지와 카메라 정보를 저장합니다. prepare는 이를 NCore와 Gaussian 초기값으로 변환합니다.
export OMNI_KIT_ACCEPT_EULA=YES
bash labs/reality-view/run.sh capture
bash labs/reality-view/run.sh prepare
CAPTURE complete: 120 training, 40 held-out, 22 policy frames가 출력되는지 확인하세요. 변환 후에는 prepared.json과 ncore/own-road.json이 생깁니다. 다시 시도할 때는 새 결과 폴더를 사용하세요. NCore 작성기는 기존 데이터 그룹에 같은 항목을 덧쓰지 않습니다.
카메라 ID camera_front_wide_120fov는 기존 연동에서 쓰는 식별자입니다. 실제 카메라의 수평 화각은 90°인 pinhole 모델이며, 파일에 저장한 내부 파라미터를 기준으로 동작합니다.
4. NuRec 학습 → 새 시점 렌더링 → Harmonizer 실행
bash labs/reality-view/run.sh train
bash labs/reality-view/run.sh render
bash labs/reality-view/run.sh enhance
학습이 끝나면 train/<run-id>/artifacts/last.usdz가 생깁니다. render는 검사용 USD와 똑같은 카메라 자세를 novel-rig.json으로 만들고, --renderer gsplat을 명시해 렌더링합니다. 이번 아티팩트에서는 26.04의 기본 렌더러가 멈추는 문제가 있어 이 경로를 사용했습니다.
성공하면 novel/에 PNG 40장, enhanced/에 보정 PNG 40장, 그리고 harmonizer-result.json이 생깁니다. TorchScript 추론에는 이 NuRec 이미지의 Transformer Engine 연산이 필요합니다. 체크포인트 내부의 CPU·GPU 상수 배치를 유지해야 하며, 초기 시험에서 모든 상수를 CUDA로 옮겼을 때는 장치 불일치가 발생했습니다.
5. 주행 모델을 실행하고 영상 만들기
bash labs/reality-view/run.sh policy
alpamayo/output.safetensors와 alpamayo/receipt.json이 만들어질 때까지 기다립니다. 실행기는 모델 가중치 파일 두 개의 SHA-256을 확인합니다. 실제 추론은 기존 Alpamayo 실행 코드를 재사용합니다.
NumPy·Pillow·FFmpeg가 있는 CPU 환경에서 한글 글꼴 경로를 지정하면 영상을 만들 수 있습니다.
python labs/reality-view/package.py \
--input "$REALITY_VIEW_ROOT" \
--output "$REALITY_VIEW_ROOT/published" \
--font /absolute/path/to/NotoSansKR.ttf
영문·한국어 20초 비교 영상, NuRec·Harmonizer·경로 표시 단독 영상, 비교 이미지와 측정 JSON을 만듭니다. 영상은 보기 편하게 재생 속도를 편집한 결과입니다. 모델이 실제로 그 속도로 추론한다는 뜻은 아닙니다.
결과 확인하기
| 확인 항목 | 이번 실행의 측정값 | 읽는 방법 |
|---|---|---|
| NuRec 학습 | 2,400스텝, 67.42초 | 설치·데이터 준비를 제외한 학습 구간 시간 |
| 새 시점 NuRec / Harmonizer PSNR | 29.21 / 27.09 dB, 같은 시점 40장 | 이 단순한 합성 장면에서는 보정 후 원본과의 픽셀 일치도가 낮아짐 |
| 프레임별 Harmonizer | 첫 프레임 제외 중앙값 0.1285초/장, 첫 프레임 12.55초 | GPU 동기화를 포함한 추론 시간. 이미지 입출력·모델 로딩 제외 |
| Alpamayo | 로딩·입력 처리 포함 23.43초, run_data 기록 19.24초 |
한 번의 예측에 걸린 시간. 실시간 성능으로 해석할 수 없음 |
| Alpamayo PyTorch 최대 할당량 | 5.76GiB | 드라이버 등을 포함한 전체 GPU 사용량과는 다름 |
| 미래 자세 | XYZ·회전 64쌍 모두 유한값 | 입출력 검사이며 주행 안전성·충돌 회피 평가가 아님 |
차선 가장자리, 차량 경계, 새로 드러난 지면을 살펴보세요. 전체 화면 PSNR에는 단순한 하늘·땅 영역도 크게 반영됩니다. 객체 인식이나 주행 정책의 점수로 대신 쓸 수 없습니다. 이번 결과를 소개할 때는 Harmonizer 적용 후 PSNR이 낮아졌다는 점도 함께 남깁니다.
전체 촬영 데이터와 원래 USD, 학습한 NuRec 아티팩트는 로컬 결과 폴더에 보관합니다. 저장소에는 가벼운 영상, 손실 없는 샘플 이미지 9장, 미래 자세 64개 JSON, 실행 기록을 넣었습니다. NVIDIA 주행 데이터셋과 사전 학습 체크포인트는 포함하지 않았습니다.
이어서 보기: NuRec 동작 원리 · Alpamayo 동작 원리 · AlpaSim 폐루프 평가. 폐루프로 확장하려면 제어를 적용한 다음 위치에서 센서 영상을 다시 만들고 재추론해야 하며, 충돌·도로 이탈도 따로 평가해야 합니다.
실행 영상과 기록
실습 소스 코드
setup_models.sh
GitHub에서 파일 보기#!/usr/bin/env bash
set -euo pipefail
model_root="${ALPAMAYO_ROOT:?Choose a separate folder for model code, environment and weights}"
task_root="${REALITY_VIEW_ROOT:?Choose the task output folder}"
uv_bin="${UV_BIN:-uv}"
mkdir -p "$model_root" "$task_root/checkpoints/Harmonizer"
source_root="$model_root/alpamayo2-edge"
if [[ ! -d "$source_root/.git" ]]; then
git clone https://github.com/NVlabs/alpamayo2-edge.git "$source_root"
fi
if [[ -n "$(git -C "$source_root" status --porcelain)" ]]; then
printf '%s\n' 'The Alpamayo checkout has local changes. Use a clean model folder.' >&2
exit 1
fi
git -C "$source_root" fetch origin 02f55a7aeabc1a2b9f7a80445c08e40bddc89f5e
git -C "$source_root" checkout --detach 02f55a7aeabc1a2b9f7a80445c08e40bddc89f5e
(cd "$source_root" && "$uv_bin" sync --locked --extra dataset --no-default-groups)
"$source_root/.venv/bin/hf" download nvidia/Alpamayo2-Edge \
--revision b92b6aa326bd3e2235db28f248ad5a30b5890e64 --local-dir "$model_root/checkpoints/Alpamayo2-Edge"
"$source_root/.venv/bin/hf" download nvidia/Harmonizer harmonizer_nontemporal.pt \
--revision 20ca33d4612b1e98e0526b3a7ee604af5b289f58 --local-dir "$task_root/checkpoints/Harmonizer"
run.sh
GitHub에서 파일 보기#!/usr/bin/env bash
set -euo pipefail
lab_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
repo_dir="$(cd -- "$lab_dir/../.." && pwd)"
task_root="${REALITY_VIEW_ROOT:?Set REALITY_VIEW_ROOT to an isolated output folder}"
mkdir -p "$task_root/runtime-home"
task_root="$(cd -- "$task_root" && pwd)"
image="nvcr.io/nvidia/nre/nre-ga:26.04@sha256:97f43e7130c5636ce3e80ea3184d97f56a87fdd989b05cce42230881dbdea284"
base=(docker run --rm --gpus all --shm-size=8g --user "$(id -u):$(id -g)"
-v "$task_root:/work" -v "$lab_dir:/lab:ro" -e REALITY_VIEW_ROOT=/work -e HOME=/work/runtime-home)
lock="${GPU_LOCK:-/tmp/physical-ai-four-domains.gpu.lock}"
case "${1:-help}" in
capture)
HEADLESS=1 flock "$lock" "${ISAAC_PYTHON:?Set ISAAC_PYTHON to your Isaac Lab Python executable}" \
"$lab_dir/capture_road.py" --scene "$repo_dir/labs/world-driving/evidence/synthetic-intersection/synthetic-intersection.usda" \
--output "$task_root/capture" --positions 40 --visualizer kit
;;
prepare)
"${base[@]}" "$image" run-script /lab/prepare_ncore.py
;;
train)
flock "$lock" "${base[@]}" -v "$lab_dir/road.yaml:/app/run.runfiles/_main/configs/reality-view.yaml:ro" \
"$image" main --config-name reality-view.yaml 2>&1 | tee "$task_root/nurec-train.log"
python3 "$lab_dir/collect_training.py"
;;
render)
python3 "$lab_dir/make_trajectory.py"
artifact="$(python3 -c 'import json,os; print(json.load(open(os.path.join(os.environ["REALITY_VIEW_ROOT"],"artifact.json")))["artifact"])')"
flock "$lock" "${base[@]}" "$image" render --artifact-path "/work/$artifact" --output-dir /work/novel \
--camera-id camera_front_wide_120fov --height 576 --renderer gsplat --custom-rig-trajectory /work/novel-rig.json \
--no-replicate-training-views --calib-source training-rig-poses --save-workers 2
;;
enhance)
flock "$lock" "${base[@]}" "$image" run-script /lab/enhance.py
;;
policy)
model_root="${ALPAMAYO_ROOT:?Set ALPAMAYO_ROOT to the folder prepared by setup_models.sh}"
flock "$lock" "$model_root/alpamayo2-edge/.venv/bin/python" "$repo_dir/labs/world-driving/run_alpamayo_synthetic.py" \
--input "$task_root/capture/policy" --model "$model_root/checkpoints/Alpamayo2-Edge" --output "$task_root/alpamayo"
;;
*) printf '%s\n' 'Choose capture, prepare, train, render, enhance, or policy. See the bilingual lab guide.'; exit 2 ;;
esac
model-pins.json
GitHub에서 파일 보기{
"checked_at": "2026-11-23",
"nurec": {
"image": "nvcr.io/nvidia/nre/nre-ga:26.04",
"documentation": "https://docs.nvidia.com/nurec/",
"note": "Use the matching 26.04 CLI and nre namespace; current documentation also describes newer APIs. Runtime terms differ from the Apache-2.0 public SDK.",
"digest": "sha256:97f43e7130c5636ce3e80ea3184d97f56a87fdd989b05cce42230881dbdea284"
},
"harmonizer": {
"model": "nvidia/Harmonizer",
"revision": "20ca33d4612b1e98e0526b3a7ee604af5b289f58",
"filename": "harmonizer_nontemporal.pt",
"mode": "non-temporal; no history conditioning",
"license": "NVIDIA Open Model License",
"license_url": "https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-open-model-license/",
"source": "https://github.com/NVIDIA/harmonizer",
"source_license": "Apache-2.0",
"attribution": "Built on NVIDIA Cosmos",
"sha256": "ece8e2daa914e8c2a027a2da94e0eb2064491d5b3fd8514009fae9a442e06e90"
},
"alpamayo": {
"source": "https://github.com/NVlabs/alpamayo2-edge",
"source_revision": "02f55a7aeabc1a2b9f7a80445c08e40bddc89f5e",
"model": "nvidia/Alpamayo2-Edge",
"model_revision": "b92b6aa326bd3e2235db28f248ad5a30b5890e64",
"source_license": "Apache-2.0",
"weights_license": "OpenMDW-1.1"
},
"inputs": "Self-authored primitive-only Isaac Sim road; no PhysicalAI-AV or NuRec dataset images/artifacts."
}
capture_road.py
GitHub에서 파일 보기"""Capture our primitive-only road as calibrated RGB/depth, held-out views and VLA inputs.
Run with Isaac Lab's Python, using the scene committed in this repository.
No downloaded driving scenes, textures, actors or NVIDIA dataset frames are used.
"""
import argparse
import hashlib
import json
import math
from importlib.metadata import version
from pathlib import Path
from isaaclab.app import AppLauncher
parser = argparse.ArgumentParser()
parser.add_argument('--scene', type=Path, required=True)
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--positions', type=int, default=40)
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 pxr import Gf, UsdGeom
out = args.output
out.mkdir(parents=True, exist_ok=True)
omni.usd.get_context().open_stage(str(args.scene.resolve()))
for _ in range(30):
app.update()
stage = omni.usd.get_context().get_stage()
camera = UsdGeom.Camera.Get(stage, '/World/Camera')
op = camera.MakeMatrixXform()
w, h = 1024, 576
aperture = 20.955
camera.GetHorizontalApertureAttr().Set(aperture)
camera.CreateVerticalApertureAttr(aperture * h / w)
camera.GetClippingRangeAttr().Set(Gf.Vec2f(.1, 250))
product = rep.create.render_product(str(camera.GetPath()), (w, h))
rgb_reader = rep.AnnotatorRegistry.get_annotator('rgb')
depth_reader = rep.AnnotatorRegistry.get_annotator('distance_to_image_plane')
for reader in [rgb_reader, depth_reader]:
reader.attach([product])
def capture(folder, name, eye, yaw=0., focal=10.4775, depth=False):
folder.mkdir(exist_ok=True, parents=True)
target = Gf.Vec3d(*eye) + Gf.Vec3d(30 * math.cos(yaw), 30 * math.sin(yaw), -.2)
matrix = Gf.Matrix4d(1).SetLookAt(Gf.Vec3d(*eye), target, Gf.Vec3d(0, 0, 1)).GetInverse()
op.Set(matrix)
camera.GetFocalLengthAttr().Set(focal)
for _ in range(10):
app.update()
rgb = np.asarray(rgb_reader.get_data())[:, :, :3].copy()
if rgb.shape != (h, w, 3) or rgb.mean() < 3:
raise RuntimeError('Camera returned an empty or unexpected image')
path = folder / f'{name}.png'
Image.fromarray(rgb).save(path)
# USD uses row vectors, -Z forward, +Y up. NCore/OpenCV uses +Z forward, +Y down.
c2w = np.asarray(matrix, dtype=np.float64).T @ np.diag([1., -1., -1., 1.])
K = [[focal / aperture * w, 0, w / 2], [0, focal / aperture * w, h / 2], [0, 0, 1]]
if depth:
z = np.asarray(depth_reader.get_data()).reshape(h, w).copy()
np.save(folder / f'{name}.depth.npy', z)
return {'image': str(path.relative_to(out)), 'camera_to_world': c2w.tolist(), 'K': K,
'sha256': hashlib.sha256(path.read_bytes()).hexdigest()}
train = []
for track, y in enumerate([-2.6, -1.8, -1.0]):
for i, x in enumerate(np.linspace(-14, 12, args.positions)):
row = capture(out/'train', f'{len(train):05d}', (float(x), y, 1.6), depth=True)
row['timestamp_us'] = 1_000_000 + len(train) * 100_000
train.append(row)
print(f'CAPTURE training track {track + 1}/3 completed', flush=True)
novel = []
for i, x in enumerate(np.linspace(-12, 10, args.positions)):
row = capture(out/'held-out', f'{i:05d}', (float(x), -1.4, 2.6))
row['timestamp_us'] = 1_000_000 + i * 100_000
novel.append(row)
print('CAPTURE held-out elevated camera completed', flush=True)
# Same six camera IDs/time history as the existing, pinned Alpamayo 2 Edge wrapper.
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 = []
policy = out/'policy'
for camera_id, (degrees, times, focal) in profiles.items():
for offset in times:
name = f'camera-{camera_id}-t{round((offset + 2)*1e6):07d}'
row = capture(policy, name, (offset * 5, -1.8, 1.6), math.radians(degrees), focal)
# Match the pre-existing smoke test resolution, without changing the scene aspect ratio.
p = out/row['image']
Image.open(p).resize((640, 360), Image.Resampling.LANCZOS).save(p)
shots.append({'camera_id': camera_id, 'timestamp_us': round((offset + 2)*1e6),
'relative_time_s': offset, 'image': p.name,
'sha256': hashlib.sha256(p.read_bytes()).hexdigest()})
manifest = {'schema': 1, 'runtime': {'isaac_sim': version('isaacsim'), 'isaac_lab': version('isaaclab')}, 'source': 'self-authored primitive-only Isaac Sim road',
'width': w, 'height': h, 'units': 'meters', 'camera_convention': 'OpenCV: x right, y down, z forward',
'world_convention': 'x road forward, y left, z up', 'train': train, 'held_out': novel,
'held_out_offset': 'elevated by 1.0 m; y=-1.4 m between capture tracks',
'scene_sha256': hashlib.sha256(args.scene.read_bytes()).hexdigest()}
(out/'capture.json').write_text(json.dumps(manifest, indent=2)+'\n')
(policy/'input.json').write_text(json.dumps({'kind': 'self-authored road; model interface experiment',
'width': 640, 'height': 360, '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')
stage.GetRootLayer().Export(str(out/'road.usda'))
for reader in [rgb_reader, depth_reader]:
reader.detach([product])
print(f'CAPTURE complete: {len(train)} training, {len(novel)} held-out, {len(shots)} policy frames', flush=True)
app.close()
prepare_ncore.py
GitHub에서 파일 보기"""Convert calibrated, self-authored RGB/depth into NCore V4 and a Gaussian seed.
Run through NuRec 26.04 `run-script` with REALITY_VIEW_ROOT set to the task folder.
Depth is synthetic ground truth, not an estimated sensor measurement. This lab
therefore studies reconstruction/rendering, not monocular geometry recovery.
"""
import json
import os
from pathlib import Path
import numpy as np
from PIL import Image
from upath import UPath
from ncore.data import OpenCVPinholeCameraModelParameters, ShutterType
from ncore.data.v4 import (SequenceComponentGroupsWriter, SequenceComponentGroupsReader,
PosesComponent, IntrinsicsComponent, MasksComponent,
CameraSensorComponent, CuboidsComponent)
from ncore.impl.common.transformations import HalfClosedInterval
root = Path(os.environ['REALITY_VIEW_ROOT'])
capture = root/'capture'
meta = json.loads((capture/'capture.json').read_text())
rows = meta['train']
times = np.array([r['timestamp_us'] for r in rows], dtype=np.uint64)
output = root/'ncore'
output.mkdir(exist_ok=True)
writer = SequenceComponentGroupsWriter(UPath(output), 'own-road', 'own-road',
HalfClosedInterval.from_start_end(int(times[0]), int(times[-1])),
{'source': 'self-authored Isaac Sim road; synthetic depth and calibration'}, store_type='directory')
def register(cls, name='default'):
return writer.register_component_writer(cls.Writer, component_instance_name=name, group_name='default')
poses = register(PosesComponent)
camera_to_rig = np.array([[0,0,1,0],[-1,0,0,0],[0,-1,0,1.6],[0,0,0,1]], dtype=np.float64)
c2w = np.array([r['camera_to_world'] for r in rows], dtype=np.float64)
rigs = c2w @ np.linalg.inv(camera_to_rig)
poses.store_dynamic_pose('rig', 'world', rigs.astype(np.float32), times)
poses.store_static_pose('camera_front_wide_120fov', 'rig', camera_to_rig.astype(np.float32))
poses.store_static_pose('world', 'world_global', np.eye(4, dtype=np.float64))
K = np.array(rows[0]['K'])
intrinsics = register(IntrinsicsComponent)
intrinsics.store_camera_intrinsics('camera_front_wide_120fov', OpenCVPinholeCameraModelParameters(
resolution=np.array([meta['width'], meta['height']], dtype=np.uint64),
shutter_type=ShutterType.GLOBAL, principal_point=K[:2,2].astype(np.float32),
focal_length=np.array([K[0,0],K[1,1]],dtype=np.float32), radial_coeffs=np.zeros(6,dtype=np.float32),
tangential_coeffs=np.zeros(2,dtype=np.float32), thin_prism_coeffs=np.zeros(4,dtype=np.float32)))
# This name follows AlpaSim/NuRec conventions; actual intrinsics here are 90° pinhole, not 120°.
register(MasksComponent).store_camera_masks('camera_front_wide_120fov', {})
register(CuboidsComponent).store_observations([])
frames = register(CameraSensorComponent, 'camera_front_wide_120fov')
for row in rows:
t = row['timestamp_us']
frames.store_frame(image_binary_data=(capture/row['image']).read_bytes(), image_format='png',
frame_timestamps_us=np.array([t,t],dtype=np.uint64), generic_data={}, generic_meta_data={})
paths = writer.finalize()
reader = SequenceComponentGroupsReader(paths)
(output/'own-road.json').write_text(json.dumps(reader.get_sequence_meta().to_dict(),indent=2)+'\n')
# Back-project rendered z-depth using pixel centers and known OpenCV camera transforms.
points, colors = [], []
for row in rows[::3]:
path = capture/row['image']
z = np.load(path.with_suffix('.depth.npy'))
rgb = np.array(Image.open(path).convert('RGB'))
yy, xx = np.mgrid[0:meta['height']:8, 0:meta['width']:8]
depth = z[yy,xx]
valid = np.isfinite(depth) & (depth>.2) & (depth<100)
p = np.stack([(xx+.5-K[0,2])/K[0,0]*depth, (yy+.5-K[1,2])/K[1,1]*depth, depth],axis=-1)[valid]
c = np.array(row['camera_to_world'])
points.append(p@c[:3,:3].T+c[:3,3]); colors.append(rgb[yy,xx][valid]/255.)
p = np.concatenate(points); c = np.concatenate(colors)
_, keep = np.unique(np.floor(p/.10).astype(np.int64), axis=0, return_index=True)
p,c = p[keep],c[keep]
fields = [(n,'f4') for n in ['x','y','z','nx','ny','nz','f_dc_0','f_dc_1','f_dc_2','opacity','scale_0','scale_1','scale_2','rot_0','rot_1','rot_2','rot_3']]
v = np.zeros(len(p), dtype=fields)
for i,n in enumerate(['x','y','z']):v[n]=p[:,i]
for i in range(3):v[f'f_dc_{i}']=(c[:,i]-.5)/.28209479177387814; v[f'scale_{i}']=np.log(.075)
v['opacity']=1.;v['rot_0']=1.
header = 'ply\nformat binary_little_endian 1.0\nelement vertex '+str(len(v))+'\n'+'\n'.join('property float '+n for n in v.dtype.names)+'\nend_header\n'
with (root/'seed.ply').open('wb') as stream:
stream.write(header.encode('ascii')); stream.write(v.tobytes())
report={'train_views':len(rows),'held_out_views':len(meta['held_out']),'seed_gaussians':len(p),
'seed_source':'back-projected synthetic z-depth; 0.10 m voxel subset',
'intrinsics':K.tolist(),'camera_to_rig':camera_to_rig.tolist(),
'camera_fov_degrees':90,'ncore_camera_id':'camera_front_wide_120fov',
'camera_id_note':'schema-compatible identifier; the actual calibration is 90-degree pinhole'}
(root/'prepared.json').write_text(json.dumps(report,indent=2)+'\n')
print('PREPARED',json.dumps(report),flush=True)
collect_training.py
GitHub에서 파일 보기"""Extract observed NuRec timing and configuration from a completed local run."""
import json
import os
from pathlib import Path
import re
root=Path(os.environ['REALITY_VIEW_ROOT'])
log=(root/'nurec-train.log').read_text(errors='replace')
steps=re.findall(r'Number of training steps:\s*(\d+)',log)
timing=re.findall(r'Train elapsed time:\s*([\d.]+) seconds',log)
artifacts=list((root/'train').rglob('last.usdz'))
if not steps or not timing or len(artifacts)!=1:
raise RuntimeError('A complete training log and exactly one last.usdz are required')
(root/'nurec-result.json').write_text(json.dumps({
'runtime':'26.4.149','image':'nvcr.io/nvidia/nre/nre-ga:26.04',
'renderer':'gsplat','training_steps':int(steps[-1]),'training_seconds':float(timing[-1]),
'timing_scope':'NuRec-reported training elapsed time; excludes environment setup and data preparation',
'artifact_bytes':artifacts[0].stat().st_size,
},indent=2)+'\n')
print('Collected completed NuRec training metadata')
road.yaml
GitHub에서 파일 보기# Self-authored RGB + synthetic depth seed, fitted by NuRec 26.04.
# The camera ID is a schema name; capture.json contains the actual 90-degree calibration.
defaults:
- /experimental/3dgut/3dgut_colmap
- override /model/gaussians/initialization@model.layers.background.initialization: ply
- _self_
out_dir: /work/train
mode: trainval
dataset:
path: /work/ncore/own-road.json
camera_ids: [camera_front_wide_120fov]
lidar_ids: []
n_samples_per_epoch: 2400
n_val_image_subsample: 2
train_sequential_camera_frame_step: 1
val_camera_frame_step: 12
camera_mask_sources: [dataset]
datamodule:
train_num_workers: 2
val_num_workers: 1
test_num_workers: 1
trainer:
max_epochs: 1
log_every_n_steps: 100
model:
layers:
background:
initialization:
path: /work/seed.ply
translate_world_to_nre: true
strategy:
add:
max_n_gaussians: 200000
system:
test:
video_fps: 10
metrics:
cpsnr:
enabled: false
make_trajectory.py
GitHub에서 파일 보기"""Replace a NuRec artifact's capture path with our held-out calibrated camera poses."""
import copy
import json
import os
from pathlib import Path
import zipfile
import numpy as np
root = Path(os.environ['REALITY_VIEW_ROOT'])
artifacts = list((root/'train').rglob('last.usdz'))
if len(artifacts) != 1:
raise RuntimeError(f'Expected one completed NuRec artifact, found {len(artifacts)}')
artifact = artifacts[0]
with zipfile.ZipFile(artifact) as archive:
name = next(n for n in archive.namelist() if n.endswith('rig_trajectories.json'))
rig = json.loads(archive.read(name))
rows = json.loads((root/'capture/capture.json').read_text())['held_out']
template = copy.deepcopy(rig['rig_trajectories'][0])
sensor = next(iter(template['cameras_frame_timestamps_us']))
times = [r['timestamp_us'] for r in rows]
c2r = np.array(json.loads((root/'prepared.json').read_text())['camera_to_rig'])
poses = np.array([r['camera_to_world'] for r in rows]) @ np.linalg.inv(c2r)
template['cameras_frame_timestamps_us'] = {sensor: [[t,t] for t in times]}
template['lidars_frame_timestamps_us'] = {}
template['T_rig_worlds'] = poses.tolist()
template['T_rig_world_timestamps_us'] = times
if 'cameras_frame_T_rig_worlds' in template:
template['cameras_frame_T_rig_worlds'] = {sensor: np.repeat(poses[:,None],2,axis=1).tolist()}
if 'cameras_linear_start_frame_indices' in template:
template['cameras_linear_start_frame_indices'] = {sensor:0}
if 'lidars_linear_start_frame_indices' in template:
template['lidars_linear_start_frame_indices'] = {}
rig['rig_trajectories'] = [template]
(root/'novel-rig.json').write_text(json.dumps(rig,indent=2)+'\n')
# Store only a task-relative name. A public receipt must not carry machine paths.
(root/'artifact.json').write_text(json.dumps({'artifact':str(artifact.relative_to(root)),
'novel_views':len(rows),'sensor_id':sensor},indent=2)+'\n')
print(f'NOVEL_TRAJECTORY prepared {len(rows)} calibrated poses',flush=True)
enhance.py
GitHub에서 파일 보기"""Run the official, non-temporal Harmonizer TorchScript checkpoint on NuRec frames.
Built on NVIDIA Cosmos. Model weights are obtained separately under the NVIDIA
Open Model License. This is per-frame inference; no temporal coherence is claimed.
Run inside the pinned NuRec runtime, which provides the required TE custom ops.
"""
import hashlib
import json
import os
from pathlib import Path
import time
import numpy as np
from PIL import Image
import torch
import transformer_engine # registers tex_ts::* TorchScript operations
root = Path(os.environ['REALITY_VIEW_ROOT'])
source = root/'novel'
target = root/'enhanced'
target.mkdir(exist_ok=True)
checkpoint = root/'checkpoints/Harmonizer/harmonizer_nontemporal.pt'
with checkpoint.open('rb') as stream:
checkpoint_digest = hashlib.file_digest(stream, 'sha256').hexdigest()
if checkpoint_digest != 'ece8e2daa914e8c2a027a2da94e0eb2064491d5b3fd8514009fae9a442e06e90':
raise ValueError('Harmonizer checkpoint differs from the pinned revision')
# Preserve the original placement of frozen CPU constants and CUDA weight tensors.
# Forcing map_location='cuda' also moves shape/timestep constants and breaks the trace.
model = torch.jit.load(str(checkpoint)).eval().cuda()
files = sorted(source.rglob('*.png'))
if not files:
raise RuntimeError('Render the novel-view sequence before running Harmonizer')
latencies = []
torch.cuda.reset_peak_memory_stats()
for i, path in enumerate(files):
rgb = np.array(Image.open(path).convert('RGB').resize((1024,576)))
x = torch.from_numpy(rgb.copy()).permute(2,0,1)[None,:,None].cuda().float()/127.5-1
torch.cuda.synchronize()
start = time.perf_counter()
with torch.inference_mode(), torch.amp.autocast('cuda', enabled=False):
y = model(x)
torch.cuda.synchronize()
latency = time.perf_counter()-start
if not torch.isfinite(y).all():
raise RuntimeError('Harmonizer produced nonfinite values')
if y.ndim == 5:y=y[:,:,0]
if tuple(y.shape) != (1,3,576,1024):
raise RuntimeError(f'Unexpected output shape: {list(y.shape)}')
result = ((y[0].float().permute(1,2,0).cpu().numpy()+1)*127.5).clip(0,255).astype('uint8')
Image.fromarray(result).save(target/path.name)
latencies.append(latency)
if i%10==0:print(f'HARMONIZER frame {i+1}/{len(files)}: {latency:.3f} s',flush=True)
receipt={'mode':'non-temporal single-frame; no previous-frame conditioning',
'model_id':'nvidia/Harmonizer','model_revision':'20ca33d4612b1e98e0526b3a7ee604af5b289f58',
'checkpoint':'harmonizer_nontemporal.pt','checkpoint_sha256':checkpoint_digest,
'frames':len(files),'resolution':[1024,576],'per_frame_seconds':latencies,
'median_seconds_excluding_first':float(np.median(latencies[1:])) if len(files)>1 else latencies[0],
'peak_allocated_gib':torch.cuda.max_memory_allocated()/2**30,
'torch':torch.__version__,'transformer_engine':transformer_engine.__version__,
'attribution':'Built on NVIDIA Cosmos','weights_license':'NVIDIA Open Model License'}
(root/'harmonizer-result.json').write_text(json.dumps(receipt,indent=2)+'\n')
print('HARMONIZER completed',flush=True)
package.py
GitHub에서 파일 보기"""Build videos, matched-frame measurements and a small, inspectable evidence bundle.
CPU only. Requires numpy, Pillow and ffmpeg. Model inference is never replaced by
this compositor: it only reads the outputs of completed NuRec/Harmonizer/Alpamayo jobs.
"""
import argparse
import hashlib
import json
import math
from pathlib import Path
import struct
import subprocess
import numpy as np
from PIL import Image, ImageDraw, ImageFont
parser=argparse.ArgumentParser()
parser.add_argument('--input',type=Path,required=True)
parser.add_argument('--output',type=Path,required=True)
parser.add_argument('--font',type=Path,required=True,help='Font with Korean glyphs, e.g. Noto Sans CJK')
args=parser.parse_args()
r=args.input;out=args.output;out.mkdir(parents=True,exist_ok=True)
meta=json.loads((r/'capture/capture.json').read_text())
raw=sorted((r/'novel').rglob('*.png'))
enhanced=sorted((r/'enhanced').glob('*.png'))
reference=[r/'capture'/row['image'] for row in meta['held_out']]
assert len(raw)==len(enhanced)==len(reference)==40
def image(path):return Image.open(path).convert('RGB')
def sha(path):
with path.open('rb') as stream:return hashlib.file_digest(stream,'sha256').hexdigest()
def psnr(a,b):
mse=np.mean(((np.asarray(a,dtype=np.float64)-np.asarray(b,dtype=np.float64))/255)**2)
return -10*math.log10(max(float(mse),1e-12))
per_frame=[]
for i,(a,b,c) in enumerate(zip(reference,raw,enhanced,strict=True)):
per_frame.append({'frame':i,'nurec_psnr_db':psnr(image(a),image(b)),
'harmonizer_psnr_db':psnr(image(a),image(c))})
# Read the actual saved tensors without requiring torch or safetensors on the CPU.
blob=(r/'alpamayo/output.safetensors').read_bytes();n=struct.unpack('<Q',blob[:8])[0]
header=json.loads(blob[8:8+n]);payload=blob[8+n:]
def tensor(key):
spec=header[key];assert spec['dtype']=='F32';begin,end=spec['data_offsets']
return np.frombuffer(payload[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) and np.isfinite(xyz).all() and np.isfinite(rot).all()
trajectory={'frame':'ego at query time: x forward, y left, z up; meters',
'dt_seconds':.1,'xyz_m':xyz.tolist(),'rotation_matrices':rot.tolist(),
'world_ego_origin_m':[0,-1.8,0],'scope':'one inference; no controls, dynamics or closed-loop evaluation'}
(out/'trajectory.json').write_text(json.dumps(trajectory,indent=2)+'\n')
# Keep three lossless matched triplets for GPU-free numerical and visual checks.
frames_dir=out/'frames';frames_dir.mkdir(exist_ok=True)
files={}
for i in [0,20,39]:
for kind,paths in [('reference',reference),('nurec',raw),('harmonizer',enhanced)]:
p=frames_dir/f'{i:02d}-{kind}.png';p.write_bytes(paths[i].read_bytes());files[str(p.relative_to(out))]=sha(p)
font=ImageFont.truetype(str(args.font),23);small=ImageFont.truetype(str(args.font),18)
for f, weight in [(font,450),(small,400)]:
try:
if len(f.get_variation_axes()) == 1:f.set_variation_by_axes([weight])
except OSError:
pass
labels={
'en':['Original USD: held-out camera','NuRec: novel viewpoint','Harmonizer: non-temporal','Alpamayo 2 Edge: predicted path','Single prediction, not closed-loop driving','Built on NVIDIA Cosmos'],
'ko':['원래 USD · 별도 검사 카메라','NuRec · 새 시점 렌더링','Harmonizer · 프레임별 보정','Alpamayo 2 Edge · 예측 경로','단일 예측 경로 · 폐루프 주행 아님','Built on NVIDIA Cosmos']}
def caption(canvas,text,x=18,y=17):
d=ImageDraw.Draw(canvas);b=d.textbbox((x,y),text,font=font)
d.rounded_rectangle((b[0]-9,b[1]-6,b[2]+9,b[3]+6),radius=5,fill=(255,255,255))
d.text((x,y),text,font=font,fill=(30,35,39))
def projected_path(canvas,row,visible=64):
# Use the model's full 3D prediction. Do not flatten its z coordinates or invent a lane-following path.
p=xyz[:visible].astype(np.float64)+np.array([0,-1.8,.08])
c=np.array(row['camera_to_world']);cam=(p-c[:3,3])@c[:3,:3]
K=np.array(row['K']);u=K[0,0]*cam[:,0]/np.maximum(cam[:,2],1e-6)+K[0,2]
v=K[1,1]*cam[:,1]/np.maximum(cam[:,2],1e-6)+K[1,2]
d=ImageDraw.Draw(canvas);last=None
for i,(a,b,z) in enumerate(zip(u,v,cam[:,2],strict=True)):
valid=z>.2 and 0<=a<1024 and 0<=b<576
if valid:
point=(float(a),float(b))
if last is not None:d.line([last,point],fill=(70,185,0),width=7)
if i%4==0:d.ellipse((a-5,b-5,a+5,b+5),fill=(255,255,255),outline=(38,104,0),width=2)
last=point
else:last=None
# BEV preserves the complete trajectory even when its beginning falls below the camera.
x0,y0=802,326;d.rounded_rectangle((x0,y0,1008,558),radius=8,fill=(255,255,255),outline=(170,180,188))
xs=np.r_[0,xyz[:,0]];ys=np.r_[0,xyz[:,1]]
span_x=max(float(xs.max()-xs.min()),15);span_y=max(float(ys.max()-ys.min()),8)
def bev(x,y):return (905-float(y)*170/span_y,535-float(x-xs.min())*180/span_x)
d.line([bev(x,y) for x,y in zip(xyz[:visible,0],xyz[:visible,1])],fill=(70,160,0),width=4)
d.ellipse((900,530,910,540),fill=(20,60,130));d.text((x0+10,y0+7),'BEV · meters',font=small,fill=(40,45,50))
return canvas
def encode(path,frames,fps=20):
proc=subprocess.Popen(['ffmpeg','-hide_banner','-loglevel','error','-y','-f','rawvideo','-pix_fmt','rgb24',
'-s','1280x720','-r',str(fps),'-i','pipe:0','-an','-c:v','libx264','-preset','fast','-crf','22',
'-pix_fmt','yuv420p','-movflags','+faststart',str(path)],stdin=subprocess.PIPE)
try:
for frame in frames:proc.stdin.write(frame.resize((1280,720),Image.Resampling.LANCZOS).tobytes())
finally:proc.stdin.close()
if proc.wait()!=0:raise RuntimeError('Video encoding failed')
def montage(lang):
l=labels[lang]
# Each 40-frame sweep is played in 8 seconds. This is editing speed, not measured inference FPS.
for i in range(160):
j=min(i//4,39);canvas=Image.new('RGB',(1024,576),'white')
left=image(raw[j]).resize((512,288));right=image(enhanced[j]).resize((512,288))
canvas.paste(left,(0,145));canvas.paste(right,(512,145))
caption(canvas,l[1],15,98);caption(canvas,l[2],526,98)
ImageDraw.Draw(canvas).text((20,476),l[5],font=small,fill=(60,65,70))
yield canvas
for i in range(160):
# A fixed novel camera isolates the route from motion of the display camera.
canvas=projected_path(image(enhanced[20]),meta['held_out'][20],max(2,round(64*(i+1)/160)))
caption(canvas,l[3]);caption(canvas,l[4],18,74)
yield canvas
for i in range(80):
j=min(i//2,39);canvas=Image.new('RGB',(1024,576),'white')
for col,(paths,label) in enumerate([(reference,l[0]),(raw,l[1]),(enhanced,l[2])]):
thumb=image(paths[j]).resize((336,189));canvas.paste(thumb,(col*344,205))
ImageDraw.Draw(canvas).text((col*344+7,166),label,font=small,fill=(40,45,50))
yield canvas
for lang in ['en','ko']:
encode(out/f'reality-view.{lang}.mp4',montage(lang))
next(montage(lang)).resize((1280,720)).save(out/f'reality-view.{lang}.jpg',quality=90)
poster=next(montage('en'));poster.resize((1280,720)).save(out/'reality-view.jpg',quality=90)
# A dedicated, uncut before/after sweep and path view are useful for inspection.
for name,kind in [('nurec-novel',raw),('harmonizer-novel',enhanced)]:
encode(out/f'{name}.mp4',(image(kind[min(i//4,39)]) for i in range(160)))
encode(out/'alpamayo-overlay.mp4',(projected_path(image(enhanced[20]),meta['held_out'][20],max(2,round(64*(i+1)/160))) for i in range(160)))
training=json.loads((r/'nurec-result.json').read_text())
prepared=json.loads((r/'prepared.json').read_text());harm=json.loads((r/'harmonizer-result.json').read_text());alpa=json.loads((r/'alpamayo/receipt.json').read_text())
report={'recorded_at':'2026-11-23','scope':'self-authored synthetic road; reconstructed rendering, per-frame enhancement and one trajectory prediction',
'capture_runtime':meta['runtime'],
'data_source':'Only our primitive-only USD scene; no NVIDIA PhysicalAI-AV/NuRec dataset content',
'nurec':{**training,
'train_views':prepared['train_views'],'held_out_views':prepared['held_out_views'],'seed_gaussians':prepared['seed_gaussians'],
'resolution':[1024,576],'held_out_camera_height_delta_m':1.,'seed_uses_training_depth_only':True,
'held_out_mean_psnr_db':float(np.mean([f['nurec_psnr_db'] for f in per_frame]))},
'harmonizer':harm,'alpamayo':alpa,'comparison':{'alignment':'same K and held-out camera poses; original USD is reference',
'nurec_mean_psnr_db':float(np.mean([f['nurec_psnr_db'] for f in per_frame])),
'harmonizer_mean_psnr_db':float(np.mean([f['harmonizer_psnr_db'] for f in per_frame])), 'frames':per_frame},
'limitations':['Static primitive-only scene; domain shift from real driving data',
'Non-temporal Harmonizer can alter geometry/appearance and does not guarantee temporal consistency',
'Alpamayo input is raw Isaac Sim RGB, not enhanced frames or NuRec sensor output',
'One inference and a display overlay; no controls, vehicle physics or closed-loop safety evaluation',
'Display playback speed differs from measured model inference throughput'],
'files':files}
for p in out.glob('*.mp4'):report['files'][p.name]=sha(p)
report['files']['trajectory.json']=sha(out/'trajectory.json')
(out/'recorded.json').write_text(json.dumps(report,indent=2)+'\n')
print(json.dumps({'comparison':report['comparison']|{'frames':len(per_frame)},'videos':len(list(out.glob('*.mp4')))},indent=2))
check.py
GitHub에서 파일 보기"""Verify published model outputs on a CPU; requires numpy and Pillow, optionally ffmpeg."""
import argparse
import hashlib
import json
import math
from pathlib import Path
import shutil
import subprocess
import numpy as np
from PIL import Image
def main():
parser=argparse.ArgumentParser()
parser.add_argument('--root',type=Path,default=Path(__file__).resolve().parent)
parser.add_argument('--decode-video',action='store_true')
args=parser.parse_args()
root=args.root
report=json.loads((root/'recorded.json').read_text())
for name,digest in report['files'].items():
path=root/name
with path.open('rb') as stream:actual=hashlib.file_digest(stream,'sha256').hexdigest()
if actual!=digest:raise ValueError(f'Changed evidence file: {name}')
trajectory=json.loads((root/'evidence/trajectory.json').read_text())
xyz=np.array(trajectory['xyz_m']);rot=np.array(trajectory['rotation_matrices'])
assert xyz.shape==(64,3) and rot.shape==(64,3,3)
assert np.isfinite(xyz).all() and np.isfinite(rot).all()
assert np.max(np.abs(rot@rot.transpose(0,2,1)-np.eye(3)))<1e-4
assert np.max(np.abs(np.linalg.det(rot)-1))<1e-4
recalculated=[]
for i in [0,20,39]:
folder=root/'evidence/frames'
reference=np.asarray(Image.open(folder/f'{i:02d}-reference.png').convert('RGB'),dtype=np.float64)/255
assert reference.shape==(576,1024,3)
row={'frame':i}
for kind in ['nurec','harmonizer']:
actual=np.asarray(Image.open(folder/f'{i:02d}-{kind}.png').convert('RGB'),dtype=np.float64)/255
assert actual.shape==reference.shape
value=-10*math.log10(max(float(np.mean((actual-reference)**2)),1e-12))
assert abs(value-report['comparison']['frames'][i][kind+'_psnr_db'])<1e-8
row[kind+'_psnr_db']=round(value,4)
recalculated.append(row)
assert report['nurec']['seed_uses_training_depth_only']
assert report['nurec']['train_views']==120 and report['nurec']['held_out_views']==40
assert report['alpamayo']['result']['finite']
assert report['alpamayo']['result']['pred_xyz_shape']==[1,1,1,64,3]
assert report['harmonizer']['frames']==40
if args.decode_video:
if not shutil.which('ffmpeg'):raise RuntimeError('Install ffmpeg to decode videos')
for name in report['files']:
if name.endswith('.mp4'):
subprocess.run(['ffmpeg','-v','error','-xerror','-i',str(root/name),'-f','null','-'],check=True)
print(json.dumps({'verified_files':len(report['files']),'finite_poses':64,
'matched_frame_psnr':recalculated,'video_decode':args.decode_video},indent=2))
if __name__=='__main__':main()
ego-car.json
GitHub에서 파일 보기{
"vehicle": "Volvo S90 Recharge",
"asset_title": "Volvo S90 Recharge (Free)",
"author": "lazercar",
"source": "https://sketchfab.com/3d-models/volvo-s90-recharge-free-9462b07c10244fd4a28d86846dc9e3a9",
"author_provided_download": "https://drive.google.com/file/d/1Q9Zz8getrYY5AA1f8k72rapH2kCTXKD6/view",
"license": "CC-BY-4.0",
"license_url": "https://creativecommons.org/licenses/by/4.0/",
"license_checked_from": "https://api.sketchfab.com/v3/models/9462b07c10244fd4a28d86846dc9e3a9",
"checked_at": "2026-11-23",
"archive_bytes": 1287191032,
"archive_sha256": "222d57d4ad29b7bafecb9ef0ded813d60dbb03343a124fec90b235b3e22cf087",
"mesh_note": "Actual detailed vehicle mesh supplied by its author; not a box proxy or an AI-generated imitation.",
"changes": [
"Pearl paint material",
"Coordinate alignment: source -Y nose to rig +X forward",
"Transparent-background render",
"Subdivision render level capped at 1",
"Measured PandaSet road-plane alignment and shadow-catcher layer, displayed at 22% strength"
],
"attribution": "Volvo S90 Recharge (Free) by lazercar, CC BY 4.0. Paint, orientation and rendering modified.",
"scope": "Added ego-position reference. Does not identify the original data-collection car, reproduce OEM driving dynamics, or imply manufacturer endorsement.",
"distribution": "The 1.2 GB source archive is downloaded from the author; it is not bundled in this repository. Background dataset rights remain separate."
}
render_ego_car.py
GitHub에서 파일 보기"""Render the credited Volvo asset into calibrated transparent pinhole layers.
Blender invocation (disable embedded scripts before opening third-party files):
blender --background --disable-autoexec /path/to/Volvo-S90.blend \
--python render_ego_car.py -- --textures /path/to/textures \
--views /path/to/ego-views.json --output /path/to/vehicle-layers
A view has id, width, height, a 3x3 K matrix and a 4x4 camera_to_rig
(OpenCV: right/down/forward). Rig axes are forward/left/up in meters.
This is a visual reference mesh, not an OEM physics or driving model.
"""
import argparse,json,math,sys
from pathlib import Path
import bpy
from mathutils import Matrix,Vector
p=argparse.ArgumentParser();p.add_argument('--textures',type=Path,required=True);p.add_argument('--views',type=Path,required=True);p.add_argument('--output',type=Path,required=True);p.add_argument('--ground-plane',type=Path);args=p.parse_args(sys.argv[sys.argv.index('--')+1:]);args.output.mkdir(parents=True,exist_ok=True)
scene=bpy.context.scene;images={f.name:f for f in args.textures.rglob('*') if f.is_file()}
for im in bpy.data.images:
if im.source=='FILE':
name=Path(im.filepath.replace('\\','/')).name
if name in images:
im.filepath=str(images[name])
try:im.colorspace_settings.name='Non-Color' if any(s in name.lower() for s in ['normal','roughness','height','metallic']) else 'sRGB'
except TypeError:pass
paint=bpy.data.materials.get('Car Paint')
if paint:
paint.use_nodes=True;paint.node_tree.nodes.clear();shader=paint.node_tree.nodes.new('ShaderNodeBsdfPrincipled');shader.inputs['Base Color'].default_value=(.62,.68,.73,1);shader.inputs['Metallic'].default_value=.45;shader.inputs['Roughness'].default_value=.28;shader.inputs['Coat Weight'].default_value=.7;out=paint.node_tree.nodes.new('ShaderNodeOutputMaterial');paint.node_tree.links.new(shader.outputs['BSDF'],out.inputs['Surface'])
T=Matrix(((0,-1,0,.8),(1,0,0,0),(0,0,1,-.02234119),(0,0,0,1)))
ground=Matrix.Identity(4)
if args.ground_plane:
g=json.loads(args.ground_plane.read_text());a,b,z=g['forward_slope'],g['left_slope'],g['height_at_rig_m'];n=Vector((-a,-b,1)).normalized();forward=Vector((1,0,a)).normalized();left=n.cross(forward).normalized();ground=Matrix((forward,left,n)).transposed().to_4x4();ground.translation=Vector((0,0,z));T=ground@T
for o in scene.objects:
if o.type=='MESH':
o.hide_render=False;o.hide_set(False);o.matrix_world=T@o.matrix_world
for m in o.modifiers:
if m.type=='SUBSURF':m.render_levels=min(1,m.render_levels)
# Shadow catcher contributes only contact shadows on the measured road plane.
bpy.ops.mesh.primitive_plane_add(size=100);plane=bpy.context.object;plane.name='Road shadow catcher';plane.matrix_world=ground;plane.is_shadow_catcher=True
scene.world=bpy.data.worlds.new('Ego daylight');scene.world.use_nodes=True;nodes=scene.world.node_tree.nodes;nodes.clear();bg=nodes.new('ShaderNodeBackground');bg.inputs['Strength'].default_value=.45;sky=nodes.new('ShaderNodeTexSky');sky.sky_type='NISHITA';sky.sun_disc=False;sky.sun_elevation=math.radians(40);sky.sun_rotation=math.radians(130);wo=nodes.new('ShaderNodeOutputWorld');scene.world.node_tree.links.new(sky.outputs['Color'],bg.inputs['Color']);scene.world.node_tree.links.new(bg.outputs[0],wo.inputs[0])
for name,loc,power in [('softbox',(-3,-4,7),700),('fill',(4,5,6),500)]:
d=bpy.data.lights.new(name,'AREA');d.energy=power;d.shape='DISK';d.size=5;o=bpy.data.objects.new(name,d);scene.collection.objects.link(o);o.location=loc;o.rotation_euler=(Vector((.8,0,.7))-o.location).to_track_quat('-Z','Y').to_euler()
scene.render.engine='CYCLES';scene.cycles.device='CPU';scene.cycles.samples=24;scene.cycles.use_denoising=True;scene.render.threads_mode='FIXED';scene.render.threads=10;scene.render.resolution_percentage=100;scene.render.film_transparent=True;scene.render.image_settings.file_format='PNG';scene.render.image_settings.color_mode='RGBA';scene.view_settings.view_transform='AgX';scene.view_settings.look='AgX - Medium High Contrast'
camdata=bpy.data.cameras.new('Ego pinhole');cam=bpy.data.objects.new('Ego camera',camdata);scene.collection.objects.link(cam);scene.camera=cam;camdata.type='PERSP';camdata.sensor_fit='HORIZONTAL';camdata.sensor_width=36;camdata.clip_start=.01;camdata.clip_end=100
for view in json.loads(args.views.read_text())['views']:
width,height=view['width'],view['height'];K=view['K']
if abs(K[0][1])+abs(K[1][0])>1e-6:raise ValueError('Skewed intrinsics are not supported')
if Path(view['id']).name!=view['id']:raise ValueError('View id must be a filename stem')
scene.render.resolution_x=width;scene.render.resolution_y=height;scene.render.pixel_aspect_x=1;scene.render.pixel_aspect_y=K[0][0]/K[1][1];camdata.lens=K[0][0]*36/width;camdata.shift_x=(width/2-K[0][2])/width;camdata.shift_y=(K[1][2]-height/2)/width
cam.matrix_world=Matrix(view['camera_to_rig'])@Matrix.Diagonal((1,-1,-1,1));plane.hide_render=False;scene.render.filepath=str(args.output/f"{view['id']}-shadowed.png");bpy.ops.render.render(write_still=True)
plane.hide_render=True;scene.render.filepath=str(args.output/f"{view['id']}-car.png");bpy.ops.render.render(write_still=True)
(args.output/'vehicle-attribution.txt').write_text('Volvo S90 Recharge (Free) by lazercar, CC BY 4.0. Paint, orientation and rendering modified.\nhttps://sketchfab.com/3d-models/volvo-s90-recharge-free-9462b07c10244fd4a28d86846dc9e3a9\nhttps://creativecommons.org/licenses/by/4.0/\n')



