RGB-only NuRec, Harmonizer and Alpamayo

Actual mouse-controlled NuRec scene → GPU Harmonizer with four previous outputs. Inspect original RGB detections, Alpamayo predictions and the native/generated pair; camera jumps reset history. Explore the saved 3D scene without a GPU or reproduce the optional local enhancer.

  • RGB only
  • NuRec 26.04
  • Depth Anything 3
  • Harmonizer
  • Alpamayo 2 Edge
  • Mask R-CNN
RGB-only Reality View: 3D geometry and temporal enhancement
Recorded runExample run and recording

Orbit around the Volvo yourself

Preview the Gaussians trained in NuRec with a browser rasterizer. Native NuRec renders and Harmonizer enhancement are shown in the comparison recording below.

RGB-reconstructed road with a Volvo S90 reference
RGB only · NuRec
—

Drag: orbit · Scroll/pinch: zoom · Right drag: pan

PandaSet: Scale AI / Hesai · Volvo S90: lazercar, CC BY 4.0 · Sources and terms

The RGB clip is reconstructed offline; viewpoint changes are interactive in your browser. Scale is relative and surrounding traffic is part of a static scene. The Volvo is a separately rendered foreground 3D reference.

Reconstruct a real road in NuRec, compare Harmonizer on the same new camera views, and inspect Alpamayo 2 Edge predictions together with actual camera detections. The reconstruction uses RGB pixels only. Start with the saved viewer and videos, then reproduce the stages on one RTX 5090.

Temporal Reality View: compare native/V1/V5 outputs and try the optional mouse-controlled GPU enhancer below. Source-RGB perception and Alpamayo stay separate from generation.

Depth-guided reconstruction: switch models in the 3D viewer without moving the camera. Read how RGB depth and normals guide training and inspect the matched comparison.

How it works

How the data moves
  1. InputRecover a camera rig from RGB162 images → COLMAP K/poses/XYZ → rig bundle adjustment

    No LiDAR or source sensor calibration. The fixed camera layout and nominal grouping are explicit assumptions.

  2. ProcessRun NuRec and enhance native rendersNCore → NuRec artifact → native RGB → Harmonizer RGB

    NuRec trains the 3D representation. Harmonizer predicts image appearance at the same camera poses.

  3. OutputInfer from original camera evidence22 RGB views + 20 estimated poses → 64 future poses

    Alpamayo uses adapted camera slots and an assumed metric scale. Mask R-CNN separately predicts actual source-image masks.

  4. Inspect the saved outputsNuRec-exported Gaussians + Volvo + contacts + predicted path

    The browser is a converted preview. Native rendering and enhancement are recorded separately; no controls are applied.

RGB camera geometry enters NuRec; native renders enter Harmonizer; original RGB and estimated history enter Alpamayo; detections and predictions join the viewer

1. Which tools actually ran?

Stage Actual input → output Its role
COLMAP 162 RGB images → camera intrinsics, poses and sparse XYZ/RGB Recover geometry from image matches, with no supplied calibration or pose labels.
Rig bundle adjustment Free-camera estimates → one six-camera rig over 27 nominal times Fit the fixed camera layout required by this NuRec input profile.
NCore Estimated cameras, RGB and SfM points → NuRec sequence + Gaussian seed Package data; NCore is a format and API, not a model.
NuRec 26.04 NCore + RGB-derived seed → trained artifact, native new-view RGB and exported Gaussians Run the actual NuRec runtime using its 3DGUT COLMAP preset.
Harmonizer Native NuRec RGB → enhanced RGB at the same camera poses Earlier non-temporal baseline plus the new V1/V5 temporal comparison below; neither changes the 3D model.
Alpamayo 2 Edge Original RGB views + estimated past motion + navigation → 64 future poses per keyframe Run the actual VLA checkpoint; display its prediction without applying controls.
Mask R-CNN Original RGB → classes, scores, boxes and instance masks Recognize road users independently of Alpamayo and enhancement.

The standalone 3DGUT lab is a comparison implementation. NuRec itself also uses a 3DGUT preset here, but this lab calls NuRec's data, training, native rendering and export entry points, rather than substituting the standalone trainer.

