RGB만으로 NuRec, Harmonizer, Alpamayo 연결하기

실제 마우스 시점의 NuRec 장면을 GPU Harmonizer로 보정하고 이전 출력 네 장을 이어 씁니다. 원본 RGB 인식·Alpamayo 경로와 원본·보정 화면을 비교하고 큰 시점 변경에서는 이력을 비웁니다. GPU 없이 저장된 3D 장면을 탐색하거나 로컬 서버로 직접 실행해 보세요.

  • RGB only
  • NuRec 26.04
  • Depth Anything 3
  • Harmonizer
  • Alpamayo 2 Edge
  • Mask R-CNN
RGB Reality View: 3D 기준과 시간축 생성 보정
실행 영상실행 영상과 기록

마우스로 Volvo 주변을 직접 둘러보기

NuRec에서 학습한 Gaussian을 브라우저용으로 변환한 미리보기입니다. 실제 NuRec 렌더링과 Harmonizer 보정은 아래 비교 영상에서 확인하세요.

RGB로 복원한 도로와 Volvo S90
RGB only · NuRec
—

드래그: 회전 · 휠/두 손가락: 확대 · 오른쪽 드래그: 이동

PandaSet: Scale AI / Hesai · Volvo S90: lazercar, CC BY 4.0 · 출처와 사용 조건

녹화한 RGB 클립을 먼저 복원하고 브라우저에서 시점을 움직입니다. 거리는 화면용 상대 단위이며 주변 차량은 정적 장면에 포함됩니다. Volvo는 전경에 따로 그리는 3D 위치 표시용 모델입니다.

실사 도로를 NuRec에서 복원하고, 같은 시점의 렌더링에 Harmonizer를 적용해 비교합니다. 여기에 Alpamayo 2 Edge의 예측 경로와 원본 카메라의 객체 인식 결과를 연결합니다. 복원 입력은 RGB 픽셀뿐입니다. 먼저 저장된 장면과 영상을 둘러보고 RTX 5090 한 장으로 각 단계를 따라 해 보세요.

깊이 기반 복원 개선: 아래 3D 뷰어에서 카메라 위치를 유지한 채 모델을 바꿔 보세요. RGB로 추정한 깊이·법선의 역할과 같은 조건의 비교 결과도 확인할 수 있습니다.

동작 원리

데이터는 어떻게 흐를까요?
  1. 입력RGB로 카메라 배열 추정사진 162장 → COLMAP K·자세·XYZ → rig 보정

    LiDAR·정답 센서 보정은 쓰지 않습니다. 고정 배열과 명목상 촬영 시점 가정을 드러냅니다.

  2. 처리NuRec 실행 후 원본 렌더링 보정NCore → NuRec 산출물 → 원본 RGB → Harmonizer RGB

    NuRec은 3D 표현을 학습하고 Harmonizer는 같은 시점 이미지의 외관을 예측합니다.

  3. 출력원본 카메라 관측으로 추론RGB 뷰 22개 + 추정 자세 20개 → 미래 자세 64개

    Alpamayo에는 카메라 배열·거리 스케일 가정이 있습니다. Mask R-CNN의 실제 원본 마스크는 별도입니다.

  4. 저장된 결과 함께 살펴보기NuRec Gaussian + Volvo + 접점 + 예측 경로

    브라우저는 변환한 미리보기입니다. 실제 렌더링·보정 영상은 따로 확인하며 제어는 하지 않습니다.

RGB로 카메라와 장면을 추정해 NuRec에 입력하고, NuRec 렌더링은 Harmonizer로 보정하며, 원본 RGB와 추정 주행 이력은 Alpamayo로 전달하는 흐름

1. 이번 실습에서 실제로 실행하는 도구

단계 실제 입력 → 출력 담당하는 일
COLMAP RGB 사진 162장 → 카메라 보정값·자세·희소 3D 점 사진의 특징점을 맞춰 카메라와 기하 구조를 추정합니다.
Rig bundle adjustment 사진별 추정치 → 카메라 6대·촬영 시점 27개의 고정 배열 NuRec 입력 형식에 맞춰 카메라의 상대 위치를 함께 보정합니다.
NCore 추정 카메라·RGB·SfM 점 → NuRec 시퀀스와 Gaussian 초기값 데이터를 묶는 형식과 API입니다. 신경망 모델은 아닙니다.
NuRec 26.04 NCore와 RGB 기반 초기값 → 학습 산출물·새 시점 RGB·Gaussian 실제 NuRec 런타임의 3DGUT COLMAP 구성을 실행합니다.
Harmonizer NuRec의 실제 렌더링 → 같은 시점의 보정 RGB 기존 non-temporal 기준 영상과 아래의 V1·V5 시간축 비교를 제공합니다. 3D 형상 자체는 바꾸지 않습니다.
Alpamayo 2 Edge 원본 RGB·추정한 과거 이동·주행 지시 → 시점마다 미래 자세 64개 실제 VLA 모델을 실행하고 예측을 표시합니다. 제어 명령은 적용하지 않습니다.
Mask R-CNN 원본 RGB → 종류·점수·검출 박스·객체별 마스크 Alpamayo나 보정 영상과 독립적으로 주변 차량과 사람을 인식합니다.

독립 실행형 3DGUT 실습은 비교 자료로 유지합니다. 여기서도 NuRec 내부의 3DGUT 구성을 쓰지만, NuRec의 데이터 입력·학습·렌더링·내보내기를 실제 호출한다는 점이 다릅니다. 독립 실행형 학습 결과를 NuRec 실행 결과로 바꿔 부르지 않습니다.

2. RGB-only로 어디까지 추정할까?

공개 예제에서 받는 파일은 카메라 JPEG와 원래 데이터 이용 조건뿐입니다. COLMAP은 겹쳐 찍힌 사진을 비교해 K[3,3], 카메라 자세 [4,4], 희소 점 XYZ[N,3]을 구합니다. LiDAR·외부 깊이·GPS·IMU·제공된 카메라 자세·보정값·센서 시각·객체 정답 라벨은 복원에 사용하지 않습니다.

카메라 폴더와 같은 프레임 번호를 기준으로 명목상 같은 촬영 시점을 묶습니다. 이후 카메라 상대 위치, rig의 이동, 3D 점을 함께 조정하고 왜곡 보정한 카메라의 내부 보정값은 고정합니다. 사진별 자유로운 카메라 모델의 재투영 오차는 약 0.875픽셀, 고정 배열 제약을 둔 모델은 약 1.150픽셀입니다. 배열을 고정했다고 이미지 오차가 더 작아지는 것은 아니며, 프레임 번호만으로 정밀한 센서 동기화를 입증하지도 않습니다.

NuRec에는 RGB 관측 162개와 사진에서 삼각측량한 점 약 2만 8,600개를 전달합니다. 이 점군은 RGB로 추정한 결과이며 거리 센서로 측정한 값이 아닙니다. NCore에는 rig의 이동, 고정된 카메라 상대 자세, 내부 보정값과 RGB를 저장합니다. LiDAR 데이터와 정답 객체 궤적은 없습니다.

RGB만으로는 실제 길이 단위를 확정할 수 없습니다. 카메라와 도로면 사이 높이의 중앙값을 화면 단위 1로 맞춥니다. 도로면 역시 사진의 특징점으로 추정합니다. 따라서 측량한 도로 지도나 미터 단위 좌표가 아닙니다. 모든 이미지가 SfM에 관여하므로 독립적인 새 시점 정확도 벤치마크로도 해석하지 않습니다.

3. NuRec과 Harmonizer는 무엇을 바꿀까?

NuRec은 Gaussian의 위치·회전·크기·불투명도·방향별 색을 조정합니다. 새 카메라에서 같은 Gaussian을 그리면 다른 시점의 RGB를 얻습니다. 저장된 실행은 16,000단계를 학습했습니다. 실제 시간과 모델 식별 값, Gaussian 개수는 recorded.json에 있습니다.

Harmonizer에는 NuRec이 실제 렌더링한 프레임을 값 범위 [-1,1]의 float[1,3,1,576,1024]로 넣습니다. 비교 영상의 좌우는 같은 카메라 자세와 프레임 번호를 사용합니다. 공개된 non-temporal 모델은 각 프레임을 독립적으로 처리하므로 세부 묘사가 바뀌거나 깜박일 수 있습니다. 도로처럼 빈 공간을 채워도 그 부분을 실제로 관측했다는 뜻은 아닙니다. Built on NVIDIA Cosmos.

브라우저에서는 NuRec의 공식 export-gaussian-plys 출력물을 SPZ로 압축해 Spark/Three.js로 그립니다. Gaussian은 유지하고 방향별 색은 degree 1로 줄입니다. 따라서 NuRec 학습 결과의 브라우저용 미리보기이며, 압축과 렌더러 차이로 NuRec 원본 렌더링과 조금 다를 수 있습니다. 공개 Pages에서는 NuRec 원본과 Harmonizer의 실제 출력 영상을 확인합니다. 아래의 선택형 로컬 서버를 연결하면 마우스로 고른 실제 화면도 보정할 수 있습니다. 정적 Pages 자체에서 GPU 추론을 실행하지는 않습니다.

4. Alpamayo 경로는 어디서 나올까?

Alpamayo에는 보정 영상이 아닌 원본 카메라 픽셀을 넣습니다. 실제 RGB 스트림 네 개에서 모델용 여섯 뷰를 만듭니다. 왼쪽·정면·오른쪽은 원래 화면을 사용하고, 후면 사진에서 좌우 하위 뷰 두 개를, 정면에서 망원에 해당하는 뷰를 잘라 만듭니다. 모든 샘플링 광선은 실제 이미지 안에 머뭅니다.

이것은 카메라 배열을 맞추기 위한 명시적인 어댑터입니다. 모델이 원래 기대하는 화각보다 좁고, 실제 NVIDIA AV 카메라 보정과 같은 구성이 아닙니다. 관측하지 않은 후방 화면을 만들어서 실제 카메라로 표시하지 않습니다.

텍스트
선택한 RGB 뷰 22개:  uint8[22,1,3,576,1024]
카메라 ID / 명목 시각: int64[22]
과거 위치:           float[1,20,3], 현재의 -1.9초부터 0초까지
과거 회전:           float[1,20,3,3]
주행 지시:           “Continue straight on the road and yield to pedestrians.”
예측 위치:           float[1,1,1,64,3]
예측 회전:           float[1,1,1,64,3,3]

과거 자세 20개는 RGB에서 추정한 움직임을 도로면에 투영해 만듭니다. 평면 도로와 yaw 회전을 가정하고, 위치를 평활화한 뒤 10Hz로 보간합니다. 각 입력 이미지는 요청 시각 이전 또는 같은 시각에 있는 가장 최근 프레임을 고릅니다. 미래 궤적 정답은 사용하지 않습니다. 다만 카메라 자세는 전체 사진으로 오프라인 복원한 값이므로, 이 실습을 미래 영상에 전혀 접근하지 않는 온라인 인지·주행 시스템으로 해석하지 않습니다.

모델은 미터 단위 주행 이력을 기대합니다. 예제에서는 상대 좌표를 바꾸기 위해 카메라 높이 1.8m를 가정합니다. RGB로 실측한 높이가 아니며 이 값을 바꾸면 예측도 달라질 수 있습니다. --assumed-camera-height-m으로 가정이 드러나고 교체할 수 있게 했습니다.

2.1·3.9·5.7·7.8초의 네 시점에서 실제 추론합니다. 초록색 점선은 현재 시점에 이미 얻을 수 있는 가장 최근 예측이며 입력 시각과 스케일 가정을 함께 표시합니다. 2.1초 이전에는 미래 시점의 예측을 미리 보여주지 않습니다. 선은 잘 보이게 높이를 조금 올려 그리며 원본 좌표는 그대로 보존합니다. 모델이 생성한 설명도 틀릴 수 있으므로 장면의 검증된 사실로 취급하지 않습니다. 이는 폐루프 주행이 아닌 개방형 경로 추론이며 실제 주행 품질 시험은 아닙니다.

5. 주변 차량과 사람은 어떻게 보여줄까?

Mask R-CNN은 원본 RGB에서 객체 종류·박스·이진 마스크를 예측합니다. 점수 0.8 이상인 도로 사용자 여섯 종류를 남깁니다. 차량은 청록색, 사람은 노란색, 자전거·이륜차는 보라색입니다. 카메라 패널에서 실제 사진과 예측을 확인하고 표시를 꺼서 원본과 비교할 수 있습니다.

마스크 아래쪽 픽셀에서 나온 광선을 추정한 도로면과 교차시켜 3D 접점을 표시합니다. 화면 가장자리에서 잘렸거나 수평선 근처이거나 너무 먼 객체는 2D 결과만 남깁니다. 표식은 실측한 3D 박스나 물리적 가림 관계가 아닙니다. 임시 ID가 바뀔 수 있고 여러 프레임의 검출 수는 고유한 사람·차량 수와 다릅니다. 마스크와 좌표의 상세 설명도 함께 보세요.

Volvo S90은 출처를 표시한 실제 3D 메시로, 자차 위치를 보여주기 위해 전경에 추가합니다. 원래 촬영 차량이나 차량 동역학 모델은 아닙니다. 장면 복원·외관 보정·객체 인식·주행 예측은 각각 확인할 수 있게 유지합니다.

6. RGB에서 추정한 깊이로 번짐 줄이기

RGB 사진에서 DA3 깊이를 추정하고 SfM으로 스케일을 맞춰 NuRec의 거리·법선 loss에 연결하는 과정

RGB만 맞추는 학습에서는 서로 다른 3D 배치가 비슷한 사진을 만들 수 있습니다. 도로가 울퉁불퉁하게 복원되거나 색이 허공에 번지는 이유 중 하나입니다. 깊이 prior는 “이 픽셀의 표면이 대략 이 거리쯤에 있다”는 보조 추정치입니다. Depth Anything 3의 DA3-BASE에 학습용 사진과 RGB에서 추정한 카메라를 넣어 깊이를 얻습니다. 코드와 이 체크포인트는 Apache-2.0이며, 더 큰 DA3 모델 모두가 같은 조건인 것은 아닙니다.

깊이 지도의 값은 그대로 쓰지 않습니다. 학습 사진의 특징점으로 삼각측량한 SfM 점과 맞춰 양수 스케일과 오프셋을 추정합니다. 차량·사람의 검출 박스, 신뢰도가 낮은 픽셀과 깊이가 불연속적인 경계는 기하 제약에서 제외합니다. RGB 재현 loss에는 원래 사진을 계속 사용합니다.

실제 학습 사진과 RGB에서 예측한 깊이, 깊이 차분으로 구한 표면 법선

깊이에는 서로 다른 두 정의가 있습니다. z-depth는 카메라 앞 방향의 거리이고 ray distance는 픽셀의 광선을 따라 잰 거리입니다. 화면 중앙에서 벗어나면 두 값이 달라집니다. NuRec의 거리 loss에 전달하는 것은 ray distance입니다. 법선(normal)은 표면이 향하는 방향을 길이 1의 벡터로 나타냅니다. 이번 법선은 별도 모델의 독립적인 예측이 아니라, 같은 깊이 지도에서 주변 3D 점의 기울기를 구한 것입니다.

실제 학습 프레임 front_camera/39.jpg의 도로 픽셀 (512, 450)은 다음처럼 변환됐습니다. 모두 상대 단위이며 미터로 측정한 값은 아닙니다.

JSON
{
  "rgb_shape": [569, 1024, 3],
  "pixel_uv": [512, 450],
  "z_depth": 5.08896,
  "ray_distance": 5.15104,
  "world_normal": [-0.00348, -0.04803, 0.99884]
}

법선의 세 번째 성분이 약 1이라는 것은 이 좌표계에서 도로가 대체로 위를 향한다는 뜻입니다. NuRec에는 거리 float[1,569,1024,1], 법선 float[1,569,1024,3]과 유효 영역을 전달합니다. 렌더러가 예측한 거리·방향을 이 값들과 비교하고, 그 오차를 역전파해 Gaussian의 위치·크기·방향을 조정합니다. 깊이 loss와 법선 loss가 실제 미분 가능한 렌더링에 연결됐는지도 실행 중 검사합니다. 실제 입출력 수치 · 구현 코드.

이 방식은 DN-Splatter의 연구와 같은 깊이·법선 정규화 접근을 참고한 독립 구현입니다. DN-Splatter 자체를 실행한 결과가 아닙니다. RGB로 추정한 깊이도 틀릴 수 있고, 정적인 Gaussian 모델만으로 움직이는 차량의 잔상을 해결할 수는 없습니다.

7. Reality View에 이전 보정 화면을 넣으면 무엇이 달라질까?

RGB로 복원한 3D 장면을 기준으로 현재 시점을 그리고, 이전 보정 출력 네 장을 Harmonizer에 넣으며 인식과 경로는 원본 RGB에서 따로 계산하는 흐름

사진을 한 장씩 보정하면 마우스를 조금만 움직여도 같은 나무의 모양이 달라질 수 있습니다. 이번에는 NuRec의 3D 장면을 공간 기준으로 유지하고, 보정 모델에 이전 출력 네 장을 함께 넣습니다. 현재 렌더링은 새 시점을 알려주고, 이전 출력은 외관이 이어지도록 돕습니다. 기존의 프레임별 보정에서 실제로 바꾼 부분입니다.

