Original reference video
This external reference is separate from the synthetic SOMA control below. It is not the RGB source of the public sample. Watch the original in the official YouTube player.
Compare RGB video with an animated Gaussian model
Inspect a matching RGB video and 3D representation on one timeline. The public rig control and locally trained reconstruction models are labeled by their data source and representation.
Selected files are read in this browser. They are not uploaded.
SOMA synthetic RGB · control
SYNTHETIC RENDERThe matching RGB video will appear here.
NVIDIA SOMA-X · Apache-2.0 · synthetic control
SOMA rigged Gaussian control
KNOWN RIG
Download and GPU memory use depend on the selected segment.
The model is downloaded only when you choose to load it.
Drag: orbit · Scroll/pinch: zoom · Right drag: pan. The same timeline controls both panels.
This public control renders SOMA’s official neutral body and example motion as rigged Gaussians. It is not an RGB-trained reconstruction or a model of the person in the YouTube reference.
Result manifestEstimate human motion from one camera, then learn a Gaussian representation that changes over time. Follow RGB frames → human motion → generated views → 4D reconstruction → browser rendering. Separate camera movement from time playback to understand how a 4D model differs from a video.
The reference is “체포하겠어🚨🚨” on YouTube Shorts, published by 지숭이_Jisoong. The original opens through YouTube's official player. Public examples carry their own source and usage notes. You can load your own video and model files locally to follow the lab.
The lab has two paths. The public 3D example is a synthetic control sample built from official SOMA example motion, for learning camera, time and rig controls. It is not presented as appearance reconstructed from real RGB. Monocular reconstruction runs on a local video you can use. Keep their inputs and evaluation criteria separate.
How it works
- InputRead RGB and time
RGB[T,H,W,3] + timestamps → observed framesUse a local video you can use. The public SOMA control is a separate synthetic example with known geometry.
- ProcessEstimate human motion
GEM-X → joints[T,77,3] + SOMA deformations[T,110,4,4]RGB estimates are not motion-capture truth. The synthetic control already supplies its official rig motion.
- OutputLearn a time-conditioned model
Generated views + actual RGB + original face/hand crops → 4D GaussiansMoGe-3 depth and normals are weak inferred priors. Preserve the real source camera and label unobserved appearance.
- Separate time from viewpoint
query time → 3D particles → user camera → rendered RGBPause and orbit, then hold the camera and play. Open your own folder locally; the public control demonstrates known-rig rendering.
1. What you will learn
| Stage | What to inspect | Data passed to the next stage |
|---|---|---|
| Video and time | How resolution, FPS and frame indices affect motion playback | RGB frames and indices/times from the shared 30Hz input |
| Human motion | The difference between joints, skin deformation and camera coordinates | 3D joints, SOMA deformation matrices and estimated cameras |
| View generation | How a model estimates side and rear appearance at the same pose | Per-camera RGB and predicted foreground masks |
| 4D reconstruction | How position, time, volume and appearance are optimized together | A time-conditioned Gaussian model |
| Detail and geometry | Where original face/hand pixels and inferred depth/normals enter training | Refined models and comparison records |
| Validation | How to distinguish observation, reconstruction and generation | Synchronized recordings, a browser model and checks |
The NVIDIA components are GEM-X and SOMA for motion estimation and human representation. Ant Research's 4DAnyone generates additional views, Microsoft's MoGe-3 predicts depth/normals, gsplat renders Gaussians, and Spark/Three.js displays them in the browser. Their connection here is this repository's implementation, not an official integrated NVIDIA product.
2. What do RGB and 3D joints contain?
An RGB image is a uint8[height, width, 3] array. Its three values describe red, green and blue. Video adds a frame index and time. Comparing mismatched times can make a correctly moving hand look like a reconstruction error.
GEM-X estimates body and hand poses. SOMA expresses those poses using human geometry and skin deformation. The tested configuration produces the following arrays, where T is the processed frame count.
rgb: uint8[T, H, W, 3] observed camera color
times: float[T] frame times in seconds
joints: float[T, 77, 3] estimated joint XYZ
deformations: float[T, 110, 4, 4] SOMA skin-deformation matrices
K: float[T, 3, 3] estimated camera intrinsics
The 77 joints and 110 skinning bones are different arrays. Estimated motion is not motion-capture ground truth. Camera focal length and body scale can also differ from physical measurements. The final output is a learned 4D Gaussian representation, rather than a conventional skeletal-animation export.
3. Where do side and rear views come from?
A predicted mask separates the person from the source background. Estimated motion is projected into virtual cameras to create skeleton conditioning videos. 4DAnyone reads the source RGB and those conditions to generate other appearances.
source RGB + the same estimated motion
→ skeleton video for each virtual camera
→ 4DAnyone multiview generation
→ per-view RGB + predicted foreground mask
Each virtual K[3,3] and camera_to_world[4,4] records an intended viewpoint. Generation is not guaranteed to obey that camera or pose exactly. If faces, clothing or feet disagree across generated views, fitting them together can create overlapping or smeared 3D appearance.
The joint 12-view experiment uses shared RCP references and TCR links between view groups. The official implementation connects two six-view groups; this is different from twelve unrelated generation calls. Observed RGB remains the source camera's training target. It is not replaced by a generated front view. Unobserved clothing backs and hair remain generated estimates.
The runner's default reproduction preset follows the selected appearance prior: six Base24 directions plus six separately generated Turbo4 offset directions. Joint 12-view generation is a separate comparison. These are not presented as the same generation condition.
4. How does a 4D Gaussian move?
A Gaussian is a soft particle with a center, size/orientation, opacity and color. Adding time describes where it appears at a query time and how visible it is.
stored model
position/time center + space/time covariance + opacity + SH color
↓ query time t
evaluate the 3D center, volume and temporal opacity
↓ user-selected camera
project and composite the particles → RGB
In the model archive, xyz[N,3] stores particle centers and time[N,1] stores their temporal centers. Degree-3 DC and SH appearance together form color_coefficients[N,16,3]. N counts particles; T counts video frames. Particles do not all contribute equally at every time.
This implementation conditions the joint space-time distribution on the requested time. Each particle's conditional spatial covariance is fixed; changing centers and temporal weights produce the moving body. You can therefore hold the pose time and orbit the camera, or hold the camera and play the motion. It represents the recorded motion interval; it is not a general character rig that accepts arbitrary new motions.
Long videos are processed in intervals supported by the model. The package records interval starts, frame ranges and playback transitions. Pose, appearance and color continuity need separate checks at interval boundaries.
5. How do short models become one full-motion timeline?
After completing the short result, extend fits later intervals with new twelve-direction video priors generated from each interval’s own RGB and motion. The seed uses six Base24 directions plus six Turbo4 offsets; later intervals use two six-direction Turbo4 passes. Equal view counts do not imply identical generation settings.
For example, 957 frames at 30Hz last 31.9 seconds. Each training window contains 121 frames and starts 120 frames after the previous one. Neighboring models share one training frame, but playback shows it once. The last 117 real frames receive four internal padding frames for the generator; those repeats do not extend playback.
All intervals retain the same world origin, axes and units. At global time 4.50 seconds, the second model is queried at local time 0.50 seconds. The camera stays in place as models change. The browser prepares only the current model and the next model.
Better source-view agreement does not validate hidden surfaces. Inspect each boundary for changing clothing colors or body thickness, and look for residual smearing around fast hands and hair.
Comparison experiment: refine --trajectory-experiment transfers the first model’s appearance to SOMA skin trajectories before fitting observed RGB. It avoids new multiview generation in later intervals, but produced more smearing there. The recommended full-motion exercise uses extend above.
6. Where do face/hand detail and geometry guidance enter?
Face/hand refinement crops pixels at the original video resolution. It does not enlarge an already reduced image. Cropping changes the image origin, so camera principal point (cx, cy) must move by the same offset. Training a crop without that adjustment mismatches image pixels and 3D rays.
MoGe-3 predicts Z-depth [H,W] and normals [H,W,3] from RGB. Z-depth measures along the camera's forward axis, rather than along an off-axis pixel ray. A normal is a unit vector describing surface orientation. Camera coordinates here are X right, Y down and Z forward.
RGB → MoGe-3 → inferred depth + normals
↓ scale/camera alignment; reject edges and contradictions
4D model → rendered depth + finite-difference normals → weak agreement loss
↓
backpropagate with observed-RGB losses → update Gaussian parameters
Generated-camera constraints receive less weight than the observed RGB camera. Adding a prior does not turn the hidden back into an observation. Normals derived from rendered depth also differ from a smooth mesh's surface normals and can remain noisy.
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.
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. Start with observation and camera controls
Read each media item's source note and view the reference through the YouTube player. The public sample is a synthetic human driven by SOMA motion, not a real person reconstructed from monocular footage. It is a separate asset from the reference video, not its reconstruction before/after pair.
Start with camera/time controls on the public synthetic sample. Source comparisons below apply to local mode with your video and the model made from that same video.
Use the 3D controls in this order:
- Pause and choose a time.
- Compare the front pose with the source. Where available, show source and 3D at equal size.
- Hold time and drag to side/rear views. Those surfaces may be generated estimates.
- Hold the camera and play. Look for sudden changes in hair, clothing and hands.
- Inspect the beginning, middle, end and processing-interval boundaries.
Open a local result folder reads your package in this browser. It does not upload files to a server or run new GPU reconstruction. Select the top-level folder containing manifest.json. Include source.mp4 in that package to compare the original.
my-result/
manifest.json
source.mp4
browser/
s00/meta.json + Gaussian data
s01/meta.json + Gaussian data
A path pointing outside the selected folder does not give the browser access to that video. Package source footage you can use inside the result folder.
The public control uses 18,056 vertex Gaussians, 110 skinning bones and up to eight weights per particle. SOMA deformation matrices computed with NVIDIA Warp move their centers. Its reference RGB is a fixed-camera triangle-mesh render of the same synthetic human.
The official SOMA motion contains 931 frames at 24Hz, giving about 38.79 seconds of video. Horizontal root translation is removed for in-place playback; height and rotation are retained. Gaussian sizes remain isotropic and fixed, so this is not a complete representation of a deforming mesh surface. This control is not RGB-learned appearance or a model of the YouTube performer. Control construction and sources.
2. Prepare one NVIDIA GPU machine
Training requires Linux x86_64, a compatible NVIDIA driver/CUDA toolchain, Git, Python and uv. The tested GPU is one RTX 5090 32GB. Follow Linux GPU onboarding, then run these lines separately from the repository root.
nvidia-smi
export HUMAN_4D_ROOT="$HOME/physical-ai-labs/human-4d"
python3 labs/human-4d-gaussian/pipeline.py --root "$HUMAN_4D_ROOT" setup
nvidia-smi should report the GPU and driver. The first setup writes a runtime.json template and exits with a prerequisite error asking for actual runtime configuration. It does not mean dependencies have been installed.
Follow runtime setup and its official installation links to prepare separate Python environments, sources and weights, then enter their paths in runtime.json. Do not install into Isaac Sim's Python. Rerun the same setup command and pass its real module, pinned-source and asset-path checks before continuing. Initial model loading and CUDA compilation can still take additional time. Check source, weight and input-data terms in SOURCES.md.
3. Prepare a local video you can use
The tested preset uses static-camera 9:16 portrait video with even dimensions and at least 121 frames at 30Hz (about 4.03 seconds). Start with one person visible from head to feet, limited occlusion and few scene cuts. Replace the example with your own file path. The lab does not automatically download YouTube videos.
python3 labs/human-4d-gaussian/pipeline.py --root "$HUMAN_4D_ROOT" \
prepare --video "$HOME/Videos/my-motion.mp4"
prepare reads resolution, frame count and timing, then prepares RGB for estimation. Check the beginning, middle and end of its input preview for a cropped-out person. The original file is retained separately. Motion, working RGB and ROIs share frame indices/times from the normalized 30Hz input; raw variable-FPS frame indices are not claimed to match one-to-one.
4. Estimate motion and inspect view conditions
python3 labs/human-4d-gaussian/pipeline.py --root "$HUMAN_4D_ROOT" rig
Set RECON_PY below to the python.reconstruction path in runtime.json. The inspection tools use NumPy, Pillow and OpenCV from that environment too.
First inspect the estimated GEM-X/SOMA joints overlaid on the original video. If wrists or ankles follow the wrong body part, check the input and estimate before continuing. Inspect foreground masks too. The following command measures mask coverage over the estimated head surface and creates RGB/mask contact sheets for frames needing review. It never edits the masks.
RECON_PY="$HUMAN_4D_ROOT/envs/reconstruction/bin/python"
"$RECON_PY" labs/human-4d-gaussian/inspect_masks.py --root "$HUMAN_4D_ROOT"
python3 labs/human-4d-gaussian/pipeline.py --root "$HUMAN_4D_ROOT" multiview
multiview projects reference-interval motion into virtual cameras and generates views. Full-video extension generates fresh views from each interval's own RGB and SOMA motion. Create the start/middle/end contact sheets below. Check whether front, side and rear views actually face the intended directions, and compare hand positions and clothing. The tool assembles images; it does not automatically classify front/back consistency.
"$RECON_PY" labs/human-4d-gaussian/inspect_teachers.py --root "$HUMAN_4D_ROOT" \
--name pilot --out "$HUMAN_4D_ROOT/diagnostics/pilot-views.jpg"
"$RECON_PY" labs/human-4d-gaussian/inspect_teachers.py --root "$HUMAN_4D_ROOT" \
--name offset --out "$HUMAN_4D_ROOT/diagnostics/offset-views.jpg"
If RGB contains a visible face but its mask is 0, the training target asks the model to reproduce background there. If a generated image labeled yaw=180° shows a frontal face, its camera and image contradict each other. Fix these inputs before spending more optimization steps. See the code README for inspection and isolated experiments.
5. Train the model and refine original details
python3 labs/human-4d-gaussian/pipeline.py --root "$HUMAN_4D_ROOT" train
python3 labs/human-4d-gaussian/pipeline.py --root "$HUMAN_4D_ROOT" refine --seed-only
Start with 121 frames (about 4.03 seconds). --seed-only keeps the first exercise within that short interval so you can inspect it before trying the experimental full-motion extension. train fits observed RGB and generated views together. refine adds original face/hand pixels and MoGe-3 guidance, preserving previous checkpoints. A falling training loss alone does not establish more accurate novel views. Continue with the checks below.
6. Render, package and inspect
python3 labs/human-4d-gaussian/pipeline.py --root "$HUMAN_4D_ROOT" render
python3 labs/human-4d-gaussian/pipeline.py --root "$HUMAN_4D_ROOT" package
python3 labs/human-4d-gaussian/pipeline.py --root "$HUMAN_4D_ROOT" --deep check
render makes matched-time native and orbit recordings. package writes the browser model and playback metadata. After check validates arrays, files and time coverage, use Open a local result folder in this page's viewer and select $HUMAN_4D_ROOT/package. Playing an existing package does not require a CUDA GPU.
Optionally serve the package data locally with the command below. Its URL exposes data for inspection, not a replacement for the complete Pages 3D application.
python3 labs/human-4d-gaussian/pipeline.py --root "$HUMAN_4D_ROOT" serve
Keep output folders outside tracked source. Publishing a model requires considering the source footage, people/capture material, model weights and included assets together. Linking to a source video and redistributing its footage or derived model are separate uses.
7. Advanced: extend the full motion with new views
After inspecting the short result, run this in the same output root. Every later interval performs generation and fitting, so a longer clip can take hours on one GPU. Completed stages are reused only after matching their input, recipe and output hashes. Rerun the same command after an interruption; use a new output root when changing an experiment’s conditions.
python3 labs/human-4d-gaussian/pipeline.py --root "$HUMAN_4D_ROOT" extend
python3 labs/human-4d-gaussian/pipeline.py --root "$HUMAN_4D_ROOT" render
python3 labs/human-4d-gaussian/pipeline.py --root "$HUMAN_4D_ROOT" \
--package-dir "$HUMAN_4D_ROOT/package-full" package
python3 labs/human-4d-gaussian/pipeline.py --root "$HUMAN_4D_ROOT" \
--package-dir "$HUMAN_4D_ROOT/package-full" --deep check
The full timeline is written only after every interval passes its checks. Your short render and package remain intact; new renders use a separate folder identified by the selected model inventory. Open package-full in the viewer and inspect the beginning, middle, end and every interval boundary.
Check the result
1. Inspect the complete interval
| Check | How to inspect | Completion criterion |
|---|---|---|
| Time correspondence | Pause source and 3D at the same time | Beginning/middle/end poses correspond and coverage is recorded |
| Free viewpoint | Compare front, both sides and rear at fixed time | The same model renders from a real 3D camera; generated regions are labeled |
| Motion continuity | Play with a fixed camera | Interval transitions and fast-hand artifacts can be inspected |
| Valid data | Inspect checks and model arrays | No empty intervals, missing files, NaNs or infinities |
| Comparison recording | Show source and manipulation side by side | Both motions are readable without relying on a small inset |
Sharp source footage still does not reveal occluded hands, hair or the back of clothing. Plausible hidden appearance is different from verified hidden appearance. Moving Gaussians are not automatically a collision-ready human mesh or robot-control data.
2. What the short comparison established
These results concern a 4.03-second experimental interval, not full-video performance. Conditions branch from the same initial model. No single metric establishes improved appearance from every direction.
| Comparison | Observed result | Interpretation |
|---|---|---|
| Original face/hand refinement vs matched 3,000-step control | VGG19 appearance error fell 5.5%; mean central-ROI PSNR was 0.26dB lower | Appearance and pixel-reconstruction metrics changed differently |
| Joint 12-view generation | Generation and 3D fitting completed; some foot/side overlap remains | More directions did not establish an overall quality improvement |
| Finer face/hand particles | Face metrics became worse | Preserved as a separate experiment, not selected as default |
| MoGe-3 vs matched 1,500-step continuation | Error against inferred depth fell about 10.5%; RGB differences were small | Better prior agreement, not measured 3D accuracy |
Face/hand metrics average 25 times × three regions, or 75 ROIs. Some frames were excluded from direct high-resolution ROI optimization but remained in low-resolution conditioning/training. They are not independent unseen-view test data. The geometry comparison likewise measures agreement with the depth/normals used for guidance.
Aggregate evaluation values retain the numerical comparisons without distributing source frames or the person model.
3. Official references and related labs
- GEM-X: body/hand pose and temporal motion estimation.
- SOMA-X: human geometry and deformation representation.
- 4DAnyone: multiview video generation and 4DGS reconstruction.
- MoGe-3: RGB-inferred depth and normals.
- RGB scene reconstruction: compare a moving person with scene reconstruction.
- fVDB Reality Capture lab: separate training and evaluation cameras in a calibrated scene.
Reference footage: 지숭이_Jisoong channel · original YouTube Shorts. See sources and licensing for the separate usage scope of reference footage, models and public samples.
Example run and recording
Full SOMA control: fixed RGB and Gaussian orbit
All 931 frames of NVIDIA’s official example motion, rendered as a known mesh and as 18,056 skinned Gaussians. This separate synthetic control tests time, cameras and skinning, rather than video-reconstruction accuracy.
Source code
Browse all stage adapters, training code and validation tools
pipeline.py
View files on GitHub#!/usr/bin/env python3
"""Reproducible local human-Gaussian stages; never download source videos.
GPU stages require explicitly configured external runtimes. A missing runtime
is an error, not a simulated successful run. Output and model caches are private
by default. See README.md and SOURCES.md before configuring assets.
"""
from __future__ import annotations
import argparse,contextlib,fcntl,gzip,hashlib,http.server,json,math,os,shutil,struct,subprocess,sys,time
from pathlib import Path
HERE=Path(__file__).resolve().parent
PINS={'gem':'4aef1452e5df171deff4f293c08e643eb450981e','four_d_anyone':'1b5c707cfe7c7fda19d08f37a10e1c444c3299ef','moge':'74fbce054ebed49800de42d0ad0e83495065719a','soma':'01ab5b5c0876058bd27d34b1607d74b2e55e0cf4'}
REPOS={'gem':'https://github.com/NVlabs/GEM-X.git','four_d_anyone':'https://github.com/ant-research/4DAnyone.git','moge':'https://github.com/microsoft/MoGe.git','soma':'https://github.com/NVlabs/SOMA-X.git'}
STAGES=('setup','prepare','rig','multiview','train','refine','extend','render','package','check','serve')
FRESH_STAGES={'views-base','seed20k','clean-seed','views-offset','hires','original-roi','roi','moge-infer','moge-align','geometry','clean-final'}
class PrerequisiteError(RuntimeError):pass
def write(path,value):
path=Path(path);path.parent.mkdir(parents=True,exist_ok=True);temp=path.with_suffix(path.suffix+'.tmp');temp.write_text(json.dumps(value,indent=2,allow_nan=False)+'\n');temp.replace(path)
def sha(path):
h=hashlib.sha256()
with Path(path).open('rb') as f:
for block in iter(lambda:f.read(8<<20),b''):h.update(block)
return h.hexdigest()
def safe(base,relative):
if not isinstance(relative,str) or '://' in relative:raise ValueError('Package file paths must be relative')
target=(base/relative).resolve()
if not target.is_relative_to(base.resolve()):raise ValueError('Package path escapes its root')
return target
def template(root):
return {'schema':1,'ffmpeg':shutil.which('ffmpeg') or 'ffmpeg','cuda_home':'/usr/local/cuda-12.9','cuda_arch':'12.0','gpu_lock':str(root/'.gpu.lock'),'python':{name:str(root/f'envs/{name}/bin/python') for name in ['gem','reconstruction','moge','control_export','control_render']},'sources':{name:str(root/'deps'/name) for name in PINS},'sam2_source':str(root/'deps/sam2'),'assets':{'soma':str(root/'assets/soma'),'sam2_checkpoint':str(root/'models/sam2.1_hiera_large.pt'),'gem_config':str(root/'gem-motion.yaml')},'models':str(root/'models'),'interval_steps':6000,'seed_train_steps':20000,'hires_steps':6000,'roi_steps':3000,'geometry_steps':1500}
class Runner:
def __init__(self,args):
self.args=args;self.root=args.root.expanduser().resolve();self.root.mkdir(parents=True,exist_ok=True);self.config_path=(args.config or self.root/'runtime.json').expanduser().resolve();self.config=json.loads(self.config_path.read_text()) if self.config_path.exists() else template(self.root);self.work=self.root/'multiview-prior';self.ref=self.work/'refinement';self.package=args.package_dir.expanduser().resolve() if args.package_dir else self.root/'package'
public=HERE.parents[1]/'site/public'
if self.root.is_relative_to(public):raise PrerequisiteError('Runtime/output root must stay outside site/public; reconstruction inputs and models are private by default.')
if args.mode=='reconstruction' and args.stage=='package' and self.package.is_relative_to(public):raise PrerequisiteError('Monocular package creates private local outputs; choose a destination outside site/public.')
def path(self,group,key=None):
value=self.config[group][key] if key else self.config[group];p=Path(value).expanduser();return p if p.is_absolute() else self.root/p
def python(self,name):
p=self.path('python',name)
if not p.is_file():raise PrerequisiteError(f'Missing {name} Python: configure python.{name} in {self.config_path}. See {HERE/"README.md"} for isolated installation commands.')
return str(p)
def ffmpeg(self):
value=self.config.get('ffmpeg','ffmpeg');found=shutil.which(value)
if not found and Path(value).is_file():found=value
if not found:raise PrerequisiteError('FFmpeg was not found. Install FFmpeg and set runtime.json ffmpeg to its executable.')
return str(Path(found).resolve())
def env(self):
env=os.environ.copy();cuda=self.config.get('cuda_home')
if cuda:env['CUDA_HOME']=cuda;env['PATH']=str(Path(cuda)/'bin')+os.pathsep+env.get('PATH','')
env['TORCH_CUDA_ARCH_LIST']=self.config.get('cuda_arch','12.0');env['MAX_JOBS']='2';env['PYTHONPATH']=os.pathsep.join([*(str(Path(x).expanduser()) for x in self.config.get('extra_python_paths',[])),*(str(self.path('sources',key)) for key in PINS),str(self.path('sam2_source')),env.get('PYTHONPATH','')]);return env
def run(self,argv,**kwargs):
command=[str(x) for x in argv];print(json.dumps({'command':command}),flush=True);subprocess.run(command,check=True,env=self.env(),**kwargs)
def script(self,python,name,*args):self.run([self.python(python),HERE/name,*args])
def render_dir(self):
# A full-length extension must not replace a previously rendered short lab.
models=self.root/'models.json'
return self.root/'renders'/hashlib.sha256(models.read_bytes()+(HERE/'render_sequence.py').read_bytes()).hexdigest()[:16] if models.is_file() else self.root/'renders'
def verify_models(self):
self.need(self.root/'models.json');models=json.loads((self.root/'models.json').read_text())
for item in models['segments']:
path=safe(self.root,item['model']);self.need(path)
if item.get('sha256') and sha(path)!=item['sha256']:raise PrerequisiteError('A selected checkpoint changed. Preserve the run and inspect its model inventory.')
return models
def journal_path(self):
key=f'{self.args.mode}-{self.args.stage}'
if self.args.mode=='reconstruction' and self.args.stage in ['render','package'] and (self.root/'models.json').is_file():key+='-'+sha(self.root/'models.json')[:16]
if self.args.mode=='reconstruction' and self.args.stage in ['render','package']:key+='-'+sha(HERE/'render_sequence.py')[:10]
if self.args.stage=='package':key+='-'+hashlib.sha256(str(self.package).encode()).hexdigest()[:12]
return self.root/'stages'/(key+'.json')
def need(self,*files):
missing=[str(p) for p in files if not Path(p).exists()]
if missing:raise PrerequisiteError('Missing prerequisite outputs/assets:\n'+'\n'.join(missing)+'\nRun the preceding stage or configure the required official asset; see SOURCES.md.')
def link(self,destination,source):
destination=Path(destination);source=Path(source).resolve();self.need(source);destination.parent.mkdir(parents=True,exist_ok=True)
if destination.exists() or destination.is_symlink():
if destination.resolve()!=source:raise PrerequisiteError(f'Refusing to replace existing {destination}; use a fresh output folder or correct configuration.')
else:destination.symlink_to(source,target_is_directory=source.is_dir())
def workspace(self):
self.work.mkdir(exist_ok=True);self.ref.mkdir(exist_ok=True)
self.link(self.work/'4danyone',self.path('sources','four_d_anyone'));self.link(self.work/'models',self.path('models'));self.link(self.root/'soma-assets',self.path('assets','soma'));self.link(self.root/'checkpoints/sam2.1_hiera_large.pt',self.path('assets','sam2_checkpoint'));self.link(self.root/'bin/ffmpeg',Path(self.ffmpeg()));self.link(self.ref/'moge-source',self.path('sources','moge'));self.link(self.ref/'moge-model',self.path('models')/'moge-3')
def setup(self):
if not self.config_path.exists():
write(self.config_path,self.config)
raise PrerequisiteError(f'Wrote {self.config_path}; no runtimes have been installed. Edit its Python/source/asset paths, follow README.md, then rerun setup. --fetch-sources can fetch pinned source inside this output root.')
if self.args.fetch_sources:
for name,url in REPOS.items():
dest=self.path('sources',name)
if not dest.resolve().is_relative_to(self.root):raise PrerequisiteError('--fetch-sources writes only within the selected output root')
dest.parent.mkdir(parents=True,exist_ok=True)
if not dest.exists():self.run(['git','clone',url,dest])
revision=subprocess.check_output(['git','-C',str(dest),'rev-parse','HEAD'],text=True).strip()
if revision!=PINS[name]:self.run(['git','-C',dest,'checkout',PINS[name]])
self.ffmpeg();names=['control_export','control_render'] if self.args.mode=='control' else ['gem','reconstruction','moge']
for name in names:self.python(name)
required=['soma'] if self.args.mode=='control' else list(PINS)
for name in required:
source=self.path('sources',name);self.need(source)
revision=subprocess.check_output(['git','-C',str(source),'rev-parse','HEAD'],text=True).strip()
if revision!=PINS[name]:raise PrerequisiteError(f'{name} source revision {revision} differs from tested pin {PINS[name]}; check out the pinned revision before running.')
self.need(self.path('assets','soma'))
if self.args.mode!='control':
self.need(self.path('assets','gem_config'),self.path('assets','sam2_checkpoint'),self.path('models')/'4danyone/model.safetensors',self.path('models')/'4danyone/Wan2.2_VAE.pth',self.path('models')/'4danyone/prompt_context.safetensors',self.path('models')/'4danyone/Wan22_TI2V_5B_Turbo_lora_rank_64_fp16.safetensors',self.path('models')/'moge-3/model.pt',self.path('models')/'birefnet')
self.workspace()
modules={'gem':['torch','gem','soma','sam2'],'reconstruction':['torch','numpy','PIL','fdanyone','gsplat'],'moge':['torch','moge.model.v3'],'control_export':['torch','soma'],'control_render':['torch','gsplat','nvdiffrast.torch']}
for name in names:self.run([self.python(name),'-c','import importlib; '+ '; '.join(f'importlib.import_module({x!r})' for x in modules[name])])
write(self.root/'setup.json',{'configured':True,'mode':self.args.mode,'source_pins':{k:PINS[k] for k in required},'note':'Imports/paths checked without GPU inference; model loading and CUDA compilation occur in their real stages.'})
def prepare(self):
if self.args.mode=='control':
motion=self.path('sources','soma')/'assets/example_animation.usd';self.need(motion,self.path('assets','soma'));digest=sha(motion)
if digest!='c09372492aaacdca3ca7ec5d737263d8e6042b66fdd29318d91848427fa40695':raise PrerequisiteError('Official SOMA motion hash differs; resolve the pinned Git LFS asset, not an LFS pointer or private animation.')
write(self.root/'control-input.json',{'official_motion_sha256':digest,'synthetic_control':True});return
if not self.args.video:raise PrerequisiteError('prepare requires --video /path/to/a/local-video-you-can-use.mp4; source video downloaders are not included.')
source=self.args.video.expanduser().resolve();self.need(source);digest=sha(source)
if (self.root/'input.json').exists():
old=json.loads((self.root/'input.json').read_text())
if old['original_sha256']!=digest:raise PrerequisiteError('This output root belongs to another input. Use a fresh root to preserve existing results.')
self.need(self.root/'input.mp4',self.root/'source.mp4')
if len(list((self.root/'frames').glob('*.jpg')))!=old['frames']:raise PrerequisiteError('Prepared RGB cache is incomplete; preserve this run and prepare a fresh output root.')
print(json.dumps({'prepare':'reusing verified prepared-frame inventory','frames':old['frames']}));return
ff=self.ffmpeg();png=subprocess.check_output([ff,'-v','error','-i',str(source),'-frames:v','1','-f','image2pipe','-vcodec','png','pipe:1']);width,height=struct.unpack('>II',png[16:24])
if abs(width/height-9/16)>.003 or min(width,height)<256 or width%2 or height%2:raise PrerequisiteError('This tested preset supports portrait 9:16 video, even dimensions >=256px on each axis. Other framing needs a camera/crop adapter; it is not silently stretched.')
original=self.root/'original.mp4';shutil.copy2(source,original)
self.run([ff,'-v','error','-n','-i',original,'-vf','fps=30','-an','-c:v','libx264','-crf','10','-pix_fmt','yuv420p',self.root/'input.mp4'])
self.run([ff,'-v','error','-n','-i',self.root/'input.mp4','-vf','scale=540:960','-an','-c:v','libx264','-crf','16','-pix_fmt','yuv420p','-movflags','+faststart',self.root/'source.mp4'])
frames=self.root/'frames';frames.mkdir();self.run([ff,'-v','error','-i',self.root/'input.mp4','-vf','scale=540:960','-q:v','2',frames/'%06d.jpg']);count=len(list(frames.glob('*.jpg')))
if count<121:raise PrerequisiteError('At least 121 normalized frames (4.03s at 30Hz) are required by this preset.')
write(self.root/'input.json',{'schema':1,'width':width,'height':height,'frames':count,'fps':30,'duration':count/30,'original_sha256':digest,'normalized_sha256':sha(self.root/'input.mp4'),'rgb_scope':'Original-resolution normalized-time video; 540x960 working RGB. Original file preserved separately.','source_is_local':True,'timing':'Shared normalized 30Hz input.mp4 drives RGB, GEM and ROI. Original file is separately preserved; no raw variable-FPS frame-index correspondence is claimed.'})
write(self.root/'frame_times.json',{'fps':30,'frames':[{'frame':i,'time':i/30} for i in range(count)],'input':'input.mp4'})
def rig(self):
if self.args.mode=='control':
self.script('control_export','control_sample.py','--stage','export','--soma-source',self.path('sources','soma'),'--assets-dir',self.path('assets','soma'),'--out',self.root/'control');return
self.workspace();self.need(self.root/'input.json');motion=self.root/'motion.pt'
if not motion.exists():self.run([self.python('gem'),'-m','gem.inference','motion-video','--task','body','--input',self.root/'input.mp4','--config',self.path('assets','gem_config'),'--device','cuda','--camera-mode','static','--postprocess','--soma-assets',self.path('assets','soma'),'--output',motion],cwd=self.path('sources','gem'))
self.script('gem','rig_export.py','--root',self.root);self.script('gem','segment.py','--root',self.root)
def multiview(self):
self.real_stage();self.workspace();self.need(self.root/'rig/geometry.npz',self.root/'masks/000121.png')
self.script('reconstruction','multiview.py','--root',self.root,'--name','pilot','--views','6')
self.script('reconstruction','multiview.py','--root',self.root,'--name','offset','--views','6','--start-yaw','30','--turbo')
def train(self):
self.real_stage();self.workspace();self.need(self.work/'pilot/generation.json')
steps=self.config['seed_train_steps'];self.script('reconstruction','seed_train.py','--root',self.root,'--name','pilot','--steps',steps,'--stop-after',steps)
self.script('reconstruction','clean_model.py','--root',self.root,'--model',self.work/'pilot/reconstruction/checkpoints/latest.npz','--out',self.work/'seed-clean.npz')
def real_stage(self):
if self.args.mode=='control':raise PrerequisiteError('The known-geometry control does not perform video reconstruction or diffusion. Run rig → render → package → check; train/refine/extend/multiview are intentionally not claimed for this mode.')
def geometry(self,data,model,suffix,cameras='0'):
raw=self.ref/f'moge-raw-{suffix}';aligned=self.ref/f'moge-aligned-{suffix}'
self.script('moge','moge_infer.py','--root',self.root,'--data',data,'--out',raw,'--cameras',cameras)
self.script('reconstruction','align_geometry.py','--root',self.root,'--model',model,'--raw',raw,'--out',aligned);return aligned
def refine(self):
self.real_stage();self.workspace();self.need(self.work/'seed-clean.npz',self.work/'offset/generation.json')
self.run([self.python('reconstruction'),'-c',f'import sys; sys.path.insert(0,{str(self.work/"4danyone")!r}); from fdanyone.download import ensure_perceptual_vgg19; print(ensure_perceptual_vgg19({str(self.work/"models")!r}))'])
self.script('reconstruction','hires.py','--root',self.root,'--steps',self.config['hires_steps'],'--stop-after',self.config['hires_steps'])
self.script('reconstruction','clean_model.py','--root',self.root,'--model',self.work/'twelve-view-hires/checkpoints/latest.npz','--out',self.work/'final-4d.npz')
roi=self.ref/'roi';self.script('reconstruction','prepare_data.py','--root',self.root,'--kind','roi','--out',roi)
roi_model=self.ref/'roi-original'/f'model-{self.config["roi_steps"]}.npz'
self.script('reconstruction','train_refine.py','--root',self.root,'--name','roi-original','--roi','--steps',self.config['roi_steps'])
data=self.work/'twelve-view-hires/data';prior=self.geometry(data,roi_model,'seed','0,2,3,4');out=self.ref/'moge3';steps=self.config['geometry_steps']
self.script('reconstruction','train_refine.py','--root',self.root,'--name','moge3','--base',roi_model,'--roi','--steps',steps,'--geometry',prior)
selected=out/f'model-{steps}.npz';meta=json.loads((self.root/'input.json').read_text());segments=[{'id':'s00','start_frame':0,'valid_frames':min(120,meta['frames']),'model':str(selected.relative_to(self.root))}]
if self.args.trajectory_experiment and not self.args.seed_only and meta['frames']>121:
for i,start in enumerate(range(120,meta['frames'],120),1):
name=f's{i:02d}';target=self.ref/'intervals'/name;target.mkdir(parents=True,exist_ok=True);init=target/'warm.npz';self.script('reconstruction','warmstart.py','--geometry',self.root/'rig/geometry.npz','--model',selected,'--origin',self.work/'pilot/soma-conditioning.npz','--start',start,'--out',init,'--mode','trajectory')
data=target/'data';self.script('reconstruction','prepare_data.py','--root',self.root,'--kind','observed','--start',start,'--out',data)
crops=target/'roi';self.script('reconstruction','prepare_data.py','--root',self.root,'--kind','roi','--start',start,'--out',crops)
prior=self.geometry(data,init,name);steps=self.config['interval_steps']
self.script('reconstruction','fit_interval.py','--root',self.root,'--out',target,'--start',start,'--steps',steps,'--geometry',prior)
segments.append({'id':name,'start_frame':start,'valid_frames':min(120,meta['frames']-start),'model':str((target/f'model-{steps}.npz').relative_to(self.root))})
else:segments[0]['valid_frames']=121
for item in segments:item['sha256']=sha(safe(self.root,item['model']))
write(self.root/'models.json',{'schema':1,'fps':30,'input_frames':meta['frames'],'covered_frames':sum(s['valid_frames'] for s in segments),'segments':segments,'method':('Seed Base24 plus six Turbo offset views, original-resolution ROI and MoGe-3' if len(segments)==1 else 'Experimental canonical SOMA appearance transfer and observed-only interval fitting'),'full_method':('seed-only' if len(segments)==1 else 'appearance-trajectory-experiment'),'source':{'credit':self.config.get('source_credit','Source: local user-supplied RGB'),'attribution_url':self.config.get('source_reference_url')},'new_full_interval_multiview_diffusion':False,'input_source_is_private':True})
def extend(self):
self.real_stage();self.workspace();self.need(self.root/'models.json',self.root/'input.json',HERE/'fresh_interval.py')
seed=self.verify_models();count=json.loads((self.root/'input.json').read_text())['frames']
if seed.get('full_method')=='fresh-twelve-direction-intervals':
# Recover a process interrupted after the atomic inventory update but before
# the outer stage journal was marked complete. Never train these models again.
self.verify_stage('extend');path=self.root/'extension-progress.json';progress=json.loads(path.read_text()) if path.exists() else {'schema':1};progress.update(complete=True,input_frames=count,fps=30,segments=seed['segments']);write(path,progress);print('FULL_EXTENSION_REUSED',count);return
if count<=121:raise PrerequisiteError('This source is already covered by the short interval. No full-length extension is needed.')
if len(seed['segments'])!=1 or seed['covered_frames']!=121:raise PrerequisiteError('extend consumes a completed refine --seed-only result. Preserve any existing full-motion experiment and use a separate output root for another recipe.')
first={**seed['segments'][0],'valid_frames':120};first['sha256']=sha(safe(self.root,first['model']));segments=[first]
progress={'schema':1,'method':'fresh-twelve-direction-intervals','input_frames':count,'fps':30,'complete':False,'segments':segments}
# Keep models.json at the verified short result until every interval exists.
write(self.root/'extension-progress.json',progress)
for i,start in enumerate(range(120,count,120),1):
name=f's{i:02d}'
self.script('reconstruction','fresh_interval.py','--root',self.root,'--config',self.config_path,'--name',name,'--start',start,'--steps',self.config.get('full_base_steps',self.config['seed_train_steps']),'--hires-steps',self.config['hires_steps'],'--roi-steps',self.config['roi_steps'],'--geometry-steps',self.config['geometry_steps'])
report_file=self.work/name/'selected.json';self.need(report_file);report=json.loads(report_file.read_text());model=safe(self.root,report['final_model']);self.need(model)
expected=min(120,count-start)
flags=report.get('actual_done_flags',{})
if report['start_frame']!=start or report['valid_frames']!=expected or not FRESH_STAGES.issubset(flags) or not all(flags[k] is True for k in FRESH_STAGES):raise PrerequisiteError('The interval report does not establish complete matching time coverage.')
digest=sha(model)
if digest!=report['final_sha256']:raise PrerequisiteError('A selected interval checkpoint changed after verification.')
segments.append({'id':name,'start_frame':start,'valid_frames':expected,'model':str(model.relative_to(self.root)),'sha256':digest,'report':str(report_file.relative_to(self.root))})
progress['segments']=segments;write(self.root/'extension-progress.json',progress)
covered=sum(x['valid_frames'] for x in segments)
if covered!=count:raise PrerequisiteError('Full-motion coverage differs from the normalized source.')
result={'schema':1,'fps':30,'input_frames':count,'covered_frames':covered,'segments':segments,'method':'Seed Base24 plus Turbo offset; later intervals use two fresh six-view Turbo passes, original ROI and MoGe-3 guidance','full_method':'fresh-twelve-direction-intervals','source':seed.get('source',{'credit':'Source: local user-supplied RGB'}),'new_full_interval_multiview_diffusion':True,'input_source_is_private':True}
write(self.root/'models.json',result);progress['complete']=True;write(self.root/'extension-progress.json',progress)
def render(self):
if self.args.mode=='control':self.script('control_render','control_sample.py','--stage','render','--out',self.root/'control','--ffmpeg',self.ffmpeg());return
self.verify_models();self.script('reconstruction','render_sequence.py','--root',self.root,'--out',self.render_dir(),'--ffmpeg',self.ffmpeg())
def package_stage(self):
if self.package.exists() and any(self.package.iterdir()):raise PrerequisiteError('Package destination is not empty; use --package-dir with a fresh folder to preserve previous exports.')
self.package.mkdir(parents=True,exist_ok=True)
if self.args.mode=='control':
src=self.root/'control';self.need(src/'manifest.json',src/'source.mp4',src/'data/meta.json')
control=json.loads((src/'data/meta.json').read_text())
if control.get('representation')!='soma-skinned-gaussians' or control.get('source_motion_sha256')!='c09372492aaacdca3ca7ec5d737263d8e6042b66fdd29318d91848427fa40695':raise PrerequisiteError('Control publication requires the verified official SOMA synthetic export; private monocular packages cannot be relabeled.')
for name in ['manifest.json','source.mp4','comparison.mp4','poster.jpg','data']:self.copy(src/name,self.package/name)
self.copy(self.path('sources','soma')/'LICENSE',self.package/'SOMA-LICENSE.txt');(self.package/'NOTICE.txt').write_text('Synthetic control based on NVIDIA SOMA-X official example motion and native neutral geometry, Apache-2.0. Wrapper code: repository MIT. No private footage.\n');return
models=self.verify_models();segments=[]
for item in models['segments']:
dest=self.package/'browser'/item['id'];self.script('reconstruction','export_model.py','--model',safe(self.root,item['model']),'--out',dest);segments.append({'id':item['id'],'start':item['start_frame']/30,'duration':item['valid_frames']/30,'root':f'browser/{item["id"]}/'})
duration=models['covered_frames']/30;self.run([self.ffmpeg(),'-v','error','-n','-i',self.root/'input.mp4','-t',duration,'-an','-c:v','libx264','-crf','16','-pix_fmt','yuv420p','-movflags','+faststart',self.package/'source.mp4'])
for name in ['comparison.mp4','poster.jpg']:
if (self.render_dir()/name).exists():self.copy(self.render_dir()/name,self.package/name)
provenance='Observed source + RGB-estimated motion + generated appearance priors; unseen surfaces are inferred.'
provenance+=(' Later intervals use fresh multiview generation and native Gaussian fitting.' if models.get('new_full_interval_multiview_diffusion') else ' Short seed fitting or explicitly selected appearance-trajectory experiment; see models.json.')
camera={};render_record=self.render_dir()/'rendered.json'
if render_record.is_file():
framing=json.loads(render_record.read_text()).get('camera',{});input_meta=json.loads((self.root/'input.json').read_text())
if all(k in framing for k in ['target','radius','fov']):camera={'target':framing['target'],'distance':framing['radius'],'fov':framing['fov'],'framing_aspect':.75,'source_width':input_meta['width'],'source_height':input_meta['height']}
write(self.package/'manifest.json',{'schema':1,'title':'Local monocular human reconstruction','fps':30,'duration':duration,'representation':'native-conditional-4d','source':{'url':'source.mp4','title':'Local source RGB','credit':models.get('source',{}).get('credit','Source: local user-supplied RGB'),'attribution_url':models.get('source',{}).get('attribution_url'),'rights':'Input-footage reuse permissions are separate from tool/model licenses'},'segments':segments,'provenance':provenance,'camera':camera,'private_local_output':True,'comparison':'comparison.mp4' if (self.package/'comparison.mp4').exists() else None,'poster':'poster.jpg' if (self.package/'poster.jpg').exists() else None})
def verify_stage(self,stage):
if stage=='rig':
if self.args.mode=='control':self.need(self.root/'control/data/meta.json',self.root/'control/control-reference.npz')
else:
self.need(self.root/'rig/geometry.npz',self.root/'rig/rig.json');count=json.loads((self.root/'input.json').read_text())['frames']
if len(list((self.root/'masks').glob('*.png')))!=count:raise PrerequisiteError('Source-mask count no longer matches prepared RGB')
elif stage=='multiview':
for name in ['pilot','offset']:
self.need(self.work/name/'generation.json');g=json.loads((self.work/name/'generation.json').read_text());self.need(*(Path(x) for x in g['target_videos']))
elif stage=='train':self.need(self.work/'seed-clean.npz')
elif stage=='refine':
m=self.verify_models()
expected=json.loads((self.root/'input.json').read_text())['frames'] if self.args.trajectory_experiment and not self.args.seed_only else 121
if m['covered_frames']!=expected:raise PrerequisiteError('Saved refinement has different time coverage; use a new root for a changed recipe')
elif stage=='extend':
self.need(self.root/'models.json');m=json.loads((self.root/'models.json').read_text())
if m.get('full_method')!='fresh-twelve-direction-intervals' or m['covered_frames']!=json.loads((self.root/'input.json').read_text())['frames']:raise PrerequisiteError('The saved full-length extension is incomplete or uses a different recipe.')
cursor=0
for item in m['segments']:
if item['start_frame']!=cursor or not 0<item['valid_frames']<=120 or item['valid_frames']!=min(120,m['covered_frames']-cursor):raise PrerequisiteError('The full-motion timeline has a gap, overlap or invalid playback length.')
cursor+=item['valid_frames']
path=safe(self.root,item['model']);self.need(path)
if sha(path)!=item['sha256']:raise PrerequisiteError('A verified full-length checkpoint changed.')
if cursor!=m['covered_frames']:raise PrerequisiteError('The saved interval sum does not cover the full source.')
elif stage=='render':
if self.args.mode=='control':self.need(*(self.root/'control'/name for name in ['source.mp4','comparison.mp4','manifest.json']))
else:
models=self.verify_models();video=self.render_dir()/'comparison.mp4';record=self.render_dir()/'rendered.json';self.need(video,record);saved=json.loads(record.read_text())
if saved.get('models_sha256')!=sha(self.root/'models.json') or saved.get('renderer_sha256')!=sha(HERE/'render_sequence.py') or saved.get('frames')!=models['covered_frames'] or saved.get('comparison_mp4_sha256')!=sha(video) or saved.get('full_video_decode') is not True:raise PrerequisiteError('Saved render metadata or video differs from the verified model inventory. Preserve the files and inspect the rendering output.')
elif stage=='package':
if self.args.mode=='reconstruction':self.verify_models()
check_package(self.package)
@staticmethod
def copy(source,dest):
if source.is_dir():shutil.copytree(source,dest)
else:shutil.copy2(source,dest)
def check_package(package,deep=False,ffmpeg=None,report_path=None):
package=package.resolve();manifest=json.loads((package/'manifest.json').read_text());end=0.;reports=[]
if not manifest.get('segments'):raise ValueError('Package has no model intervals')
for item in manifest['segments']:
if abs(float(item['start'])-end)>1e-4:raise ValueError('Missing or overlapping timeline interval')
duration=float(item['duration'])
if not math.isfinite(duration) or duration<=0:raise ValueError('Invalid interval duration')
end+=duration;folder=safe(package,item['root']);meta=json.loads((folder/'meta.json').read_text());N=meta['gaussians'];files={}
if not isinstance(N,int) or N<=0 or meta['frames']<=0 or meta['fps']<=0:raise ValueError('Model dimensions/time base must be positive')
if duration>float(meta['duration'])+1e-4:raise ValueError('Played interval exceeds model time coverage')
for name,record in meta['files'].items():
path=safe(folder,name);raw=gzip.decompress(path.read_bytes());assert len(raw)==record['raw_bytes'];assert hashlib.sha256(raw).hexdigest()==record['raw_sha256'];files[name]=raw
if deep and name.endswith(('.f32.gz','.f16.gz')):
fmt='<e' if name.endswith('.f16.gz') else '<f'
if not all(math.isfinite(x[0]) for x in struct.iter_unpack(fmt,raw)):raise ValueError(f'Nonfinite values in {name}')
field=files['gaussians.f32.gz'];assert len(field)==N*14*4
if meta.get('representation')=='soma-skinned-gaussians':
bones=meta['bones'];influences=meta['influences'];assert len(files['bone-matrices.f32.gz'])==meta['frames']*bones*16*4;assert len(files['bone-weights.f32.gz'])==N*influences*4
error=0.
for sample in meta['parity_samples']:
idx,frame=sample['index'],sample['frame'];xyz=struct.unpack_from('<3f',field,idx*56);position=[0.,0.,0.]
for k in range(influences):
bi=struct.unpack_from('<H',files['bone-indices.u16.gz'],(idx*influences+k)*2)[0];assert bi<bones;weight=struct.unpack_from('<f',files['bone-weights.f32.gz'],(idx*influences+k)*4)[0];matrix=struct.unpack_from('<16f',files['bone-matrices.f32.gz'],(frame*bones+bi)*64)
for axis in range(3):position[axis]+=weight*(sum(matrix[axis*4+j]*xyz[j] for j in range(3))+matrix[axis*4+3])
error=max(error,max(abs(a-b) for a,b in zip(position,sample['position'])))
if error>1e-4:raise ValueError('SOMA native position parity failed')
else:
assert len(files['motion.f32.gz'])==N*16 and len(files['variance.f32.gz'])==N*16 and len(files['sh.f16.gz'])==N*48*2;error=0.
for sample in meta['parity_samples']:
idx=sample['index'];xyz=struct.unpack_from('<3f',field,idx*56);vel=struct.unpack_from('<4f',files['motion.f32.gz'],idx*16);dt=sample['time']-vel[3];position=[xyz[j]+vel[j]*dt for j in range(3)];error=max(error,max(abs(a-b) for a,b in zip(position,sample['position'])))
if 'opacity' in sample:
peak=struct.unpack_from('<f',field,idx*56+40)[0];invvar=struct.unpack_from('<f',files['variance.f32.gz'],idx*16)[0];error=max(error,abs(peak*math.exp(-.5*dt*dt*invvar)-sample['opacity']))
if error>1e-4:raise ValueError('Native conditional numeric parity failed')
reports.append({'id':item['id'],'gaussians':N,'frames':meta['frames'],'native_numeric_max_position_error':error,'hashes_verified':True})
if abs(end-float(manifest['duration']))>1e-4:raise ValueError('Timeline total differs from manifest')
source=safe(package,manifest['source']['url']);assert source.is_file() and source.stat().st_size>0
videos_decoded=[]
if ffmpeg:
for name in [manifest['source']['url'],manifest.get('comparison')]:
if name:subprocess.run([ffmpeg,'-v','error','-i',str(safe(package,name)),'-f','null','-'],check=True);videos_decoded.append(name)
result={'schema':1,'pass':True,'duration':end,'segments':reports,'deep_finite_check':deep,'videos_fully_decoded':videos_decoded,'scope':'File/time/numeric export validation, not real-person geometry accuracy'};
if report_path:write(report_path,result)
return result
def main():
p=argparse.ArgumentParser(description=__doc__);p.add_argument('--root',type=Path,required=True);p.add_argument('--config',type=Path);p.add_argument('--mode',choices=['reconstruction','control'],default='reconstruction');p.add_argument('--package-dir',type=Path);p.add_argument('--video',type=Path);p.add_argument('--seed-only',action='store_true');p.add_argument('--trajectory-experiment',action='store_true');p.add_argument('--fetch-sources',action='store_true');p.add_argument('--deep',action='store_true');p.add_argument('--port',type=int,default=8099);p.add_argument('stage',choices=STAGES);a=p.parse_args()
if a.seed_only and a.trajectory_experiment:p.error('--seed-only and --trajectory-experiment select different refinement scopes')
try:r=Runner(a)
except (PrerequisiteError,ValueError,OSError) as exc:print(f'ERROR: {exc}',file=sys.stderr);raise SystemExit(2)
try:
if a.stage=='check':print(json.dumps(check_package(r.package,a.deep,shutil.which(r.config.get('ffmpeg','ffmpeg')),r.root/'checks.json'),indent=2));return
if a.stage=='serve':
r.need(r.package/'manifest.json');print(f'Package: http://127.0.0.1:{a.port}/manifest.json\nOpen the Pages human-4d-gaussian lab and select this local result folder. This local server serves data only, not GPU inference.',flush=True)
handler=lambda *args,**kwargs:http.server.SimpleHTTPRequestHandler(*args,directory=str(r.package),**kwargs);http.server.ThreadingHTTPServer(('127.0.0.1',a.port),handler).serve_forever();return
journal=r.journal_path();recipe={'config':r.config,'mode':a.mode,'seed_only':a.seed_only if a.stage=='refine' else False}
if a.stage=='refine':recipe['trajectory_experiment']=a.trajectory_experiment
if a.stage in ['render','package'] and (r.root/'models.json').is_file():recipe['models']=sha(r.root/'models.json')
if a.stage=='package':recipe['package']=str(r.package)
fingerprint=hashlib.sha256(json.dumps(recipe,sort_keys=True).encode()).hexdigest()
if a.stage not in ['setup','prepare'] and journal.exists():
old=json.loads(journal.read_text())
if old.get('status')=='completed':
if old.get('configuration_sha256')!=fingerprint:raise PrerequisiteError('Completed stage has a different configuration. Use a fresh output root to preserve existing results.')
r.verify_stage(a.stage);print(json.dumps({'stage':a.stage,'status':'reused-verified-existing-outputs','new_gpu_execution':False}));return
if a.stage=='refine' and (r.ref/'roi-original').exists():raise PrerequisiteError('Partial refinement outputs already exist. Preserve them and use a fresh root or finish the explicit adapter stages; this runner will not silently overwrite model experiments.')
write(journal,{'stage':a.stage,'status':'running','started_unix':time.time(),'configuration_sha256':fingerprint});gpu=a.stage in ['rig','multiview','train','refine','extend','render']
if gpu:r.need(r.root/'setup.json')
with contextlib.ExitStack() as stack:
if gpu:
lock=r.path('gpu_lock');lock.parent.mkdir(parents=True,exist_ok=True);f=stack.enter_context(lock.open('a+'));fcntl.flock(f,fcntl.LOCK_EX)
getattr(r,'package_stage' if a.stage=='package' else a.stage)()
write(journal,{'stage':a.stage,'status':'completed','finished_unix':time.time(),'configuration_sha256':fingerprint});print(json.dumps({'stage':a.stage,'status':'completed','root':str(r.root)}))
except (PrerequisiteError,ValueError,AssertionError,KeyError,TypeError,OSError,subprocess.CalledProcessError) as exc:
if a.stage not in ['check','serve'] and not (r.journal_path().exists() and json.loads(r.journal_path().read_text()).get('status')=='completed'):write(r.journal_path(),{'stage':a.stage,'status':'failed','error':str(exc),'finished_unix':time.time()})
print(f'ERROR: {exc}',file=sys.stderr);raise SystemExit(2)
if __name__=='__main__':main()
runtime.example.json
View files on GitHub{
"schema": 1,
"ffmpeg": "ffmpeg",
"cuda_home": "/usr/local/cuda-12.9",
"cuda_arch": "12.0",
"gpu_lock": ".gpu.lock",
"python": {
"gem": "envs/gem/bin/python",
"reconstruction": "envs/reconstruction/bin/python",
"moge": "envs/moge/bin/python",
"control_export": "envs/control_export/bin/python",
"control_render": "envs/control_render/bin/python"
},
"sources": {
"gem": "deps/gem",
"four_d_anyone": "deps/four_d_anyone",
"moge": "deps/moge",
"soma": "deps/soma"
},
"sam2_source": "deps/sam2",
"assets": {
"soma": "assets/soma",
"sam2_checkpoint": "models/sam2.1_hiera_large.pt",
"gem_config": "gem-motion.yaml"
},
"models": "models",
"interval_steps": 6000,
"seed_train_steps": 20000,
"hires_steps": 6000,
"roi_steps": 3000,
"geometry_steps": 1500,
"extra_python_paths": []
}
control_sample.py
View files on GitHub"""Build a public, known-geometry SOMA control sample.
This is skinning and rendering, NOT monocular reconstruction or a trained 4DGS.
Only the pinned official example motion and neutral native SOMA identity are used.
No footage, motion estimate, appearance, or geometry from a private clip is read.
"""
from __future__ import annotations
import argparse,gzip,hashlib,json,sys,time
from pathlib import Path
import numpy as np
SOMA_REVISION='01ab5b5c0876058bd27d34b1607d74b2e55e0cf4'
MOTION_SHA256='c09372492aaacdca3ca7ec5d737263d8e6042b66fdd29318d91848427fa40695'
SOURCE=f'https://github.com/NVlabs/SOMA-X/blob/{SOMA_REVISION}/assets/example_animation.usd'
def write_json(path,value):
Path(path).write_text(json.dumps(value,indent=2,allow_nan=False)+'\n')
def packed(path,array):
raw=np.ascontiguousarray(array).tobytes()
with Path(path).open('wb') as stream:
with gzip.GzipFile(filename='',fileobj=stream,mode='wb',mtime=0) as handle:handle.write(raw)
return {'bytes':Path(path).stat().st_size,'raw_bytes':len(raw),'raw_sha256':hashlib.sha256(raw).hexdigest()}
def framing(vertices):
H,W=768,640
f=H/(2*np.tan(np.deg2rad(21)))
target_y=float(np.quantile(vertices[:,:,1],.995))*.52
radial=np.linalg.norm(vertices[:,:,[0,2]],axis=-1)
horizontal=float(radial.max())*np.sqrt(1+(f/(W*.46))**2)
vertical=float(np.max(radial+np.abs(vertices[:,:,1]-target_y)*(f/(H*.46))))
radius=float(np.ceil(max(horizontal,vertical)*10)/10+.1)
return {'position':[0.,target_y,radius],'target':[0.,target_y,0.],'fov':42.,'source_width':W,'source_height':H}
def export(args):
import torch
sys.path.insert(0,str(args.soma_source.resolve()))
from soma import SOMALayer
import soma.geometry.lbs_warp as native_lbs
torch.set_num_threads(8)
motion=args.motion or args.soma_source/'assets/example_animation.usd'
if hashlib.sha256(motion.read_bytes()).hexdigest()!=MOTION_SHA256:
raise ValueError('The public control builder accepts only the pinned official SOMA example motion.')
out=args.out;data=out/'data';data.mkdir(parents=True,exist_ok=True)
model=SOMALayer(data_root=args.assets_dir,device='cuda',identity_model_type='soma',lod='mid',mode='warp',correctives_model_path=None)
poses,translation,fps=model.load_motion(motion)
# In-place presentation preserves the official rotations/vertical motion.
translation=translation.clone();translation[:,0]=0;translation[:,2]=0
model.prepare_identity(torch.zeros(1,model.identity_model.num_identity_coeffs,device='cuda'))
capture=[];original=native_lbs.linear_blend_skinning
def record(vertices,weights,indices,matrices):
capture.append(tuple(x.detach().cpu().numpy().copy() for x in [vertices,weights,indices,matrices]))
return original(vertices,weights,indices,matrices)
native_lbs.linear_blend_skinning=record
vertices=[];matrices=[];rest=weights=indices=None;started=time.monotonic()
try:
for start in range(0,len(poses),32):
capture.clear()
with torch.inference_mode():result=model.pose(poses[start:start+32].to('cuda'),transl=translation[start:start+32].to('cuda'),pose2rot=False,apply_correctives=False)
if not capture:raise RuntimeError('Expected actual native Warp skinning.')
bind,bw,bi,D=capture[-1]
if rest is None:rest=bind[0];weights=bw;indices=bi
assert np.max(abs(bind-rest[None]))<1e-4
vertices.append(result.vertices.detach().cpu().numpy());matrices.append(D)
print('PUBLIC_SOMA_POSE',min(start+32,len(poses)),len(poses),flush=True)
finally:native_lbs.linear_blend_skinning=original
V=np.concatenate(vertices);D=np.concatenate(matrices);faces=model.faces.detach().cpu().numpy().astype(np.int32)
ground=float(V[:,:,1].min());V[:,:,1]-=ground;D[:,:,1,3]-=ground
T,N=V.shape[:2];bones=D.shape[1];influences=weights.shape[1]
assert bones<=256 and np.allclose(weights.sum(-1),1,atol=1e-5)
# Neutral procedural colors; these are not textures inferred from a person.
height=(rest[:,1]-rest[:,1].min())/np.ptp(rest[:,1]);x=abs(rest[:,0])
color=np.tile([.16,.24,.31],(N,1));color[height>.45]=[.25,.55,.17];color[(x>.28)&(height>.45)]=[.55,.63,.67];color[x>.64]=[.82,.62,.20];color[height>.81]=[.62,.70,.73];color[height<.07]=[.11,.15,.18]
cross=np.cross(rest[faces[:,1]]-rest[faces[:,0]],rest[faces[:,2]]-rest[faces[:,0]]);normal=np.zeros_like(rest);length=np.zeros(N);count=np.zeros(N)
for k in range(3):
np.add.at(normal,faces[:,k],cross)
edge=np.linalg.norm(rest[faces[:,k]]-rest[faces[:,(k+1)%3]],axis=-1);np.add.at(length,faces[:,k],edge);np.add.at(count,faces[:,k],1)
normal/=np.maximum(np.linalg.norm(normal,axis=-1,keepdims=True),1e-8);light=np.array([.3,.6,.9]);light/=np.linalg.norm(light);color*=.65+.35*np.maximum(normal@light,0)[:,None]
radius=np.clip(length/np.maximum(count,1)*.72,.0025,.017).astype(np.float32)
fields=np.c_[rest,np.repeat(radius[:,None],3,axis=1),np.tile([0,0,0,1],(N,1)),np.full(N,.92),color].astype(np.float32)
rng=np.random.default_rng(42);parity=[];error=0.
for frame,index in zip(rng.integers(0,T,40),rng.integers(0,N,40)):
mats=D[frame,indices[index]];point=((mats[:,:3,:3]@rest[index,:,None])[...,0]+mats[:,:3,3]);position=(point*weights[index,:,None]).sum(0);err=float(np.linalg.norm(position-V[frame,index]));error=max(error,err)
parity.append({'frame':int(frame),'time':float(frame/fps),'index':int(index),'position':position.tolist()})
assert error<1e-4,(error,'Export must match native SOMA vertices.')
files={}
for name,value in [('gaussians.f32.gz',fields),('bone-indices.u16.gz',indices.astype(np.uint16)),('bone-weights.f32.gz',weights.astype(np.float32)),('bone-matrices.f32.gz',D.astype(np.float32))]:files[name]=packed(data/name,value)
camera=framing(V)
meta={'schema':1,'representation':'soma-skinned-gaussians','gaussians':N,'frames':T,'fps':float(fps),'duration':float(T/fps),'bones':bones,'influences':influences,'matrix_layout':'row-major','units':'meters','files':files,'camera':camera,'parity_samples':parity,'native_skinning_max_error_m':error,'source':SOURCE,'source_motion_sha256':MOTION_SHA256,'license':'Apache-2.0 (SOMA motion/geometry); repository MIT wrapper code','scope':'Synthetic known-geometry control. Not learned from RGB. No private-person data. Isotropic Gaussian sizes are held fixed while centers use exact native LBS.','motion_transform':'Official local rotations/vertical motion; horizontal root translation removed; global floor shifted to zero.','appearance':'Neutral shape coefficients=0, procedural matte colors and baked rest-space shading; no real-person likeness or copied texture.'}
write_json(data/'meta.json',meta)
np.savez_compressed(out/'control-reference.npz',vertices=V,faces=faces,fields=fields,matrices=D,indices=indices,weights=weights)
write_json(out/'PROVENANCE.json',{'schema':1,'source':SOURCE,'source_code_revision':SOMA_REVISION,'motion_sha256':MOTION_SHA256,'identity':'Native SOMA neutral, all identity coefficients zero, correctives disabled','private_data_used':False,'frames':T,'fps':float(fps),'seconds_export':time.monotonic()-started,'max_native_skinning_error_m':error,'camera':camera,'synthetic_control':True})
print('PUBLIC_CONTROL_EXPORT_READY',json.dumps({'frames':T,'points':N,'bones':bones,'bytes':sum(x['bytes'] for x in files.values()),'max_error_m':error}),flush=True)
def render(args):
import subprocess,torch
import torch.nn.functional as F
from PIL import Image,ImageDraw,ImageFont
from gsplat import rasterization
if args.nvdiffrast_dir:sys.path.insert(0,str(args.nvdiffrast_dir))
import nvdiffrast.torch as dr
torch.set_num_threads(8);out=args.out;meta=json.loads((out/'data/meta.json').read_text());z=np.load(out/'control-reference.npz');V=torch.tensor(z['vertices'],device='cuda');faces=torch.tensor(z['faces'],device='cuda',dtype=torch.int32);fields=torch.tensor(z['fields'],device='cuda');N=len(fields);T=len(V);meta['camera']=framing(z['vertices']);write_json(out/'data/meta.json',meta);provenance=json.loads((out/'PROVENANCE.json').read_text());provenance['camera']=meta['camera'];write_json(out/'PROVENANCE.json',provenance);H,W=meta['camera']['source_height'],meta['camera']['source_width'];f=H/(2*np.tan(np.deg2rad(42/2)));K=torch.tensor([[f,0,W/2],[0,f,H/2],[0,0,1]],device='cuda',dtype=torch.float32);target=np.asarray(meta['camera']['target']);radius=meta['camera']['position'][2]
ctx=dr.RasterizeCudaContext();font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf',13)
def encoder(path,width,height):return subprocess.Popen([str(args.ffmpeg),'-v','error','-y','-f','rawvideo','-pix_fmt','rgb24','-s',f'{width}x{height}','-r',str(meta['fps']),'-i','pipe:0','-an','-c:v','libx264','-crf','20','-preset','fast','-pix_fmt','yuv420p','-movflags','+faststart',str(path)],stdin=subprocess.PIPE)
source=encoder(out/'source.mp4',W,H);comparison=encoder(out/'comparison.mp4',W*2,H+48)
def view(angle):
eye=target+np.array([radius*np.sin(angle),0,radius*np.cos(angle)]);zaxis=target-eye;zaxis/=np.linalg.norm(zaxis);xaxis=np.cross(zaxis,[0,1,0]);xaxis/=np.linalg.norm(xaxis);yaxis=np.cross(zaxis,xaxis);c2w=np.eye(4);c2w[:3,:3]=np.stack([xaxis,yaxis,zaxis],-1);c2w[:3,3]=eye;return torch.tensor(np.linalg.inv(c2w),device='cuda',dtype=torch.float32)
front=view(0);colors=fields[:,11:14].contiguous();quats=fields[:,[9,6,7,8]].contiguous();scales=fields[:,3:6].contiguous();opacities=fields[:,10].contiguous()
with torch.no_grad():
for t in range(T):
# Reference RGB comes from the actual posed triangle mesh.
cv=V[t]@front[:3,:3].T+front[:3,3];depth=cv[:,2];clip=torch.stack([2*K[0,0]/W*cv[:,0],-2*K[1,1]/H*cv[:,1],(20.1/19.9)*depth-4/19.9,depth],-1)[None]
rast,_=dr.rasterize(ctx,clip.contiguous(),faces,resolution=[H,W]);rgb,_=dr.interpolate(colors[None],rast,faces);alpha=(rast[...,3:]>0).float();reference=(rgb*alpha+.96*(1-alpha))[0].flip(0);ref=(reference.clamp(0,1).cpu().numpy()*255).astype(np.uint8)
camera=view(2*np.pi*t/max(1,T-1));image,a,_=rasterization(V[t].contiguous(),quats,scales,opacities,colors,camera[None],K[None],W,H,render_mode='RGB',packed=True,near_plane=.1,far_plane=20.);image=image[0]+.96*(1-a[0]);gaussian=(image.clamp(0,1).cpu().numpy()*255).astype(np.uint8)
source.stdin.write(ref.tobytes());canvas=Image.new('RGB',(W*2,H+48),'white');canvas.paste(Image.fromarray(ref),(0,28));canvas.paste(Image.fromarray(gaussian),(W,28));draw=ImageDraw.Draw(canvas);draw.text((10,8),'KNOWN SOMA MESH / SYNTHETIC RGB',fill='#36454f',font=font);draw.text((W+10,8),'SKINNED GAUSSIANS / 3D CAMERA ORBIT',fill='#36454f',font=font);draw.text((10,H+31),'Synthetic control / official SOMA motion / no RGB reconstruction or private footage',fill='#627078',font=font);comparison.stdin.write(np.asarray(canvas).tobytes())
if t==0:canvas.save(out/'poster.jpg',quality=95)
if t%120==0:print('PUBLIC_CONTROL_RENDER',t,T,flush=True)
source.stdin.close();comparison.stdin.close();assert source.wait()==0 and comparison.wait()==0
manifest={'schema':1,'sample_kind':'soma-synthetic-control','title':'SOMA synthetic control','duration':meta['duration'],'fps':meta['fps'],'source':{'url':'source.mp4','title':'Known SOMA mesh RGB','credit':'NVIDIA SOMA-X official example motion; neutral SOMA geometry; our procedural matte render','license':'Apache-2.0 (upstream SOMA assets); MIT wrapper code','attribution_url':SOURCE},'segments':[{'id':'control','start':0,'duration':meta['duration'],'root':'data/'}],'provenance':'Synthetic control sample with known rig/geometry, not a monocular reconstruction; separate from the referenced YouTube video.','representation':'soma-skinned-gaussians','poster':'poster.jpg','comparison':'comparison.mp4'}
write_json(out/'manifest.json',manifest);print('PUBLIC_CONTROL_MEDIA_READY',flush=True)
def main():
p=argparse.ArgumentParser(description=__doc__);p.add_argument('--stage',choices=['export','render'],required=True);p.add_argument('--out',type=Path,required=True);p.add_argument('--soma-source',type=Path);p.add_argument('--assets-dir',type=Path);p.add_argument('--motion',type=Path);p.add_argument('--ffmpeg',type=Path,default=Path('ffmpeg'));p.add_argument('--nvdiffrast-dir',type=Path);a=p.parse_args();a.out.mkdir(parents=True,exist_ok=True)
if a.stage=='export':
if not a.soma_source or not a.assets_dir:p.error('export requires --soma-source and --assets-dir')
export(a)
else:render(a)
if __name__=='__main__':main()