2. What does RGB-only mean here?

The pinned public example fetches only camera JPEGs and the original data terms. COLMAP estimates K[3,3], camera-to-world matrices [4,4] and sparse points XYZ[N,3] from overlapping images. No LiDAR, supplied depth, GPS, IMU, sensor poses, intrinsics, sensor timestamps or object annotations enter reconstruction.

Six folders and matching frame numbers define a nominal camera grouping. Rig bundle adjustment jointly refines camera extrinsics, rig poses and points while keeping the estimated undistorted intrinsics fixed. The free-camera fit had 0.875 px mean reprojection error; the fixed-rig fit has about 1.150 px. The stronger physical layout constraint does not make the image residual smaller, and nominal grouping does not establish precise sensor synchronization.

NuRec receives 162 RGB observations and about 28,600 triangulated points. The point cloud is derived from RGB, not measured by a range sensor. NCore stores a dynamic rig trajectory, static camera-to-rig transforms, intrinsics and RGB frames. The dataset contains no LiDAR component or ground-truth object tracks.

Global scale remains ambiguous. The estimated camera-to-road height is normalized to one display unit. The road plane is fitted from RGB feature tracks. This is a relative coordinate system, not a surveyed road map. All images inform SfM, so the saved run is not an independent novel-view benchmark.

3. What changes in NuRec and Harmonizer?

NuRec optimizes Gaussian positions, orientation, size, opacity and view-dependent appearance. Its native renderer evaluates those Gaussians from a new camera. The saved run trains 16,000 steps; exact timing, artifact identity and Gaussian count are in recorded.json.

Harmonizer receives an actual native NuRec frame as float[1,3,1,576,1024] in [-1,1] and returns enhanced RGB. The side-by-side recording pairs the same camera pose and frame index. Its released non-temporal checkpoint treats frames independently, so details may change or flicker. Filling a road-shaped gap is an appearance prediction, not evidence that the hidden surface was observed. Built on NVIDIA Cosmos.

The browser viewer uses the official NuRec export-gaussian-plys result, converted to a compressed SPZ. It retains the Gaussians with degree-1 view-dependent color, then renders them with Spark/Three.js. This is a NuRec-trained browser preview; rasterization and compression can differ from native NuRec output. Public Pages shows recorded Harmonizer results. The optional local service below additionally processes actual captured mouse-controlled views; it does not run in static Pages.

4. Where does Alpamayo's route come from?

Alpamayo uses original camera pixels, not Harmonizer-generated details. Four physical RGB streams supply six virtual model slots: left, front and right views, two rotated rear subviews from the back camera, and a telephoto crop from the front. Crop rays stay inside the recorded images. This is an explicit camera-layout adaptation, with narrower fields of view than the model's native profile; it is not native NVIDIA AV calibration.

Text
22 selected RGB views:     uint8[22,1,3,576,1024]
Camera IDs / nominal times: int64[22]
Past positions:            float[1,20,3], -1.9 s through 0 s
Past orientations:         float[1,20,3,3]
Navigation:                “Continue straight on the road and yield to pedestrians.”
Output positions:          float[1,1,1,64,3]
Output rotations:          float[1,1,1,64,3,3]

Twenty past poses come from RGB-estimated, ground-projected motion: planar yaw orientation, position smoothing and interpolation to 10 Hz. Image selection uses the latest available frame at or before each requested time. There are no future trajectory labels. Camera poses are reconstructed offline from the whole image set, so this is not a strictly causal online perception or driving system.

The model expects meter-based history. The example explicitly assumes a 1.8 m camera height to convert relative SfM units. That scale is not measured from RGB. Changing it can change the prediction. The CLI exposes --assumed-camera-height-m so this prior is visible and replaceable.

Four actual inferences are anchored at 2.1, 3.9, 5.7 and 7.8 seconds. A dashed green line displays the latest available prediction, with its input time and scale assumption. Before 2.1 seconds, no future keyframe is shown. The line receives a small display-height offset; raw coordinates remain in the saved model output. Generated explanations may be wrong and are preserved as model output, not treated as verified scene facts. This is open-loop inference, not a closed-loop drive or driving-quality test.

5. How are cars and people shown?