궁금한 점 기존 구현 이번 구현
장면의 공간 기준은? RGB로 복원한 NuRec Gaussian 깊이 제약으로 개선한 NuRec Gaussian. 비교할 때 같은 카메라 사용
화면을 어떻게 보정하나? non-temporal 가중치로 한 장씩 처리 공개된 temporal 가중치 하나로 V1·V5를 비교
마우스로 돌리면? 브라우저에서 3D 렌더링, 보정은 저장 영상으로 확인 선택한 실제 화면을 로컬 GPU 서버로 보내 보정. 밀린 화면을 쌓아두지 않음
시점이 갑자기 바뀌면? 보정 이력이 없음 큰 회전·이동, 시간 점프, 투영·복원 모델 변경 시 이력 초기화
인식 표식과 경로의 입력은? 원본 RGB와 추정 움직임 같은 원본 입력 유지. 보정 이후에 표식과 경로를 겹쳐 표시
RGB 근거가 약한 곳은? 별도 표시 없음 Gaussian 형상은 유지한 채 깊이 일치 추정치를 색으로 확인

데이터를 살펴봅시다. 현재 시점의 렌더링은 [-1,1] 범위의 float[1,3,1,576,1024]가 됩니다. 이전 보정 출력이 네 장 쌓이면 다음처럼 묶습니다.

텍스트
x[:, :, 0] = 현재 시점의 3D 렌더링
x[:, :, 1] = 직전 보정 출력, t−1
x[:, :, 2] = 두 번째 이전 보정 출력, t−2
x[:, :, 3] = 세 번째 이전 보정 출력, t−3
x[:, :, 4] = 네 번째 이전 보정 출력, t−4
x.shape    = [1, 3, 5, 576, 1024]
y.shape    = [1, 3, 5, 576, 1024] → y[:, :, 0]을 표시

처음 네 장은 V1으로 처리하고, 이력을 비우면 다시 네 장을 모읍니다. 여기서 과거 입력은 모델이 앞서 생성한 출력입니다. 미래 카메라 사진이나 앞으로의 여덟 프레임을 예측하는 구조와 다릅니다. 단일 단계 diffusion으로 외관을 보정하며, 3D 형상을 다시 학습하거나 채워 넣은 표면의 정확성을 보장하지는 않습니다. 공식 코드와 모델 카드에서 원래 구현을 확인할 수 있습니다.

제공받은 Tesla 해설은 하나의 시각 인코더에서 주행 모델과 diffusion·mean-flow 표시 모델로 갈라지는 구조를 제안합니다. 설계에 참고할 가설이지만 모델 크기·36fps·여덟 프레임이라는 주장은 이 실습에서 확인한 사실이 아닙니다. 연결된 원본 X 게시물은 확인 과정에서 직접 열리지 않았습니다. 우리는 Tesla 가중치나 공유 UVE를 재현하지 않았습니다. 원본 RGB에서 복원·인식·Alpamayo를 각각 실행하고, 표시용 분기에서 실제 NuRec 렌더링과 공개 Harmonizer 가중치를 사용합니다.

색은 정답이 아니라 보조 근거입니다. 뷰어에서 RGB 깊이 근거 살펴보기를 고르세요. Gaussian 중심을 투영했을 때 깊이가 일치하는 카메라가 0개면 빨강, 1개면 노랑, 2개 이상이면 청록입니다. 여섯 카메라 이름을 구분하므로 같은 카메라의 여러 프레임을 별개 카메라로 세지 않습니다. RGB에서 추정한 카메라와 예측 깊이를 10% + 상대 단위 0.1의 오차 범위로 비교합니다. 가림·움직이는 객체 제외·깊이 오차 때문에 낮게 나올 수 있습니다. 실측 가시성, 픽셀별 신뢰도나 환각 판정으로 읽으면 안 됩니다.

같은 160개 시점의 원본·V1·V5 비교 영상 · 마우스로 시점을 바꿔 GPU에서 보정한 실제 화면

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

GPU 실습은 필요한 NVIDIA GPU가 있는 머신에서 터미널을 엽니다. 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. CUDA GPU 없이 저장된 결과부터 보기

이 페이지의 뷰어와 NuRec·Harmonizer 비교 영상을 열어보세요. 원본 RGB 인식, 카메라 선택, 예측 경로와 마우스 조작을 직접 확인할 수 있습니다. 브라우저는 미리 실행해 둔 모델 출력을 읽습니다.

Shell
python3 labs/nurec-rgb-reality/check.py
python3 labs/rgb-reality-view/serve.py --root site/public/showcase/nurec-rgb-reality --port 8092

**http://127.0.0.1:8092/**에 접속합니다. 뷰어의 지정된 JavaScript 모듈을 불러오려면 인터넷 연결이 필요합니다. 영상 재생과 증거 파일 검사에는 NVIDIA GPU가 필요하지 않습니다.

2. GPU 머신 준비하기

검증에 사용한 환경은 Linux x86_64, RTX 5090 32GB 한 장, 시스템 메모리 약 32GB입니다. 호환되는 NVIDIA 드라이버, NVIDIA Container Toolkit이 연결된 Docker, Python, Git, uv, Node.js/npm을 준비하세요. NVIDIA Linux 온보딩부터 확인하면 됩니다.

Shell
nvidia-smi
export NUREC_RGB_ROOT="$HOME/physical-ai-labs/nurec-rgb-road"
python3 labs/nurec-rgb-reality/pipeline.py --root "$NUREC_RGB_ROOT" setup

먼저 SOURCES.md의 이용 조건을 확인하세요. NuRec 런타임, 모델 가중치, 데이터셋, 차량 모델의 조건은 각각 다릅니다. setup은 지정한 런타임을 받고 격리된 환경을 설치한 뒤 공개 모델 체크포인트와 NuRec 지표 계산용 의존 파일을 받습니다. 다운로드와 첫 컴파일 시간은 예제의 실제 학습 시간보다 길 수 있습니다. 가중치·원본 로그·입력 캐시는 Git 밖에 저장합니다.

3. 한 단계씩 실행하기

저장소 폴더의 터미널에서 실행합니다. 앞 명령이 성공한 뒤 다음 명령을 넣으세요.

Shell
python3 labs/nurec-rgb-reality/pipeline.py --root "$NUREC_RGB_ROOT" rgb
python3 labs/nurec-rgb-reality/pipeline.py --root "$NUREC_RGB_ROOT" rig
python3 labs/nurec-rgb-reality/pipeline.py --root "$NUREC_RGB_ROOT" prepare
python3 labs/nurec-rgb-reality/pipeline.py --root "$NUREC_RGB_ROOT" train
python3 labs/nurec-rgb-reality/pipeline.py --root "$NUREC_RGB_ROOT" render
python3 labs/nurec-rgb-reality/pipeline.py --root "$NUREC_RGB_ROOT" enhance
python3 labs/nurec-rgb-reality/pipeline.py --root "$NUREC_RGB_ROOT" --assumed-camera-height-m 1.8 policy
python3 labs/nurec-rgb-reality/pipeline.py --root "$NUREC_RGB_ROOT" perceive
python3 labs/nurec-rgb-reality/pipeline.py --root "$NUREC_RGB_ROOT" export
python3 labs/nurec-rgb-reality/pipeline.py --root "$NUREC_RGB_ROOT" serve

rgb에서 카메라를 추정하고 rig에서 고정 배열로 조정합니다. prepare는 NCore 입력을 만들고 train은 NuRec을 학습해 Gaussian을 내보냅니다. render는 정면·사선·회전 시점의 NuRec 원본을 만들며, enhance는 회전 프레임에 Harmonizer를 실행합니다. policy와 perceive는 원본 RGB로 각 모델을 실행하고, export가 뷰어를 묶습니다.

새 출력 폴더에서는 pipeline.py --root "$NUREC_RGB_ROOT" all로 전체 과정을 이어 실행할 수 있습니다. GPU 단계는 같은 잠금과 GPU 한 장을 사용합니다. 이 예제는 문서에 나온 PandaSet 방식의 카메라 폴더 여섯 개를 기대합니다. 정면 카메라 하나로는 후방 관측을 얻을 수 없으므로, 다른 카메라 배열은 입력을 명시적으로 맞춰야 합니다.

4. 깊이·법선 보조 학습 비교하기

위 실습으로 prepare와 perceive까지 완료한 입력 폴더를 사용합니다. 첫 비교는 별도 폴더에서 학습 사진 138장과 검사 사진 24장을 나눠 실행합니다. 아래 명령은 저장소 폴더의 터미널에서 한 줄씩 실행하세요. 설치 단계는 DA3 전용 Python 환경을 만들며 기존 실습 환경을 바꾸지 않습니다.

Shell
export RGB_BASE="$HOME/physical-ai-labs/nurec-rgb-road"
export RGB_GUIDED="$HOME/physical-ai-labs/nurec-guidance-test"
python3 labs/nurec-rgb-reality/guidance/pipeline.py --base "$RGB_BASE" --root "$RGB_GUIDED" setup
python3 labs/nurec-rgb-reality/guidance/pipeline.py --base "$RGB_BASE" --root "$RGB_GUIDED" inputs
python3 labs/nurec-rgb-reality/guidance/pipeline.py --base "$RGB_BASE" --root "$RGB_GUIDED" prepare
python3 labs/nurec-rgb-reality/guidance/pipeline.py --base "$RGB_BASE" --root "$RGB_GUIDED" priors
python3 labs/nurec-rgb-reality/guidance/pipeline.py --base "$RGB_BASE" --root "$RGB_GUIDED" train
python3 labs/nurec-rgb-reality/guidance/pipeline.py --base "$RGB_BASE" --root "$RGB_GUIDED" evaluate

inputs는 검사 사진을 먼저 분리하고, 학습 사진의 관측만으로 초기 점의 위치와 색을 다시 구합니다. priors는 학습 사진만 DA3에 넣습니다. train은 동일한 초기값·난수 seed·16,000단계·Gaussian 상한 45만 개로 RGB 기준 모델, 깊이 모델, 깊이+법선 모델을 차례로 학습합니다. evaluate는 같은 카메라의 원본 해상도에서 검사 사진 24장과 비교해 comparison.json을 만듭니다. Harmonizer나 이미지 보정은 이 점수에 사용하지 않습니다.

약한 법선 제약도 시험하려면 train 명령에 --variant depth-normal-soft를 넣고 evaluate를 다시 실행합니다. 이 설정은 첫 비교 결과를 본 뒤 조정한 후속 실험이므로 별도의 독립 테스트 결과로 해석하지 않습니다.

뷰어용 고해상도 모델은 새 출력 폴더에서 각 명령에 --production --variant depth를 추가해 만듭니다. 이 모드에서는 전체 RGB 162장을 사용합니다. priors 다음에 dense를 실행하고 train, export 순서로 진행하세요. 인접한 학습 뷰에서 깊이·색·방향이 함께 일치하는 점을 모아 초기 점군을 조밀하게 만들고, 32,000단계·Gaussian 상한 120만 개로 학습합니다. 이 모델은 검사 사진도 포함한 표시용 모델이며, 아래의 loss 비교 점수와 구분합니다. package로 기존 실습의 카메라·인식·경로 결과와 묶고 serve를 실행하면 **http://127.0.0.1:8093/**에서 직접 둘러볼 수 있습니다. 기존 실습의 export 단계가 먼저 끝나 있어야 합니다. export는 NuRec 원본을 PLY로 내보내 SPZ로 압축합니다. 선택형 서버를 연결하지 않은 마우스 조작은 Spark의 브라우저 렌더링입니다. 단계별 실행 코드 · 모델 내보내기.

5. GPU에서 시간축 보정 실행하기

앞에서 복원과 렌더링까지 마친 뒤 진행하세요. NuRec 컨테이너는 그대로 두고 공식 Harmonizer 환경을 따로 만듭니다. Python 3.12 이상, Linux x86_64, NVIDIA Container Toolkit이 연결된 Docker, uv가 필요합니다. 공개 가중치는 약 5GB이며 NVIDIA Open Model License가 적용됩니다. 공식 코드의 Apache-2.0과 이 저장소 어댑터의 MIT 라이선스는 별개입니다.

Shell
export RV_TEMPORAL_ROOT="$HOME/physical-ai-labs/reality-temporal"
export RV_INPUT="$NUREC_RGB_ROOT/renders/orbit/front_camera"
python3 labs/nurec-rgb-reality/temporal/pipeline.py --root "$RV_TEMPORAL_ROOT" setup
python3 labs/nurec-rgb-reality/temporal/pipeline.py --root "$RV_TEMPORAL_ROOT" --input "$RV_INPUT" compare
python3 labs/nurec-rgb-reality/temporal/pipeline.py --root "$RV_TEMPORAL_ROOT" --input "$RV_INPUT" evaluate
python3 labs/nurec-rgb-reality/temporal/pipeline.py --root "$RV_TEMPORAL_ROOT" check

setup은 고정한 공식 코드와 가중치 해시를 확인합니다. compare는 같은 순서의 렌더링을 V1·V5로 처리해 따로 저장합니다. 기존 실험을 보존하려면 새 결과 폴더를 쓰세요. evaluate는 영상의 시간적 안정성과 윤곽을 비교하고, check는 출력 파일 해시와 실제 네 장 문맥 사용을 확인합니다. 공개한 160프레임 비교는 개선 모델의 NuRec 원본 렌더링을 사용했습니다. 같은 시점 경로 재현과 선택형 실시간 뷰어 설정.

GPU나 가중치를 받지 않고 공개한 실행 기록을 검사하려면 다음 한 줄만 실행하세요.

Shell
python3 labs/nurec-rgb-reality/temporal/check.py

GPU 서버는 필요할 때만 켭니다. 마우스로 선택한 실제 3D 화면의 중앙 16:9 영역을 깨끗하게 캡처해 보내고, 보정이 끝난 뒤 양쪽 화면에 원본 RGB의 인식 표식과 Alpamayo 경로를 덧그립니다. 공개 Pages에서는 3D 장면과 실제 녹화 영상을 볼 수 있으며, 방문자의 컴퓨터에 연결을 시도하지 않습니다. GPU 서버와 SSH 터널 설정.

결과 확인

시간축 보정 결과는 어떻게 읽어야 할까?

RTX 5090 한 장, 1024×576, BF16, 같은 공개 temporal 가중치와 NuRec 원본 렌더링 160장을 사용했습니다. 이번 V1·V5는 같은 가중치로 비교했으며, 이전 TorchScript non-temporal 데모와 구분합니다. 지연은 처음 네 프레임을 제외하고 GPU 모델 계산만 동기화해 측정했습니다.

방식 중앙값 / p95 최대 할당 VRAM 같은 flow의 warp L1 ↓ 윤곽 크기
원본 렌더링 — — 0.02898 0.02609
V1: 프레임별 보정 124 / 124ms 3.61GiB 0.02550 0.02240
V5: 이전 출력 네 장 484 / 485ms 7.01GiB 0.01722 0.01973

V5의 시간적 흔들림 지표는 V1보다 약 32% 낮고, 윤곽 크기도 약 12% 낮습니다. 화면을 부드럽게 만드는 것만으로 지표가 좋아질 수 있으므로, 관측하지 않은 시점의 정확도가 32% 올랐다는 뜻은 아닙니다. 모델 계산만 환산하면 약 8.1장/초와 2.1장/초이며 캡처·인코딩·전송 시간은 빠져 있습니다. 비교 영상은 살펴보기 편하게 빠르게 재생합니다. 브라우저가 약 60Hz로 움직여도 diffusion이 60fps로 실행되는 것은 아닙니다. 첫 초기화·컴파일에도 시간이 더 걸립니다.

처음에는 시점을 크게 바꾸면 앞선 차량 외관이 잔상으로 남았습니다. 지금은 회전 12도·상대 거리 0.75를 넘는 이동, 투영·모델 변경과 시간 점프에서 이력을 비웁니다. 데모용 보수적 기준이며 학습된 보장 조건은 아닙니다. 실제 브라우저에서 작은 마우스 이동 시 V5 유지, 운전자 시점 전환 시 이력 초기화, 모드 전환과 두 언어의 390px 화면을 확인했습니다.

프레임별 계산 시간·해시 · 동일 입력 비교 결과와 계산 방식 · 실제 브라우저 조작 기록

여전히 미리 복원한 정적 장면이므로 움직이는 주변 차량이 겹칠 수 있고 스케일도 모호합니다. 보이지 않던 면은 추정이며 차량을 제어하지 않습니다. 원본 RGB·복원 형상·생성 보정·인식 추정·예측 경로를 구분해 살펴보세요.

깊이·법선 loss를 넣으면 얼마나 달라질까?

같은 운전자 시점의 기존 45만 개 모델과 깊이 기반 120만 개 모델

기존 모델과 고해상도 모델의 같은 새 시점 영상에서 도로의 빈틈과 번짐을 비교해 보세요. 이 영상은 초기 점군과 학습 예산도 달라지는 별도 비교입니다. 뷰어의 기본 추적 시점도 원래 촬영 높이에 가까운 위치로 낮췄으며, 비교 모델 모두 같은 시점을 사용합니다.

같은 검사 사진에 대한 RGB 기준 모델과 깊이 기반 복원 비교

학습에 쓰지 않은 6개 카메라 × 4개 시점, 총 24장의 평균입니다. 두 지표 모두 높을수록 원본 RGB와 가깝습니다.

같은 조건의 실험 PSNR (dB) SSIM 깊이 / 법선 / 평탄화 가중치
RGB 기준 21.974 0.7113 0 / 0 / 0
깊이 22.249 0.7171 0.1 / 0 / 0
깊이 + 법선 21.924 0.7168 0.1 / 0.03 / 0.0005
약한 법선 제약 · 후속 조정 22.249 0.7175 0.1 / 0.005 / 0.00005