Mask R-CNN predicts classes, boxes and binary instance masks on the original RGB. A score threshold of 0.8 keeps six road-user classes. Cyan marks vehicles, amber marks people and purple marks cycles. The camera panel shows the actual photos with their predictions; recognition can be switched off for comparison.

A mask-bottom pixel, estimated camera geometry and the RGB-derived road plane produce an approximate 3D contact marker. Edge-truncated, horizon and far intersections remain 2D-only. Markers are not measured 3D boxes or occlusion-correct physical actors. Temporary associations can change IDs; detection observations across frames are not unique-person or unique-car counts. Detailed mask and coordinate explanation.

The credited Volvo S90 is an added 3D foreground reference, not the original collection vehicle or a dynamics model. Native reconstruction, appearance enhancement, object perception and behavior prediction remain separately inspectable.

6. Reduce smearing with RGB-predicted depth

Predict RGB depth with DA3, align it to training SfM points, and connect ray distances and normals to native NuRec losses

An RGB-only objective can fit similar photographs with different 3D geometry. This ambiguity can produce uneven roads and colors floating in space. A depth prior estimates where the surface behind a pixel should lie. We run DA3-BASE from Depth Anything 3 on training RGB and RGB-estimated cameras. Both this checkpoint and its code are Apache-2.0; other DA3 checkpoints have different terms.

We align the predicted depth to RGB-triangulated training points using a robust positive scale and shift. Road-user detection boxes, low-confidence pixels and depth discontinuities are excluded from geometric guidance. The original images remain in the RGB objective.

Actual training photograph, RGB-predicted depth and surface normals derived from that depth

Z-depth measures distance along the camera's forward axis. Ray distance measures along the pixel's viewing ray; away from the optical axis they differ. NuRec receives ray distance. A normal is a unit vector describing a surface's orientation. Here normals come from neighboring 3D points reconstructed from the same predicted depth, not an independent normal-estimation model.

An actual road pixel (512, 450) in training image front_camera/39.jpg produced:

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]
}

The third normal component is near 1: the road faces mostly upward in this world frame. Distances use relative units, not measured meters. Native NuRec labels have shapes float[1,569,1024,1] for distance and float[1,569,1024,3] for normals, with invalid regions masked. Native differentiable renderings are compared with these targets and backpropagation adjusts Gaussian geometry. The adapter checks that both distance and normal rendering remain differentiable and finite. Actual numeric example · Loss adapter.

This is an independent implementation informed by depth/normal regularization research such as DN-Splatter, not a run of DN-Splatter itself. Predicted geometry can be wrong. Static Gaussians still cannot resolve moving-vehicle ghosting.

7. Why does a temporal decoder help a Reality View?

RGB geometry anchors the view; four previous enhanced outputs condition Harmonizer; perception and policy remain on original RGB

A single-frame enhancer can repaint the same tree differently after a small camera movement. We keep the persistent NuRec scene as the geometric anchor and give the enhancer its four previous outputs. The latest render supplies the new camera view; history helps maintain appearance. This is the implemented improvement over our earlier frame-independent demo.

Question Previous implementation Updated implementation
Where is the scene? RGB-only NuRec Gaussians Depth-guided NuRec Gaussians; same camera across comparisons
How is the image improved? Independent non-temporal checkpoint Released Harmonizer temporal checkpoint, compared in V1 and V5 modes with identical weights
What happens when I move the mouse? Browser rasterization; saved enhancement video Optional local GPU service enhances the actual captured viewpoint, with no queued obsolete views
How are abrupt changes handled? No temporal history Clear history on cuts, large camera changes, timeline jumps, projection or model changes
Where do detections and paths come from? Original RGB and estimated motion Same original inputs; overlays are added after enhancement
Which regions have RGB support? No diagnostic Switch to a depth-agreement diagnostic while retaining Gaussian geometry

Data example. The current camera render becomes float[1,3,1,576,1024], normalized to [-1,1]. Once four previous enhanced frames exist, it becomes:

Text
x[:, :, 0] = current 3D camera render
x[:, :, 1] = previous enhanced output, t−1
x[:, :, 2] = previous enhanced output, t−2
x[:, :, 3] = previous enhanced output, t−3
x[:, :, 4] = previous enhanced output, t−4
x.shape    = [1, 3, 5, 576, 1024]
y.shape    = [1, 3, 5, 576, 1024] → display y[:, :, 0]

The first four frames use V1. A reset repeats that startup. These are previous generated outputs, not future camera observations or an eight-frame future prediction. The model performs single-step diffusion-based appearance enhancement; it does not rebuild the 3D scene or prove the correctness of a filled surface. See the official source and model card.

The supplied Tesla commentary proposes a shared visual encoder feeding separate policy and diffusion/mean-flow branches. That is a useful architectural hypothesis, but its model sizes, 36 fps and eight-frame claims are not verified facts here. The linked original X post could not be directly retrieved during our check. Our implementation has no Tesla weights or shared UVE: source RGB feeds reconstruction, perception and Alpamayo separately; the visualization branch uses actual NuRec renders and public Harmonizer weights.

Inspect support, not “truth.” Select Inspect RGB depth support in the viewer. Red means zero, amber one and teal two or more distinct named cameras with a depth-consistent Gaussian-center projection. Six camera names are counted; repeated frames from one camera do not become independent cameras. This compares RGB-estimated poses with RGB-predicted depth using a 10% + 0.1-relative-unit tolerance. Occlusion, excluded moving objects and depth errors can lower the count. It is not measured visibility, a per-pixel confidence map or a hallucination detector.

Watch the same 160 camera poses in native, V1 and V5 modes · Watch actual mouse-controlled GPU enhancement

First time? Get the lab files

Open a terminal on the NVIDIA GPU machine for GPU labs, or on your own computer for CPU-only steps. Press Enter after each line. You can copy a multi-line command block as a whole.

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

This example clones into your home folder. If you already cloned the repo, skip git clone and enter your project folder. In each new terminal, check that pwd ends in awesome-nvidia-physical-ai so commands can find the labs/ files.

Run the lab

1. Explore without a CUDA GPU

Use the viewer on this page and the native NuRec/Harmonizer comparison. The source-RGB recognition panel, camera selector, predicted path and mouse controls are interactive. Browser playback reuses saved inference outputs.

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

Open http://127.0.0.1:8092/. An internet connection supplies pinned viewer JavaScript modules. Video and evidence checks also work without an NVIDIA GPU.

2. Prepare one GPU machine

The tested host uses Linux x86_64, one RTX 5090 32 GB and about 32 GB system RAM. Install a compatible NVIDIA driver, Docker with NVIDIA Container Toolkit, Python, Git, uv and Node.js/npm. Check NVIDIA Linux onboarding.

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

Read SOURCES.md first: the NuRec runtime, model weights, dataset and vehicle have separate terms. Setup pulls the pinned runtime, installs isolated environments and downloads public model checkpoints plus the NuRec metric dependency. These downloads and initial compilation take longer than the warmed-up sample run. Model weights, raw logs and input caches stay outside Git.

3. Follow each stage

Run from the repository folder. Each command must finish successfully before the next:

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 recovers cameras; rig enforces the fixed layout; prepare writes NCore; train runs NuRec and exports its Gaussians. render produces native front, quarter and orbit views; enhance processes the orbit frames with Harmonizer. policy and perceive run their own models on source RGB, and export packages the viewer.

For a fresh output folder, pipeline.py --root "$NUREC_RGB_ROOT" all runs the full sequence. GPU stages use the same lock and one visible device. The demo preset expects six camera folders with the documented PandaSet-style names; a single forward camera cannot observe the rear context needed by this example. Custom camera layouts need an explicit adapter, not relabeling unseen views.

4. Compare depth and normal guidance

Complete the parent pipeline through prepare and perceive first. Use a separate output folder for the comparison. Run these lines one at a time from the repository root. Setup creates a dedicated DA3 environment without changing the parent lab's environment.

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 holds out 24 images and re-triangulates/recolors the seed using only the remaining 138 images. priors uses training images only. train runs RGB baseline, depth, and depth+normal variants with the same initialization, seed 42, 16,000 steps and 450,000-Gaussian limit. evaluate compares all 24 held-out images at matching native resolution and writes comparison.json, without Harmonizer or image enhancement.