깊이 보조 학습은 이 비교에서 개선됐지만, 강한 법선 제약은 PSNR을 낮췄습니다. 법선 제약을 약하게 조정하면 깊이 모델과 거의 같은 결과가 나왔습니다. 뷰어용 모델에는 깊이 loss를 사용하고, 법선은 조밀한 초기 점군의 방향과 일관성 검사에 활용했습니다. “loss를 더하면 무조건 좋아진다”는 결과가 아닙니다. 카메라 자세는 전체 RGB로 미리 구한 값을 고정했으므로, 카메라 추정까지 완전히 분리한 독립 검증은 아닙니다. 사진별 수치와 해시, 학습 완료 시간, 실제 loss 연결 기록은 비교 결과와 실행 기록 요약에 있습니다.

표시용 모델은 RTX 5090 한 장에서 723.07초 학습했습니다. DA3 추론·카메라 복원·내보내기 시간은 제외한 값입니다. Gaussian 120만 개 뷰어는 M2 Max의 Chrome에서 정지·회전·경로 재생 모두 약 60FPS를 유지했습니다. 렌더링 버퍼는 896×504와 1344×756이며, 브라우저의 약 60Hz 루프를 측정한 것입니다. GPU의 최대 FPS나 전체 파이프라인의 실시간 처리 속도로 해석하지 않습니다. 클라이언트 측정 기록 · 학습·초기화·내보내기 기록.

Shell
python3 labs/nurec-rgb-reality/check.py --decode-video
python3 labs/nurec-rgb-reality/guidance/check.py
python3 -m unittest discover -s labs/nurec-rgb-reality/guidance -p 'test_*.py'
python3 -m unittest discover -s labs/rgb-reality-view -p 'test_*.py'

검사기는 입력 출처, 카메라·rig 기하 구조, NuRec 실제 완료 기록, 원본과 Harmonizer 프레임 짝, 예측 텐서의 형태와 회전·유한값, 원본 RGB 인식 결과, 압축 모델 개수, 파일 해시와 실제 조작 기록을 확인합니다. 영상 전체 디코딩에는 FFmpeg가 필요합니다. 구현과 파일 일관성 검사이며 주행 안전·검출 정확도·가려진 면의 정답을 검증하는 시험은 아닙니다.

독립 실행형 3DGUT, 앞서 만든 RGB + LiDAR NuRec 비교 실험, 직접 만든 합성 도로의 인터페이스 실험과 입력 조건을 비교해 보세요. 각 실행 경로를 구분해 표시합니다. 자차 중심 표현을 참고한 공개 실습이며 Tesla의 비공개 모델이나 실차 Reality View 시스템을 재현한 결과로 설명하지 않습니다.

실행 영상과 기록

같은 시점의 원본·프레임별·시간축 보정 비교

실제 NuRec 렌더링 160장에 같은 가중치로 V1·V5를 실행했습니다. 시간적 흔들림 지표는 낮아지고 윤곽도 부드러워집니다. RTX 5090 모델 계산 중앙값 124ms·484ms이며 영상 재생 속도는 추론 FPS가 아닙니다.

이전 기준 영상: 복원·인식·예측 연결

시간축 보정 전의 전체 소개 영상을 보존했습니다. 기존 RGB NuRec 장면, non-temporal Harmonizer와 별도 인식·경로 출력을 확인하세요.

개선한 Gaussian 120만 개 장면 직접 조작하기

실제 브라우저 화면에서 같은 운전자 시점으로 모델을 바꾸고, 마우스로 회전한 뒤 경로를 재생합니다. 원본 RGB의 인식 접점과 Alpamayo 예측을 함께 표시합니다. 미리 복원한 장면을 탐색하는 예제이며 차량 제어는 하지 않습니다.

깊이 기반 복원: 기존 모델과 고해상도 모델 비교

같은 사선·회전 경로를 NuRec에서 직접 렌더링하고 같은 영역을 확대했습니다. 개선 모델은 깊이 제약과 함께 초기 점군·학습량·Gaussian 상한도 늘렸습니다. loss만의 효과는 검사 사진 비교표에서 확인하세요. Harmonizer나 이미지 보정은 사용하지 않았습니다.

NuRec 학습 장면을 실제 마우스로 조작한 영상

원본 RGB 인식, 3D 접점과 Alpamayo 실제 예측을 확인합니다. 표시를 껐다 켜고 카메라를 바꾸며 같은 Gaussian 장면을 회전합니다.

같은 시점 48곳의 NuRec 원본·Harmonizer 보정 비교

왼쪽은 실제 NuRec 렌더링, 오른쪽은 공개 non-temporal Harmonizer 출력입니다. 새로 생성되는 세부 묘사와 프레임 간 깜박임을 구분해 보세요. Built on NVIDIA Cosmos.

실습 소스 코드

pipeline.pyGitHub에서 파일 보기
Python
"""Reproduce the RGB-only NuRec + Harmonizer + Alpamayo demonstration.

One NVIDIA GPU is used sequentially. All generated data, caches and raw logs are
stored in --root outside the repository. Runtime/model/data terms stay separate.
"""
import argparse,os,platform,shutil,subprocess
from pathlib import Path
LAB=Path(__file__).resolve().parent;SHARED=LAB.parent/'rgb-reality-view'
p=argparse.ArgumentParser();p.add_argument('--root',type=Path,default=Path.home()/'physical-ai-labs/nurec-rgb-road');p.add_argument('--model-root',type=Path,default=Path.home()/'physical-ai-models');p.add_argument('--assumed-camera-height-m',type=float,default=1.8,help='Explicit scale prior for Alpamayo only; not measured from RGB');p.add_argument('--port',type=int,default=8092);p.add_argument('--no-serve',action='store_true',help='Complete GPU/export stages and exit without starting HTTP');p.add_argument('stage',choices=['setup','rgb','rig','prepare','train','render','enhance','policy','perceive','export','serve','all']);a=p.parse_args();root=a.root.expanduser().resolve();root.mkdir(parents=True,exist_ok=True);modelroot=a.model_root.expanduser().resolve();sfm=root/'.venv/bin/python';detector=root/'.perception-venv/bin/python';uv=shutil.which('uv') or str(Path.home()/'.local/bin/uv');env={**os.environ,'NUREC_RGB_ROOT':str(root),'RGB_VIEW_ROOT':str(root/'rgb-source'),'RGB_SFM_PYTHON':str(sfm),'ALPAMAYO_ROOT':str(modelroot),'REALITY_VIEW_ROOT':str(root),'HARMONIZER_WEIGHTS':str(root/'checkpoints/Harmonizer'),'UV_BIN':uv,'CUDA_VISIBLE_DEVICES':'0','OMP_NUM_THREADS':'8'}
def run(args,**kw):return subprocess.run([str(v) for v in args],check=True,env=env,**kw)
def lockrun(args):return run(['flock',env.get('GPU_LOCK','/tmp/rgb-reality-view.gpu.lock'),*args])
def shell(stage):return run(['bash',LAB/'run.sh',stage])
def setup():
 if platform.system()!='Linux':raise SystemExit('GPU workflow: Linux with NVIDIA Container Toolkit. Saved-result viewing also works on Mac/Windows.')
 if not Path(uv).is_file():raise SystemExit('Install uv: https://docs.astral.sh/uv/getting-started/installation/')
 if not sfm.exists():run([uv,'venv','--python','3.11',sfm.parent.parent])
 run([uv,'pip','install','--python',sfm,'pycolmap-cuda12==3.13.0','numpy==2.4.6','Pillow==13.0.0','scipy==1.17.1','plyfile==1.1.5'])
 # Review NGC runtime terms and model licenses in SOURCES.md before setup.
 run(['docker','pull','nvcr.io/nvidia/nre/nre-ga:26.04@sha256:97f43e7130c5636ce3e80ea3184d97f56a87fdd989b05cce42230881dbdea284'])
 run(['bash',LAB.parent/'reality-view/setup_models.sh']);run([sfm,LAB/'setup_metrics.py','--root',root])
 if not detector.exists():run([uv,'venv','--python','3.11',detector.parent.parent])
 run([uv,'pip','install','--python',detector,'torch==2.8.0','torchvision==0.23.0','--index-url','https://download.pytorch.org/whl/cu128'])
 run([uv,'pip','install','--python',detector,'pycolmap-cuda12==3.13.0','numpy==2.4.6','Pillow==13.0.0','scipy==1.17.1'])
def rgb():
 source=root/'rgb-source'
 run([sfm,SHARED/'fetch_example.py','--root',source]);shutil.copy2(source/'PANDASET-DATA-LICENSE.txt',root/'PANDASET-DATA-LICENSE.txt')
 lockrun([sfm,SHARED/'sfm.py','--root',source/'work','--device','cuda'])
def rig():
 run([sfm,LAB/'rig_bundle.py','--rgb-root',root/'rgb-source','--output',root/'rig-source']);run([sfm,SHARED/'prepare_viewer.py','--root',root/'rig-source/work','--output',root/'rig-source/viewer']);env['RGB_VIEW_ROOT']=str(root/'rig-source');shell('export-rgb')
def policy():
 run([sfm,LAB/'prepare_policy.py','--root',root,'--assumed-camera-height-m',a.assumed_camera_height_m]);lockrun([modelroot/'alpamayo2-edge/.venv/bin/python',LAB/'run_policy.py','--root',root,'--model',modelroot/'checkpoints/Alpamayo2-Edge'])
def perceive():lockrun([detector,SHARED/'perceive.py','--root',root/'rig-source'])
def export():run([sfm,LAB/'export_viewer.py','--root',root])
def serve():run(['python3',SHARED/'serve.py','--root',root/'viewer','--port',a.port])
def train():shell('train');shell('collect');shell('export-ply')
functions={'setup':setup,'rgb':rgb,'rig':rig,'prepare':lambda:shell('prepare'),'train':train,'render':lambda:shell('render'),'enhance':lambda:shell('enhance'),'policy':policy,'perceive':perceive,'export':export,'serve':serve}
if a.stage=='all':
 for stage in ['setup','rgb','rig','prepare','train','render','enhance','policy','perceive','export']:
  print('RGB_NUREC_STAGE',stage,flush=True);functions[stage]()
 if not a.no_serve:serve()
 print('RGB_NUREC_PIPELINE_COMPLETE',flush=True)
else:functions[a.stage]()
rig_bundle.pyGitHub에서 파일 보기
Python
"""Constrain the RGB-estimated cameras to a fixed rig with COLMAP bundle adjustment.

Uses camera folder/stem grouping as a nominal synchronization assumption. No
provided calibration, timestamps, GPS, LiDAR or object labels enter the solver.
"""
import argparse,json,shutil,time
from pathlib import Path
import pycolmap as c
p=argparse.ArgumentParser();p.add_argument('--rgb-root',type=Path,required=True);p.add_argument('--output',type=Path,required=True);a=p.parse_args();src=a.rgb_root;out=a.output;out.mkdir(parents=True,exist_ok=True);start=time.perf_counter();m=c.Reconstruction(str(src/'work/undistorted/sparse/0'));before=m.compute_mean_reprojection_error();groups={im.name.split('/')[0] for im in m.images.values()};expected={'front_camera','front_left_camera','front_right_camera','left_camera','right_camera','back_camera'}
if groups!=expected:raise ValueError('This six-camera example needs front_camera, front_left_camera, front_right_camera, left_camera, right_camera and back_camera folders. Use an explicit adapter for another layout.')
shutil.copy2(src/'work/database.db',out/'database.db');config=c.RigConfig(cameras=[c.RigConfigCamera(image_prefix=f'{cam}/',ref_sensor=cam=='front_camera') for cam in ['front_camera','front_left_camera','front_right_camera','left_camera','right_camera','back_camera']])
with c.Database.open(str(out/'database.db')) as db:c.apply_rig_config([config],db,m)
options=c.BundleAdjustmentOptions();options.refine_focal_length=False;options.refine_principal_point=False;options.refine_extra_params=False;options.refine_sensor_from_rig=True;options.use_gpu=False;options.solver_options.num_threads=8;options.solver_options.max_num_iterations=200;options.solver_options.function_tolerance=1e-6;options.solver_options.parameter_tolerance=1e-6;options.loss_function_type=c.LossFunctionType.CAUCHY;options.loss_function_scale=2
c.bundle_adjustment(m,options);target=out/'work/undistorted/sparse/0';target.mkdir(parents=True,exist_ok=True);m.write(str(target));m.write_text(str(target));(out/'work/undistorted/images').symlink_to((src/'work/undistorted/images').resolve(),target_is_directory=True);(out/'work/images').symlink_to((src/'work/images').resolve(),target_is_directory=True);shutil.copy2(src/'work/input-manifest.json',out/'work/input-manifest.json')
report={'input_images':m.num_reg_images(),'points':m.num_points3D(),'rig_frames':m.num_frames(),'rigs':m.num_rigs(),'reprojection_before_px':before,'reprojection_after_px':m.compute_mean_reprojection_error(),'elapsed_seconds':time.perf_counter()-start,'constraints':'one fixed six-camera rig; folder/stem nominal time pairing; RGB-derived intrinsics frozen; no source sensor calibration or pose labels'};(out/'rig-bundle-result.json').write_text(json.dumps(report,indent=2)+'\n');print('RGB_RIG_BUNDLE_COMPLETE',report,flush=True)
export_rgb.pyGitHub에서 파일 보기
Python
"""Export only RGB-derived COLMAP cameras/points for the NuRec container.

No source sensor calibration, poses, timestamps, depth, LiDAR or annotations.
Times are nominal frame-number/capture-fps values, not measured sensor times.
"""
import argparse,hashlib,json,shutil
from pathlib import Path
import numpy as np
import pycolmap
p=argparse.ArgumentParser();p.add_argument('--rgb-root',type=Path,required=True);p.add_argument('--output',type=Path,required=True);a=p.parse_args();src=a.rgb_root;out=a.output;out.mkdir(parents=True,exist_ok=True)
import sys
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'rgb-reality-view'))
from input_guard import verify_rgb_inputs
verify_rgb_inputs(src/'work');g=json.loads((src/'viewer/cameras.json').read_text());T=np.array(g['world_to_viewer']);scale=np.linalg.norm(T[0,:3]);R=T[:3,:3]/scale;m=pycolmap.Reconstruction(str(src/'work/undistorted/sparse/0'));rows=[]
for im in sorted(m.images.values(),key=lambda im:im.name):
 cam=m.cameras[im.camera_id];M=np.eye(4);M[:3]=im.cam_from_world().matrix();C=np.linalg.inv(M);N=np.eye(4);N[:3,:3]=R@C[:3,:3];N[:3,3]=(T@np.r_[C[:3,3],1])[:3];dest=out/'rgb'/im.name;dest.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(src/'work/undistorted/images'/im.name,dest)
 rows.append({'image':im.name,'camera':im.name.split('/')[0],'timestamp_us':1000000+round(int(Path(im.name).stem)/10*1e6),'camera_to_world':N.tolist(),'K':cam.calibration_matrix().tolist(),'width':cam.width,'height':cam.height,'sha256':hashlib.sha256(dest.read_bytes()).hexdigest()})