To test weaker normal regularization, add --variant depth-normal-soft to train and run evaluate again. This setting was adjusted after inspecting the first comparison; it is a follow-up experiment, not an independent test set result.

For the higher-detail viewer model, use a fresh output folder and add --production --variant depth to each command. This mode uses all 162 images. After priors, run dense, then train and export. Depth, normal and RGB agreement with neighboring training views select a denser seed; training uses 32,000 steps and a 1.2-million Gaussian limit. This all-image display model is separate from the held-out loss comparison below. Run package to include the parent lab's cameras, perception and policy, then serve to open http://127.0.0.1:8093/. Complete the parent pipeline's export stage first. Export uses NuRec's official PLY command, followed by SPZ compression. Without the optional service, mouse interaction uses only Spark's browser rasterizer. Stage runner · Official-model export adapter.

5. Run temporal enhancement on the GPU

First complete the preceding reconstruction and rendering stages. This extension builds an isolated official Harmonizer environment; it does not alter the NuRec container. Use Python 3.12+, Linux x86_64, Docker with NVIDIA Container Toolkit and uv. The published checkpoint is about 5 GB. Its terms are the NVIDIA Open Model License, separately from the Apache-2.0 upstream code and our MIT adapter.

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 verifies the pinned source and public checkpoint. compare runs the same ordered RGB frames with V1 and V5, writing separate outputs; select a fresh runtime folder to preserve earlier experiments. evaluate measures image stability and edge sharpness. check verifies the saved output hashes and actual four-frame context. The published 160-frame comparison used the improved model's native render path; reproduce that path and optional live viewer.

To inspect the published receipts without a GPU or model download, run:

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

The persistent GPU service is opt-in. It receives the clean 16:9 crop of the actual mouse-controlled render. Source-RGB detection markers and Alpamayo's path are then added to both display panels. Public static Pages shows the browser scene and recorded results; it never tries to connect to your computer. Local GPU service and SSH tunnel instructions.

Check the result

What did temporal enhancement change?

RTX 5090, 1024×576, BF16, identical public temporal checkpoint and 160 ordered native NuRec frames. V1 and V5 here share weights; this is separate from the older TorchScript non-temporal demo. Latency excludes the first four frames and measures synchronized model forward only.

Mode Median / p95 Peak allocated VRAM Shared-flow warp L1 ↓ Edge magnitude
Native render — — 0.02898 0.02609
V1: independent 124 / 124 ms 3.61 GiB 0.02550 0.02240
V5: four prior outputs 484 / 485 ms 7.01 GiB 0.01722 0.01973

V5 reduces this stability proxy about 32% relative to V1, while edge magnitude is about 12% lower. Smoothing can reduce the metric: these are not accuracy gains against unseen-view ground truth. Model-only throughput is roughly 8.1 / 2.1 images per second, excluding capture, encoding and transport. The video plays faster for inspection; browser rasterization near 60Hz does not mean diffusion runs at 60fps. Cold initialization/compilation adds time.

Large interactive camera jumps initially produced doubled foreground objects. The live service now resets history above 12° rotation or 0.75 relative units of translation, on projection/model changes and on timeline jumps. These are conservative demo heuristics, not learned guarantees. Our browser checks include small mouse motion retaining V5, a driver-view jump resetting history, mode switching and 390px layouts in both languages.

Per-frame timings and hashes · Matched evaluation and method · Actual browser interactions

The scene is still reconstructed offline, with static traffic and ambiguous scale. Unseen surfaces remain predictions, and no vehicle is controlled. See the source RGB, native geometry, generated view, detection estimates and policy overlay separately before interpreting the demo.

Do depth and normal losses help?

Original 450k and guided 1.2M models at the identical driver viewpoint

Compare original and production models at identical novel cameras. This visual comparison also changes initialization and training budget. The default browser chase view is lower, closer to capture height; every comparison model shares that viewpoint.

The same held-out photograph compared with RGB baseline and depth-guided reconstruction

Means over six cameras × four held-out timestamps = 24 images. Higher PSNR and SSIM indicate closer RGB reconstruction.

Matched experiment PSNR (dB) SSIM Depth / normal / flatten weights
RGB baseline 21.974 0.7113 0 / 0 / 0
Depth 22.249 0.7171 0.1 / 0 / 0
Depth + normal 21.924 0.7168 0.1 / 0.03 / 0.0005
Weaker normals · follow-up tuning 22.249 0.7175 0.1 / 0.005 / 0.00005

Depth guidance improves this comparison; strong normal regularization lowers PSNR. Weaker normal regularization is almost tied with depth alone. The viewer production model uses depth loss; normals support dense-seed orientation and consistency checks. Adding more losses does not guarantee better images. All camera poses were estimated offline using the full RGB set: this is not a benchmark that independently holds out camera estimation. Per-image metrics/hashes, training times and native differentiable-loss checks are in the comparison and run summaries.

The display model trained on one RTX 5090 in 723.07 seconds, excluding DA3 inference, camera recovery and export. The 1.2M-Gaussian viewer maintained approximately 60 FPS for static, orbit and path playback in Chrome on an M2 Max, at 896×504 and 1344×756 drawing buffers. This measures the browser’s roughly 60 Hz render-loop cadence, not maximum GPU throughput or an end-to-end real-time pipeline. Client measurements · Production training/seed/export receipt.

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'

The checker validates data provenance, camera/rig geometry, actual NuRec completion, native/Harmonizer frame pairing, policy tensor shapes and finite rotations, source-RGB detection outputs, compressed model count, artifact hashes and recorded controls. Full-video decoding needs FFmpeg. It verifies implementation and integrity, not driving safety, detector accuracy or hidden-surface truth.

Compare this run with standalone 3DGUT, the earlier RGB + LiDAR NuRec baseline, and the self-authored synthetic-road interface test. Their data assumptions and execution paths are labeled separately. The interactive view is ego-centered, but no Tesla proprietary model or live Reality View system is being reproduced.

Example run and recording

Matched native / independent / temporal comparison

160 actual native camera renders, one checkpoint in V1 and V5. Temporal warp error is lower, while edges also soften. Model-only medians are 124ms and 484ms on one RTX 5090; playback speed is not inference FPS.

Earlier baseline: reconstruction, recognition and prediction

Preserved original overview before temporal enhancement. Compare the original RGB-only NuRec scene, non-temporal Harmonizer and separate perception / policy outputs.

Use the improved 1.2M-Gaussian scene

Actual browser capture: switch from the original driver view to the guided model at the same camera, orbit with the mouse, and replay the RGB-estimated path with perception contacts and Alpamayo predictions. Offline-trained reconstruction; open-loop display.

Depth-guided reconstruction: original and production model

Actual native NuRec renders on the same quarter-view and orbit paths, with matching detail crops. The production fit changes seed density, steps and Gaussian capacity as well as guidance; use the held-out table for a loss-only comparison. No Harmonizer or image enhancement.

Actual mouse interaction with the NuRec-trained preview

Source-RGB detections, 3D contacts and actual Alpamayo predictions. Toggle the overlays, change cameras and rotate the same Gaussian scene.

Native NuRec renders and Harmonizer at the same 48 poses

Left: actual NuRec render. Right: released non-temporal Harmonizer. This is image enhancement, with generated details and possible flicker. Built on NVIDIA Cosmos.

Source code

pipeline.pyView files on GitHub
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.pyView files on GitHub
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.pyView files on GitHub
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.pyView files on GitHub
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.yamlView files on GitHub
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.shView files on GitHub
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.pyView files on GitHub
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.pyView files on GitHub
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.pyView files on GitHub
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.pyView files on GitHub
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.pyView files on GitHub
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.pyView files on GitHub
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.yamlView files on GitHub
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.pyView files on GitHub
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.pyView files on GitHub
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.pyView files on GitHub
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.pyView files on GitHub
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.pyView files on GitHub
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.pyView files on GitHub
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.pyView files on GitHub
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.pyView files on GitHub
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.pyView files on GitHub
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.pyView files on GitHub
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.mjsView files on GitHub
Text
// 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.pyView files on GitHub
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.pyView files on GitHub
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.pyView files on GitHub
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)