points=list(m.points3D.values());P=np.array([p.xyz for p in points]);P=(P@R.T)*scale+T[:3,3];colors=np.array([p.color for p in points],dtype=np.uint8);np.savez_compressed(out/'sfm-points.npz',xyz=P.astype('float32'),rgb=colors)
receipt={'schema':1,'input':'RGB-only COLMAP estimates','uses_lidar':False,'uses_supplied_calibration':False,'uses_supplied_poses':False,'uses_supplied_timestamps':False,'uses_source_annotations':False,'units':'relative camera-height units; not measured meters','time_assumption':'nominal 10 Hz source frame numbers; no provided sensor timestamp files used','frames':rows,'sparse_points':len(P),'front_poses':g['frames'],'scale_assumption':g['scale_assumption']}
(out/'rgb-cameras.json').write_text(json.dumps(receipt,indent=2)+'\n');print('EXPORTED_RGB_ONLY',len(rows),'images',len(P),'SfM points',flush=True)
prepare_ncore.pyGitHub에서 파일 보기
Python
"""Write NuRec NCore input from RGB-only estimated cameras, preserving poses.

NuRec requires dynamic rig motion and static camera-to-rig transforms. Fit the
fixed transforms from RGB-derived poses and retain residuals explicitly.
All timestamps are nominal, not source sensor metadata.
"""
import hashlib,io,json,os
from pathlib import Path
import numpy as np
from PIL import Image
from scipy.spatial.transform import Rotation
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.get('NUREC_RGB_ROOT','/work'));meta=json.loads((root/'rgb-cameras.json').read_text());rows=meta['frames'];out=root/'ncore';out.mkdir(exist_ok=True)
writer=SequenceComponentGroupsWriter(UPath(out),'rgb-only-road','rgb-only-road',HalfClosedInterval.from_start_end(min(r['timestamp_us'] for r in rows),max(r['timestamp_us'] for r in rows)),{'source':'RGB-only COLMAP estimates; no source sensor data; relative units; nominal frame times'},store_type='directory')
def reg(cls,name='default'):return writer.register_component_writer(cls.Writer,component_instance_name=name,group_name='default')
pw=reg(PosesComponent);front=sorted((r for r in rows if r['camera']=='front_camera'),key=lambda r:r['timestamp_us']);F=np.array([[0,0,1,0],[-1,0,0,0],[0,-1,0,1],[0,0,0,1]],float);rigs={r['timestamp_us']:np.array(r['camera_to_world'])@np.linalg.inv(F) for r in front};nominal_times=np.array(sorted(rigs),np.uint64);pw.store_dynamic_pose('rig','world',np.array([rigs[t] for t in nominal_times],np.float32),nominal_times);pw.store_static_pose('world','world_global',np.eye(4));iw=reg(IntrinsicsComponent);mw=reg(MasksComponent);reg(CuboidsComponent).store_observations([]);residuals={}
for camera in sorted({r['camera'] for r in rows}):
 group=sorted((r for r in rows if r['camera']==camera),key=lambda r:r['timestamp_us']);relative=np.array([np.linalg.inv(rigs[r['timestamp_us']])@np.array(r['camera_to_world']) for r in group]);fixed=np.eye(4);fixed[:3,:3]=Rotation.from_matrix(relative[:,:3,:3]).mean().as_matrix();fixed[:3,3]=np.median(relative[:,:3,3],axis=0);error=np.linalg.inv(fixed)@relative;residuals[camera]={'translation_max_relative_units':float(np.linalg.norm(error[:,:3,3],axis=1).max()),'translation_mean_relative_units':float(np.linalg.norm(error[:,:3,3],axis=1).mean()),'rotation_max_degrees':float(np.rad2deg(Rotation.from_matrix(error[:,:3,:3]).magnitude()).max())};pw.store_static_pose(camera,'rig',fixed.astype(np.float32));r=group[0];K=np.array(r['K']);assert all(np.allclose(np.array(g['K']),K) for g in group)
 iw.store_camera_intrinsics(camera,OpenCVPinholeCameraModelParameters(resolution=np.array([r['width'],r['height']],np.uint64),shutter_type=ShutterType.GLOBAL,principal_point=K[:2,2].astype(np.float32),focal_length=np.array([K[0,0],K[1,1]],np.float32),radial_coeffs=np.zeros(6,np.float32),tangential_coeffs=np.zeros(2,np.float32),thin_prism_coeffs=np.zeros(4,np.float32)));mw.store_camera_masks(camera,{});cw=reg(CameraSensorComponent,camera)
 for r in group:
  path=root/'rgb'/r['image'];data=path.read_bytes();assert hashlib.sha256(data).hexdigest()==r['sha256'];ts=r['timestamp_us'];cw.store_frame(image_binary_data=data,image_format='jpeg',frame_timestamps_us=np.array([ts,ts],np.uint64),generic_data={},generic_meta_data={})
 print('NCORE_RGB_CAMERA',camera,len(group),flush=True)
paths=writer.finalize();reader=SequenceComponentGroupsReader(paths);(out/'rgb-only-road.json').write_text(json.dumps(reader.get_sequence_meta().to_dict(),indent=2)+'\n')
z=np.load(root/'sfm-points.npz');P=z['xyz'];C=z['rgb']/255.;names=['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'];a=np.zeros(len(P),dtype=[(n,'f4') for n in names])
for i,k in enumerate(['x','y','z']):a[k]=P[:,i]
for i in range(3):a[f'f_dc_{i}']=(C[:,i]-.5)/.28209479177387814;a[f'scale_{i}']=np.log(.035)
a['opacity']=1;a['rot_0']=1
header='ply\nformat binary_little_endian 1.0\nelement vertex '+str(len(a))+'\n'+'\n'.join('property float '+n for n in names)+'\nend_header\n'
with (root/'seed.ply').open('wb') as f:f.write(header.encode());f.write(a.tobytes())
(root/'prepared.json').write_text(json.dumps({'image_count':len(rows),'camera_count':6,'seed_gaussians':len(P),'seed_source':'RGB-triangulated COLMAP sparse points only','camera_pose_handling':'RGB-estimated front trajectory + fitted static camera-to-rig transforms; approximation residuals retained','rig_fit_residuals':residuals,'units':meta['units']},indent=2)+'\n');print('NCORE_RGB_READY',flush=True)
scene.yamlGitHub에서 파일 보기
YAML
# NuRec 26.04, RGB-only COLMAP seed. Scene units are relative, not measured meters.
defaults:
  - /experimental/3dgut/3dgut_colmap
  - override /model/gaussians/initialization@model.layers.background.initialization: ply
  - _self_
out_dir: /work/train-final
mode: trainval
dataset:
  path: /work/ncore/rgb-only-road.json
  camera_ids: [front_camera, front_left_camera, front_right_camera, left_camera, right_camera, back_camera]
  lidar_ids: []
  n_samples_per_epoch: 16000
  n_val_image_subsample: 1
  train_sequential_camera_frame_step: 1
  val_camera_frame_step: 8
  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: 450000
system:
  test:
    video_fps: 10
    metrics:
      cpsnr:
        enabled: false
run.shGitHub에서 파일 보기
Shell
#!/usr/bin/env bash
set -euo pipefail
lab="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
repo="$(cd -- "$lab/../.." && pwd)"
root="${NUREC_RGB_ROOT:?Set NUREC_RGB_ROOT to a fresh output folder}"
mkdir -p "$root/runtime-home"
root="$(cd -- "$root" && pwd)"
image="nvcr.io/nvidia/nre/nre-ga:26.04@sha256:97f43e7130c5636ce3e80ea3184d97f56a87fdd989b05cce42230881dbdea284"
base=(docker run --rm --gpus device=0 --network none --shm-size=8g --user "$(id -u):$(id -g)" -v "$root:/work" -v "$lab:/lab:ro" -e NUREC_RGB_ROOT=/work -e HOME=/work/runtime-home)
cpu_python="${RGB_SFM_PYTHON:-python3}"
lock="${GPU_LOCK:-/tmp/rgb-reality-view.gpu.lock}"
case "${1:-help}" in
 export-rgb) "${RGB_SFM_PYTHON:?Point RGB_SFM_PYTHON to the RGB lab SfM environment Python}" "$lab/export_rgb.py" --rgb-root "${RGB_VIEW_ROOT:?Set RGB_VIEW_ROOT to the completed RGB reconstruction folder}" --output "$root" ;;
 prepare) flock "$lock" "${base[@]}" "$image" run-script /lab/prepare_ncore.py ;;
 train) flock "$lock" "${base[@]}" -v "$lab/scene.yaml:/app/run.runfiles/_main/configs/nurec-rgb.yaml:ro" "$image" main --config-name nurec-rgb.yaml 2>&1 | tee "$root/nurec-train.log" ;;
 collect) "$cpu_python" "$lab/collect_result.py" --root "$root" ;;
 render)
  "$cpu_python" "$lab/make_views.py" --root "$root"
  artifact="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["artifact"])' "$root/nurec-result.json")"
  for view in front quarter orbit; do
   flock "$lock" "${base[@]}" "$image" render --artifact-path "/work/$artifact" --output-dir "/work/renders/$view" --camera-id front_camera --height 576 --renderer gsplat --custom-rig-trajectory "/work/rig-$view.json" --no-replicate-training-views --calib-source training-rig-poses --save-workers 2
  done ;;
 export-ply) flock "$lock" "${base[@]}" -v "$root/resolved-export.yaml:/app/run.runfiles/_main/configs/resolved-nurec-rgb.yaml:ro" "$image" export-gaussian-plys --config-name resolved-nurec-rgb.yaml --checkpoint-name last.ckpt --output-dir /work/gaussians ;;
 enhance)
  weights="${HARMONIZER_WEIGHTS:?Set HARMONIZER_WEIGHTS to the official checkpoint directory}"
  flock "$lock" "${base[@]}" -v "$weights:/work/checkpoints/Harmonizer:ro" "$image" run-script /lab/enhance.py ;;
 *) printf '%s\n' 'Choose export-rgb, prepare or train. See the bilingual guide.'; exit 2 ;;
esac
prepare_policy.pyGitHub에서 파일 보기
Python
"""RGB-only camera adapter and explicitly assumed metric history for Alpamayo.

Four real RGB streams supply six virtual slots. Rear subviews and front tele are
rotation/crop resamples of recorded pixels, never generated scene content.
This is a documented camera-layout/domain adaptation, not the native AV profile.
"""
import argparse,json
from pathlib import Path
import numpy as np
from PIL import Image
from scipy.ndimage import map_coordinates
from scipy.spatial.transform import Rotation,Slerp
from scipy.signal import savgol_filter
p=argparse.ArgumentParser();p.add_argument('--root',type=Path,required=True);p.add_argument('--assumed-camera-height-m',type=float,required=True);p.add_argument('--times',type=float,nargs='+',default=[2.1,3.9,5.7,7.8]);a=p.parse_args();root=a.root
if not .5<a.assumed_camera_height_m<4:raise ValueError('Use an explicit plausible camera-height assumption in meters; this is not measured by RGB')
meta=json.loads((root/'rgb-cameras.json').read_text());front=sorted((r for r in meta['frames'] if r['camera']=='front_camera'),key=lambda r:r['timestamp_us']);times=np.array([(r['timestamp_us']-1000000)/1e6 for r in front]);C=np.array([r['camera_to_world'] for r in front]);F=np.array([[0,0,1,0],[-1,0,0,0],[0,-1,0,1],[0,0,0,1]],float);rig=C@np.linalg.inv(F)
ground=np.array([f['ground_position'] for f in meta['front_poses']]);yaw=savgol_filter(np.unwrap([f['yaw_radians'] for f in meta['front_poses']]),7,2);positions=savgol_filter(ground,7,2,axis=0);positions[:,2]=0;rotations=Slerp(times,Rotation.from_euler('z',yaw.reshape(-1,1)));by_cam={c:sorted((r for r in meta['frames'] if r['camera']==c),key=lambda r:r['timestamp_us']) for c in ['front_camera','left_camera','right_camera','back_camera']}
slots={0:('left_camera',0,1),1:('front_camera',0,1),2:('right_camera',0,1),3:('back_camera',15,2.4),5:('back_camera',-15,2.4),6:('front_camera',0,2)}
def resample(row,yaw,zoom):
 im=np.array(Image.open(root/'rgb'/row['image']).convert('RGB'));H,W=im.shape[:2];K=np.array(row['K'])
 if zoom==1 and yaw==0:return Image.fromarray(im).resize((1024,576),Image.Resampling.LANCZOS)
 target=K.copy();target[0,0]*=zoom;target[1,1]*=zoom;target[0,2]=W/2;target[1,2]=H/2;yy,xx=np.mgrid[:H,:W];rays=np.stack([xx,yy,np.ones_like(xx)],axis=-1)@np.linalg.inv(target).T;Q=Rotation.from_euler('y',yaw,degrees=True).as_matrix();rays=rays@Q.T;uv=rays@K.T;u=uv[...,0]/uv[...,2];v=uv[...,1]/uv[...,2]
 if np.min(u)<0 or np.max(u)>W-1 or np.min(v)<0 or np.max(v)>H-1:raise ValueError('Virtual subview reaches outside observed RGB; reduce yaw or increase zoom')
 rgb=np.stack([map_coordinates(im[...,c],[v,u],order=1,mode='nearest') for c in range(3)],axis=-1).astype('uint8');return Image.fromarray(rgb).resize((1024,576),Image.Resampling.LANCZOS)
receipts=[]
for t0 in a.times:
 if t0<times[0]+2 or t0>times[-1]+1e-6:raise ValueError('Policy keyframe lacks two seconds of past RGB')
 dest=root/'policy'/f'{round(t0*10):03d}';dest.mkdir(parents=True,exist_ok=True);shots=[]
 hist= t0+np.arange(-19,1)/10;pos=np.stack([np.interp(hist,times,positions[:,j]) for j in range(3)],axis=1);rot=rotations(hist).as_matrix();P0=np.array([np.interp(t0,times,positions[:,j]) for j in range(3)]);R0=rotations(t0).as_matrix();xyz=(pos-P0)@R0*a.assumed_camera_height_m;history_rot=np.einsum('ji,njk->nik',R0,rot)
 for slot,(camera,yaw,zoom) in slots.items():
  offsets=[-2,-1,-.5,-.1,0] if slot in {1,6} else [-1,-.1,0]
  for si,offset in enumerate(offsets):
   request=1000000+round((t0+offset)*1e6);available=[r for r in by_cam[camera] if r['timestamp_us']<=request];row=available[-1];file=f'camera-{slot}-{si}.jpg';resample(row,yaw,zoom).save(dest/file,quality=95);shots.append({'image':file,'camera_id':slot,'timestamp_us':row['timestamp_us']-1000000,'source_image':row['image'],'requested_time_seconds':t0+offset,'virtual_camera_yaw_deg':yaw,'virtual_camera_zoom':zoom})
 record={'schema':1,'t0_seconds':t0,'shots':shots,'history_xyz_m':xyz.tolist(),'history_rot':history_rot.tolist(),'world_anchor_position_relative_units':P0.tolist(),'world_anchor_rotation':R0.tolist(),'assumed_camera_height_m':a.assumed_camera_height_m,'scale_status':'assumed, not measured; RGB SfM has no absolute scale','history_source':'RGB-derived ground-projected positions and yaw-only body orientation; planar-road assumption; Savitzky-Golay smoothing and 10 Hz interpolation; no future labels','camera_profile':'4 physical RGB streams -> 6 virtual slots: actual left/front/right; two rear crops from back RGB; tele crop from front. Narrower FOV than the native training profile; no claim of native calibration or driving accuracy','time_source':'nominal source frame number / 10; causal previous-frame selection, not supplied sensor timestamps','navigation':'Continue straight on the road and yield to pedestrians.'};(dest/'input.json').write_text(json.dumps(record,indent=2)+'\n');receipts.append({'keyframe':dest.name,'t0_seconds':t0,'images':len(shots)})
(root/'policy-inputs.json').write_text(json.dumps({'assumed_camera_height_m':a.assumed_camera_height_m,'keyframes':receipts,'uses_lidar':False,'uses_source_ego_poses':False,'uses_future_labels':False},indent=2)+'\n');print('POLICY_RGB_INPUTS',receipts,flush=True)
run_policy.pyGitHub에서 파일 보기
Python
"""Actual Alpamayo 2 Edge inference on real RGB with explicit domain/scale assumptions."""
import argparse,hashlib,json,time
from pathlib import Path
import numpy as np
from PIL import Image
import torch
from safetensors.torch import load_file
from alpamayo2_edge.checkpoint import load_model
from alpamayo2_edge.inference import run_data
from alpamayo2_edge.sample import CAMERA_PIXEL_BOUNDS
p=argparse.ArgumentParser();p.add_argument('--root',type=Path,required=True);p.add_argument('--model',type=Path,required=True);a=p.parse_args();root=a.root;expected={'00000.safetensors':'d13c1a427218baf7b7d365098c0f5496c0e5e6a6bf662836b8eebbe7eb7cfe7f','00001.safetensors':'cfe424a7320ce729cd927b5ceaab4323a62443b50f461a2f5c0dd0b10634e0b5'}
for file,sha in expected.items():
 with (a.model/file).open('rb') as f:assert hashlib.file_digest(f,'sha256').hexdigest()==sha
start=time.perf_counter();torch.cuda.reset_peak_memory_stats();model,info=load_model(str(a.model.resolve()),device='cuda',dtype='bfloat16',attn_implementation='sdpa',local_files_only=True);records=[]
settings=dict(seed=43,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})
for folder in sorted((root/'policy').iterdir()):
 m=json.loads((folder/'input.json').read_text());images=np.stack([np.array(Image.open(folder/r['image']).convert('RGB')) for r in m['shots']]);data={'image_frames':torch.from_numpy(images).permute(0,3,1,2).unsqueeze(1).contiguous(),'camera_indices':torch.tensor([r['camera_id'] for r in m['shots']],dtype=torch.int64),'absolute_timestamps':torch.tensor([r['timestamp_us'] for r in m['shots']],dtype=torch.int64),'ego_history_xyz':torch.tensor([m['history_xyz_m']],dtype=torch.float32),'ego_history_rot':torch.tensor([m['history_rot']],dtype=torch.float32),'camera_pixel_bounds':CAMERA_PIXEL_BOUNDS,'nav_text':[m['navigation']]};dest=root/'alpamayo'/folder.name;result=run_data(model,data,'pandaset-rgb-'+folder.name,dest,settings,'cuda');tensors=load_file(str(dest/'output.safetensors'));xyz=tensors['pred_xyz'][0,0,0].numpy();rot=tensors['pred_rot'][0,0,0].numpy();R=np.array(m['world_anchor_rotation']);P=np.array(m['world_anchor_position_relative_units']);world=(xyz/m['assumed_camera_height_m'])@R.T+P
 records.append({'keyframe':folder.name,'t0_seconds':m['t0_seconds'],'prediction':result,'xyz_m_assumed_scale':xyz.tolist(),'rotations':rot.tolist(),'world_xyz_relative_units':world.tolist(),'anchor_relative_units':P.tolist(),'assumed_camera_height_m':m['assumed_camera_height_m']})
report={'source':'NVlabs/alpamayo2-edge','source_revision':'02f55a7aeabc1a2b9f7a80445c08e40bddc89f5e','model':'nvidia/Alpamayo2-Edge','model_revision':'b92b6aa326bd3e2235db28f248ad5a30b5890e64','weights_verified':expected,'gpu_count':1,'torch_peak_allocated_gib':torch.cuda.max_memory_allocated()/2**30,'wall_seconds_including_load':time.perf_counter()-start,'scope':'Actual inference on source RGB, with explicitly adapted virtual-camera layout and assumed metric scale. No source pose labels, measured speed, future trajectory labels or vehicle control. This is not a policy evaluation.','input_shapes':{k:list(v.shape) for k,v in data.items() if isinstance(v,torch.Tensor)},'keyframes':records};(root/'alpamayo-result.json').write_text(json.dumps(report,indent=2)+'\n');print('ALPAMAYO_RGB_COMPLETE',len(records),flush=True)
enhance.pyGitHub에서 파일 보기
Python
"""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['NUREC_RGB_ROOT'])
source = root/'renders/orbit'
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)
export_viewer.pyGitHub에서 파일 보기
Python
"""Package the NuRec-exported Gaussian model, RGB perception and Alpamayo output.

NuRec trains on normalized RGB-derived coordinates; its world-space PLY therefore
already uses the viewer's relative coordinate frame. Do not apply COLMAP's
world-to-viewer normalization a second time. Third-party rasterization can differ
from the native NuRec renderer; the native before/after recordings are separate.
"""
import argparse,json,shutil,subprocess,gzip,struct
from pathlib import Path
p=argparse.ArgumentParser();p.add_argument('--root',type=Path,required=True);a=p.parse_args();root=a.root;lab=Path(__file__).resolve().parent;shared=lab.parent/'rgb-reality-view';out=root/'viewer';out.mkdir(exist_ok=True);source=root/'rig-source/viewer'
model=root/'gaussians/background/model.ply'
if not model.exists():raise RuntimeError('Run the official NuRec export-gaussian-plys command first')
subprocess.run(['npm','exec','--yes','--package=@playcanvas/splat-transform@3.12.0','--','splat-transform','-w',str(model),'--filter-harmonics','1',str(out/'road.spz'),'--spz-version','3'],check=True)
g=json.loads((source/'cameras.json').read_text());g['world_to_viewer']=[[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]];g['backend']='NuRec 26.04';g['native_renderer']='NuRec gsplat';g['browser_renderer']='Spark / Three.js, converted 3DGS preview';g['trained_gaussians']=struct.unpack('<III',gzip.decompress((out/'road.spz').read_bytes())[:12])[2];g['reconstruction_title']='RGB only · NuRec';g['pipeline_notice']='NuRec-trained Gaussian preview in a browser rasterizer; native NuRec and Harmonizer outputs are recorded separately'
if (source/'perception.json').exists():shutil.copy2(source/'perception.json',out/'perception.json');shutil.copytree(source/'camera',out/'camera',dirs_exist_ok=True);g['perception_file']='perception.json'
policy=root/'alpamayo-result.json'
if policy.exists():
 full=json.loads(policy.read_text());(out/'alpamayo.json').write_text(json.dumps({'schema':1,'model':full['model'],'scope':full['scope'],'keyframes':full['keyframes']},separators=(',',':'))+'\n');g['policy_file']='alpamayo.json'
(out/'cameras.json').write_text(json.dumps(g,indent=2)+'\n')
for name in ['viewer.html','viewer.js','viewer.css','perception-view.js','policy-view.js']:shutil.copy2(shared/name,out/name)
shutil.copy2(shared/'assets/volvo-s90.glb',out/'volvo-s90.glb');shutil.copy2(shared/'assets/VEHICLE-LICENSE.txt',out/'VEHICLE-LICENSE.txt')
if (root/'PANDASET-DATA-LICENSE.txt').exists():shutil.copy2(root/'PANDASET-DATA-LICENSE.txt',out/'PANDASET-DATA-LICENSE.txt')
credit=(shared/'assets/EXAMPLE-ATTRIBUTION.txt').read_text().replace('3DGRUT learned a static scene.','NuRec learned a static scene using its 3DGUT preset.');credit+='\nNuRec 26.04 native reconstruction/rendering; browser preview converted with the official export-gaussian-plys command.\nHarmonizer comparison footage: Built on NVIDIA Cosmos; NVIDIA Open Model License.\nAlpamayo 2 Edge: actual source-RGB inference, adapted virtual-camera layout and assumed camera-height scale; no vehicle control.\n'
(out/'ATTRIBUTION.txt').write_text(credit);print('NUREC_BROWSER_READY',flush=True)
guidance/pipeline.pyGitHub에서 파일 보기
Python
"""One-stage-at-a-time entry point for the RGB geometry guidance lab.

First complete the parent RGB reconstruction through the prepare/perceive
stages. Keep each comparison/production experiment in its own output folder.
"""
import argparse, os, subprocess
from pathlib import Path


def main():
    p=argparse.ArgumentParser();p.add_argument('--root',type=Path,required=True);p.add_argument('--base',type=Path,required=True)
    p.add_argument('--production',action='store_true');p.add_argument('--variant',choices=['all','baseline','depth','depth-normal','depth-normal-soft'],default='all')
    p.add_argument('stage',choices=['setup','inputs','prepare','priors','dense','train','evaluate','export','package','serve']);a=p.parse_args()
    root=a.root.expanduser().resolve();base=a.base.expanduser().resolve();here=Path(__file__).resolve().parent;python=root/'.venv/bin/python'
    env={**os.environ,'NUREC_RGB_ROOT':str(root),'CUDA_VISIBLE_DEVICES':'0','OMP_NUM_THREADS':'8'}
    def run(args):subprocess.run([str(v) for v in args],check=True,env=env)
    if a.stage=='setup':run(['python3',here/'setup.py','--root',root])
    elif a.stage=='inputs':run([python,here/'make_inputs.py','--root',root,'--base',base,*(['--no-holdout'] if a.production else [])])
    elif a.stage=='prepare':run(['bash',here.parent/'run.sh','prepare'])
    elif a.stage=='priors':run(['flock',env.get('GPU_LOCK','/tmp/rgb-reality-view.gpu.lock'),python,here/'infer_priors.py','--root',root,'--perception',base/'rig-source/viewer/perception.json'])
    elif a.stage=='dense':run([python,here/'dense_seed.py','--root',root])
    elif a.stage=='train':
        if a.production and a.variant=='all':raise SystemExit('Choose a single --variant for the production model, e.g. depth.')
        run([python,here/'run_experiment.py','--root',root,'--variant',a.variant,*(['--steps','32000','--max-gaussians','1200000','--seed-file','seed-dense.ply','--no-render'] if a.production else [])])
    elif a.stage=='evaluate':run([python,here/'evaluate.py','--root',root,'--perception',base/'rig-source/viewer/perception.json'])
    elif a.stage=='export':
        if a.variant=='all':raise SystemExit('Choose a completed --variant to export.')
        run([python,here/'export_model.py','--root',root,'--variant',a.variant])
    elif a.stage=='package':run([python,here/'package_viewer.py','--root',root,'--base',base])
    elif a.stage=='serve':run(['python3',here.parent.parent/'rgb-reality-view/serve.py','--root',root/'viewer','--port','8093'])


if __name__=='__main__':main()
guidance/geometry.pyGitHub에서 파일 보기
Python
"""RGB-derived geometric priors in the existing relative coordinate frame."""
import numpy as np


def align_depth(prediction, target, iterations=8):
    """Robust positive scale/shift fit to training-view SfM z depths only."""
    x, y = np.asarray(prediction, float), np.asarray(target, float)
    valid = np.isfinite(x) & np.isfinite(y) & (x > 0) & (y > 0)
    x, y = x[valid], y[valid]
    if len(x) < 30:
        raise ValueError('At least 30 valid training correspondences are required')
    keep = (y < np.percentile(y, 95)) & (y > np.percentile(y, 5))
    x, y = x[keep], y[keep]
    a, b = float(np.median(y / x)), 0.0
    A = np.stack([x, np.ones_like(x)], axis=1)
    for _ in range(iterations):
        residual = a*x + b - y
        sigma = max(float(np.median(np.abs(residual))) * 1.4826, .01*np.median(y))
        weights = np.minimum(1., 1.5*sigma/np.maximum(np.abs(residual), 1e-12))
        fit = np.linalg.lstsq(A*np.sqrt(weights[:, None]), y*np.sqrt(weights), rcond=None)[0]
        if fit[0] <= 0 or abs(fit[1]) > np.median(y):
            break
        a, b = map(float, fit)
    # Remove gross outliers after robust fitting so their residual influence
    # does not bias a clean, well-conditioned scale/shift estimate.
    residual=np.abs(a*x+b-y)
    threshold=max(3*1.4826*float(np.median(residual)),.03*float(np.median(y)))
    inliers=residual<threshold
    if inliers.sum()>=30:
        fit=np.linalg.lstsq(A[inliers],y[inliers],rcond=None)[0]
        if fit[0]>0 and abs(fit[1])<=np.median(y):a,b=map(float,fit)
    return a, b, {'samples': len(x), 'inliers': int(inliers.sum()), 'median_relative_error': float(np.median(np.abs(a*x+b-y)/y))}


def normals_from_z(depth, K, valid):
    """Camera-facing unit normals from z-depth; invalid boundaries stay zero."""
    h, w = depth.shape
    yy, xx = np.mgrid[:h, :w]
    rays = np.stack([(xx-K[0, 2])/K[0, 0], (yy-K[1, 2])/K[1, 1], np.ones((h, w))], axis=-1)
    points = rays * depth[..., None]
    dx = points[1:-1, 2:] - points[1:-1, :-2]
    dy = points[2:, 1:-1] - points[:-2, 1:-1]
    n = np.cross(dy, dx)
    length = np.linalg.norm(n, axis=-1, keepdims=True)
    n /= np.maximum(length, 1e-10)
    local = valid[1:-1, 1:-1] & valid[1:-1, 2:] & valid[1:-1, :-2] & valid[2:, 1:-1] & valid[:-2, 1:-1]
    z = depth[1:-1, 1:-1]
    jump = np.maximum(np.abs(depth[1:-1, 2:]-depth[1:-1, :-2]), np.abs(depth[2:, 1:-1]-depth[:-2, 1:-1]))
    local &= (length[..., 0] > 1e-10) & (jump < .08*np.maximum(z, 1e-3))
    out = np.zeros((h, w, 3), np.float32)
    out[1:-1, 1:-1] = np.where(local[..., None], n, 0)
    return out, rays.astype(np.float32)
guidance/scene.yamlGitHub에서 파일 보기
YAML
# Matched-budget RGB-only geometry experiment. Values are scene-relative.
defaults:
  - /experimental/3dgut/3dgut_colmap
  - override /model/gaussians/initialization@model.layers.background.initialization: ply
  - _self_
out_dir: /work/train-guided
mode: trainval
seed: 42
dataset:
  path: /work/ncore/rgb-only-road.json
  camera_ids: [front_camera, front_left_camera, front_right_camera, left_camera, right_camera, back_camera]
  lidar_ids: []
  n_samples_per_epoch: 16000
  n_val_image_subsample: 1
  train_sequential_camera_frame_step: 1
  val_camera_frame_step: 8
  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: 450000
  renderer:
    outputs:
      camera:
        enable_normals: true
loss:
  distance:
    fn: log_l1
    reduce: {name: mean}
    lambda_: 0.1
    start_step: 500
    min_distance: 0.001
    max_distance: 1000000.0
    normalize_by_opacity: true
    allow_missing_supervision: false
  normal:
    fn: rgb_normal_cosine
    reduce: {name: mean}
    lambda_: 0.03
    start_step: 500
    allow_missing_supervision: false
  gaussian_flatten:
    fn: abs
    reduce: {name: mean}
    axes_type: fixed
    max_to_median_ratio_threshold: 5.0
    lambda_: 0.0005
system:
  test:
    video_fps: 10
    metrics:
      cpsnr:
        enabled: false
guidance/train.pyGitHub에서 파일 보기
Python
"""Attach independently generated RGB priors to NuRec's native loss inputs.

This adapter imports the separately licensed, pinned NuRec runtime. It does not
copy or redistribute runtime source. Native distance/normal losses and rendering
remain responsible for optimization and backpropagation.
"""
import functools, json, os, sys
from pathlib import Path
import cv2
import numpy as np
import torch
from ncore.data import FrameTimepoint
from nre.datasets.ncore import NCOREDataset
from nre.utils.types import RayFlags
sys.path.insert(0,'/lab/guidance')
from normal_loss import rgb_normal_cosine

root=Path(os.environ.get('NUREC_RGB_ROOT','/work'))
prior_folder=root/os.environ.get('RGB_PRIOR_FOLDER','priors-base')
original=NCOREDataset.get_camera_data_batch


@functools.lru_cache(maxsize=64)
def load_prior(sensor,stamp):
    path=prior_folder/sensor/f'{stamp}.npz'
    if not path.is_file():raise FileNotFoundError('A required RGB prior is missing; regenerate the matching training split')
    with np.load(path) as values:return values['distance'],values['normals']


def get_camera_data_batch(self,sensor_id,sensor_frame_idx,sampled_pixels=None):
    batch=original(self,sensor_id,sensor_frame_idx,sampled_pixels)
    sensor=self.datasource.camera_sensors[sensor_id]
    stamp=int(sensor.get_frame_timestamp_us(sensor_frame_idx,frame_timepoint=FrameTimepoint.END))
    distance,normals=load_prior(sensor_id,stamp)
    distance=distance[...,None]
    if sampled_pixels is not None:
        distance=sampled_pixels.apply_to_array(distance,interpolation=cv2.INTER_NEAREST)
        normals=sampled_pixels.apply_to_array(normals,interpolation=cv2.INTER_NEAREST)
    # NuRec's field is called metric_distance, but these numbers remain in its
    # scene units after scale conversion; they are not measured metric depth.
    scale=self.datasource.world_to_nre.target_scale
    batch.labels.metric_distance=torch.from_numpy(np.ascontiguousarray(distance*scale,dtype=np.float32)).unsqueeze(0)
    batch.labels.normals=torch.from_numpy(np.ascontiguousarray(normals,dtype=np.float32)).unsqueeze(0)
    valid=torch.linalg.vector_norm(batch.labels.normals,dim=-1,keepdim=True)>.5
    batch.labels.flags |= valid.to(torch.int32)*RayFlags.VALID_NORMAL.value
    return batch


NCOREDataset.get_camera_data_batch=get_camera_data_batch
from libs.losses.models.render_losses import DistanceLoss, NormalLoss


def report_native_loss(cls,label):
    forward=cls.forward
    checked=False
    def instrument(self,results,target,model):
        nonlocal checked
        result=forward(self,results,target,model)
        if not checked and torch.is_grad_enabled() and result is not None:
            value=results.rendered_cam.distance if label=='depth' else results.rendered_cam.normal
            assert value is not None and value.requires_grad, f'{label} must be differentiable'
            assert torch.isfinite(value).all(), f'{label} contains non-finite render values'
            labels=target.data.camera.labels
            count=int((labels.metric_distance>0).sum()) if label=='depth' else int((torch.linalg.vector_norm(labels.normals,dim=-1)>.5).sum())
            assert count>0,'Empty guidance mask'
            print('RGB_GUIDANCE_NATIVE_LOSS',json.dumps({'kind':label,'valid_pixels':count,'differentiable':True,'finite':True}),flush=True)
            checked=True
        return result
    cls.forward=instrument


report_native_loss(DistanceLoss,'depth')
report_native_loss(NormalLoss,'normal')
from nre.run.main import main
case=os.environ.get('RGB_GUIDANCE_CASE','depth-normal')
print('RGB_GUIDANCE_TRAIN',case,str(prior_folder.name),flush=True)
overrides=json.loads(os.environ.get('RGB_GUIDANCE_OVERRIDES','[]'))
main.main(args=['--config-name','geometry-guided.yaml',*overrides],standalone_mode=False)
guidance/normal_loss.pyGitHub에서 파일 보기
Python
"""Channel-preserving cosine loss for NuRec's native [N,1] reduction mask."""
import torch.nn.functional as F
from libs.losses.models.registry import register_loss_fn


@register_loss_fn('rgb_normal_cosine')
def rgb_normal_cosine(prediction,target,**kwargs):
    assert prediction.shape==target.shape and prediction.shape[-1]==3
    # A plain [N] result broadcasts against [N,1] to a quadratic [N,N] array.
    return 1-(F.normalize(prediction,dim=-1)*F.normalize(target,dim=-1)).sum(dim=-1,keepdim=True)
temporal/pipeline.pyGitHub에서 파일 보기
Python
"""One-GPU, public-checkpoint-only temporal Reality View workflow."""
from __future__ import annotations
import argparse,hashlib,io,json,os,platform,shutil,subprocess,tarfile
from pathlib import Path

HERE=Path(__file__).resolve().parent
SOURCE_PIN='826c1998796e024bc82c9843b3ec515c50737573'
DEPS_PIN='a2c298b0a3df3778b973fe65e9e58877b292d8a7'
MODEL_PIN='20ca33d4612b1e98e0526b3a7ee604af5b289f58'
MODEL_SHA='6e65e9ec33019a49f7f0d15f81f5e089c2527e131bd5339d6a14f9b3531db524'
BASE='nvcr.io/nvidia/pytorch:25.10-py3@sha256:42263b2424fc237b34c4fc4a91c30d603c57eed36e37d31ff6d9a4f1f801edee'

def run(args,**kw):subprocess.run([str(x) for x in args],check=True,**kw)
def sha(path):return hashlib.file_digest(Path(path).open('rb'),'sha256').hexdigest()
def main():
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--root',type=Path,required=True);p.add_argument('--input',type=Path);p.add_argument('--image',default='physical-ai-harmonizer:826c199');p.add_argument('--max-frames',type=int);p.add_argument('--port',type=int,default=8765);p.add_argument('--comparison-dir',type=Path);p.add_argument('stage',choices=['setup','compare','evaluate','check','serve']);a=p.parse_args()
    root=a.root.expanduser().resolve();root.mkdir(parents=True,exist_ok=True)
    if root.is_relative_to(HERE.parents[2]/'site/public'):raise ValueError('Keep checkpoints, runtime data and raw logs outside site/public')
    source=root/'deps/harmonizer';checkpoint=source/'models/diffusion_harmonizer.pkl';comparison=(a.comparison_dir or root/'comparison').resolve();lock=os.environ.get('GPU_LOCK','/tmp/rgb-reality-view.gpu.lock')
    if a.stage=='setup':
        if platform.system()!='Linux' or platform.machine() not in ['x86_64','AMD64']:raise ValueError('GPU setup requires Linux x86_64; inspect saved results and use the browser on other machines')
        uv=shutil.which('uv') or str(Path.home()/'.local/bin/uv')
        if not Path(uv).is_file():raise ValueError('Install uv first; see the GPU onboarding guide')
        for tool in ['git','docker','flock']:
            if not shutil.which(tool):raise ValueError(f'Install {tool} first; see the GPU onboarding guide')
        source.parent.mkdir(exist_ok=True)
        if not source.exists():run(['git','clone','https://github.com/NVIDIA/harmonizer.git',source]);run(['git','-C',source,'checkout',SOURCE_PIN])
        if subprocess.check_output(['git','-C',str(source),'rev-parse','HEAD'],text=True).strip()!=SOURCE_PIN:raise ValueError('Dependency source differs; preserve it and select a fresh root')
        context=root/'docker-context'
        if not context.exists():
            context.mkdir();archive=tarfile.open(fileobj=io.BytesIO(subprocess.check_output(['git','-C',str(source),'archive','HEAD'])))
            for member in archive.getmembers():
                if member.issym() or member.islnk() or not (context/member.name).resolve().is_relative_to(context.resolve()):raise ValueError('Unexpected dependency archive member')
            archive.extractall(context,filter='data')
            dockerfile=context/'Dockerfile.cosmos';text=dockerfile.read_text();clone='RUN git clone --recursive --depth 1 https://github.com/nvidia-cosmos/cosmos-predict2.5.git /cosmos-predict2.5';assert clone in text
            text=text.replace(clone,clone+f' && cd /cosmos-predict2.5 && git fetch --depth 1 origin {DEPS_PIN} && git checkout --detach {DEPS_PIN} && git submodule update --init --recursive');dockerfile.write_text(text)
        run(['docker','build','--build-arg','BASE='+BASE,'-t',a.image,'-f',context/'Dockerfile.cosmos',context])
        # The only downloaded model artifact is the fully released Harmonizer
        # checkpoint. No gated Cosmos base weights or license acceptance API.
        code='from huggingface_hub import hf_hub_download;import sys;hf_hub_download("nvidia/Harmonizer","diffusion_harmonizer.pkl",revision="'+MODEL_PIN+'",local_dir=sys.argv[1])'
        run([uv,'run','--no-project','--with','huggingface-hub==0.36.0','python','-c',code,checkpoint.parent])
        if sha(checkpoint)!=MODEL_SHA:raise ValueError('Official checkpoint checksum mismatch')
        (root/'setup.json').write_text(json.dumps({'source_revision':SOURCE_PIN,'dependency_revision':DEPS_PIN,'base_image':BASE,'image_id':subprocess.check_output(['docker','image','inspect',a.image,'--format','{{.Id}}'],text=True).strip(),'model_revision':MODEL_PIN,'model_sha256':MODEL_SHA,'no_gated_base_checkpoint':True},indent=2)+'\n');return
    if not checkpoint.is_file() or sha(checkpoint)!=MODEL_SHA:raise ValueError('Run setup and verify the pinned public checkpoint first')
    if a.stage in ['compare','serve']:
        if subprocess.check_output(['git','-C',str(source),'rev-parse','HEAD'],text=True).strip()!=SOURCE_PIN:raise ValueError('Use the pinned upstream source')
        run(['git','-C',source,'diff','--quiet','HEAD','--','src'])
    if a.stage=='check':
        for mode in ['independent','temporal']:
            folder=comparison/mode;data=json.loads((folder/'result.json').read_text());assert data['checkpoint_sha256']==MODEL_SHA and data['standalone_initialization']['all_learned_parameters_equal_released_tensors']
            for row in data['records']:
                file=(folder/row['output']).resolve();assert file.is_relative_to(folder) and sha(file)==row['output_sha256']
            if mode=='temporal':assert any(x['history_frames']==4 for x in data['records'])
        print('VERIFIED_REAL_TEMPORAL_RESULTS');return
    common=['docker','run','--rm','--user',f'{os.getuid()}:{os.getgid()}','-v',f'{root}:/data','-v',f'{source}:/work:ro','-v',f'{HERE}:/adapters:ro','-w','/work/src','-e','HOME=/tmp','-e','PYTHONPATH=/work/src:/adapters','-e','HF_HUB_OFFLINE=1','-e','TRANSFORMERS_OFFLINE=1']
    if a.stage=='serve':
        run(['flock',lock,*common,'--gpus','device=0','--network','host','--shm-size=8g','--entrypoint','python',a.image,'/adapters/service.py','--checkpoint','/work/models/diffusion_harmonizer.pkl','--components','/data/components','--record-root','/data/live-captures','--port',a.port]);return
    if a.input:a.input=a.input.expanduser().resolve()
    if not a.input or not a.input.is_dir():raise ValueError('Supply --input with ordered16:9 novel-view render frames')
    if not comparison.is_relative_to(root):raise ValueError('Keep comparison outputs inside the selected private runtime root')
    if a.stage=='compare':
        for mode in ['independent','temporal']:
            run(['flock',lock,*common,'--gpus','device=0','--network','none','--shm-size=8g','-v',f'{a.input}:/input:ro','--entrypoint','python',a.image,'/adapters/enhance.py','--input','/input','--out','/data/'+str((comparison/mode).relative_to(root)),'--checkpoint','/work/models/diffusion_harmonizer.pkl','--standalone-components','/data/components','--mode',mode,*(['--max-frames',a.max_frames] if a.max_frames else [])])
    elif a.stage=='evaluate':
        run([*common,'--network','none','-v',f'{a.input}:/input:ro','--entrypoint','python',a.image,'/adapters/evaluate.py','--input','/input','--independent','/data/'+str((comparison/'independent').relative_to(root)),'--temporal','/data/'+str((comparison/'temporal').relative_to(root)),'--out','/data/'+str((comparison/'evaluation.json').relative_to(root))])
if __name__=='__main__':main()
temporal/enhance.pyGitHub에서 파일 보기
Python
"""Matched V=1 / V=5 inference with the official temporal Harmonizer model.

Launch in the pinned official Cosmos environment, from its src directory.
The original render and generated output remain separate. This is an image
enhancer, not Tesla UVE, a driving policy, or a reconstruction ground truth.
"""
from __future__ import annotations
import argparse,hashlib,json,time
from pathlib import Path
import numpy as np
from PIL import Image
import torch

def main():
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--input',type=Path,required=True);p.add_argument('--out',type=Path,required=True);p.add_argument('--checkpoint',type=Path,required=True);p.add_argument('--mode',choices=['temporal','independent'],required=True);p.add_argument('--standalone-components',type=Path);p.add_argument('--cut-frames',default='');p.add_argument('--max-frames',type=int);a=p.parse_args()
    import pix2pix_turbo_harmonizer as upstream
    standalone=None
    if a.standalone_components:
        from standalone import prepare,patch_config
        paths,standalone=prepare(a.checkpoint,a.standalone_components);patch_config(upstream,paths)
    if a.out.exists() and any(a.out.iterdir()):raise ValueError('Choose a fresh output folder; autoregressive outputs cannot be silently reused')
    files=sorted(p for p in a.input.iterdir() if p.suffix.lower() in ['.jpg','.png','.jpeg'])
    if a.max_frames:files=files[:a.max_frames]
    if not files:raise ValueError('No input frames')
    cuts={0,*[int(x) for x in a.cut_frames.split(',') if x]}
    if min(cuts)<0 or max(cuts)>=len(files):raise ValueError('Cut indices must belong to the selected frame range')
    a.out.mkdir(parents=True);torch.manual_seed(42);torch.set_num_threads(8)
    model=upstream.Pix2Pix_Turbo(pretrained_path=str(a.checkpoint),timestep=250,train_full_unet=True,freeze_vae=False,vae_skip_connection=False,use_sched=False,device='cuda',dtype=torch.bfloat16)
    if standalone is not None:
        from standalone import verify_parameters
        standalone.update(verify_parameters(model,a.checkpoint))
    model.set_eval();model=model.to(device='cuda',dtype=torch.bfloat16);history=[];records=[];torch.cuda.reset_peak_memory_stats()
    def tensor(rgb):
        if rgb.size!=(1024,576):rgb=rgb.resize((1024,576),Image.Resampling.BILINEAR)
        return torch.from_numpy(np.asarray(rgb,dtype=np.uint8).copy()).permute(2,0,1)[None].to(device='cuda',dtype=torch.bfloat16)/127.5-1
    with torch.inference_mode():
        for index,path in enumerate(files):
            if index in cuts:history.clear()
            image=Image.open(path).convert('RGB')
            if image.width*9!=image.height*16:raise ValueError('Use16:9 input; the model directly resizes to1024x576')
            current=tensor(image.resize((1024,576),Image.Resampling.BILINEAR));references=[]
            if a.mode=='temporal' and len(history)>=4:references=[tensor(p) for p in history[-1:-5:-1]]
            stacked=torch.stack([current,*references],dim=2)
            torch.cuda.synchronize();start=time.perf_counter();pred=model(stacked);torch.cuda.synchronize();seconds=time.perf_counter()-start
            if tuple(pred.shape)!=(1,3,len(references)+1,576,1024) or not torch.isfinite(pred).all():raise ValueError(f'Invalid model output {tuple(pred.shape)}')
            rgb=((pred[0,:,0].float().permute(1,2,0).cpu().numpy()+1)*127.5).clip(0,255).astype(np.uint8);small=Image.fromarray(rgb);result=small.resize(image.size,Image.Resampling.BICUBIC);destination=a.out/f'{index:06d}.png';result.save(destination)
            # Match official autoregressive PNG feedback: previous enhanced
            # outputs, never future frames or independent ground truth.
            history.append(result);history=history[-4:]
            records.append({'frame':index,'input':path.name,'input_sha256':hashlib.sha256(path.read_bytes()).hexdigest(),'output':destination.name,'output_sha256':hashlib.sha256(destination.read_bytes()).hexdigest(),'history_frames':len(references),'model_seconds':seconds,'cut_reset':index in cuts})
            if index%20==0:print('TEMPORAL_ENHANCE',a.mode,index+1,len(files),round(seconds,4),len(references),flush=True)
    warm=[r['model_seconds'] for r in records if r['frame']>=4]
    report={'schema':1,'mode':a.mode,'model':'nvidia/Harmonizer','model_revision':'20ca33d4612b1e98e0526b3a7ee604af5b289f58','checkpoint_sha256':hashlib.sha256(a.checkpoint.read_bytes()).hexdigest(),'model_license':'NVIDIA Open Model License','source_code_license':'Apache-2.0','attribution':'Built on NVIDIA Cosmos','frames':len(files),'internal_resolution':[1024,576],'context':'Current rendered RGB plus four previous enhanced outputs when available; reset at declared cuts','uses_future_frames':False,'model_median_seconds_after_frame4':float(np.median(warm)) if warm else None,'model_p95_seconds_after_frame4':float(np.percentile(warm,95)) if warm else None,'peak_allocated_gib':torch.cuda.max_memory_allocated()/2**30,'timing_scope':'Synchronized model forward only, not capture, preparation, transport, encoding, or end-to-end generation FPS','torch':torch.__version__,'records':records}
    if standalone is not None:report['standalone_initialization']=standalone
    (a.out/'result.json').write_text(json.dumps(report,indent=2)+'\n');print('TEMPORAL_ENHANCE_COMPLETE',a.mode,len(files),flush=True)
if __name__=='__main__':main()
temporal/standalone.pyGitHub에서 파일 보기
Python
"""Initialize exclusively from the publicly released Harmonizer checkpoint.

No base-model weights are fetched. The release includes the complete trained
live DiT and VAE parameters. Derived files stay in a private output directory;
the original checkpoint and upstream source are never modified. Inference is
refused if any learned parameter lacks an exact released tensor of its shape.
"""
from __future__ import annotations
import hashlib,json
from pathlib import Path
import torch
MODEL_SHA256='6e65e9ec33019a49f7f0d15f81f5e089c2527e131bd5339d6a14f9b3531db524'

def prepare(checkpoint,folder):
    folder=Path(folder);folder.mkdir(parents=True,exist_ok=True)
    digest=hashlib.file_digest(Path(checkpoint).open('rb'),'sha256').hexdigest()
    if digest!=MODEL_SHA256:raise ValueError('Use the pinned public Harmonizer checkpoint; preserve other model experiments separately')
    receipt=folder/'components.json';paths={'dit':folder/'harmonizer-live-dit.pt','vae':folder/'harmonizer-vae.pt'}
    if receipt.exists():
        old=json.loads(receipt.read_text())
        if old['checkpoint_sha256']!=digest:raise ValueError('Standalone component cache belongs to a different release')
        for k,path in paths.items():
            if hashlib.file_digest(path.open('rb'),'sha256').hexdigest()!=old['components'][k]['sha256']:raise ValueError('A standalone component cache changed')
        return paths,old
    if any(x.exists() for x in paths.values()):raise ValueError('Unknown partial component cache; preserve it and select a fresh directory')
    state=torch.load(checkpoint,map_location='cpu',weights_only=True,mmap=True);live={}
    for key,value in state['state_dict_unet'].items():
        if key.startswith('dit.'):live[key[4:]]=value
        elif key.startswith('net.'):live[key[4:]]=value
    if not live or not state['state_dict_vae']:raise ValueError('The public checkpoint does not contain complete model components')
    components={'dit':live,'vae':state['state_dict_vae']}
    for k,path in paths.items():torch.save(components[k],path)
    report={'schema':1,'checkpoint_sha256':digest,'weights_source':'Only nvidia/Harmonizer diffusion_harmonizer.pkl; no gated Cosmos checkpoint retrieved','components':{k:{'tensors':len(components[k]),'sha256':hashlib.file_digest(path.open('rb'),'sha256').hexdigest()} for k,path in paths.items()}}
    receipt.write_text(json.dumps(report,indent=2)+'\n');return paths,report

def patch_config(module,paths):
    original=module.get_pipeline_config
    def config(*args,**kwargs):
        value=original(*args,**kwargs);value.dit_path=str(paths['dit']);value.tokenizer['vae_pth']=str(paths['vae']);return value
    module.get_pipeline_config=config

def verify_parameters(model,checkpoint):
    released=torch.load(checkpoint,map_location='cpu',weights_only=True,mmap=True);unet={}
    for key,value in released['state_dict_unet'].items():
        if key.startswith('net.'):key='dit.'+key[4:]
        elif key.startswith('net_ema.'):key='dit_ema.'+key[8:]
        unet[key]=value
    groups={'dit':(model.unet,unet),'vae':(model._inner_vae(),released['state_dict_vae'])};counts={};mapping_counts={}
    canonical=lambda name:name.replace('_checkpoint_wrapped_module.','').replace('_orig_mod.','')
    for group,(target,source) in groups.items():
        # Activation-checkpoint/compile wrappers can expose different parameter
        # and state-dict names without changing the learned operation. Check
        # canonical names and actual values; strict=False alone is not proof.
        lookup={}
        for key,value in source.items():
            name=canonical(key)
            if name in lookup:raise ValueError(f'Ambiguous released parameter name: {name}')
            lookup[name]=value
        assignments={}
        for key,param in target.named_parameters():
            name=canonical(key)
            if name not in lookup or tuple(lookup[name].shape)!=tuple(param.shape):raise ValueError(f'Uncovered learned parameter: {group}.{key}')
        for key in target.state_dict():
            if canonical(key) in lookup:assignments[key]=lookup[canonical(key)]
        target.load_state_dict(assignments,strict=False)
        mapping_counts[group]=sum(canonical(key)!=key for key,_ in target.named_parameters())
        total=0
        for key,param in target.named_parameters():
            if param.is_meta:raise ValueError(f'Unmaterialized learned parameter: {group}.{key}')
            if not torch.equal(param.detach().cpu(),lookup[canonical(key)].to(dtype=param.dtype)):raise ValueError(f'Released parameter did not load exactly: {group}.{key}')
            total+=param.numel()
        counts[group]=total
    return {'all_learned_parameters_covered':True,'all_learned_parameters_equal_released_tensors':True,'parameter_counts':counts,'wrapper_names_remapped':mapping_counts,'scope':'All learned tensors loaded and exactly checked after dtype conversion, including activation-checkpoint wrapper names; architectural nonlearned buffers follow the pinned upstream implementation.'}
temporal/evaluate.pyGitHub에서 파일 보기
Python
"""Matched optical-flow stability proxies, not unseen-view accuracy or safety."""
from __future__ import annotations
import argparse,hashlib,json
from pathlib import Path
import cv2
import numpy as np

def backward_map(previous,current):
    gray=lambda x:cv2.cvtColor(x,cv2.COLOR_RGB2GRAY)
    args=(None,.5,4,21,4,7,1.5,cv2.OPTFLOW_FARNEBACK_GAUSSIAN)
    backward=cv2.calcOpticalFlowFarneback(gray(current),gray(previous),*args)
    forward=cv2.calcOpticalFlowFarneback(gray(previous),gray(current),*args)
    h,w=current.shape[:2];yy,xx=np.mgrid[:h,:w].astype(np.float32);mx=xx+backward[...,0];my=yy+backward[...,1]
    inverse=cv2.remap(forward,mx,my,cv2.INTER_LINEAR,borderMode=cv2.BORDER_CONSTANT)
    valid=(mx>=1)&(my>=1)&(mx<w-2)&(my<h-2)&(np.linalg.norm(backward+inverse,axis=-1)<1.5)
    return mx,my,valid

def main():
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--input',type=Path,required=True);p.add_argument('--independent',type=Path,required=True);p.add_argument('--temporal',type=Path,required=True);p.add_argument('--out',type=Path,required=True);a=p.parse_args()
    modes={k:json.loads((getattr(a,k)/'result.json').read_text()) for k in ['independent','temporal']}
    x,y=modes['independent'],modes['temporal']
    if x['mode']!='independent' or y['mode']!='temporal' or x['checkpoint_sha256']!=y['checkpoint_sha256']:raise ValueError('Compare the same checkpoint in independent and temporal modes')
    if [r['input_sha256'] for r in x['records']]!=[r['input_sha256'] for r in y['records']]:raise ValueError('The two runs did not receive identical ordered source frames')
    if len(x['records'])<6 or not any(r['history_frames']==4 for r in y['records']):raise ValueError('No actual temporal-context inference was completed')
    def image(path):
        bgr=cv2.imread(str(path))
        if bgr is None:raise ValueError(f'Missing image: {path}')
        return cv2.cvtColor(cv2.resize(bgr,(512,288),interpolation=cv2.INTER_AREA),cv2.COLOR_BGR2RGB)
    records=[];previous=None
    for i,row in enumerate(x['records']):
        source=a.input/row['input']
        if hashlib.sha256(source.read_bytes()).hexdigest()!=row['input_sha256']:raise ValueError('A source frame changed after inference')
        frames={'native':image(source),**{k:image(getattr(a,k)/modes[k]['records'][i]['output']) for k in modes}}
        if previous is not None and not y['records'][i]['cut_reset']:
            mx,my,valid=backward_map(previous['native'],frames['native']);scores={}
            for k,frame in frames.items():
                warped=cv2.remap(previous[k],mx,my,cv2.INTER_LINEAR,borderMode=cv2.BORDER_CONSTANT)
                error=np.abs(frame.astype(np.float32)-warped)/255
                scores[k]={'flow_warp_l1':float(error[valid].mean()) if valid.any() else None,'edge_magnitude':float(np.abs(cv2.Laplacian(cv2.cvtColor(frame,cv2.COLOR_RGB2GRAY),cv2.CV_32F)).mean()/255)}
            records.append({'frame':i,'valid_fraction':float(valid.mean()),'actual_history_frames':y['records'][i]['history_frames'],'scores':scores})
        previous=frames
    contextual=[r for r in records if r['actual_history_frames']==4 and r['valid_fraction']>.1]
    if not contextual:raise ValueError('No valid matched temporal pairs')
    summary={k:{'flow_warp_l1':float(np.mean([r['scores'][k]['flow_warp_l1'] for r in contextual])),'edge_magnitude':float(np.mean([r['scores'][k]['edge_magnitude'] for r in contextual]))} for k in ['native','independent','temporal']}
    report={'schema':1,'frames':len(x['records']),'contextual_pairs':len(contextual),'checkpoint_sha256':x['checkpoint_sha256'],'summary':summary,'method':'Shared backward Farneback flow from the native input; forward/backward round-trip threshold1.5px at512x288; same valid pixels for all modes. Cuts and context-free startup frames excluded from summary.','scope':'Temporal stability proxy; not ground-truth depth, novel-view fidelity, object correctness, or driving safety. Blur or frozen output can reduce warp error; inspect edge sharpness and actual camera response alongside it.','timing':{k:{n:modes[k][n] for n in ['model_median_seconds_after_frame4','model_p95_seconds_after_frame4','peak_allocated_gib']} for k in modes},'pairs':records}
    a.out.parent.mkdir(parents=True,exist_ok=True);a.out.write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(summary))
if __name__=='__main__':main()
temporal/service.pyGitHub에서 파일 보기
Python
"""Optional loopback GPU image enhancer; no workspace or model downloads API."""
from __future__ import annotations
import argparse,base64,collections,io,json,math,threading,time
from http.server import BaseHTTPRequestHandler,ThreadingHTTPServer
from pathlib import Path
import numpy as np
from PIL import Image,UnidentifiedImageError
import torch
from context import reset_reasons

class Engine:
    def __init__(self,checkpoint,components,record_root=None):
        import pix2pix_turbo_harmonizer as upstream
        from standalone import prepare,patch_config,verify_parameters
        paths,self.provenance=prepare(checkpoint,components);patch_config(upstream,paths)
        torch.manual_seed(42);torch.set_num_threads(8)
        self.model=upstream.Pix2Pix_Turbo(pretrained_path=str(checkpoint),timestep=250,train_full_unet=True,freeze_vae=False,vae_skip_connection=False,use_sched=False,device='cuda',dtype=torch.bfloat16)
        self.provenance.update(verify_parameters(self.model,checkpoint));self.model.set_eval();self.model.to(device='cuda',dtype=torch.bfloat16)
        self.lock=threading.Lock();self.sessions=collections.OrderedDict();self.record_root=record_root;self.sequence=0
        if record_root:record_root.mkdir(parents=True,exist_ok=True)
    @staticmethod
    def image_tensor(image):
        return torch.from_numpy(np.array(image.resize((1024,576),Image.Resampling.BILINEAR),copy=True)).permute(2,0,1)[None].to(device='cuda',dtype=torch.bfloat16)/127.5-1
    def infer(self,request):
        if not isinstance(request,dict):raise ValueError('JSON object required')
        session=request.get('session','');mode=request.get('mode','temporal');info=request.get('view',{})
        if not isinstance(info,dict):raise ValueError('View metadata object required')
        if not session or len(session)>64 or any(c not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_' for c in session):raise ValueError('Invalid local session identifier')
        if mode not in ['independent','temporal']:raise ValueError('Unsupported enhancement mode')
        try:raw=base64.b64decode(request['image'],validate=True)
        except Exception:raise ValueError('Expected base64 PNG or JPEG image') from None
        if len(raw)>2500000:raise ValueError('Image exceeds local preview limit')
        image=Image.open(io.BytesIO(raw));w,h=image.size
        if w*h>2100000 or w<256 or h<144 or w*9!=h*16:raise ValueError('Use a16:9 image of at most2.1megapixels')
        image=image.convert('RGB')
        numeric=[*info.get('camera',[]),*info.get('forward',[])]
        if len(numeric)!=6 or not all(isinstance(x,(int,float)) and math.isfinite(x) for x in numeric):raise ValueError('Supply finite camera and forward three-vectors')
        if np.linalg.norm(info['forward'])<1e-6 or not isinstance(info.get('frame'),int):raise ValueError('Invalid view direction or frame index')
        with self.lock:
            previous=self.sessions.pop(session,{'history':[],'view':None,'mode':mode});history=previous['history'];reset=bool(request.get('reset')) or previous['mode']!=mode
            reasons=reset_reasons(previous['view'],info);reset|=bool(reasons)
            if reset:history=[]
            refs=[self.image_tensor(p) for p in history[-1:-5:-1]] if mode=='temporal' and len(history)>=4 else []
            x=torch.stack([self.image_tensor(image),*refs],dim=2)
            torch.cuda.synchronize();start=time.perf_counter()
            with torch.inference_mode():y=self.model(x)
            torch.cuda.synchronize();seconds=time.perf_counter()-start
            if tuple(y.shape)!=(1,3,len(refs)+1,576,1024) or not torch.isfinite(y).all():raise RuntimeError('Invalid enhanced output')
            rgb=((y[0,:,0].float().permute(1,2,0).cpu().numpy()+1)*127.5).clip(0,255).astype(np.uint8);result=Image.fromarray(rgb);buffer=io.BytesIO();result.save(buffer,format='PNG');encoded=base64.b64encode(buffer.getvalue()).decode()
            self.sessions[session]={'history':[*history,result][-4:],'view':info,'mode':mode}
            while len(self.sessions)>2:self.sessions.popitem(last=False)
            self.sequence+=1
            receipt={'sequence':self.sequence,'mode':mode,'history_frames':len(refs),'history_reset':bool(reset),'reset_reasons':reasons,'model_ms':seconds*1000,'view':info,'resolution':[1024,576],'checkpoint_sha256':self.provenance['checkpoint_sha256'],'scope':'Generated enhancement of a captured offline3D reconstruction; no driving control or unseen-view ground truth'}
            if self.record_root:
                prefix=self.record_root/f'{self.sequence:06d}';image.save(prefix.with_suffix('.input.png'));result.save(prefix.with_suffix('.output.png'));prefix.with_suffix('.json').write_text(json.dumps(receipt,indent=2)+'\n')
            return {'image':encoded,**receipt}

def handler(engine):
    class Handler(BaseHTTPRequestHandler):
        def reply(self,status,value):
            raw=json.dumps(value).encode();self.send_response(status);self.send_header('Content-Type','application/json');self.send_header('Content-Length',str(len(raw)));self.send_header('Cache-Control','no-store');self.end_headers();self.wfile.write(raw)
        def do_GET(self):
            if self.path!='/health':self.reply(404,{'error':'Unknown endpoint'});return
            self.reply(200,{'ready':True,'model':'nvidia/Harmonizer','learned_parameters_verified':self.engine.provenance['all_learned_parameters_equal_released_tensors'],'modes':['independent','temporal']})
        def do_POST(self):
            if self.path!='/infer':self.reply(404,{'error':'Unknown endpoint'});return
            if self.headers.get('Content-Type','').split(';')[0]!='application/json':self.reply(415,{'error':'JSON required'});return
            if self.headers.get('Origin'):self.reply(403,{'error':'Use the same-origin local viewer proxy'});return
            try:
                length=int(self.headers.get('Content-Length','0'))
                if not 0<length<=3500000:raise ValueError('Request size limit exceeded')
                value=json.loads(self.rfile.read(length));result=self.engine.infer(value)
            except (ValueError,KeyError,TypeError,UnidentifiedImageError,Image.DecompressionBombError):self.reply(400,{'error':'Invalid preview request'});return
            except Exception:self.reply(500,{'error':'GPU enhancement failed; inspect the private service log'});raise
            self.reply(200,result)
        def log_message(self,*args):pass
    Handler.engine=engine;return Handler

def main():
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--checkpoint',type=Path,required=True);p.add_argument('--components',type=Path,required=True);p.add_argument('--port',type=int,default=8765);p.add_argument('--record-root',type=Path);a=p.parse_args()
    engine=Engine(a.checkpoint,a.components,a.record_root);print('LOCAL_ENHANCER_READY',a.port,flush=True);ThreadingHTTPServer(('127.0.0.1',a.port),handler(engine)).serve_forever()
if __name__=='__main__':main()
temporal/context.pyGitHub에서 파일 보기
Python
"""Discontinuity guards for sparse interactive viewpoints, in relative units."""
import math

def reset_reasons(previous,current):
    if previous is None:return []
    reasons=[];a=previous['forward'];b=current['forward'];norm=lambda v:math.sqrt(sum(x*x for x in v))
    cosine=sum(x*y for x,y in zip(a,b))/(norm(a)*norm(b))
    if cosine<math.cos(math.radians(12)):reasons.append('camera_rotation')
    if norm([x-y for x,y in zip(previous['camera'],current['camera'])])>.75:reasons.append('camera_translation')
    if previous.get('projection')!=current.get('projection'):reasons.append('projection_changed')
    if previous.get('variant')!=current.get('variant'):reasons.append('reconstruction_changed')
    if current['frame']<previous['frame'] or abs(current['frame']-previous['frame'])>4:reasons.append('timeline_jump')
    return reasons
temporal/support.pyGitHub에서 파일 보기
Python
"""Inspect Gaussian centers against RGB-predicted depth; no measured-depth claim.

Counts distinct named cameras, not repeated frames as independent cameras.
The false-color export retains geometry/opacity and removes directional color.
"""
from __future__ import annotations
import argparse, hashlib, json, subprocess
from pathlib import Path
import numpy as np

COLORS=np.array([[.95,.24,.12],[1.,.67,.12],[.08,.77,.65]],np.float32)

def visible_depth_agreement(points,camera_to_world,K,distance,relative=.10,absolute=.10):
    """Gaussian-center projection with predicted ray-distance consistency."""
    points=np.asarray(points);C=np.asarray(camera_to_world);K=np.asarray(K)
    if not np.isfinite(C).all() or not np.isfinite(K).all():raise ValueError('Nonfinite estimated camera')
    q=(points-C[:3,3])@C[:3,:3];finite=np.isfinite(q).all(axis=1);front=finite&(q[:,2]>1e-4)
    projected=q@K.T;uv=np.zeros((len(q),2),np.int64)
    uv[front]=np.rint(projected[front,:2]/projected[front,2:]).astype(np.int64)
    h,w=distance.shape;inside=front&(uv[:,0]>=0)&(uv[:,0]<w)&(uv[:,1]>=0)&(uv[:,1]<h)
    ids=np.flatnonzero(inside);result=np.zeros(len(q),bool)
    predicted=distance[uv[ids,1],uv[ids,0]];ray=np.linalg.norm(q[ids],axis=1)
    result[ids]=np.isfinite(predicted)&(predicted>0)&(np.abs(ray-predicted)<=absolute+relative*predicted)
    return result

def main():
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--root',type=Path,required=True);p.add_argument('--out',type=Path,required=True);p.add_argument('--relative-tolerance',type=float,default=.10);p.add_argument('--absolute-tolerance',type=float,default=.10);a=p.parse_args()
    from plyfile import PlyData
    r=a.root;out=a.out
    if out.exists() and any(out.iterdir()):raise ValueError('Choose a fresh support-output folder')
    out.mkdir(parents=True,exist_ok=True);model=r/'gaussians/background/model.ply';ply=PlyData.read(model);v=ply['vertex'];xyz=np.stack([v[x] for x in ['x','y','z']],axis=1)
    rows=json.loads((r/'rgb-cameras.json').read_text())['frames'];names=sorted({x['camera'] for x in rows})
    if len(names)>16:raise ValueError('This export supports at most16 named cameras')
    bits=np.zeros(len(xyz),np.uint16);observations=np.zeros(len(xyz),np.uint16);inputs=[]
    for i,row in enumerate(rows):
        prior=r/'priors-base'/row['camera']/f"{row['timestamp_us']}.npz"
        with np.load(prior,allow_pickle=False) as data:distance=data['distance']
        for start in range(0,len(xyz),200000):
            end=min(start+200000,len(xyz));yes=visible_depth_agreement(xyz[start:end],row['camera_to_world'],row['K'],distance,a.relative_tolerance,a.absolute_tolerance)
            bits[start:end]|=yes.astype(np.uint16)<<names.index(row['camera']);observations[start:end]+=yes
        inputs.append({'image':row['image'],'depth_sha256':hashlib.sha256(prior.read_bytes()).hexdigest()})
        if i%24==0:print('SUPPORT_FRAME',i+1,len(rows),flush=True)
    counts=np.zeros(len(xyz),np.uint8)
    for bit in range(len(names)):counts+=((bits>>bit)&1).astype(np.uint8)
    colors=COLORS[np.minimum(counts,2)]
    for axis in range(3):v[f'f_dc_{axis}']=(colors[:,axis]-.5)/.28209479177387814
    for name in v.data.dtype.names:
        if name.startswith('f_rest_'):v[name]=0
    target=out/'support.ply';ply.write(target);np.savez_compressed(out/'support-counts.npz',named_camera_count=counts,frame_count=observations)
    subprocess.run(['npm','exec','--yes','--package=@playcanvas/splat-transform@3.12.0','--','splat-transform','-w',str(target),'--filter-harmonics','0',str(out/'support.spz'),'--spz-version','3'],check=True)
    report={'schema':1,'gaussians':len(xyz),'source_images':len(rows),'camera_names':names,'relative_tolerance':a.relative_tolerance,'absolute_tolerance_relative_units':a.absolute_tolerance,'histogram':{str(n):int((counts==n).sum()) for n in range(len(names)+1)},'legend':{'0':'No depth-consistent estimated RGB observation','1':'One named camera','2+':'At least two named cameras'},'scope':'Gaussian-center consistency with RGB-predicted depth and RGB-estimated poses. Not measured visibility, ground truth, per-pixel provenance, or a hallucination detector. Occlusion is approximated by predicted depth.','geometry_opacity_unchanged':True,'source_model_sha256':hashlib.sha256(model.read_bytes()).hexdigest(),'support_spz_sha256':hashlib.sha256((out/'support.spz').read_bytes()).hexdigest(),'inputs':inputs}
    (out/'support.json').write_text(json.dumps(report,indent=2)+'\n');print('SUPPORT_COMPLETE',report['histogram'],flush=True)
if __name__=='__main__':main()
temporal/check.pyGitHub에서 파일 보기
Python
"""Inspect published execution receipts and media integrity without a GPU."""
from pathlib import Path
import gzip
import hashlib
import json
import math
import struct

REPO = Path(__file__).resolve().parents[3]
EVIDENCE = REPO / 'labs/nurec-rgb-reality/evidence/temporal'


def read(file):
    return json.loads(file.read_text())


def main():
    independent, temporal = [read(EVIDENCE / f'{mode}.json') for mode in ('independent', 'temporal')]
    assert independent['mode'] == 'independent' and temporal['mode'] == 'temporal'
    assert len(independent['records']) == len(temporal['records']) == 160
    assert independent['checkpoint_sha256'] == temporal['checkpoint_sha256']
    assert [r['input_sha256'] for r in independent['records']] == [r['input_sha256'] for r in temporal['records']]
    for report in (independent, temporal):
        assert report['internal_resolution'] == [1024, 576] and not report['uses_future_frames']
        init = report['standalone_initialization']
        assert init['all_learned_parameters_covered'] and init['all_learned_parameters_equal_released_tensors']
        assert init['parameter_counts'] == {'dit': 597536000, 'vae': 126892531}
        assert all(math.isfinite(r['model_seconds']) and r['model_seconds'] > 0 for r in report['records'])
    assert all(r['history_frames'] == 0 for r in independent['records'])
    assert [r['history_frames'] for r in temporal['records'][:5]] == [0, 0, 0, 0, 4]
    evaluation = read(EVIDENCE / 'evaluation.json')
    assert evaluation['frames'] == 160 and evaluation['contextual_pairs'] == 156
    assert evaluation['checkpoint_sha256'] == temporal['checkpoint_sha256']
    assert evaluation['summary']['temporal']['flow_warp_l1'] < evaluation['summary']['independent']['flow_warp_l1']
    portable = read(EVIDENCE / 'portable-validation.json')
    assert portable['setup']['no_gated_base_checkpoint']
    for mode, values in evaluation['summary'].items():
        for metric, value in values.items():
            assert math.isclose(portable['portable_cpu_evaluation']['summary'][mode][metric], value, rel_tol=1e-6, abs_tol=1e-8)
    for mode in ('independent', 'temporal'):
        smoke = portable['portable_wrapper_gpu_smoke'][mode]
        assert smoke['frames'] == 6 and smoke['all_learned_parameters_equal_released_tensors']
    assert portable['portable_wrapper_gpu_smoke']['temporal']['history_frames'] == [0, 0, 0, 0, 4, 4]
    browser = read(EVIDENCE / 'browser.json')
    assert {r['language'] for r in browser} == {'en', 'ko'}
    for report in browser:
        assert not report['errors'] and report['mobile']['width'] <= report['mobile']['viewport']
        assert any(e['action'] == 'small_mouse_orbit' and e['history_frames'] == 4 for e in report['events'])
        assert any(e['action'] == 'driver_view_resets_history' and e['history_reset'] for e in report['events'])
        assert any(e['action'] == 'independent_mode' and e['history_frames'] == 0 for e in report['events'])
        assert all(e['model_ms'] > 0 and e['round_trip_ms'] >= e['model_ms'] for e in report['events'])
    media = read(EVIDENCE / 'media.json')
    assert len(media['media']) == 4
    for item in media['media']:
        file = (REPO / item['file']).resolve()
        assert file.is_relative_to(REPO / 'site/public/showcase')
        assert file.stat().st_size == item['bytes'] < 100 * 1024**2
        assert hashlib.sha256(file.read_bytes()).hexdigest() == item['sha256']
    viewer = REPO / 'site/public/showcase/nurec-rgb-reality'
    assert 'enhancement_endpoint' not in read(viewer / 'cameras.json')
    variants = read(viewer / 'guidance.json')['variants']
    for variant in variants:
        file = viewer / variant['file']
        assert hashlib.sha256(file.read_bytes()).hexdigest() == variant['sha256']
        with gzip.open(file, 'rb') as stream:
            magic, version, count = struct.unpack('<III', stream.read(12))
        assert magic == 0x5053474e and version == 3 and count == variant['gaussians']
    support = read(viewer / 'support.json')
    assert sum(support['histogram'].values()) == 1200000 and support['geometry_opacity_unchanged']
    assert support['support_spz_sha256'] == next(v['sha256'] for v in variants if v['id'] == 'support')
    print('PASS: 160 matched frames, exact learned parameters, actual GPU interactions, four videos and model hashes. Integrity/execution only; not driving safety or unseen-view accuracy.')


if __name__ == '__main__':
    main()
temporal/record_viewer.mjsGitHub에서 파일 보기
텍스트
// Record the real optional local GPU preview, including actual mouse changes.
import fs from 'node:fs';
import path from 'node:path';
import {pathToFileURL} from 'node:url';
const args=Object.fromEntries(process.argv.slice(2).reduce((r,s,i,a)=>{if(s.startsWith('--'))r.push([s.slice(2),a[i+1]]);return r;},[]));
const lang=args.language??'en',out=path.resolve(args.output??'temporal-recording');fs.mkdirSync(out,{recursive:true});
const {chromium}=await import(process.env.PLAYWRIGHT_MODULE?pathToFileURL(process.env.PLAYWRIGHT_MODULE).href:'playwright');
const browser=await chromium.launch({channel:'chrome',headless:true,args:process.platform==='darwin'?['--use-angle=metal']:[]});
const context=await browser.newContext({viewport:{width:1440,height:1000},recordVideo:{dir:out,size:{width:1440,height:1000}}});
const page=await context.newPage(),video=page.video(),born=Date.now(),errors=[],events=[];page.on('pageerror',e=>errors.push(String(e)));
try{
 await page.goto(args.url??`http://127.0.0.1:8092/?lang=${lang}`);await page.locator('[data-rgb-load]').click();await page.waitForFunction(()=>document.querySelector('[data-rgb-viewer]').dataset.rgbReady==='true',null,{timeout:120000});await page.waitForTimeout(1600);
 if(!await page.locator('[data-enhance]').count())throw Error('Start the viewer with its explicit --enhancer-url option');
 const trim=(Date.now()-born)/1000;
 async function capture(action){const last=await page.evaluate(()=>document.querySelector('[data-rgb-viewer]').rgbEnhancementState?.sequence??0);await page.locator('[data-enhance]').click();await page.waitForFunction(n=>{const r=document.querySelector('[data-rgb-viewer]');return r.rgbEnhancementState?.sequence>n||r.rgbEnhancementError;},last,{timeout:90000});const result=await page.evaluate(()=>{const r=document.querySelector('[data-rgb-viewer]');if(r.rgbEnhancementError)throw Error(r.rgbEnhancementError);return r.rgbEnhancementState;});events.push({action,video_time:(Date.now()-born)/1000-trim,...result});return result;}
 await capture('initial');await page.waitForTimeout(1600);
 for(let i=0;i<5;i++)await capture('build_actual_history');
 if(events.at(-1).history_frames!==4)throw Error('Actual four-output context did not initialize');
 await page.screenshot({path:path.join(out,`live.${lang}.jpg`),type:'jpeg',quality:90});
 const box=await page.locator('[data-rgb-stage] > canvas').boundingBox();
 for(let i=0;i<6;i++){const x=box.x+box.width*.5,y=box.y+box.height*.48;await page.mouse.move(x,y);await page.mouse.down();await page.mouse.move(x+box.width*.004,y,{steps:8});await page.mouse.up();await page.waitForTimeout(160);await capture('small_mouse_orbit');}
 if(!events.some(e=>e.action==='small_mouse_orbit'&&e.history_frames===4))throw Error('Small camera changes never retained temporal context');
 await page.locator('[data-rgb-preset=driver]').click();const changed=await capture('driver_view_resets_history');if(!changed.history_reset)throw Error('Preset jump retained stale context');await page.waitForTimeout(2200);
 await page.locator('[data-enhance-mode]').selectOption('independent');await capture('independent_mode');await page.waitForTimeout(1600);
 await page.locator('[data-rgb-preset=chase]').click();await page.locator('[data-enhance-mode]').selectOption('temporal');for(let i=0;i<5;i++)await capture('chase_temporal');await page.waitForTimeout(1600);
 const finish=(Date.now()-born)/1000;await page.setViewportSize({width:390,height:844});await page.waitForTimeout(400);const mobile=await page.evaluate(()=>({viewport:innerWidth,width:document.documentElement.scrollWidth}));await page.screenshot({path:path.join(out,`mobile.${lang}.png`),fullPage:true});if(mobile.width>mobile.viewport||errors.length)throw Error(JSON.stringify({mobile,errors}));
 await context.close();fs.renameSync(await video.path(),path.join(out,`raw.${lang}.webm`));fs.writeFileSync(path.join(out,`recording.${lang}.json`),JSON.stringify({language:lang,viewport:[1440,1000],trim_start_seconds:trim,content_seconds:finish-trim,events,mobile,errors,method:'Actual local browser and actual GPU outputs. No simulated inference or pre-rendered camera substitution.'},null,2));console.log('PASS',lang,(finish-trim).toFixed(1),'seconds',events.length,'actual responses');
}finally{await browser.close();}
temporal/test_context.pyGitHub에서 파일 보기
Python
import math,unittest
from context import reset_reasons

def view(angle=0,x=0,frame=13,projection=None):
    return {'forward':[math.sin(math.radians(angle)),0,math.cos(math.radians(angle))],'camera':[x,0,3],'frame':frame,'variant':'guided','projection':projection or [64,1,1,.5]}

class ContextTests(unittest.TestCase):
    def test_smooth_orbit_keeps_context(self):self.assertEqual(reset_reasons(view(),view(3,.2)),[])
    def test_interactive_jump_does_not_reuse_old_car_pose(self):self.assertIn('camera_rotation',reset_reasons(view(),view(30)))
    def test_large_translation_resets(self):self.assertIn('camera_translation',reset_reasons(view(),view(x=1)))
    def test_resize_or_lens_change_resets(self):self.assertIn('projection_changed',reset_reasons(view(),view(projection=[30,1,1,.5])))
    def test_backward_seek_resets(self):self.assertIn('timeline_jump',reset_reasons(view(frame=13),view(frame=12)))
if __name__=='__main__':unittest.main()
temporal/test_support.pyGitHub에서 파일 보기
Python
import unittest
import numpy as np
from support import visible_depth_agreement

class ProjectionTests(unittest.TestCase):
    def test_ray_distance_and_occlusion(self):
        K=np.array([[1.,0,1],[0,1,1],[0,0,1]])
        depth=np.zeros((3,3));depth[1,1]=2;depth[1,2]=np.sqrt(8)
        points=np.array([[0,0,2],[2,0,2],[0,0,4],[0,0,-2],[99,0,2]])
        actual=visible_depth_agreement(points,np.eye(4),K,depth,0,.001)
        np.testing.assert_array_equal(actual,[True,True,False,False,False])
    def test_camera_translation(self):
        C=np.eye(4);C[0,3]=10;depth=np.ones((1,1))*3
        np.testing.assert_array_equal(visible_depth_agreement([[10,0,3],[0,0,3]],C,np.eye(3),depth,0,.001),[True,False])
    def test_invalid_depth_is_not_observation(self):
        self.assertFalse(visible_depth_agreement([[0,0,1]],np.eye(4),np.eye(3),np.array([[np.nan]]))[0])
if __name__=='__main__':unittest.main()
check.pyGitHub에서 파일 보기
Python
"""CPU checks of actual RGB-only NuRec, enhancement, perception and VLA outputs.

Integrity and execution checks do not establish driving or detector accuracy.
"""
import argparse,gzip,hashlib,json,math,struct,subprocess
from pathlib import Path
LAB=Path(__file__).resolve().parent
REPO=LAB.parents[1]
def read(name):return json.loads((LAB/name).read_text())
def proper_rotation(R):
 assert len(R)==3 and all(len(row)==3 for row in R) and all(math.isfinite(x) for row in R for x in row)
 for i in range(3):
  for j in range(3):assert abs(sum(R[k][i]*R[k][j] for k in range(3))-(i==j))<2e-3
 det=sum(R[0][i]*(R[1][(i+1)%3]*R[2][(i+2)%3]-R[1][(i+2)%3]*R[2][(i+1)%3]) for i in range(3));assert abs(det-1)<2e-3

def main(decode=False):
 report=read('recorded.json');n=read('evidence/nurec-result.json');assert n['training_steps']==16000 and n['training_seconds']>0
 assert not n['uses_lidar'] and not n['uses_source_sensor_poses'] and not n['uses_source_annotations']
 assert n['preset']=='experimental/3dgut/3dgut_colmap' and len(n['artifact_sha256'])==64
 prep=read('evidence/prepared.json');assert prep['image_count']==162 and prep['camera_count']==6 and prep['seed_gaussians']>20000
 assert 'RGB' in prep['seed_source']
 rig=read('evidence/rig-bundle-result.json');assert rig['input_images']==162 and rig['rig_frames']==27 and rig['rigs']==1 and rig['reprojection_after_px']<2
 harm=read('evidence/harmonizer-result.json');pairs=read('evidence/render-pairs.json');assert harm['frames']==pairs['frames']==48 and len(pairs['pairs'])==48
 assert pairs['nurec_artifact_sha256']==n['artifact_sha256'] and harm['checkpoint_sha256']==pairs['harmonizer_checkpoint_sha256']
 assert all(math.isfinite(t) and t>0 for t in harm['per_frame_seconds'])
 fresh=read('evidence/fresh-pipeline-check.json');assert fresh['exit_code']==0 and fresh['fresh_output_folder'] and fresh['new_python_environments']
 assert fresh['stages_completed']==['setup','rgb','rig','prepare','train','render','enhance','policy','perceive','export']
 assert fresh['completion_marker']=='RGB_NUREC_PIPELINE_COMPLETE' and not fresh['uses_lidar']
 assert fresh['exported_gaussians']==450000 and fresh['enhanced_frames']==48 and fresh['actual_alpamayo_keyframes']==4
 browsers=read('evidence/browser-check.json');assert {(r['language'],r['mobile']) for r in browsers}=={('en',False),('ko',False),('en',True),('ko',True)}
 for browser in browsers:
  assert not browser['errors'] and not browser['failed'] and browser['nurec_backend'] and browser['actual_alpamayo_path']
  assert browser['dimensions']['content']<=browser['dimensions']['width']+1 and browser['inline_video']['inline']
 policy=read('evidence/alpamayo-result.json');assert len(policy['keyframes'])==4 and policy['gpu_count']==1
 assert policy['input_shapes']['image_frames']==[22,1,3,576,1024] and policy['input_shapes']['ego_history_xyz']==[1,20,3]
 for k in policy['keyframes']:
  assert k['prediction']['finite'] and len(k['xyz_m_assumed_scale'])==len(k['world_xyz_relative_units'])==len(k['rotations'])==64
  assert k['assumed_camera_height_m']==1.8
  assert all(len(p)==3 and all(math.isfinite(x) for x in p) for p in k['world_xyz_relative_units'])
  for R in k['rotations']:proper_rotation(R)
 sample=read('evidence/policy-input-sample.json');assert len(sample['shots'])==22 and len(sample['history_xyz_m'])==len(sample['history_rot'])==20
 assert 'assumed' in sample['scale_status'] and 'RGB' in sample['history_source']
 for row in sample['shots']:assert row['timestamp_us']/1e6<=row['requested_time_seconds']+1e-8
 for R in sample['history_rot']:proper_rotation(R)
 assert max(abs(x) for x in sample['history_xyz_m'][-1])<1e-5
 web=REPO/'site/public/showcase/nurec-rgb-reality';g=json.loads((web/'cameras.json').read_text());assert g['backend']=='NuRec 26.04' and len(g['frames'])==27
 assert g['world_to_viewer']==[[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]
 with gzip.open(web/'road.spz','rb') as f:magic,version,count=struct.unpack('<III',f.read(12))
 assert magic==0x5053474E and version==3 and count==450000==g['trained_gaussians']
 data=json.loads((web/'perception.json').read_text());perception=read('evidence/perception-result.json');assert hashlib.sha256((web/'perception.json').read_bytes()).hexdigest()==perception['perception_sha256']
 assert not perception['uses_source_annotations'] and not perception['uses_lidar'] and len(data['frames'])==27
 for relative,sha in perception['rgb_preview_sha256'].items():
  path=web/relative;assert path.resolve().is_relative_to(web.resolve());assert hashlib.sha256(path.read_bytes()).hexdigest()==sha
 viewpolicy=json.loads((web/'alpamayo.json').read_text());assert viewpolicy['keyframes']==policy['keyframes']
 for lang in ['en','ko']:
  trace=read(f'evidence/interaction.{lang}.json');events={e['action']:e for e in trace['events']};assert trace['errors']==[] and len(events)==11
  assert events['initial']['gaussians']==450000 and events['initial']['policy']['poses']==64 and events['initial']['perception']['people_in_camera']>0
  assert not events['policy_off']['policy']['enabled'] and events['policy_on']['policy']['enabled']
  assert not events['recognition_off']['perception']['enabled'] and events['recognition_on']['perception']['enabled']
  assert math.dist(events['initial']['camera'],events['orbit']['camera'])>.1 and events['perception_replay']['frame']!=events['initial']['frame']
 for relative,expected in report['files'].items():
  path=REPO/relative;assert path.resolve().is_relative_to(REPO.resolve());assert path.stat().st_size==expected['bytes'],relative;assert hashlib.sha256(path.read_bytes()).hexdigest()==expected['sha256'],relative
  if decode and path.suffix=='.mp4':subprocess.run(['ffmpeg','-v','error','-i',str(path),'-f','null','-'],check=True)
 print('Verified RGB-only NuRec completion, 450k exported Gaussians, 48 native/enhanced pairs, four actual Alpamayo outputs, perception, causal input times and browser interactions.')
if __name__=='__main__':
 p=argparse.ArgumentParser();p.add_argument('--decode-video',action='store_true');main(p.parse_args().decode_video)