Download script.py from jskvrna/2026_s23dr: direct link, hf CLI and curl.
- Browser
- Download file 184 kB
-
https://huggingface.co/jskvrna/2026_s23dr/resolve/main/script.py
- Command line
-
hf download hf://jskvrna/2026_s23dr/script.py
-
curl -L -o script.py https://huggingface.co/jskvrna/2026_s23dr/resolve/main/script.py
184 kB
"""S23DR 2026 β submission script (trained WireframeDiffusion).
HF Competitions entry point: the test runner executes ``python script.py``
in the submission repo's working directory. We therefore:
* Load ``params.json`` (mirrors ``usm3d/empty_submission_2026``).
* Resolve the dataset (test server: ``/tmp/data``; local: snapshot_download).
* Read the samples straight from the webdataset tars (``--loader tar``; or
through the HF loader script, ``--loader hf``), **load the diffusion model
exactly once** on CUDA, run inference, and write ``submission.json``.
Online preprocessing
--------------------
Uses V10 online preprocessing by default β ``build_scene_input`` produces
the V10 feature point cloud (COLMAP+camera tokens + depth-unprojected
tokens, per-point RGB, soft top-2 gestalt). Matches the cache layout the
model was trained on.
Efficiency notes
----------------
* Models live only in the main process, which runs one GPU loop over batches
of ``--batch_samples`` samples (stage 1, then stage 2; fixed batch shape).
* All CPU work (tar read, COLMAP parse, scene build, stage-2 hull crop,
ensemble selection) runs in ``--n_workers`` spawned worker processes with one
BLAS thread each; the worker that preprocessed a sample keeps its stage-1
cache and does that sample's stage-2 build and selection (see run_pipeline).
* A sample whose CPU work raises gets the empty solution and is reported as
FAILED (counted at the end); a GPU error or a dead / stalled worker stops
the run.
Specifying the checkpoint
-------------------------
Resolution order (first hit wins):
1. ``--ckpt PATH`` (CLI, for local testing)
2. ``S23DR_CKPT`` env var (set by SLURM / docker entrypoint)
3. ``params['ckpt']`` (extra field in params.json)
4. ``./test_checkpoint.pth`` (default β what you'd commit to the
submission repo)
The script auto-resolves model architecture (small vs. large) from the
``args`` dict embedded in the checkpoint, so the same script handles both.
Local sanity check
------------------
Before pushing a submission repo, run::
python script.py --sanity
This loads the public ``usm3d/hoho22k_2026_trainval`` dataset (which has
GT wireframes), runs the trained model on a few validation samples, and
prints per-sample + mean HSS / F1 / IoU. It writes no submission.json β
its only job is to verify that the checkpoint loads, the V10 online
preprocessing path works end-to-end, and the model produces sane output
before you submit.
"""
from __future__ import annotations
import argparse
import copy
import fcntl
import hashlib
import io
import json
import multiprocessing as mp
import multiprocessing.connection
import os
import signal
import queue
import resource
import shlex
import sys
import threading
import time
import traceback
import zipfile
from collections import Counter, defaultdict, deque
from contextlib import contextmanager
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Tuple
import numpy as np
import torch
try:
from datasets import load_dataset
except ModuleNotFoundError:
load_dataset = None
from tqdm import tqdm
# --- our project imports ----------------------------------------------------
from data.preprocess import (
read_colmap_zip,
_cam_matrix_from_image,
build_scene_input,
_image_to_rgb_array,
gestalt_img_to_ids,
_camera_for_image,
_resolve_colmap_image,
GESTALT_CLASSES,
)
from data.dataset import (_seed_from_order_id, index_tar, read_tar_members, decode_tar_sample,
hf_row_images, stream_tar_prefix)
from data.stage2_build import build_stage2_scene
from data.stage2_dataset import stage2_row_to_sample, _pad_init_verts
import models.scene_encoder
from models.scene_encoder import SceneEncoder
from models.denoiser import VertexDenoiser
from models.diffusion import WireframeDiffusion
from models.stage2 import Stage2Diffusion
# ---------------------------------------------------------------------------
# Empty / safe fallback
# ---------------------------------------------------------------------------
def empty_solution() -> Tuple[np.ndarray, List[Tuple[int, int]]]:
"""Minimal valid solution: 2 coincident vertices + 1 edge."""
return np.zeros((2, 3)), [(0, 1)]
# ---------------------------------------------------------------------------
# Model loading (called once)
# ---------------------------------------------------------------------------
def resolve_ckpt_path(cli_arg: Optional[str], params: Dict[str, Any]) -> Path:
for candidate, src in [
(cli_arg, "--ckpt"),
(os.environ.get("S23DR_CKPT"), "$S23DR_CKPT"),
(params.get("ckpt"), "params.json[ckpt]"),
("./test_checkpoint.pth", "default ./test_checkpoint.pth"),
]:
if candidate:
print(f"[ckpt] using {candidate} (from {src})", flush=True)
return Path(candidate)
raise SystemExit("[ckpt] no checkpoint specified")
def resolve_stage2_ckpt_path(cli_arg: Optional[str], params: Dict[str, Any]) -> Path:
"""Stage-2 checkpoint resolution. The two-stage architecture is mandatory;
if no stage-2 ckpt is configured the script aborts. Resolution mirrors
``resolve_ckpt_path``: CLI β env β params.json β committed default."""
for candidate, src in [
(cli_arg, "--stage2_ckpt"),
(os.environ.get("S23DR_STAGE2_CKPT"), "$S23DR_STAGE2_CKPT"),
(params.get("stage2_ckpt"), "params.json[stage2_ckpt]"),
("./test_checkpoint_stage2.pth", "default ./test_checkpoint_stage2.pth"),
]:
if candidate:
print(f"[stage2/ckpt] using {candidate} (from {src})", flush=True)
return Path(candidate)
raise SystemExit("[stage2/ckpt] no stage-2 checkpoint specified β "
"two-stage pipeline is mandatory.")
def _load_state_strict(model: torch.nn.Module, ckpt: Dict[str, Any], ckpt_path: Path) -> None:
"""Load the checkpoint weights with strict key AND shape matching (every checkpoint tensor
consumed, every model parameter loaded; raises otherwise) and switch to eval mode."""
state = ckpt.get("model") or ckpt.get("state_dict")
if state is None:
raise RuntimeError(f"checkpoint {ckpt_path} has no 'model' or 'state_dict' key")
# Strip DDP prefix if present.
if any(k.startswith("module.") for k in state):
state = {k[len("module."):]: v for k, v in state.items()}
model.load_state_dict(state, strict=True)
n_params = sum(1 for _ in model.state_dict())
if n_params != len(state):
raise RuntimeError(f"{ckpt_path}: {len(state)} checkpoint tensors vs {n_params} model tensors")
model.eval()
def load_model(ckpt_path: Path, device: torch.device):
"""Return (model, ckpt_args) β model is .eval() on `device`.
Architecture hyperparameters (d_model, n_heads, n_layers, d_ff,
n_pool, encoder layer counts, ...) are read from the ``args`` dict
embedded in the checkpoint. Same loader handles small and large
configs transparently.
"""
print(f"[model] loading {ckpt_path} on {device}", flush=True)
t0 = time.perf_counter()
ckpt = torch.load(ckpt_path, map_location=device, weights_only=False)
ckpt_args = ckpt.get("args", {}) or {}
# RGB branch is present in v10+ caches and was used when training models
# on those shards. Older sem_v7 checkpoints disable the RGB MLP.
cache_version = str(ckpt_args.get("cache_version", "sem_v10")).lower()
use_rgb = cache_version not in {"v7", "sem_v7"}
enc = SceneEncoder(
d_model=ckpt_args.get("d_model", 256),
n_heads=ckpt_args.get("n_heads", 8),
d_ff=ckpt_args.get("d_ff", 1024),
n_full_layers=ckpt_args.get("n_encoder_full_layers", 2),
n_pool=ckpt_args.get("n_pool", 1024),
n_pool_cross_layers=ckpt_args.get("n_encoder_pool_cross_layers", 1),
n_pool_layers=ckpt_args.get("n_encoder_pool_layers", 2),
use_rgb=use_rgb,
)
den = VertexDenoiser(
d_model=ckpt_args.get("d_model", 256),
n_heads=ckpt_args.get("n_heads", 8),
n_layers=ckpt_args.get("n_layers", 8),
d_ff=ckpt_args.get("d_ff", 1024),
k_verts=ckpt_args.get("k_verts", 64),
)
model = WireframeDiffusion(
enc, den,
noise_sigma_xyz=ckpt_args.get("noise_sigma_xyz", 1.0),
init_from_scene=ckpt_args.get("init_from_scene", False),
scene_init_jitter=ckpt_args.get("scene_init_jitter", 0.05),
).to(device)
_load_state_strict(model, ckpt, ckpt_path)
print(f"[model] loaded in {time.perf_counter() - t0:.1f}s "
f"d_model={ckpt_args.get('d_model')} n_layers={ckpt_args.get('n_layers')} "
f"use_rgb={use_rgb} step={ckpt.get('step')} best_hss={ckpt.get('best_hss')}",
flush=True)
return model, ckpt_args
def load_stage2_model(ckpt_path: Path, device: torch.device):
"""Build a Stage2Diffusion model from its checkpoint. Architecture is read
from the embedded ``args`` dict so the same loader handles small / large
variants. Returns (model, ckpt_args).
"""
print(f"[stage2/model] loading {ckpt_path} on {device}", flush=True)
t0 = time.perf_counter()
ckpt = torch.load(ckpt_path, map_location=device, weights_only=False)
a = ckpt.get("args", {}) or {}
if not isinstance(a, dict):
a = vars(a)
enc = SceneEncoder(
d_model=a.get("d_model", 256),
n_heads=a.get("n_heads", 8),
d_ff=a.get("d_ff", 1024),
n_full_layers=a.get("n_encoder_full_layers", 2),
n_pool=a.get("n_pool", 1024),
n_pool_cross_layers=a.get("n_encoder_pool_cross_layers", 1),
n_pool_layers=a.get("n_encoder_pool_layers", 2),
use_rgb=True, # stage-2 cache always carries RGB
)
den = VertexDenoiser(
d_model=a.get("d_model", 256),
n_heads=a.get("n_heads", 8),
n_layers=a.get("n_layers", 8),
d_ff=a.get("d_ff", 1024),
k_verts=a.get("k_verts", 64),
)
model = Stage2Diffusion(
enc, den,
noise_sigma_xyz=a.get("noise_sigma_xyz", 0.5),
init_from_scene=a.get("init_from_scene", True),
scene_init_jitter=a.get("scene_init_jitter", 0.05),
).to(device)
_load_state_strict(model, ckpt, ckpt_path)
print(f"[stage2/model] loaded in {time.perf_counter() - t0:.1f}s "
f"d_model={a.get('d_model')} n_layers={a.get('n_layers')} "
f"step={ckpt.get('step')} best_hss={ckpt.get('best_hss')}",
flush=True)
return model, a
# ---------------------------------------------------------------------------
# Per-sample preprocessing (CPU, runs in the pipeline worker processes)
# ---------------------------------------------------------------------------
def preprocess_sample(
sample: Dict[str, Any],
n_pts: int,
use_depth: bool,
voxel_size_m: float = 0.1,
keep_raw: bool = False,
*,
colmap_order: str,
) -> Dict[str, Any]:
"""Heavy CPU work: COLMAP parse + V10 scene input build. No torch / GPU here.
Mirrors `data.dataset.process_sample` exactly: same `voxel_size_m`
(configs set this to 0.1; build_scene_input's bare default is 0.0
which would skip voxel downsampling and produce a different point
set) and same per-order_id deterministic RNG seed (so the same
points are sampled as were cached at training time).
With ``keep_raw=True`` the return value is ``{"scene": ..., "raw_sample":
..., "colmap_rec": ...}`` so the stage-2 builder can reuse the already-
decoded COLMAP record instead of parsing the zip twice. ``colmap_order``:
point / image order of the COLMAP record (``read_colmap_zip``; "pycolmap" =
the released preprocessing bit for bit).
"""
colmap_rec = read_colmap_zip(sample["colmap"], order=colmap_order)
order_id = sample.get("order_id", "")
rng = np.random.default_rng(_seed_from_order_id(order_id))
scene = build_scene_input(
{**sample, "colmap": colmap_rec},
n_pts=n_pts, use_depth=use_depth,
voxel_size_m=voxel_size_m,
rng=rng,
return_cache=keep_raw,
)
if not keep_raw:
return scene
cache = scene.pop("_cache", None)
return {
"scene": scene,
"raw_sample": sample,
"colmap_rec": colmap_rec,
"cache": cache,
}
_SCENE_KEYS = ("scene_xyz", "scene_type_ids", "scene_gestalt_ids", "scene_gestalt_id2",
"scene_gestalt_w1", "scene_ade_ids", "scene_geom_conf", "scene_sem_conf", "scene_rgb")
def scenes_to_batch(scenes: Sequence[Dict[str, np.ndarray]], device: torch.device) -> Dict[str, torch.Tensor]:
"""Stack S stage-1 scenes (``build_scene_input`` dicts, equal point counts) into one device
batch with leading dim S (one host->device copy per field)."""
batch = {k: torch.from_numpy(np.stack([s[k] for s in scenes])).to(device)
for k in _SCENE_KEYS + ("bbox_center", "bbox_R")}
batch["bbox_scale"] = torch.tensor([s["bbox_scale"] for s in scenes], dtype=torch.float32, device=device)
return batch
def scene_to_batch(scene: Dict[str, np.ndarray], device: torch.device) -> Dict[str, torch.Tensor]:
return scenes_to_batch([scene], device)
# ---------------------------------------------------------------------------
# Stage-2 inference helpers
# ---------------------------------------------------------------------------
class Stage2Config:
"""Frozen knobs for the stage-2 refinement path. Built once in `main`."""
__slots__ = ("model", "n_pts", "k_verts", "n_sample_steps", "validity_thresh",
"above_m", "below_m", "side_m",
"n_col_oversample", "n_dep_oversample",
"n_depth_per_image_cap", "sampling",
"density_voxel_size_m", "density_kernel_radius",
"density_kernel_axis", "density_response_power",
"density_planarity_suppression", "density_planarity_radius",
"density_planarity_min_points", "density_min_per_voxel",
"ensemble_n", "ensemble_merge_m", "ensemble_mode",
"ensemble_strategy", "ensemble_refine_positions",
"ensemble_refine_agg", "ensemble_top_k",
"ensemble_edge_vote", "ensemble_edge_vote_frac",
"ensemble_vertex_vote_frac",
"ensemble_stage2_last_k", "ensemble_selector",
"ensemble_ranker_path", "ensemble_ranker",
"ensemble_fixed_candidate",
"ensemble_topk_fuse",
"fps_max_exact_iters",
"seed", "encoder_bf16", "denoiser_bf16", "cuda_graph", "compile")
def __init__(self, model, n_pts: int, k_verts: int, n_sample_steps: int,
validity_thresh: float, above_m: float, below_m: float, side_m: float,
n_col_oversample: int, n_dep_oversample: int,
n_depth_per_image_cap: int, sampling: str = "random",
density_voxel_size_m: float = 0.25,
density_kernel_radius: int = 3,
density_kernel_axis: str = "cube",
density_response_power: float = 1.0,
density_planarity_suppression: float = 1.0,
density_planarity_radius: int = 1,
density_planarity_min_points: int = 12,
density_min_per_voxel: int = 0,
ensemble_n: int = 1,
ensemble_merge_m: float = 0.5,
ensemble_mode: str = "medoid",
ensemble_strategy: str = "union_hull",
ensemble_refine_positions: bool = True,
ensemble_refine_agg: str = "mean",
ensemble_top_k: int = 0,
ensemble_edge_vote: bool = True,
ensemble_edge_vote_frac: float = 0.5,
ensemble_vertex_vote_frac: float = 0.0,
ensemble_stage2_last_k: int = 1,
ensemble_selector: str = "legacy",
ensemble_ranker_path: Optional[str] = None,
ensemble_ranker: Optional[Dict[str, np.ndarray]] = None,
ensemble_fixed_candidate: str = "confidence_mean_add",
ensemble_topk_fuse: int = 1,
fps_max_exact_iters: Optional[int] = None,
seed: int = 0,
encoder_bf16: bool = False,
denoiser_bf16: bool = False,
cuda_graph: bool = False,
compile: bool = False):
self.model = model
self.n_pts = int(n_pts)
self.k_verts = int(k_verts)
self.n_sample_steps = int(n_sample_steps)
self.validity_thresh = float(validity_thresh)
self.above_m = float(above_m); self.below_m = float(below_m); self.side_m = float(side_m)
self.n_col_oversample = int(n_col_oversample)
self.n_dep_oversample = int(n_dep_oversample)
self.n_depth_per_image_cap = int(n_depth_per_image_cap)
if sampling not in ("random", "fps", "voxel"):
raise ValueError(f"sampling must be 'random', 'fps', or 'voxel', got {sampling!r}")
self.sampling = sampling
self.density_voxel_size_m = float(density_voxel_size_m)
self.density_kernel_radius = int(density_kernel_radius)
self.density_kernel_axis = str(density_kernel_axis)
self.density_response_power = float(density_response_power)
self.density_planarity_suppression = float(density_planarity_suppression)
self.density_planarity_radius = int(density_planarity_radius)
self.density_planarity_min_points = int(density_planarity_min_points)
self.density_min_per_voxel = int(density_min_per_voxel)
self.ensemble_n = max(1, int(ensemble_n))
self.ensemble_merge_m = float(ensemble_merge_m)
if ensemble_mode not in ("medoid", "consensus", "confidence"):
raise ValueError(f"ensemble_mode must be 'medoid', 'consensus', or 'confidence', got {ensemble_mode!r}")
self.ensemble_mode = str(ensemble_mode)
if ensemble_strategy not in ("union_hull", "per_seed"):
raise ValueError(f"ensemble_strategy must be 'union_hull' or 'per_seed', got {ensemble_strategy!r}")
self.ensemble_strategy = str(ensemble_strategy)
self.ensemble_refine_positions = bool(ensemble_refine_positions)
if ensemble_refine_agg not in ("median", "mean", "wmean"):
raise ValueError(
f"ensemble_refine_agg must be 'median', 'mean', or 'wmean', "
f"got {ensemble_refine_agg!r}")
self.ensemble_refine_agg = str(ensemble_refine_agg)
self.ensemble_top_k = max(0, int(ensemble_top_k))
self.ensemble_edge_vote = bool(ensemble_edge_vote)
if not (0.0 < float(ensemble_edge_vote_frac) <= 1.0):
raise ValueError(
f"ensemble_edge_vote_frac must be in (0, 1], got {ensemble_edge_vote_frac!r}")
self.ensemble_edge_vote_frac = float(ensemble_edge_vote_frac)
if not (0.0 <= float(ensemble_vertex_vote_frac) <= 1.0):
raise ValueError(
f"ensemble_vertex_vote_frac must be in [0, 1], "
f"got {ensemble_vertex_vote_frac!r}")
self.ensemble_vertex_vote_frac = float(ensemble_vertex_vote_frac)
self.ensemble_stage2_last_k = max(1, int(ensemble_stage2_last_k))
if ensemble_selector not in ("legacy", "ranker", "fixed"):
raise ValueError(
f"ensemble_selector must be 'legacy', 'ranker', or 'fixed', got {ensemble_selector!r}")
self.ensemble_selector = str(ensemble_selector)
self.ensemble_ranker_path = ensemble_ranker_path
self.ensemble_ranker = ensemble_ranker
self.ensemble_fixed_candidate = str(ensemble_fixed_candidate)
self.ensemble_topk_fuse = max(1, int(ensemble_topk_fuse))
# None => full exact FPS. Set to the value the model trained with so
# the per-provenance anchor count matches; otherwise the encoder sees
# a markedly different point distribution at inference (all exact
# anchors vs. exact prefix + deterministic random fill).
self.fps_max_exact_iters = (None if fps_max_exact_iters is None
else int(fps_max_exact_iters))
# GPU numerics + paired seeding (see stage1_predict_batch / stage2_predict_batch).
self.seed = int(seed)
self.encoder_bf16 = bool(encoder_bf16)
self.denoiser_bf16 = bool(denoiser_bf16)
self.cuda_graph = bool(cuda_graph)
self.compile = bool(compile)
def _stage2_sample_to_batch(sample: Dict[str, Any], device: torch.device) -> Dict[str, torch.Tensor]:
"""Same shape as ``scene_to_batch`` but for the stage-2 sample dict produced
by ``stage2_row_to_sample`` (includes ``init_verts`` + valid mask)."""
keys = (
"scene_xyz", "scene_type_ids",
"scene_gestalt_ids", "scene_gestalt_id2", "scene_gestalt_w1",
"scene_ade_ids", "scene_geom_conf", "scene_sem_conf",
"scene_rgb", "init_verts", "init_verts_valid",
"bbox_center", "bbox_scale", "bbox_R",
# FPS-mode extras (only present when pre_subsample=False):
"scene_valid_mask", "init_verts_world", "verts_gt_world",
)
return {k: sample[k].unsqueeze(0).to(device) for k in keys if k in sample}
def _stage2_samples_to_batch(samples: Sequence[Dict[str, Any]], device: torch.device) -> Dict[str, torch.Tensor]:
"""Stack S built stage-2 samples (equal point counts and member counts M) into one device batch:
scene fields (S, ...), ``init_verts`` (S*M, K, 3) and ``init_verts_valid`` (S*M, K)."""
batch = {k: torch.stack([s[k] for s in samples]).to(device) for k in _SCENE_KEYS}
for k in ("init_verts", "init_verts_valid"):
batch[k] = torch.cat([s[k] for s in samples]).to(device)
return batch
def _torch_seed(order_id: str, seed: int, stage: str, n: int) -> int:
"""Per-sample torch seed sha1(f"{order_id}/{seed}/{stage}/{n}")[:8] (big endian) & (2**63 - 1),
the formula of tools/infer_bench.py:stable_seed. ``stage`` is "s1" or "s2"; ``n`` counts that
stage's scene encodes within the sample (0 except in the per-seed stage-2 path)."""
h = hashlib.sha1(f"{order_id}/{seed}/{stage}/{n}".encode()).digest()
return int.from_bytes(h[:8], "big") & ((1 << 63) - 1)
@contextmanager
def _phase(timings: Optional[Dict[str, float]], key: str, device: torch.device):
"""Add the CUDA-synchronised wall seconds of the block to timings[key]; no-op when None."""
if timings is None:
yield
return
if device.type == "cuda":
torch.cuda.synchronize(device)
t0 = time.perf_counter()
yield
if device.type == "cuda":
torch.cuda.synchronize(device)
timings[key] = timings.setdefault(key, 0.0) + time.perf_counter() - t0
def _init_members(model: WireframeDiffusion, batch: Dict[str, torch.Tensor], M: int,
order_ids: Sequence[str], seed: int, stage: str, enc_idx: Sequence[int]) -> torch.Tensor:
"""x0 (S*M, K, 3) for the M members of each of the S scenes in ``batch`` (sample-major rows).
Sample s reseeds the torch RNG with _torch_seed(order_ids[s], seed, stage, enc_idx[s]) and then
makes exactly the draws of the released per-sample path (``model._init_x0`` on its scene
replicated to M rows), so each sample is paired with the seeded phase-0 baseline."""
S = batch["scene_xyz"].shape[0]
x0 = []
for s in range(S):
sub = {k: batch[k][s:s + 1].expand(M, *batch[k].shape[1:]) for k in _SCENE_KEYS}
if "init_verts" in batch:
sub["init_verts"] = batch["init_verts"][s * M:(s + 1) * M]
sub["init_verts_valid"] = batch["init_verts_valid"][s * M:(s + 1) * M]
torch.manual_seed(_torch_seed(order_ids[s], seed, stage, enc_idx[s]))
x0.append(model._init_x0(sub, model.denoiser.k_verts, batch["scene_xyz"].device, M))
return torch.cat(x0)
def _decode_members(x: torch.Tensor, valid_logit: torch.Tensor, edge_logit: torch.Tensor,
frames: Sequence[Tuple[Any, Any, Any]], M: int, validity_thresh: float,
xyz_clip: Optional[float]) -> List[List[Tuple[np.ndarray, np.ndarray, np.ndarray]]]:
"""World-space members from the final ODE outputs with ONE device->host copy.
x (S*M, K, 3), valid_logit (S*M, K), edge_logit (S*M, K, K) on the device; ``frames`` holds S
host tuples (bbox_center (3,), bbox_scale, bbox_R (3, 3)). ``xyz_clip`` (stage 1) sanitises and
clamps the normalised state first; None (stage 2) uses it as is. Returns S lists of M host tuples
(verts_world (m, 3) float32, edges (e, 2) int64 pairs i < j into verts, valid_logits (m,) float32):
a slot is kept iff its validity logit > validity_thresh, an edge iff its logit > 0."""
B, K, _ = x.shape
if xyz_clip is not None:
x = torch.nan_to_num(x, nan=0.0, posinf=xyz_clip, neginf=-xyz_clip).clamp(-xyz_clip, xyz_clip)
host = torch.cat([x.reshape(B, 3 * K), valid_logit,
(edge_logit > 0.0).reshape(B, K * K).float()], dim=1).cpu().numpy()
xs, logits = host[:, :3 * K].reshape(B, K, 3), host[:, 3 * K:4 * K]
edge_pos = host[:, 4 * K:].reshape(B, K, K) > 0.5
out = []
for s, (center, scale, R) in enumerate(frames):
center, R, scale = np.asarray(center, np.float32), np.asarray(R, np.float32), np.float32(scale)
members = []
for b in range(s * M, (s + 1) * M):
idx = np.flatnonzero(logits[b] > validity_thresh)
verts = ((xs[b, idx] * scale) @ R + center).astype(np.float32)
edges = np.argwhere(np.triu(edge_pos[b][np.ix_(idx, idx)], 1)).astype(np.int64)
members.append((verts, edges, logits[b, idx]))
out.append(members)
return out
@torch.inference_mode()
def stage1_predict_batch(
model: WireframeDiffusion,
scenes: Sequence[Dict[str, np.ndarray]],
order_ids: Sequence[str],
cfg: "Stage2Config",
n_steps: int,
validity_thresh: float,
device: torch.device,
timings: Optional[Dict[str, float]] = None,
) -> List[List[Tuple[np.ndarray, np.ndarray, np.ndarray]]]:
"""Stage 1 on the GPU for S samples at once: one scene encode per sample, cfg.ensemble_n
members per sample integrated together (B = S * ensemble_n).
Inputs (host): ``scenes`` = S ``preprocess_sample(...)["scene"]`` dicts with equal point counts,
``order_ids`` = their S order_id strings. Sample s reseeds the torch RNG with
_torch_seed(order_ids[s], cfg.seed, "s1", 0) right before its x0 draws, so results do not depend
on S or on the batch composition beyond float rounding. Precision: cfg.encoder_bf16 /
cfg.denoiser_bf16 / the global TF32 setting.
Returns S lists of cfg.ensemble_n host tuples (verts_world (m, 3) float32, edges (e, 2) int64,
valid_logits (m,) float32); nothing returned references device memory. ``timings`` (optional)
accumulates CUDA-synchronised seconds under s1_enc / s1_den / s1_post."""
M = cfg.ensemble_n
if cfg.compile and model.denoiser._compiled is None:
model.denoiser.compile_step()
with _phase(timings, "s1_enc", device):
batch = scenes_to_batch(scenes, device)
feats, sxyz = model.encode(batch, cfg.encoder_bf16)
with _phase(timings, "s1_den", device):
x0 = _init_members(model, batch, M, order_ids, cfg.seed, "s1", [0] * len(scenes))
x, logit, edge = model.integrate(feats, sxyz, x0, n_steps, 1, cfg.denoiser_bf16, cfg.cuda_graph)
with _phase(timings, "s1_post", device):
return _decode_members(x, logit, edge,
[(s["bbox_center"], s["bbox_scale"], s["bbox_R"]) for s in scenes],
M, validity_thresh, model.xyz_clip)
def _fuse_wireframes(
runs: List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]],
n_total: int,
merge_tau_m: float,
vertex_vote_frac: float = 0.5,
edge_vote_frac: float = 0.5,
aggregator: str = "mean",
) -> Tuple[np.ndarray, List[Tuple[int, int]]]:
"""Vertex-merge consensus fusion.
1. Greedy single-link cluster all run vertices in world coords (threshold
``merge_tau_m`` metres). Each cluster centroid is the running mean of
its members (or a logit-weighted mean when ``aggregator="wmean"``).
2. Keep clusters supported by at least
``ceil(n_total * vertex_vote_frac)`` distinct runs.
3. For each pair of kept clusters, vote an edge if it appears in at least
``ceil(n_total * edge_vote_frac)`` runs.
Falls back to the single run with the most predicted vertices when no
cluster meets the support bar β we never collapse to empty when individual
runs were non-empty. ``runs`` entries are ``(verts, edges, logits)``;
``logits`` is only consulted under ``aggregator="wmean"``."""
if aggregator not in ("mean", "median", "wmean"):
raise ValueError(
f"aggregator must be 'mean', 'median', or 'wmean', got {aggregator!r}")
valid: List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]] = []
for r in runs:
v_raw = r[0]
if v_raw is None or len(v_raw) == 0:
continue
v = np.asarray(v_raw, dtype=np.float64).reshape(-1, 3)
e = list(r[1]) if len(r) > 1 and r[1] is not None else []
lg_raw = r[2] if len(r) > 2 else None
lg = (np.asarray(lg_raw, dtype=np.float64).reshape(-1)
if lg_raw is not None else np.zeros(v.shape[0], dtype=np.float64))
if lg.shape[0] != v.shape[0]:
lg = np.zeros(v.shape[0], dtype=np.float64)
valid.append((v, e, lg))
if not valid:
return np.zeros((0, 3), dtype=np.float64), []
v_support = max(1, int(np.ceil(n_total * float(vertex_vote_frac))))
e_support = max(1, int(np.ceil(n_total * float(edge_vote_frac))))
# Per-cluster bookkeeping: member positions, member logits, and the set
# of run indices contributing. Centroid is computed once at the end so
# 'median' / 'wmean' can use all members (running-mean only worked for
# the plain 'mean' aggregator).
cluster_members: List[List[np.ndarray]] = []
cluster_member_lg: List[List[float]] = []
cluster_centroids: List[np.ndarray] = [] # running mean β used for matching
cluster_count: List[int] = []
cluster_runs: List[set] = []
vertex_to_cluster: List[List[int]] = []
for r, (verts, _edges, lg) in enumerate(valid):
local_map: List[int] = []
for vi in range(verts.shape[0]):
v = verts[vi]
best_c, best_d = -1, float("inf")
for ci, cc in enumerate(cluster_centroids):
d = float(np.linalg.norm(v - cc))
if d < best_d:
best_d, best_c = d, ci
if best_c >= 0 and best_d <= merge_tau_m:
n = cluster_count[best_c]
cluster_centroids[best_c] = (cluster_centroids[best_c] * n + v) / (n + 1)
cluster_count[best_c] = n + 1
cluster_runs[best_c].add(r)
cluster_members[best_c].append(v)
cluster_member_lg[best_c].append(float(lg[vi]))
local_map.append(best_c)
else:
cluster_centroids.append(v.copy())
cluster_count.append(1)
cluster_runs.append({r})
cluster_members.append([v])
cluster_member_lg.append([float(lg[vi])])
local_map.append(len(cluster_centroids) - 1)
vertex_to_cluster.append(local_map)
kept = [ci for ci, rs in enumerate(cluster_runs) if len(rs) >= v_support]
if not kept:
best = max(range(len(valid)), key=lambda r: valid[r][0].shape[0])
return valid[best][0].astype(np.float64), list(valid[best][1])
# Final centroids per kept cluster, per aggregator.
fused_verts = np.empty((len(kept), 3), dtype=np.float64)
for new_i, ci in enumerate(kept):
stack = np.stack(cluster_members[ci], axis=0)
if aggregator == "median":
fused_verts[new_i] = np.median(stack, axis=0)
elif aggregator == "wmean":
lg = np.asarray(cluster_member_lg[ci], dtype=np.float64)
lg = lg - lg.max()
w = np.exp(lg)
ws = float(w.sum())
if ws <= 1e-12 or not np.isfinite(ws):
fused_verts[new_i] = stack.mean(axis=0)
else:
fused_verts[new_i] = (stack * (w / ws)[:, None]).sum(axis=0)
else: # "mean"
fused_verts[new_i] = stack.mean(axis=0)
old_to_new = {old: new for new, old in enumerate(kept)}
n_kept = len(kept)
edge_votes = np.zeros((n_kept, n_kept), dtype=np.int32)
for r, (_verts, edges, _lg) in enumerate(valid):
seen_pairs: set = set()
for (a, b) in edges:
if a < 0 or b < 0 or a == b:
continue
if a >= len(vertex_to_cluster[r]) or b >= len(vertex_to_cluster[r]):
continue
ca = vertex_to_cluster[r][a]
cb = vertex_to_cluster[r][b]
if ca == cb or ca not in old_to_new or cb not in old_to_new:
continue
i, j = old_to_new[ca], old_to_new[cb]
if i > j:
i, j = j, i
if (i, j) in seen_pairs:
continue
seen_pairs.add((i, j))
edge_votes[i, j] += 1
ii, jj = np.where(edge_votes >= e_support)
fused_edges = [(int(a), int(b)) for a, b in zip(ii.tolist(), jj.tolist())]
return fused_verts, fused_edges
def _wireframe_pair_distance(
va: np.ndarray, ea: List[Tuple[int, int]],
vb: np.ndarray, eb: List[Tuple[int, int]],
match_tau_m: float = 0.4,
) -> float:
"""Symmetric distance between two wireframes for medoid selection.
Uses Hungarian (optimal 1-1) vertex assignment, which is naturally
symmetric and aligned with how the HSS metric matches predictions to GT.
Components:
* **Vertex term** (metres, capped at ``match_tau_m``): solve the
rectangular linear-sum-assignment on the pairwise distance matrix
capped at ``match_tau_m``. Matched pair cost = capped distance;
unmatched leftover vertices (size mismatch) cost ``match_tau_m`` each.
Mean over ``max(|Va|, |Vb|)`` slots so the term lives in
``[0, match_tau_m]``.
* **Edge term** (Jaccard, in ``[0, 1]``): the Hungarian assignment
gives a 1-1 vertex map; use it to relabel B's edges into A's index
space (only for matches actually within ``match_tau_m``) and compute
``1 - IoU`` over the two edge sets.
Returns a single scalar; lower = more similar. Degenerate empty inputs
return ``+inf`` so they cannot be picked as the medoid.
"""
from scipy.optimize import linear_sum_assignment
va = np.asarray(va, dtype=np.float64).reshape(-1, 3)
vb = np.asarray(vb, dtype=np.float64).reshape(-1, 3)
Na, Nb = va.shape[0], vb.shape[0]
if Na == 0 or Nb == 0:
return float("inf")
D = np.linalg.norm(va[:, None, :] - vb[None, :, :], axis=-1)
D_capped = np.minimum(D, match_tau_m)
row_ind, col_ind = linear_sum_assignment(D_capped)
matched_cost = float(D_capped[row_ind, col_ind].sum())
n_unmatched = abs(Na - Nb) # leftover on the larger side
vertex_dist = (matched_cost + n_unmatched * match_tau_m) / max(Na, Nb)
# Map B β A via the Hungarian assignment, but only when the match is
# actually within tau (capped matches at exactly tau are unreliable).
b_to_a = -np.ones(Nb, dtype=np.int64)
for r, c in zip(row_ind, col_ind):
if D[r, c] <= match_tau_m:
b_to_a[c] = r
ea_norm = set((min(int(i), int(j)), max(int(i), int(j)))
for i, j in ea if i != j)
eb_mapped = set()
for (i, j) in eb:
if i == j or i < 0 or j < 0 or i >= Nb or j >= Nb:
continue
ai, aj = int(b_to_a[i]), int(b_to_a[j])
if ai < 0 or aj < 0 or ai == aj:
continue
eb_mapped.add((min(ai, aj), max(ai, aj)))
if not ea_norm and not eb_mapped:
edge_dist = 0.0
elif not ea_norm or not eb_mapped:
edge_dist = 1.0
else:
inter = len(ea_norm & eb_mapped)
union = len(ea_norm | eb_mapped)
edge_dist = 1.0 - (inter / union)
return vertex_dist + edge_dist
def _medoid_rank(
runs: List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]],
match_tau_m: float = 0.4,
) -> List[int]:
"""Return indices into ``runs`` sorted by centrality (lowest pairwise
Hungarian distance first β most-central run is index ``[0]``). Empty /
edgeless runs are excluded from the pairwise computation; if none qualify
the singleton list ``[longest_run_index]`` is returned. Always returns
at least one valid index when ``runs`` is non-empty."""
if not runs:
return []
candidates_idx = [r for r, (v, e, *_) in enumerate(runs)
if len(v) > 0 and len(e) > 0]
if not candidates_idx:
return [max(range(len(runs)),
key=lambda r: (len(runs[r][0]) if runs[r][0] is not None else -1,
len(runs[r][1]) if runs[r][1] is not None else -1))]
if len(candidates_idx) == 1:
return [candidates_idx[0]]
n = len(candidates_idx)
verts = [np.asarray(runs[idx][0], dtype=np.float64).reshape(-1, 3)
for idx in candidates_idx]
edges = [list(runs[idx][1]) for idx in candidates_idx]
dist = np.zeros((n, n), dtype=np.float64)
for i in range(n):
for j in range(i + 1, n):
d = _wireframe_pair_distance(
verts[i], edges[i], verts[j], edges[j],
match_tau_m=match_tau_m,
)
dist[i, j] = d
dist[j, i] = d
centrality = dist.sum(axis=1)
order = np.argsort(centrality, kind="stable")
return [candidates_idx[int(k)] for k in order]
def _medoid_select_idx(
runs: List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]],
match_tau_m: float = 0.4,
) -> int:
"""Return the index into ``runs`` of the medoid β the run whose wireframe
is most similar to the others by Hungarian-matched distance. Thin wrapper
around ``_medoid_rank`` that returns just the most-central index."""
ranking = _medoid_rank(runs, match_tau_m=match_tau_m)
return ranking[0] if ranking else 0
def _confidence_select_idx(
runs: List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]],
) -> int:
"""Return the index into ``runs`` of the highest mean-validity-logit run.
Skips empty / all-NaN runs in the scoring; falls back to the longest run
when no run has meaningful confidence."""
if not runs:
return 0
scored: List[Tuple[float, int]] = []
for i, (v, _e, logits) in enumerate(runs):
if v is None or len(v) == 0 or logits is None or len(logits) == 0:
continue
arr = np.asarray(logits, dtype=np.float64)
if not np.all(np.isfinite(arr)):
arr = arr[np.isfinite(arr)]
if arr.size == 0:
continue
scored.append((float(arr.mean()), i))
if not scored:
return max(range(len(runs)),
key=lambda r: (len(runs[r][0]) if runs[r][0] is not None else -1,
len(runs[r][1]) if runs[r][1] is not None else -1))
return max(scored, key=lambda t: t[0])[1]
def _refine_positions(
runs: List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]],
picked_idx: int,
match_tau_m: float,
aggregator: str = "mean",
member_indices: Optional[Sequence[int]] = None,
vertex_vote_frac: float = 0.0,
) -> Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]:
"""Position refinement on top of a single picked run.
Keep the picked run's vertices and edges (topology unchanged). For each
vertex ``v`` of the picked run, find its Hungarian-matched correspondent
in every other run (only matches within ``match_tau_m`` count), then
replace ``v`` with the per-axis ``aggregator`` of ``{v}`` βͺ
correspondents.
``aggregator`` β {"mean", "median", "wmean"}:
* ``"mean"`` (default) β simple average; lower variance under iid noise
but sensitive to outliers.
* ``"median"`` β per-axis median. Robust to a single bad correspondent
(e.g., an off-by-one Hungarian match at the Ο boundary).
* ``"wmean"`` β softmax-of-validity-logit weighted mean.
Rationale: vertex prediction is the dominant noise source (F1 hits HSS
harder than IoU). Selectors (medoid / confidence) pick a *vertex set*
that's already good; this step denoises each vertex's *position* by
aggregating with consensus detections from the other Nβ1 runs. Topology
(edges) is untouched so we never lose recall on edges.
Returns ``(verts_refined, edges_picked)``. Falls back to the picked
run's verts/edges verbatim when no refinement signal is available."""
from scipy.optimize import linear_sum_assignment
if aggregator not in ("median", "mean", "wmean"):
raise ValueError(
f"aggregator must be 'median', 'mean', or 'wmean', got {aggregator!r}")
if not runs:
return np.zeros((0, 3), dtype=np.float64), [], np.zeros((0,), dtype=np.int64)
picked_v_raw, picked_e_raw, picked_logits = runs[picked_idx]
picked_v = np.asarray(picked_v_raw, dtype=np.float64).reshape(-1, 3)
picked_e = list(picked_e_raw)
if picked_v.shape[0] == 0:
return picked_v, picked_e, np.zeros((0,), dtype=np.int64)
M = picked_v.shape[0]
picked_lg = (np.asarray(picked_logits, dtype=np.float64).reshape(-1)
if picked_logits is not None else np.zeros(M, dtype=np.float64))
if picked_lg.shape[0] != M:
picked_lg = np.zeros(M, dtype=np.float64)
# Per-picked-vertex correspondent positions and per-correspondent logits
# (used for 'wmean' aggregation). Picked run is always the first entry.
correspondents: List[List[np.ndarray]] = [[picked_v[i]] for i in range(M)]
corr_logits: List[List[float]] = [[float(picked_lg[i])] for i in range(M)]
if member_indices is None:
contributor_iter: List[int] = list(range(len(runs)))
else:
contributor_iter = list(member_indices)
if picked_idx not in contributor_iter:
contributor_iter.append(picked_idx)
# Voter set includes picked (self-vote on each vertex).
M_voters = max(1, len(set(contributor_iter)))
for j in contributor_iter:
if j == picked_idx or j < 0 or j >= len(runs):
continue
vj_raw, _ej, lj_raw = runs[j]
vj = np.asarray(vj_raw, dtype=np.float64).reshape(-1, 3)
if vj.shape[0] == 0:
continue
lj = (np.asarray(lj_raw, dtype=np.float64).reshape(-1)
if lj_raw is not None else np.zeros(vj.shape[0], dtype=np.float64))
if lj.shape[0] != vj.shape[0]:
lj = np.zeros(vj.shape[0], dtype=np.float64)
D = np.linalg.norm(picked_v[:, None, :] - vj[None, :, :], axis=-1)
D_capped = np.minimum(D, match_tau_m)
row_ind, col_ind = linear_sum_assignment(D_capped)
for r, c in zip(row_ind, col_ind):
if D[r, c] <= match_tau_m:
correspondents[r].append(vj[c])
corr_logits[r].append(float(lj[c]))
# Vertex consensus drop. A picked vertex survives iff at least
# ceil(M_voters * vertex_vote_frac) voters support it (including the
# picked run's self-vote).
if vertex_vote_frac > 0.0:
threshold = int(np.ceil(M_voters * float(vertex_vote_frac)))
keep_mask = np.array(
[len(correspondents[i]) >= threshold for i in range(M)],
dtype=bool,
)
if not keep_mask.any():
# Don't collapse to empty β fall back to keeping all picked verts.
keep_mask[:] = True
else:
keep_mask = np.ones(M, dtype=bool)
keep_idx = np.flatnonzero(keep_mask).astype(np.int64)
refined = np.empty((keep_idx.size, 3), dtype=np.float64)
for new_i, old_i in enumerate(keep_idx):
stack = np.stack(correspondents[int(old_i)], axis=0)
if aggregator == "median":
refined[new_i] = np.median(stack, axis=0)
elif aggregator == "mean":
refined[new_i] = stack.mean(axis=0)
else: # "wmean"
lg = np.asarray(corr_logits[int(old_i)], dtype=np.float64)
# Softmax over logits for stable positive weights; falls back to
# uniform when logits are all-equal / missing.
lg = lg - lg.max()
w = np.exp(lg)
w_sum = float(w.sum())
if w_sum <= 1e-12 or not np.isfinite(w_sum):
refined[new_i] = stack.mean(axis=0)
else:
w = w / w_sum
refined[new_i] = (stack * w[:, None]).sum(axis=0)
# Remap picked-run edges into the kept-vertex index space; drop edges
# whose endpoints didn't survive the vertex vote.
old_to_new = -np.ones(M, dtype=np.int64)
for new_i, old_i in enumerate(keep_idx):
old_to_new[int(old_i)] = new_i
edges_remapped: List[Tuple[int, int]] = []
for (a, b) in picked_e:
ia, ib = int(a), int(b)
if ia < 0 or ib < 0 or ia >= M or ib >= M or ia == ib:
continue
na, nb = int(old_to_new[ia]), int(old_to_new[ib])
if na < 0 or nb < 0 or na == nb:
continue
edges_remapped.append((na, nb))
return refined, edges_remapped, keep_idx
def _vote_edges(
runs: List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]],
picked_idx: int,
match_tau_m: float,
vote_frac: float = 0.5,
member_indices: Optional[Sequence[int]] = None,
keep_idx: Optional[np.ndarray] = None,
) -> List[Tuple[int, int]]:
"""Majority-vote edge refinement.
For each voter run, Hungarian-match its vertices to the picked run's
vertices (matches outside ``match_tau_m`` ignored), relabel its edges
into picked-vertex index space, and tally votes per ``(i, j)`` pair.
An edge survives if at least ``ceil(M * vote_frac)`` voters (out of
``M`` = ``len(member_indices)`` or ``len(runs)``) vote for it. The
picked run itself is always a voter β its own edges therefore enter
with one self-vote.
Returns the filtered edge list in picked-vertex index space.
"""
from scipy.optimize import linear_sum_assignment
if not runs:
return []
picked_v = np.asarray(runs[picked_idx][0], dtype=np.float64).reshape(-1, 3)
if picked_v.shape[0] == 0:
return list(runs[picked_idx][1])
if member_indices is None:
voters: List[int] = list(range(len(runs)))
else:
voters = [int(j) for j in member_indices if 0 <= int(j) < len(runs)]
if picked_idx not in voters:
voters.append(int(picked_idx))
M = max(1, len(voters))
threshold = int(np.ceil(M * float(vote_frac)))
votes: Dict[Tuple[int, int], int] = {}
Mp = picked_v.shape[0]
for j in voters:
vj_raw, ej_raw, _lj = runs[j]
vj = np.asarray(vj_raw, dtype=np.float64).reshape(-1, 3)
if j == picked_idx:
j_to_p = np.arange(Mp, dtype=np.int64)
else:
if vj.shape[0] == 0:
continue
D = np.linalg.norm(picked_v[:, None, :] - vj[None, :, :], axis=-1)
D_capped = np.minimum(D, match_tau_m)
row_ind, col_ind = linear_sum_assignment(D_capped)
j_to_p = -np.ones(vj.shape[0], dtype=np.int64)
for r, c in zip(row_ind, col_ind):
if D[r, c] <= match_tau_m:
j_to_p[c] = r
for (a, b) in ej_raw:
ia, ib = int(a), int(b)
if ia == ib or ia < 0 or ib < 0 or ia >= len(j_to_p) or ib >= len(j_to_p):
continue
pa, pb = int(j_to_p[ia]), int(j_to_p[ib])
if pa < 0 or pb < 0 or pa == pb:
continue
key = (min(pa, pb), max(pa, pb))
votes[key] = votes.get(key, 0) + 1
kept_old = [(int(i), int(j)) for (i, j), c in votes.items() if c >= threshold]
if not kept_old:
# Degenerate vote tally (e.g. only the picked run voted on edges with
# vote_frac > 1/M). Fall back to picked edges so we never lose all
# edges β F1 would zero out HSS.
kept_old = [(int(a), int(b)) for (a, b) in runs[picked_idx][1]
if int(a) != int(b)]
if keep_idx is None:
return kept_old
# Remap from picked-vertex index space β kept-vertex index space (the
# output of _refine_positions when vertex_vote_frac > 0 drops some
# picked vertices). Edges referencing dropped vertices are filtered out.
old_to_new = -np.ones(Mp, dtype=np.int64)
for new_i, old_i in enumerate(np.asarray(keep_idx).reshape(-1)):
oi = int(old_i)
if 0 <= oi < Mp:
old_to_new[oi] = new_i
out: List[Tuple[int, int]] = []
for (a, b) in kept_old:
na, nb = int(old_to_new[a]), int(old_to_new[b])
if na < 0 or nb < 0 or na == nb:
continue
out.append((min(na, nb), max(na, nb)))
return out
# ------------------------------------------------------------------
# 2D gestalt-mask reprojection features
# ------------------------------------------------------------------
# Pixels of these gestalt classes mark wireframe edges (lines).
_GESTALT_EDGE_NAMES = (
"ridge", "eave", "rake", "hip", "valley",
"fascia", "transition_line", "flashing", "step_flashing",
"ground_line", "soffit",
)
# Pixels of these classes mark wireframe vertices (line endpoints).
_GESTALT_VERT_NAMES = (
"apex", "eave_end_point", "flashing_end_point",
)
def _ids_from_class_names(names: Tuple[str, ...]) -> np.ndarray:
return np.array(
sorted(GESTALT_CLASSES.index(n) for n in names if n in GESTALT_CLASSES),
dtype=np.int64,
)
_EDGE_GESTALT_IDS = _ids_from_class_names(_GESTALT_EDGE_NAMES)
_VERT_GESTALT_IDS = _ids_from_class_names(_GESTALT_VERT_NAMES)
def _build_reprojection_views(
raw_sample: Dict[str, Any],
colmap_rec,
edge_dilate: int = 2,
vert_dilate: int = 4,
) -> List[Dict[str, Any]]:
"""Pre-compute per-view camera + dilated gestalt masks for reprojection.
Returns a list of dicts with keys
``R`` (3,3), ``t`` (3,), ``fx``, ``fy``, ``cx``, ``cy``, ``W``, ``H``,
``edge_mask`` and ``vert_mask`` (both uint8 HxW).
The masks are 1 where pixels belong to wireframe edge / vertex gestalt
classes (dilated by ``edge_dilate`` / ``vert_dilate`` 3x3 iterations to
tolerate small projection error and label boundary noise).
"""
try:
from scipy.ndimage import binary_dilation
except Exception:
binary_dilation = None # type: ignore
image_ids = raw_sample.get("image_ids", []) or []
gestalt_imgs = raw_sample.get("gestalt", []) or []
if not image_ids or not gestalt_imgs:
return []
colmap_by_name = {
col_img.name: col_img for col_img in colmap_rec.images.values()
}
structure = np.ones((3, 3), dtype=bool)
out: List[Dict[str, Any]] = []
for i, img_id in enumerate(image_ids):
if i >= len(gestalt_imgs) or gestalt_imgs[i] is None:
continue
col_img = _resolve_colmap_image(colmap_by_name, img_id)
if col_img is None:
continue
cam = _camera_for_image(colmap_rec, col_img)
cam_w = int(getattr(cam, "width", 0) or 0)
cam_h = int(getattr(cam, "height", 0) or 0)
if cam_w <= 0 or cam_h <= 0:
continue
try:
R, t = _cam_matrix_from_image(col_img)
R = np.asarray(R, dtype=np.float64).reshape(3, 3)
t = np.asarray(t, dtype=np.float64).reshape(3)
K = cam.calibration_matrix()
except Exception:
continue
try:
gest_np = _image_to_rgb_array(gestalt_imgs[i])
except Exception:
continue
ids = gestalt_img_to_ids(gest_np)
edge_tight = np.isin(ids, _EDGE_GESTALT_IDS)
vert_tight = np.isin(ids, _VERT_GESTALT_IDS)
edge_mask = edge_tight.copy()
vert_mask = vert_tight.copy()
if binary_dilation is not None:
if edge_dilate > 0 and edge_mask.any():
edge_mask = binary_dilation(
edge_mask, structure=structure, iterations=int(edge_dilate))
if vert_dilate > 0 and vert_mask.any():
vert_mask = binary_dilation(
vert_mask, structure=structure, iterations=int(vert_dilate))
H, W = ids.shape[:2]
out.append({
"R": R, "t": t,
"fx": float(K[0, 0]), "fy": float(K[1, 1]),
"cx": float(K[0, 2]), "cy": float(K[1, 2]),
"cam_w": float(cam_w), "cam_h": float(cam_h),
"W": int(W), "H": int(H),
"edge_mask": np.ascontiguousarray(edge_mask, dtype=bool),
"vert_mask": np.ascontiguousarray(vert_mask, dtype=bool),
"edge_mask_tight": np.ascontiguousarray(edge_tight, dtype=bool),
"vert_mask_tight": np.ascontiguousarray(vert_tight, dtype=bool),
"ids": np.ascontiguousarray(ids, dtype=np.int32),
})
return out
def _project_to_mask(
pts: np.ndarray,
view: Dict[str, Any],
which: str,
) -> Tuple[np.ndarray, np.ndarray]:
"""Project (N,3) world points into one view's mask.
Returns (in_view, hit) bool arrays of length N. ``in_view`` is True when
the point is in front of the camera and lands inside the image; ``hit``
is True when in_view AND the mask is set at the corresponding pixel.
"""
R = view["R"]; t = view["t"]
p_cam = pts @ R.T + t
z = p_cam[:, 2]
valid = z > 1e-6
u = np.empty_like(z); v = np.empty_like(z)
zsafe = np.where(valid, z, 1.0)
u_proj = p_cam[:, 0] / zsafe * view["fx"] + view["cx"]
v_proj = p_cam[:, 1] / zsafe * view["fy"] + view["cy"]
sx = view["W"] / view["cam_w"]; sy = view["H"] / view["cam_h"]
ui = np.rint(u_proj * sx).astype(np.int64)
vi = np.rint(v_proj * sy).astype(np.int64)
in_view = valid & (ui >= 0) & (ui < view["W"]) & (vi >= 0) & (vi < view["H"])
mask = view[which]
hit = np.zeros(pts.shape[0], dtype=bool)
if in_view.any():
idx = np.where(in_view)[0]
hit[idx] = mask[vi[idx], ui[idx]]
return in_view, hit
def _reprojection_features(
verts: np.ndarray,
edges: List[Tuple[int, int]],
views: List[Dict[str, Any]],
n_edge_samples: int = 8,
) -> Tuple[float, float, float, float]:
"""Return ``(vert_mean, vert_min, edge_mean, edge_min)`` β legacy stub.
Mostly kept for backwards-compatibility; new code should call
:func:`_reprojection_features_extended` for the richer per-vertex /
per-edge breakdown.
"""
res = _reprojection_features_extended(verts, edges, views, n_edge_samples)
return res["vert_mean"], res["vert_min"], res["edge_mean"], res["edge_min"]
def _reprojection_features_extended(
verts: np.ndarray,
edges: List[Tuple[int, int]],
views: List[Dict[str, Any]],
n_edge_samples: int = 8,
) -> Dict[str, Any]:
"""Full reprojection scoring with per-vertex / per-edge arrays.
Returns a dict with scalar fields:
vert_mean, vert_min, vert_worst3_mean, vert_bad_frac,
vert_soft_mean,
edge_mean, edge_min, edge_worst3_mean, edge_bad_frac,
edge_soft_mean,
endpoint_corner_mean, endpoint_corner_min,
plus arrays:
per_v (Nv,), per_e (Ne,)
All scalars in [0, 1]. "soft" uses the non-dilated (tight) masks;
"bad" thresholds at 0.1; "worst3" averages the 3 lowest scores.
"""
out = {
"vert_mean": 0.0, "vert_min": 0.0,
"vert_worst3_mean": 0.0, "vert_bad_frac": 0.0,
"vert_soft_mean": 0.0,
"edge_mean": 0.0, "edge_min": 0.0,
"edge_worst3_mean": 0.0, "edge_bad_frac": 0.0,
"edge_soft_mean": 0.0,
"endpoint_corner_mean": 0.0, "endpoint_corner_min": 0.0,
"per_v": np.zeros((0,), dtype=np.float64),
"per_e": np.zeros((0,), dtype=np.float64),
}
if not views or verts.size == 0:
return out
v = np.asarray(verts, dtype=np.float64).reshape(-1, 3)
Nv = v.shape[0]
# --- vertices: dilated + tight masks ---
vert_hits = np.zeros(Nv, dtype=np.float64)
vert_soft = np.zeros(Nv, dtype=np.float64)
vert_views = np.zeros(Nv, dtype=np.float64)
for view in views:
in_view, hit = _project_to_mask(v, view, "vert_mask")
_, hit_soft = _project_to_mask(v, view, "vert_mask_tight")
vert_views += in_view.astype(np.float64)
vert_hits += hit.astype(np.float64)
vert_soft += hit_soft.astype(np.float64)
denom = np.maximum(vert_views, 1.0)
per_v = np.where(vert_views > 0, vert_hits / denom, 0.0)
per_v_soft = np.where(vert_views > 0, vert_soft / denom, 0.0)
out["per_v"] = per_v
out["vert_mean"] = float(per_v.mean())
out["vert_min"] = float(per_v.min())
k3 = min(3, Nv)
out["vert_worst3_mean"] = float(np.sort(per_v)[:k3].mean()) if k3 else 0.0
out["vert_bad_frac"] = float(np.mean(per_v < 0.1))
out["vert_soft_mean"] = float(per_v_soft.mean())
if not edges:
return out
e_arr = np.asarray(edges, dtype=np.int64).reshape(-1, 2)
Ne = e_arr.shape[0]
# --- edges: sample interior, dilated + tight masks ---
ts = np.linspace(0.0, 1.0, n_edge_samples + 2)[1:-1]
a = v[e_arr[:, 0]]; b = v[e_arr[:, 1]]
samples = a[:, None, :] + (b - a)[:, None, :] * ts[None, :, None]
sflat = samples.reshape(-1, 3)
eh = np.zeros(Ne * n_edge_samples, dtype=np.float64)
eh_soft = np.zeros_like(eh)
ev = np.zeros_like(eh)
for view in views:
in_view, hit = _project_to_mask(sflat, view, "edge_mask")
_, hit_soft = _project_to_mask(sflat, view, "edge_mask_tight")
ev += in_view.astype(np.float64)
eh += hit.astype(np.float64)
eh_soft += hit_soft.astype(np.float64)
edenom = np.maximum(ev, 1.0)
per_sample = np.where(ev > 0, eh / edenom, 0.0)
per_sample_soft = np.where(ev > 0, eh_soft / edenom, 0.0)
per_e = per_sample.reshape(Ne, n_edge_samples).mean(axis=1)
per_e_soft = per_sample_soft.reshape(Ne, n_edge_samples).mean(axis=1)
out["per_e"] = per_e
out["edge_mean"] = float(per_e.mean())
out["edge_min"] = float(per_e.min())
k3e = min(3, Ne)
out["edge_worst3_mean"] = float(np.sort(per_e)[:k3e].mean()) if k3e else 0.0
out["edge_bad_frac"] = float(np.mean(per_e < 0.1))
out["edge_soft_mean"] = float(per_e_soft.mean())
# --- endpoint-on-corner: per-edge min(endpoint vertex scores) ---
if Nv > 0:
e_endpoint_min = np.minimum(per_v[e_arr[:, 0]], per_v[e_arr[:, 1]])
out["endpoint_corner_mean"] = float(e_endpoint_min.mean())
out["endpoint_corner_min"] = float(e_endpoint_min.min())
return out
def _stage1_displacement_features(
verts: np.ndarray,
s1_runs: Optional[List[Tuple[np.ndarray, Any, Any]]],
) -> Tuple[float, float, float]:
"""Distance from candidate vertices to nearest stage-1 prediction.
Returns ``(disp_mean, disp_max, disp_far_frac)``, where ``disp_far_frac``
is the fraction of candidate vertices > 0.5 m from any stage-1 vertex.
"""
if not s1_runs or verts.size == 0:
return 0.0, 0.0, 0.0
cv = np.asarray(verts, dtype=np.float64).reshape(-1, 3)
if cv.shape[0] == 0:
return 0.0, 0.0, 0.0
s1_v: List[np.ndarray] = []
for entry in s1_runs:
rv = entry[0] if isinstance(entry, (tuple, list)) else entry
rv = np.asarray(rv, dtype=np.float64).reshape(-1, 3)
if rv.shape[0] > 0:
s1_v.append(rv)
if not s1_v:
return 0.0, 0.0, 0.0
pool = np.concatenate(s1_v, axis=0)
D = np.linalg.norm(cv[:, None, :] - pool[None, :, :], axis=-1)
d_min = D.min(axis=1)
return (float(d_min.mean()), float(d_min.max()),
float(np.mean(d_min > 0.5)))
def _connectivity_features(
verts: np.ndarray,
edges: List[Tuple[int, int]],
) -> Tuple[float, float, float]:
"""``(n_components_norm, cycle_rank_norm, degree_entropy)``.
* ``n_components_norm`` = (n_components - 1) / max(1, Nv) β 0 when fully
connected, grows with disconnected fragments.
* ``cycle_rank_norm`` = (Ne - Nv + n_components) / max(1, Nv) β Betti-1
density; very low (tree-like) or very high (over-connected) are both
suspicious.
* ``degree_entropy`` = Shannon entropy of the degree distribution in nats.
"""
v = np.asarray(verts, dtype=np.float64).reshape(-1, 3)
Nv = v.shape[0]
if Nv == 0 or not edges:
return 0.0, 0.0, 0.0
e_arr = np.asarray(edges, dtype=np.int64).reshape(-1, 2)
Ne = e_arr.shape[0]
adj: List[List[int]] = [[] for _ in range(Nv)]
for a, b in e_arr:
if 0 <= a < Nv and 0 <= b < Nv and a != b:
adj[a].append(b); adj[b].append(a)
visited = [False] * Nv
n_components = 0
for s in range(Nv):
if visited[s]:
continue
n_components += 1
stack = [s]
while stack:
u = stack.pop()
if visited[u]: continue
visited[u] = True
for w in adj[u]:
if not visited[w]:
stack.append(w)
cycle_rank = Ne - Nv + n_components
deg = np.array([len(a) for a in adj], dtype=np.float64)
p = np.bincount(deg.astype(np.int64))
p = p / p.sum() if p.sum() > 0 else p
p = p[p > 0]
deg_entropy = float(-(p * np.log(p)).sum()) if p.size > 0 else 0.0
return (
float((n_components - 1) / max(1, Nv)),
float(cycle_rank / max(1, Nv)),
deg_entropy,
)
def _symmetry_residual(
verts: np.ndarray,
edges: List[Tuple[int, int]],
) -> float:
"""Best reflection-plane residual normalised by mean edge length.
Computes PCA on the candidate vertices, tries reflecting across each of
the three principal planes (normal = each eigenvector through the
centroid), Hungarian-matches reflected vs. original verts, and returns
the minimum mean matched distance / mean edge length. Lower = more
symmetric. 0 when the wireframe has fewer than 4 vertices or any edge.
"""
from scipy.optimize import linear_sum_assignment
v = np.asarray(verts, dtype=np.float64).reshape(-1, 3)
Nv = v.shape[0]
if Nv < 4 or not edges:
return 0.0
e_arr = np.asarray(edges, dtype=np.int64).reshape(-1, 2)
lengths = np.linalg.norm(v[e_arr[:, 0]] - v[e_arr[:, 1]], axis=1)
mean_len = float(lengths.mean()) if lengths.size > 0 else 0.0
if mean_len < 1e-6:
return 0.0
centroid = v.mean(axis=0)
Q = v - centroid
try:
_, S, Vt = np.linalg.svd(Q, full_matrices=False)
except np.linalg.LinAlgError:
return 0.0
axes = Vt # rows are unit principal directions
best = float("inf")
for k in range(min(3, axes.shape[0])):
n = axes[k]
# Reflect Q across plane through centroid with normal n.
ref = Q - 2.0 * (Q @ n)[:, None] * n[None, :]
D = np.linalg.norm(Q[:, None, :] - ref[None, :, :], axis=-1)
row, col = linear_sum_assignment(D)
matched_d = D[row, col]
cost = float(matched_d.mean())
if cost < best:
best = cost
if not np.isfinite(best):
return 0.0
return float(best / mean_len)
def _per_edge_class_consistency(
verts: np.ndarray,
edges: List[Tuple[int, int]],
views: List[Dict[str, Any]],
n_edge_samples: int = 8,
) -> Tuple[float, float]:
"""Gestalt-class purity per edge, aggregated to candidate-level stats.
For each edge we sample interior points, project to each view, and look
up the gestalt-class id at the pixel. Across all (sample Γ view) hits we
take the modal class and define edge-purity as the fraction of hits
belonging to that mode. Returns ``(mean_purity, high_purity_frac)``
where ``high_purity_frac = mean(purity > 0.5)``. Both are 0 with no
views or edges.
"""
if not views or not edges or verts.size == 0:
return 0.0, 0.0
v = np.asarray(verts, dtype=np.float64).reshape(-1, 3)
e_arr = np.asarray(edges, dtype=np.int64).reshape(-1, 2)
Ne = e_arr.shape[0]
ts = np.linspace(0.0, 1.0, n_edge_samples + 2)[1:-1]
a = v[e_arr[:, 0]]; b = v[e_arr[:, 1]]
samples = a[:, None, :] + (b - a)[:, None, :] * ts[None, :, None]
sflat = samples.reshape(-1, 3)
# (Ne*S, V) classes; -1 = no hit
cls_per_view: List[np.ndarray] = []
for view in views:
R = view["R"]; t = view["t"]
p_cam = sflat @ R.T + t
z = p_cam[:, 2]
valid = z > 1e-6
zsafe = np.where(valid, z, 1.0)
u_proj = p_cam[:, 0] / zsafe * view["fx"] + view["cx"]
v_proj = p_cam[:, 1] / zsafe * view["fy"] + view["cy"]
sx = view["W"] / view["cam_w"]; sy = view["H"] / view["cam_h"]
ui = np.rint(u_proj * sx).astype(np.int64)
vi = np.rint(v_proj * sy).astype(np.int64)
in_view = (valid & (ui >= 0) & (ui < view["W"])
& (vi >= 0) & (vi < view["H"]))
cls = -np.ones(sflat.shape[0], dtype=np.int64)
if in_view.any():
idx = np.where(in_view)[0]
cls[idx] = view["ids"][vi[idx], ui[idx]]
# Only keep edge-class hits (other classes are background-ish noise)
is_edge_cls = np.isin(cls, _EDGE_GESTALT_IDS)
cls = np.where(is_edge_cls, cls, -1)
cls_per_view.append(cls)
if not cls_per_view:
return 0.0, 0.0
cls_stack = np.stack(cls_per_view, axis=0).reshape(
len(views), Ne, n_edge_samples)
# For each edge: flatten (V*S) hits, drop -1, compute mode purity.
purities = np.zeros(Ne, dtype=np.float64)
for e_i in range(Ne):
hits = cls_stack[:, e_i, :].reshape(-1)
hits = hits[hits >= 0]
if hits.size == 0:
purities[e_i] = 0.0
continue
counts = np.bincount(hits.astype(np.int64))
purities[e_i] = float(counts.max()) / float(hits.size)
return float(purities.mean()), float(np.mean(purities > 0.5))
def _structural_features(
verts: np.ndarray,
edges: List[Tuple[int, int]],
) -> Tuple[float, float]:
"""Cheap structural priors: degree-1 vertex fraction + edge-length CV."""
v = np.asarray(verts, dtype=np.float64).reshape(-1, 3)
Nv = v.shape[0]
if Nv == 0 or not edges:
return 0.0, 0.0
e_arr = np.asarray(edges, dtype=np.int64).reshape(-1, 2)
deg = np.zeros(Nv, dtype=np.int64)
for a, b in e_arr:
if 0 <= a < Nv: deg[a] += 1
if 0 <= b < Nv: deg[b] += 1
degree1_frac = float(np.mean(deg == 1))
lengths = np.linalg.norm(v[e_arr[:, 0]] - v[e_arr[:, 1]], axis=1)
mean_len = float(lengths.mean()) if lengths.size > 0 else 0.0
cv = float(lengths.std() / mean_len) if mean_len > 1e-6 else 0.0
return degree1_frac, cv
def _coplanarity_score(
verts: np.ndarray,
edges: List[Tuple[int, int]],
max_cycles: int = 64,
) -> float:
"""Median plane-fit residual of 4-cycles, mapped to [0, 1] (higher = flatter).
Buildings are mostly composed of planar quads (roof faces, wall panels).
For every length-4 cycle in the wireframe we compute the third singular
value of the centred (4,3) vertex matrix β the out-of-plane spread β
normalised by the cycle's average edge length. The median residual is
then mapped to ``exp(-5*r)`` so the feature is in [0, 1] with 1 = perfectly
planar. Returns 0 when no cycles exist.
"""
Nv = verts.shape[0]
if Nv < 4 or not edges:
return 0.0
adj = [set() for _ in range(Nv)]
for a, b in edges:
a, b = int(a), int(b)
if 0 <= a < Nv and 0 <= b < Nv and a != b:
adj[a].add(b); adj[b].add(a)
cycles: List[Tuple[int, int, int, int]] = []
for u in range(Nv):
for v_idx in range(u + 1, Nv):
common = adj[u] & adj[v_idx]
if len(common) < 2:
continue
comm = sorted(c for c in common if c != u and c != v_idx)
for i in range(len(comm)):
for j in range(i + 1, len(comm)):
cycles.append((u, comm[i], v_idx, comm[j]))
if len(cycles) >= max_cycles:
break
if len(cycles) >= max_cycles: break
if len(cycles) >= max_cycles: break
if len(cycles) >= max_cycles: break
if not cycles:
return 0.0
vals = []
for cyc in cycles:
pts = verts[list(cyc)]
centroid = pts.mean(axis=0)
Q = pts - centroid
try:
S = np.linalg.svd(Q, compute_uv=False)
except np.linalg.LinAlgError:
continue
if S.size < 3:
continue
dev = float(S[-1])
perim = 0.0
for k in range(4):
a, b = cyc[k], cyc[(k + 1) % 4]
perim += float(np.linalg.norm(verts[a] - verts[b]))
mean_len = perim / 4.0
if mean_len < 1e-6:
continue
vals.append(dev / mean_len)
if not vals:
return 0.0
return float(np.exp(-5.0 * float(np.median(vals))))
def _junction_angle_dev(
verts: np.ndarray,
edges: List[Tuple[int, int]],
) -> float:
"""Mean angular deviation of edge-pair junctions from {90Β°, 180Β°} in radians.
At each vertex with degree >= 2, we compute the angle between every pair
of incident edges and take the smaller deviation to 90Β° or 180Β° (the two
angles that dominate roof/wall geometry). Lower is better; 0 means every
junction sits exactly at a right or straight angle.
"""
Nv = verts.shape[0]
if Nv == 0 or not edges:
return 0.0
nbrs: List[List[int]] = [[] for _ in range(Nv)]
for a, b in edges:
a, b = int(a), int(b)
if 0 <= a < Nv and 0 <= b < Nv and a != b:
nbrs[a].append(b); nbrs[b].append(a)
devs: List[float] = []
for u in range(Nv):
if len(nbrs[u]) < 2:
continue
dirs: List[np.ndarray] = []
for v_idx in nbrs[u]:
d = verts[v_idx] - verts[u]
n = float(np.linalg.norm(d))
if n > 1e-6:
dirs.append(d / n)
for i in range(len(dirs)):
for j in range(i + 1, len(dirs)):
c = float(np.clip(np.dot(dirs[i], dirs[j]), -1.0, 1.0))
ang = float(np.arccos(c))
devs.append(min(abs(ang - np.pi / 2), abs(ang - np.pi)))
if not devs:
return 0.0
return float(np.mean(devs))
def _principal_axis_features(
verts: np.ndarray,
edges: List[Tuple[int, int]],
cos_thresh: float = 0.9659, # cos(15Β°)
) -> Tuple[float, float]:
"""Manhattan structure features from per-edge direction PCA.
Returns ``(manhattan_frac, top1_frac)``:
* ``manhattan_frac`` β fraction of edges within 15Β° of any of the top-3
eigenvectors of the symmetric second-moment matrix ``sum_i d_i d_i^T``
(antipodal-symmetric: signs don't matter).
* ``top1_frac`` β same, but only against the *dominant* eigenvector;
a proxy for "fraction of edges aligned with the building's principal
axis" (often vertical in COLMAP world).
"""
if not edges or verts.shape[0] == 0:
return 0.0, 0.0
e_arr = np.asarray(edges, dtype=np.int64).reshape(-1, 2)
if e_arr.shape[0] == 0:
return 0.0, 0.0
d = verts[e_arr[:, 1]] - verts[e_arr[:, 0]]
nrm = np.linalg.norm(d, axis=1)
valid = nrm > 1e-6
if not valid.any():
return 0.0, 0.0
u = d[valid] / nrm[valid, None]
M = u.T @ u
try:
eigvals, eigvecs = np.linalg.eigh(M)
except np.linalg.LinAlgError:
return 0.0, 0.0
order = np.argsort(-eigvals)
eigvecs = eigvecs[:, order]
dots = np.abs(u @ eigvecs)
max_any = dots.max(axis=1)
max_top1 = dots[:, 0]
return (float(np.mean(max_any >= cos_thresh)),
float(np.mean(max_top1 >= cos_thresh)))
_RANKER_FEATURE_NAMES = [
"n_v",
"n_e",
"edge_density",
"logit_mean",
"logit_std",
"logit_min",
"logit_max",
"vertex_support_mean",
"vertex_support_std",
"vertex_support_min",
"edge_support_mean",
"edge_support_max",
"centrality_mean",
"centrality_min",
"centrality_rank",
"is_raw_member",
"is_medoid_source",
"is_conf_source",
"is_refined",
"uses_edge_vote",
"uses_add_edges",
"uses_topk",
"source_idx",
# --- 2D reprojection + structural priors (added) ---
"vert_reproj_mean",
"vert_reproj_min",
"edge_reproj_mean",
"edge_reproj_min",
"degree1_frac",
"edge_length_cv",
# --- geometric priors (added) ---
"coplanarity_score",
"junction_angle_dev",
"manhattan_frac",
"principal_axis_align",
# --- v5 features (selected from v4 ablation: only those that survived
# 5-fold CV with positive lift in addition to v3) ---
"s1_disp_far_frac",
"degree_entropy",
"symmetry_residual",
]
def _edge_key_set(edges: List[Tuple[int, int]]) -> set:
out = set()
for a, b in edges:
ia, ib = int(a), int(b)
if ia == ib:
continue
out.add((min(ia, ib), max(ia, ib)))
return out
def _candidate_logits_from_source(
runs: List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]],
source_idx: int,
keep_idx: Optional[np.ndarray],
n_verts: int,
) -> np.ndarray:
if source_idx < 0 or source_idx >= len(runs):
return np.zeros((n_verts,), dtype=np.float64)
lg = np.asarray(runs[source_idx][2], dtype=np.float64).reshape(-1)
if keep_idx is not None and lg.size > 0:
ki = np.asarray(keep_idx, dtype=np.int64).reshape(-1)
valid = (ki >= 0) & (ki < lg.size)
if valid.all() and ki.size == n_verts:
return lg[ki]
if lg.size == n_verts:
return lg
if lg.size == 0:
return np.zeros((n_verts,), dtype=np.float64)
return np.full((n_verts,), float(np.nanmean(lg)), dtype=np.float64)
def _candidate_support_features(
verts: np.ndarray,
edges: List[Tuple[int, int]],
runs: List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]],
match_tau_m: float,
) -> Tuple[float, float, float, float, float]:
"""Agreement features for one candidate against the ensemble members."""
from scipy.optimize import linear_sum_assignment
v = np.asarray(verts, dtype=np.float64).reshape(-1, 3)
Nv = v.shape[0]
if Nv == 0 or not runs:
return 0.0, 0.0, 0.0, 0.0, 0.0
v_support = np.zeros((Nv,), dtype=np.float64)
e_keys = _edge_key_set(edges)
e_votes: Dict[Tuple[int, int], int] = {k: 0 for k in e_keys}
for rv_raw, re_raw, _rlg in runs:
rv = np.asarray(rv_raw, dtype=np.float64).reshape(-1, 3)
if rv.shape[0] == 0:
continue
D = np.linalg.norm(v[:, None, :] - rv[None, :, :], axis=-1)
D_capped = np.minimum(D, match_tau_m)
row_ind, col_ind = linear_sum_assignment(D_capped)
r_to_c = -np.ones(rv.shape[0], dtype=np.int64)
for r, c in zip(row_ind, col_ind):
if D[r, c] <= match_tau_m:
v_support[r] += 1.0
r_to_c[c] = r
if e_keys:
seen = set()
for a, b in re_raw:
ia, ib = int(a), int(b)
if (ia == ib or ia < 0 or ib < 0
or ia >= r_to_c.size or ib >= r_to_c.size):
continue
ca, cb = int(r_to_c[ia]), int(r_to_c[ib])
if ca < 0 or cb < 0 or ca == cb:
continue
key = (min(ca, cb), max(ca, cb))
if key in e_votes:
seen.add(key)
for key in seen:
e_votes[key] += 1
denom = float(max(1, len(runs)))
v_frac = v_support / denom
if e_votes:
e_frac = np.asarray(list(e_votes.values()), dtype=np.float64) / denom
e_mean = float(e_frac.mean())
e_max = float(e_frac.max())
else:
e_mean = 0.0
e_max = 0.0
return (
float(v_frac.mean()),
float(v_frac.std()),
float(v_frac.min()),
e_mean,
e_max,
)
def _candidate_feature_vector(
name: str,
verts: np.ndarray,
edges: List[Tuple[int, int]],
logits: np.ndarray,
runs: List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]],
match_tau_m: float,
source_idx: int,
medoid_idx: int,
confidence_idx: int,
ranking: List[int],
is_raw_member: bool,
is_refined: bool,
uses_edge_vote: bool,
uses_add_edges: bool,
uses_topk: bool,
reproj_views: Optional[List[Dict[str, Any]]] = None,
s1_runs: Optional[List[Tuple[np.ndarray, Any, Any]]] = None,
) -> np.ndarray:
v = np.asarray(verts, dtype=np.float64).reshape(-1, 3)
e = list(edges)
lg = np.asarray(logits, dtype=np.float64).reshape(-1)
lg = lg[np.isfinite(lg)]
if lg.size == 0:
lg = np.zeros((1,), dtype=np.float64)
n_v = float(v.shape[0])
n_e = float(len(e))
max_edges = max(1.0, n_v * max(0.0, n_v - 1.0) / 2.0)
v_sup_mean, v_sup_std, v_sup_min, e_sup_mean, e_sup_max = (
_candidate_support_features(v, e, runs, match_tau_m)
)
dists = []
for rv, re, _rl in runs:
try:
dists.append(_wireframe_pair_distance(
v, e, np.asarray(rv, dtype=np.float64), list(re),
match_tau_m=match_tau_m,
))
except Exception:
continue
d_arr = np.asarray([d for d in dists if np.isfinite(d)], dtype=np.float64)
if d_arr.size == 0:
centrality_mean = 10.0
centrality_min = 10.0
else:
centrality_mean = float(d_arr.mean())
centrality_min = float(d_arr.min())
rank_pos = float(len(ranking))
if source_idx in ranking:
rank_pos = float(ranking.index(source_idx))
if reproj_views:
vr_mean, vr_min, er_mean, er_min = _reprojection_features(
v, e, reproj_views,
)
else:
vr_mean = vr_min = er_mean = er_min = 0.0
deg1_frac, edge_len_cv = _structural_features(v, e)
coplanarity = _coplanarity_score(v, e)
junction_dev = _junction_angle_dev(v, e)
manhattan_frac, princ_axis_align = _principal_axis_features(v, e)
_, _, s1_disp_far = _stage1_displacement_features(v, s1_runs)
_, _, deg_ent = _connectivity_features(v, e)
sym_res = _symmetry_residual(v, e)
feats = np.asarray([
n_v / 64.0,
n_e / 128.0,
n_e / max_edges,
float(lg.mean()),
float(lg.std()),
float(lg.min()),
float(lg.max()),
v_sup_mean,
v_sup_std,
v_sup_min,
e_sup_mean,
e_sup_max,
centrality_mean,
centrality_min,
rank_pos / float(max(1, len(ranking))),
1.0 if is_raw_member else 0.0,
1.0 if source_idx == medoid_idx else 0.0,
1.0 if source_idx == confidence_idx else 0.0,
1.0 if is_refined else 0.0,
1.0 if uses_edge_vote else 0.0,
1.0 if uses_add_edges else 0.0,
1.0 if uses_topk else 0.0,
float(source_idx) / float(max(1, len(runs) - 1)),
vr_mean,
vr_min,
er_mean,
er_min,
deg1_frac,
edge_len_cv,
coplanarity,
junction_dev,
manhattan_frac,
princ_axis_align,
# --- v5 features ---
s1_disp_far,
deg_ent,
sym_res,
], dtype=np.float64)
if feats.shape[0] != len(_RANKER_FEATURE_NAMES):
raise RuntimeError(f"ranker feature mismatch for {name}")
return feats
def _ensemble_heuristic_score(features: np.ndarray) -> float:
f = {k: float(v) for k, v in zip(_RANKER_FEATURE_NAMES, features)}
return (
1.20 * f["vertex_support_mean"]
+ 0.55 * f["edge_support_mean"]
+ 0.08 * f["logit_mean"]
- 0.30 * f["centrality_mean"]
- 0.08 * abs(f["n_v"] - 0.33)
- 0.04 * abs(f["n_e"] - 0.18)
+ 0.04 * f["is_refined"]
+ 0.02 * f["is_medoid_source"]
- 0.03 * f["uses_edge_vote"]
)
def _score_ranker_candidate(
features: np.ndarray,
ranker: Optional[Dict[str, np.ndarray]],
) -> float:
if ranker is None:
return _ensemble_heuristic_score(features)
mean = np.asarray(ranker["mean"], dtype=np.float64)
scale = np.asarray(ranker["scale"], dtype=np.float64)
weights = np.asarray(ranker["weights"], dtype=np.float64)
x = (features - mean) / np.maximum(scale, 1e-8)
return float(np.dot(x, weights[1:]) + weights[0])
def _fuse_topk_candidates(
candidates: List[Dict[str, Any]],
scores: np.ndarray,
k: int,
match_tau_m: float,
edge_vote_frac: float,
) -> Tuple[np.ndarray, List[Tuple[int, int]], int]:
"""Fuse the top-K ranker-scored candidates into one wireframe.
Strategy mirrors ``medoid_mean_add`` but applies it to the top-K
*ranker-quality-filtered* candidates rather than all ensemble members:
1. Sort candidates by ``scores`` descending; keep ``top_k = min(k, len)``.
2. Pivot = top-1 candidate. For each pivot vertex, Hungarian-match to
each of the other top-K candidates' vertices (cap Ο = ``match_tau_m``)
and average the positions of matched correspondents.
3. Union pivot's edges with edges voted by at least
``edge_vote_frac`` of the top-K (counted on matched vertex pairs).
Returns ``(verts, edges, best_idx)`` where ``best_idx`` is the position
of the top-1 candidate in the input list (for diagnostics).
"""
scores_arr = np.asarray(scores, dtype=np.float64).reshape(-1)
n = scores_arr.size
if n == 0:
return np.zeros((0, 3), dtype=np.float64), [], 0
k_eff = max(1, min(int(k), n))
order = np.argsort(-scores_arr)[:k_eff].astype(np.int64)
best_idx = int(order[0])
if k_eff == 1:
c = candidates[best_idx]
return (np.asarray(c["verts"], dtype=np.float64),
list(c["edges"]), best_idx)
runs: List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]] = []
for j in order:
c = candidates[int(j)]
v = np.asarray(c["verts"], dtype=np.float64).reshape(-1, 3)
e = list(c["edges"])
lg_src = c.get("logits", None)
lg = (np.asarray(lg_src, dtype=np.float64).reshape(-1)
if lg_src is not None and len(np.asarray(lg_src).ravel()) == v.shape[0]
else np.zeros((v.shape[0],), dtype=np.float64))
runs.append((v, e, lg))
refined_v, refined_e, keep_idx = _refine_positions(
runs, picked_idx=0, match_tau_m=match_tau_m,
aggregator="mean", member_indices=None, vertex_vote_frac=0.0,
)
voted = _vote_edges(
runs, picked_idx=0, match_tau_m=match_tau_m,
vote_frac=edge_vote_frac, member_indices=None,
keep_idx=keep_idx,
)
edge_set = set()
for (a, b) in refined_e:
ia, ib = int(a), int(b)
if ia == ib: continue
edge_set.add((min(ia, ib), max(ia, ib)))
for (a, b) in voted:
ia, ib = int(a), int(b)
if ia == ib: continue
edge_set.add((min(ia, ib), max(ia, ib)))
return refined_v, sorted(edge_set), best_idx
def _load_ensemble_ranker(path: Optional[str]) -> Optional[Dict[str, np.ndarray]]:
if not path:
return None
p = Path(path)
if not p.exists():
print(f"[ranker] {p} not found; using built-in heuristic scorer", flush=True)
return None
data = np.load(p, allow_pickle=False)
names = [str(x) for x in data["feature_names"].tolist()]
if names != _RANKER_FEATURE_NAMES:
print(
f"[ranker] feature-name mismatch in {p} "
f"(have {len(names)}-d, expected {len(_RANKER_FEATURE_NAMES)}-d); "
f"falling back to built-in heuristic scorer", flush=True)
return None
ranker = {
"mean": np.asarray(data["mean"], dtype=np.float64),
"scale": np.asarray(data["scale"], dtype=np.float64),
"weights": np.asarray(data["weights"], dtype=np.float64),
}
print(f"[ranker] loaded {p}", flush=True)
return ranker
def _build_ranker_candidates(
runs: List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]],
match_tau_m: float,
edge_vote_frac: float,
ranking: Optional[List[int]] = None,
medoid_idx: Optional[int] = None,
confidence_idx: Optional[int] = None,
reproj_views: Optional[List[Dict[str, Any]]] = None,
s1_runs: Optional[List[Tuple[np.ndarray, Any, Any]]] = None,
) -> List[Dict[str, Any]]:
"""Produce candidate wireframes for learned/heuristic ensemble selection."""
if not runs:
return []
if ranking is None:
ranking = _medoid_rank(runs, match_tau_m=match_tau_m)
medoid_idx = int(medoid_idx if medoid_idx is not None
else (ranking[0] if ranking else 0))
confidence_idx = int(confidence_idx if confidence_idx is not None
else _confidence_select_idx(runs))
candidates: List[Dict[str, Any]] = []
def add_candidate(
name: str,
verts: np.ndarray,
edges: List[Tuple[int, int]],
source_idx: int,
keep_idx: Optional[np.ndarray],
is_raw_member: bool,
is_refined: bool,
uses_edge_vote: bool,
uses_add_edges: bool,
uses_topk: bool,
) -> None:
v = np.asarray(verts, dtype=np.float64).reshape(-1, 3)
e = [(int(a), int(b)) for a, b in edges if int(a) != int(b)]
if v.shape[0] == 0 or len(e) == 0:
return
logits = _candidate_logits_from_source(runs, source_idx, keep_idx, v.shape[0])
features = _candidate_feature_vector(
name=name, verts=v, edges=e, logits=logits, runs=runs,
match_tau_m=match_tau_m, source_idx=source_idx,
medoid_idx=medoid_idx, confidence_idx=confidence_idx,
ranking=ranking, is_raw_member=is_raw_member,
is_refined=is_refined, uses_edge_vote=uses_edge_vote,
uses_add_edges=uses_add_edges, uses_topk=uses_topk,
reproj_views=reproj_views,
s1_runs=s1_runs,
)
candidates.append({
"name": name,
"verts": v,
"edges": e,
"logits": logits,
"features": features,
"source_idx": int(source_idx),
})
for i, (v, e, _lg) in enumerate(runs):
add_candidate(
name=f"member_{i:02d}", verts=v, edges=list(e), source_idx=i,
keep_idx=None, is_raw_member=True, is_refined=False,
uses_edge_vote=False, uses_add_edges=False, uses_topk=False,
)
def refined_candidates(source_idx: int, label: str, member_indices: Optional[List[int]]) -> None:
uses_topk = member_indices is not None
rv, re, keep_idx = _refine_positions(
runs, source_idx, match_tau_m=match_tau_m,
aggregator="mean", member_indices=member_indices,
vertex_vote_frac=0.0,
)
add_candidate(
name=f"{label}_mean_picked" + ("_topk" if uses_topk else ""),
verts=rv, edges=re, source_idx=source_idx, keep_idx=keep_idx,
is_raw_member=False, is_refined=True,
uses_edge_vote=False, uses_add_edges=False, uses_topk=uses_topk,
)
voted = _vote_edges(
runs, source_idx, match_tau_m=match_tau_m,
vote_frac=edge_vote_frac, member_indices=member_indices,
keep_idx=keep_idx,
)
add_candidate(
name=f"{label}_mean_voted" + ("_topk" if uses_topk else ""),
verts=rv, edges=voted, source_idx=source_idx, keep_idx=keep_idx,
is_raw_member=False, is_refined=True,
uses_edge_vote=True, uses_add_edges=False, uses_topk=uses_topk,
)
add_edges = sorted(_edge_key_set(re) | _edge_key_set(voted))
add_candidate(
name=f"{label}_mean_add" + ("_topk" if uses_topk else ""),
verts=rv, edges=add_edges, source_idx=source_idx, keep_idx=keep_idx,
is_raw_member=False, is_refined=True,
uses_edge_vote=True, uses_add_edges=True, uses_topk=uses_topk,
)
refined_candidates(medoid_idx, "medoid", None)
if confidence_idx != medoid_idx:
refined_candidates(confidence_idx, "confidence", None)
for k in (5, 8):
if ranking and len(ranking) >= k:
members = list(ranking[:k])
if medoid_idx not in members:
members.append(medoid_idx)
refined_candidates(medoid_idx, f"medoid_top{k}", members)
return candidates
def train_ensemble_ranker_jsonl(jsonl_path: str, out_path: str, l2: float = 1e-2) -> None:
"""Fit a tiny ridge ranker from within-sample candidate comparisons.
Absolute HSS is dominated by sample difficulty ("easy building" vs.
"hard building"), but inference only needs to choose among candidates for
the same sample. Training on pairwise feature differences cancels that
nuisance and directly optimizes the ordering we care about.
"""
rows_by_sample: Dict[str, List[Tuple[np.ndarray, float]]] = {}
with open(jsonl_path, "r") as f:
for line in f:
line = line.strip()
if not line:
continue
row = json.loads(line)
feats = np.asarray(row.get("features", []), dtype=np.float64)
if feats.shape[0] != len(_RANKER_FEATURE_NAMES):
continue
y = float(row.get("hss", 0.0))
if not np.isfinite(y) or not np.all(np.isfinite(feats)):
continue
sid = str(row.get("order_id", row.get("sample_index", "")))
rows_by_sample.setdefault(sid, []).append((feats, y))
xs = [feat for rows in rows_by_sample.values() for feat, _y in rows]
if len(xs) < 10 or len(rows_by_sample) < 2:
raise SystemExit(
f"[ranker/train] need >=10 rows and >=2 samples, got "
f"{len(xs)} rows / {len(rows_by_sample)} samples")
X = np.stack(xs, axis=0)
mean = X.mean(axis=0)
scale = X.std(axis=0)
scale[scale < 1e-8] = 1.0
pair_x: List[np.ndarray] = []
pair_y: List[float] = []
for rows in rows_by_sample.values():
if len(rows) < 2:
continue
feats = [(feat - mean) / scale for feat, _y in rows]
ys = [float(y) for _feat, y in rows]
for i in range(len(rows)):
for j in range(i + 1, len(rows)):
dy = ys[i] - ys[j]
if abs(dy) < 1e-9:
continue
pair_x.append(feats[i] - feats[j])
pair_y.append(dy)
if len(pair_x) < 10:
raise SystemExit(f"[ranker/train] need >=10 informative pairs, got {len(pair_x)}")
DX = np.stack(pair_x, axis=0)
dy = np.asarray(pair_y, dtype=np.float64)
reg = np.eye(DX.shape[1], dtype=np.float64) * float(l2)
w = np.linalg.solve(DX.T @ DX + reg, DX.T @ dy)
weights = np.concatenate([[0.0], w], axis=0)
pred = DX @ w
mse = float(np.mean((pred - dy) ** 2))
corr = float(np.corrcoef(pred, dy)[0, 1]) if pred.std() > 0 and dy.std() > 0 else 0.0
# Grouped oracle estimate: how good would this ranker be on the same dump?
# This is optimistic when train==eval, but useful as a smoke test.
picked = []
oracle = []
for rows in rows_by_sample.values():
scored = []
for feat, y in rows:
x = np.concatenate([[1.0], (feat - mean) / scale])
scored.append((float(np.dot(x, weights)), float(y)))
picked.append(max(scored, key=lambda t: t[0])[1])
oracle.append(max(scored, key=lambda t: t[1])[1])
np.savez(
out_path,
feature_names=np.asarray(_RANKER_FEATURE_NAMES, dtype="<U64"),
mean=mean,
scale=scale,
weights=weights,
)
print(f"[ranker/train] rows={len(xs)} samples={len(rows_by_sample)} "
f"pairs={len(pair_x)} pair_mse={mse:.6f} pair_corr={corr:.4f}",
flush=True)
if picked:
print(f"[ranker/train] train-picked mean={float(np.mean(picked)):.4f} "
f"candidate-oracle mean={float(np.mean(oracle)):.4f}", flush=True)
print(f"[ranker/train] wrote {out_path}", flush=True)
def _build_stage2_sample(
raw_sample: Dict[str, Any],
colmap_rec,
pred_verts: np.ndarray,
pred_edges: np.ndarray,
stage2_cfg: Stage2Config,
preprocess_cache: Optional[Dict[str, Any]],
order_id: str,
timings: Optional[Dict[str, float]],
) -> Optional[Dict[str, Any]]:
"""Host: stage-2 scene around one set of stage-1 vertices/edges (``build_stage2_scene`` +
``stage2_row_to_sample``). Returns the model-ready sample (host tensors, ``init_verts`` (K, 3)
from ``pred_verts``) or None when the hull is invalid."""
if stage2_cfg.sampling == "fps":
raise NotImplementedError("stage-2 'fps' sampling is not supported by the inference path")
t0 = time.perf_counter()
s2_row = build_stage2_scene(
raw_sample=raw_sample,
colmap_rec=colmap_rec,
pred_verts=pred_verts,
pred_edges=pred_edges,
above_m=stage2_cfg.above_m,
below_m=stage2_cfg.below_m,
side_m=stage2_cfg.side_m,
n_col_oversample=stage2_cfg.n_col_oversample,
n_dep_oversample=stage2_cfg.n_dep_oversample,
n_depth_per_image_cap=stage2_cfg.n_depth_per_image_cap,
sampling_mode=("voxel" if stage2_cfg.sampling == "voxel" else "random"),
density_voxel_size_m=stage2_cfg.density_voxel_size_m,
density_kernel_radius=stage2_cfg.density_kernel_radius,
density_kernel_axis=stage2_cfg.density_kernel_axis,
density_response_power=stage2_cfg.density_response_power,
density_planarity_suppression=stage2_cfg.density_planarity_suppression,
density_planarity_radius=stage2_cfg.density_planarity_radius,
density_planarity_min_points=stage2_cfg.density_planarity_min_points,
density_min_per_voxel=stage2_cfg.density_min_per_voxel,
rng=np.random.default_rng(_seed_from_order_id(order_id)),
cache=preprocess_cache,
)
if timings is not None:
timings["s2_build"] = timings.setdefault("s2_build", 0.0) + time.perf_counter() - t0
if not s2_row["hull_valid"]:
return None
t0 = time.perf_counter()
s2_sample = stage2_row_to_sample(
s2_row,
n_pts=stage2_cfg.n_pts,
k_verts=stage2_cfg.k_verts,
augment=False,
flip=False, yaw=False, jitter_sigma=0.0,
pre_subsample=True,
)
if timings is not None:
timings["s2_transform"] = timings.setdefault("s2_transform", 0.0) + time.perf_counter() - t0
return s2_sample
def build_stage2_union_sample(
raw_sample: Dict[str, Any],
colmap_rec,
s1_runs: List[Tuple[np.ndarray, np.ndarray, np.ndarray]],
stage2_cfg: Stage2Config,
preprocess_cache: Optional[Dict[str, Any]],
timings: Optional[Dict[str, float]] = None,
) -> Optional[Dict[str, Any]]:
"""Host only (safe in a CPU worker): the union-hull stage-2 input of one sample.
ONE stage-2 scene (hull, point cloud, bbox) is built from the union of the N = len(s1_runs)
stage-1 members' vertices and edges; ``init_verts`` (N, K, 3) / ``init_verts_valid`` (N, K) hold
each member's vertices normalised into that shared bbox, so every member starts its stage-2
trajectory from its own stage-1 hypothesis. Returns the sample (host tensors, the input of
``stage2_predict_batch``) or None when all members are empty or the hull is invalid."""
order_id = str(raw_sample["order_id"])
parts = [(np.asarray(v, dtype=np.float32).reshape(-1, 3), np.asarray(e, dtype=np.int64).reshape(-1, 2))
for v, e, _l in s1_runs if len(v) > 0]
if not parts:
return None
offsets = np.cumsum([0] + [len(v) for v, _e in parts[:-1]])
union_verts = np.concatenate([v for v, _e in parts])
union_edges = np.concatenate([e + o for (_v, e), o in zip(parts, offsets)])
s2_sample = _build_stage2_sample(raw_sample, colmap_rec, union_verts, union_edges, stage2_cfg,
preprocess_cache, order_id, timings)
if s2_sample is None:
return None
K, N = stage2_cfg.k_verts, len(s1_runs)
center = s2_sample["bbox_center"].numpy().astype(np.float32)
scale = max(float(s2_sample["bbox_scale"]), 1e-6)
init = np.zeros((N, K, 3), dtype=np.float32)
valid = np.zeros((N, K), dtype=bool)
for i, (v, _e, _l) in enumerate(s1_runs):
if len(v) > 0:
norm = ((np.asarray(v, dtype=np.float32).reshape(-1, 3) - center) / scale).astype(np.float32)
init[i], valid[i] = _pad_init_verts(norm, K)
s2_sample["init_verts"] = torch.from_numpy(init)
s2_sample["init_verts_valid"] = torch.from_numpy(valid)
return s2_sample
def build_stage2_seed_sample(
raw_sample: Dict[str, Any],
colmap_rec,
pred_verts: np.ndarray,
pred_edges: np.ndarray,
stage2_cfg: Stage2Config,
preprocess_cache: Optional[Dict[str, Any]],
timings: Optional[Dict[str, float]] = None,
) -> Optional[Dict[str, Any]]:
"""Host only: per-seed stage-2 input around ONE stage-1 member (M = 1: ``init_verts`` (1, K, 3)).
None when its hull is invalid."""
s2_sample = _build_stage2_sample(raw_sample, colmap_rec, pred_verts, pred_edges, stage2_cfg,
preprocess_cache, str(raw_sample["order_id"]), timings)
if s2_sample is not None:
s2_sample["init_verts"] = s2_sample["init_verts"][None]
s2_sample["init_verts_valid"] = s2_sample["init_verts_valid"][None]
return s2_sample
@torch.inference_mode()
def stage2_predict_batch(
stage2_cfg: Stage2Config,
samples: Sequence[Dict[str, Any]],
order_ids: Sequence[str],
enc_idx: Sequence[int],
device: torch.device,
timings: Optional[Dict[str, float]] = None,
) -> List[List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]]]:
"""Stage 2 on the GPU for S built samples at once (one scene encode each, all members integrated
together). ``samples``: S outputs of ``build_stage2_union_sample`` / ``build_stage2_seed_sample``
(host tensors; equal point counts and equal member counts M = init_verts.shape[0]);
``order_ids`` / ``enc_idx``: per sample its order_id and the index n of this stage-2 encode within
the sample (0 for the union hull; enc_base + member index on the per-seed path). Sample s reseeds
the torch RNG with _torch_seed(order_ids[s], cfg.seed, "s2", enc_idx[s]) before its x0 draws.
Returns S lists of M host tuples (verts_world (m, 3) float32, edges [(i, j)] with i < j,
valid_logits (m,) float32), WITHOUT the stage-1 fallback (see ``merge_stage_members``).
``timings`` (optional) accumulates CUDA-synchronised seconds under s2_enc / s2_den / s2_post."""
M = samples[0]["init_verts"].shape[0]
if any(s["init_verts"].shape[0] != M for s in samples):
raise ValueError("stage2_predict_batch needs the same member count in every sample")
model = stage2_cfg.model
if stage2_cfg.compile and model.denoiser._compiled is None:
model.denoiser.compile_step()
with _phase(timings, "s2_enc", device):
batch = _stage2_samples_to_batch(samples, device)
feats, sxyz = model.encode(batch, stage2_cfg.encoder_bf16)
with _phase(timings, "s2_den", device):
x0 = _init_members(model, batch, M, order_ids, stage2_cfg.seed, "s2", enc_idx)
x, logit, edge = model.integrate(feats, sxyz, x0, stage2_cfg.n_sample_steps,
stage2_cfg.ensemble_stage2_last_k, stage2_cfg.denoiser_bf16,
stage2_cfg.cuda_graph)
with _phase(timings, "s2_post", device):
out = _decode_members(x, logit, edge,
[(s["bbox_center"].numpy(), float(s["bbox_scale"]), s["bbox_R"].numpy())
for s in samples], M, stage2_cfg.validity_thresh, None)
return [[(v, [(int(a), int(b)) for a, b in e], l) for v, e, l in members] for members in out]
def merge_stage_members(
s1_runs: List[Tuple[np.ndarray, np.ndarray, np.ndarray]],
s2_runs: List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]],
) -> List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]]:
"""Member i keeps its stage-2 result when that has vertices and edges, else its stage-1
prediction when that has both, else it is dropped. Returns the ensemble ``seed_results``
[(verts (m, 3) float64, edges [(i, j)], valid_logits (m,) float32)] for ``select_ensemble``."""
out = []
for (v1, e1, l1), (v2, e2, l2) in zip(s1_runs, s2_runs, strict=True):
if len(v2) > 0 and len(e2) > 0:
out.append((np.asarray(v2, dtype=float), list(e2), np.asarray(l2, dtype=np.float32)))
continue
e1 = [(int(a), int(b)) for a, b in np.asarray(e1).tolist()]
if len(v1) > 0 and len(e1) > 0:
out.append((np.asarray(v1, dtype=float), e1, np.asarray(l1, dtype=np.float32)))
return out
_NO_MEMBER = (np.zeros((0, 3), dtype=np.float32), [], np.zeros(0, dtype=np.float32))
def select_ensemble(
seed_results: List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]],
s1_runs: List[Tuple[np.ndarray, np.ndarray, np.ndarray]],
n_hull_valid: int,
stage2_cfg: Stage2Config,
raw_sample: Dict[str, Any],
colmap_rec,
stats: Optional[Dict[str, int]] = None,
diagnostics: Optional[Dict[str, Any]] = None,
) -> Tuple[np.ndarray, List[Tuple[int, int]]]:
"""Host only (safe in a CPU worker): fuse / select the final wireframe of one sample from its
ensemble ``seed_results`` (``merge_stage_members`` output, see ``_Worker``). Reads only
the ensemble_* fields of ``stage2_cfg`` (never ``stage2_cfg.model``); ``raw_sample`` /
``colmap_rec`` are used by the ranker selector only. Returns (verts (V, 3) float64, edges)."""
n_ensemble = stage2_cfg.ensemble_n
if not seed_results:
if stats is not None:
stats["empty_fallback"] = stats.get("empty_fallback", 0) + 1
if diagnostics is not None:
diagnostics["members"] = []
diagnostics["final"] = empty_solution()
ev, ee = empty_solution()
return np.asarray(ev, dtype=float), [(int(a), int(b)) for a, b in ee]
if diagnostics is not None:
diagnostics["members"] = [
(np.asarray(v, dtype=float), list(e), np.asarray(l, dtype=np.float32))
for v, e, l in seed_results
]
diagnostics["s1_runs"] = [
(np.asarray(v, dtype=float), list(e), np.asarray(l, dtype=np.float32))
for v, e, l in s1_runs
]
diagnostics["n_hull_valid"] = int(n_hull_valid)
# When n_ensemble=1 the single run is returned verbatim.
if n_ensemble == 1:
fused_v, fused_e = seed_results[0][0], seed_results[0][1]
if diagnostics is not None:
diagnostics["single"] = (np.asarray(fused_v, dtype=float), list(fused_e))
else:
selector = stage2_cfg.ensemble_selector
mode = stage2_cfg.ensemble_mode
tau = stage2_cfg.ensemble_merge_m
refine = stage2_cfg.ensemble_refine_positions
top_k = stage2_cfg.ensemble_top_k
edge_vote = stage2_cfg.ensemble_edge_vote
edge_vote_frac = stage2_cfg.ensemble_edge_vote_frac
vertex_vote_frac = stage2_cfg.ensemble_vertex_vote_frac
agg = stage2_cfg.ensemble_refine_agg
ranking: Optional[List[int]] = None
if mode == "medoid" or top_k > 0 or selector == "ranker":
ranking = _medoid_rank(seed_results, match_tau_m=tau)
medoid_pick = (ranking[0] if ranking else
_medoid_select_idx(seed_results, match_tau_m=tau))
conf_pick = _confidence_select_idx(seed_results)
if diagnostics is not None:
diagnostics["single"] = (
np.asarray(seed_results[0][0], dtype=float),
list(seed_results[0][1]),
)
diagnostics["medoid_pick"] = (
np.asarray(seed_results[medoid_pick][0], dtype=float),
list(seed_results[medoid_pick][1]),
)
diagnostics["confidence_pick"] = (
np.asarray(seed_results[conf_pick][0], dtype=float),
list(seed_results[conf_pick][1]),
)
diagnostics["medoid_idx"] = int(medoid_pick)
diagnostics["confidence_idx"] = int(conf_pick)
if selector in ("ranker", "fixed"):
reproj_views_cached = _build_reprojection_views(
raw_sample, colmap_rec,
) if selector == "ranker" else None
candidates = _build_ranker_candidates(
seed_results, match_tau_m=tau, edge_vote_frac=edge_vote_frac,
ranking=ranking, medoid_idx=medoid_pick,
confidence_idx=conf_pick,
reproj_views=reproj_views_cached,
s1_runs=s1_runs,
)
if candidates:
if selector == "fixed":
wanted = str(stage2_cfg.ensemble_fixed_candidate)
fallback = "medoid_mean_add"
scores = [
(2.0 if c["name"] == wanted else
1.0 if c["name"] == fallback else 0.0)
for c in candidates
]
else:
ranker = stage2_cfg.ensemble_ranker
scores = [
_score_ranker_candidate(c["features"], ranker)
for c in candidates
]
scores_arr = np.asarray(scores, dtype=np.float64)
best_c = int(np.argmax(scores_arr))
chosen = candidates[best_c]
topk_k = stage2_cfg.ensemble_topk_fuse
if (selector == "ranker" and topk_k > 1
and len(candidates) > 1):
fused_v, fused_e, _ = _fuse_topk_candidates(
candidates, scores_arr, topk_k,
match_tau_m=tau, edge_vote_frac=edge_vote_frac,
)
else:
fused_v = np.asarray(chosen["verts"], dtype=np.float64)
fused_e = list(chosen["edges"])
if diagnostics is not None:
diagnostics["candidates"] = [
{
"name": str(c["name"]),
"features": np.asarray(c["features"], dtype=np.float64),
"score": float(scores[j]),
"verts": np.asarray(c["verts"], dtype=float),
"edges": list(c["edges"]),
}
for j, c in enumerate(candidates)
]
diagnostics["selected_candidate"] = str(chosen["name"])
diagnostics["selected_candidate_score"] = float(scores[best_c])
diagnostics["pick_idx"] = int(chosen.get("source_idx", -1))
diagnostics["topk_fuse_k"] = int(topk_k)
else:
fused_v = np.asarray(seed_results[medoid_pick][0], dtype=np.float64)
fused_e = list(seed_results[medoid_pick][1])
if diagnostics is not None:
diagnostics["pick_idx"] = int(medoid_pick)
elif mode == "consensus":
# Consensus already aggregates across runs β refinement is
# logically subsumed. Vertex / edge vote fractions come straight
# from the same flags (vertex frac defaults to 0.5 here since
# consensus needs *some* support bar, not 0).
v_frac_consensus = vertex_vote_frac if vertex_vote_frac > 0.0 else 0.5
e_frac_consensus = edge_vote_frac if edge_vote else 0.5
fused_v, fused_e = _fuse_wireframes(
list(seed_results),
n_total=n_ensemble, merge_tau_m=tau,
vertex_vote_frac=v_frac_consensus,
edge_vote_frac=e_frac_consensus,
aggregator=agg,
)
else:
if mode == "confidence":
pick = conf_pick
else: # "medoid"
pick = medoid_pick
if diagnostics is not None:
diagnostics["pick_idx"] = int(pick)
if top_k > 0 and ranking:
members: Optional[List[int]] = list(ranking[:max(1, top_k)])
if pick not in members:
members.append(pick)
else:
members = None # use all runs
keep_idx: Optional[np.ndarray] = None
if refine:
fused_v, fused_e, keep_idx = _refine_positions(
seed_results, pick, match_tau_m=tau,
aggregator=agg, member_indices=members,
vertex_vote_frac=vertex_vote_frac,
)
else:
fused_v = np.asarray(seed_results[pick][0], dtype=np.float64).reshape(-1, 3)
fused_e = list(seed_results[pick][1])
keep_idx = np.arange(fused_v.shape[0], dtype=np.int64)
if edge_vote:
fused_e = _vote_edges(
seed_results, pick, match_tau_m=tau,
vote_frac=edge_vote_frac,
member_indices=members,
keep_idx=keep_idx,
)
if stats is not None:
if n_hull_valid == 0:
stats["stage1_fallback"] = stats.get("stage1_fallback", 0) + 1
else:
stats["stage2_used"] = stats.get("stage2_used", 0) + 1
if len(fused_v) == 0 or len(fused_e) == 0:
if stats is not None:
stats["empty_fallback"] = stats.get("empty_fallback", 0) + 1
if diagnostics is not None:
diagnostics["final"] = empty_solution()
ev, ee = empty_solution()
return np.asarray(ev, dtype=float), [(int(a), int(b)) for a, b in ee]
if diagnostics is not None:
diagnostics["final"] = (np.asarray(fused_v, dtype=float), list(fused_e))
return np.asarray(fused_v, dtype=float), fused_e
# ---------------------------------------------------------------------------
# Data sources: the test-server tars, read directly (--loader tar) or through
# the HF loader script (--loader hf)
# ---------------------------------------------------------------------------
def resolve_data_dir(data_dir: str, params: Dict[str, Any]) -> Path:
"""The test-server data dir; downloaded with snapshot_download(params['dataset']) when missing."""
path = Path(data_dir)
if path.exists():
print(f"[data] test environment detected ({path} exists)", flush=True)
else:
print(f"[data] local run β snapshot_download '{params['dataset']}' β {path}", flush=True)
from huggingface_hub import snapshot_download
snapshot_download(repo_id=params["dataset"], local_dir=str(path), repo_type="dataset")
return path
def split_tars(data_path: Path) -> Dict[str, List[str]]:
"""Split -> tars as the released script hands them to the loader script (validation =
*public*/**/*.tar, test = *private*/**/*.tar, rglob order); splits without tars are left out."""
files = {"validation": [str(p) for p in data_path.rglob("*public*/**/*.tar")],
"test": [str(p) for p in data_path.rglob("*private*/**/*.tar")]}
print(f"[data] resolved data_files: { {k: len(v) for k, v in files.items()} } shards", flush=True)
return {k: v for k, v in files.items() if v}
def tar_items(files: Dict[str, List[str]], limit: int) -> List[Tuple[str, tuple]]:
"""[(order_id, worker reference)] of every sample in the loader script's order (splits, their tars,
tar order), at most ``limit`` (> 0) per split; built from the tar headers only (``index_tar``). Members
the loader script does not read are skipped as it skips them; one line reports them."""
items: List[Tuple[str, tuple]] = []
skipped: Counter = Counter()
for paths in files.values():
rows = []
for p in paths:
samples, skip = index_tar(p)
skipped += skip
rows += [(key.replace("order_", ""), ("tar", p, key, members)) for key, members in samples]
items += rows[:limit] if limit > 0 else rows
if skipped:
print(f"[data] skipped tar members the loader script does not read (suffix: count): {dict(skipped)}",
flush=True)
return items
def hf_items(data_path: Path, files: Dict[str, List[str]], limit: int):
"""--loader hf: the released ``load_dataset`` call on the loader script. Returns the items (worker
references (split, row)) and the split datasets, which the workers read rows from undecoded."""
if load_dataset is None:
raise SystemExit("[data] --loader hf needs the Python package 'datasets'")
dataset = load_dataset(str(data_path / "hoho22k_2026_test_x_anon.py"), data_files=files,
trust_remote_code=True, writer_batch_size=100)
print(dataset, flush=True)
items: List[Tuple[str, tuple]] = []
splits = {}
for name in dataset:
ds = dataset[name]
splits[name] = ds.select(range(min(limit, len(ds)))) if limit > 0 else ds
items += [(str(o), ("hf", name, i)) for i, o in enumerate(splits[name]["order_id"])]
return items, splits
def sanity_items(args) -> List[Tuple[str, tuple]]:
"""--sanity: the first --sanity_n samples of --sanity_split (all with --sanity_n 0) as tar items, from
- --sanity_data_dir: all *.tar below it;
- else, with --sanity_n 0: the split's shards of --sanity_dataset, downloaded into --sanity_cache_dir;
- else: those full shards when a --sanity_n 0 run downloaded them, otherwise streamed prefixes of the
shards (``_streamed_prefix_tars``): only the first --sanity_n samples are fetched.
Shards are taken in sorted order, as the HF loader script lists them, so every route picks the same
samples in the same order."""
split = args.sanity_split
local = Path(args.sanity_cache_dir) / args.sanity_dataset.replace("/", "--")
full, done = local / "data" / split, local / "data" / split / ".complete"
if args.sanity_data_dir:
tars = sorted(str(p) for p in Path(args.sanity_data_dir).rglob("*.tar"))
elif args.sanity_n <= 0:
from huggingface_hub import snapshot_download
print(f"[sanity] downloading {args.sanity_dataset} data/{split}/*.tar β {local}", flush=True)
snapshot_download(repo_id=args.sanity_dataset, repo_type="dataset",
allow_patterns=[f"data/{split}/*.tar"], local_dir=str(local))
done.write_text("") # the full split is here (a later --sanity_n > 0 run uses it)
tars = sorted(str(p) for p in full.glob("*.tar"))
elif done.exists():
tars = sorted(str(p) for p in full.glob("*.tar"))
else:
tars = _streamed_prefix_tars(args.sanity_dataset, split, args.sanity_n, local / "stream" / split)
if not tars:
raise SystemExit(f"[sanity] no tars for split {split!r}")
print(f"[sanity] {len(tars)} tars: {tars}", flush=True)
return tar_items({split: tars}, args.sanity_n)
def _streamed_prefix_tars(repo: str, split: str, n: int, cache: Path) -> List[str]:
"""Local tars that hold the first ``n`` samples of the split. Per shard (sorted names; the list is
cached in ``shards.json``) a cached ``<shard>.first<k>.tar`` with k >= the samples still needed, or a
cached ``<shard>.all<k>.tar`` (the whole shard), is used; otherwise the shard is read from the Hub as one
sequential stream until enough samples are complete (``stream_tar_prefix``: a byte-identical prefix of
the shard). Files are written under a temporary name and renamed when complete. Hub errors (gated
dataset, missing login) are raised as huggingface_hub raises them."""
from huggingface_hub import HfFileSystem
cache.mkdir(parents=True, exist_ok=True)
listing = cache / "shards.json"
if not listing.exists():
names = sorted(p.rsplit("/", 1)[1] for p in HfFileSystem().ls(f"datasets/{repo}/data/{split}", detail=False)
if p.endswith(".tar"))
(cache / ".shards.json.partial").write_text(json.dumps(names))
(cache / ".shards.json.partial").rename(listing)
tars, need = [], n
for name in json.loads(listing.read_text()):
if need <= 0:
break
cached = [] # (samples, whole shard, path) of <name>.first<k>.tar / <name>.all<k>.tar
for p in cache.glob(f"{name}.*.tar"):
tag = p.name[len(name) + 1:-len(".tar")]
kind = tag.rstrip("0123456789")
if kind in ("first", "all") and tag != kind:
cached.append((int(tag[len(kind):]), kind == "all", p))
cached.sort()
hit = next(((k, p) for k, whole, p in cached if whole or k >= need), None)
if hit is None:
tmp = cache / f".{name}.partial"
t0 = time.perf_counter()
with HfFileSystem().open(f"datasets/{repo}/data/{split}/{name}", "rb", block_size=0) as src, \
open(tmp, "w+b") as dst:
k, whole, n_read = stream_tar_prefix(src, dst, need)
path = cache / f"{name}.{'all' if whole else 'first'}{k}.tar"
tmp.rename(path)
print(f"[sanity] streamed {repo} data/{split}/{name}: "
f"{'whole shard,' if whole else 'first'} {k} samples, {n_read / 1e6:.1f} MB read in "
f"{time.perf_counter() - t0:.1f} s β {path}", flush=True)
hit = (k, path)
tars.append(str(hit[1]))
need -= hit[0]
return tars
# ---------------------------------------------------------------------------
# Pipeline: CPU worker processes + one GPU loop in the main process
# ---------------------------------------------------------------------------
_THREAD_ENV = ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS")
_S2_KEYS = _SCENE_KEYS + ("init_verts", "init_verts_valid", "bbox_center", "bbox_scale", "bbox_R")
def _host_s2(sample: Dict[str, Any]) -> Dict[str, np.ndarray]:
"""A built stage-2 input as plain arrays for the queue (torch CPU tensors would be moved to shared memory)."""
return {k: sample[k].numpy() for k in _S2_KEYS}
def _torch_s2(arrays: Dict[str, np.ndarray]) -> Dict[str, torch.Tensor]:
return {k: torch.from_numpy(v) for k, v in arrays.items()}
def _warmup_colmap(order: str) -> None:
"""The first read_colmap_zip of a process pays pyarrow's compute warm-up (and, for "pycolmap", the
libstdc++ lookup); do it on a one-point reconstruction."""
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf:
zf.writestr("cameras.txt", "1 SIMPLE_PINHOLE 4 4 1 2 2\n")
zf.writestr("images.txt", "1 1 0 0 0 0 0 0 1 a.png\n\n")
zf.writestr("points3D.txt", "1 0 0 0 0 0 0 0.5 1 0\n")
read_colmap_zip(buf.getvalue(), order)
def _sanity_score(sample, colmap_rec, verts, edges, diag, cfg, dump: bool, idx: int) -> Dict[str, Any]:
"""--sanity, in the worker that owns the sample: HSS / F1 / IoU of the final wireframe against the GT
(hoho2025.metric_helper.hss, failures scored 0 as before), plus the ensemble diagnostics (``diag`` from
select_ensemble) and the ranker-candidate JSONL rows (``dump``)."""
from hoho2025.metric_helper import hss as hss_fn, HSSReturnType
gt_v, gt_e = np.asarray(sample["wf_vertices"]), np.asarray(sample["wf_edges"])
out: Dict[str, Any] = {"gt_nv": len(gt_v), "gt_ne": len(gt_e), "notes": [], "diag_line": "", "cand_rows": [],
"diag_hss": defaultdict(list), "diag_counts": defaultdict(list)}
def variant(name: str, vv, ee) -> float:
try:
val = float(hss_fn(np.asarray(vv, dtype=float), list(ee), gt_v, gt_e).hss)
except Exception:
val = 0.0
out["diag_hss"][name].append(val)
out["diag_counts"][f"{name}_v"].append(len(vv))
out["diag_counts"][f"{name}_e"].append(len(ee))
return val
if diag:
scored = {name: variant(name, *diag[name]) for name in ("single", "medoid_pick", "confidence_pick", "final")
if name in diag}
member_scores = [variant("member", vv, ee) for vv, ee, _ll in diag["members"]]
if member_scores:
oracle = max(member_scores)
out["diag_hss"]["oracle"].append(oracle)
best, final_h = int(np.argmax(member_scores)), scored["final"]
out["diag_line"] = (f" | diag single={scored.get('single', 0.0):.3f} "
f"medoid={scored.get('medoid_pick', 0.0):.3f} "
f"conf={scored.get('confidence_pick', 0.0):.3f} final={final_h:.3f} "
f"oracle={oracle:.3f}@{best} gap={oracle - final_h:+.3f}")
if dump and diag["members"]:
candidates = diag.get("candidates")
if not candidates:
candidates = _build_ranker_candidates(
[(np.asarray(v, dtype=float), list(e), np.asarray(l, dtype=np.float32)) for v, e, l in diag["members"]],
match_tau_m=cfg.ensemble_merge_m, edge_vote_frac=cfg.ensemble_edge_vote_frac,
medoid_idx=diag.get("medoid_idx"), confidence_idx=diag.get("confidence_idx"),
reproj_views=_build_reprojection_views(sample, colmap_rec),
s1_runs=[(np.asarray(v, dtype=float), list(e), np.asarray(l, dtype=np.float32))
for v, e, l in diag["s1_runs"]])
selected = str(diag.get("selected_candidate", ""))
for cand in candidates:
cv, ce = np.asarray(cand["verts"], dtype=float), list(cand["edges"])
try:
cr = hss_fn(cv, ce, gt_v, gt_e)
chss, cf1, ciou = float(cr.hss), float(cr.f1), float(cr.iou)
except Exception:
chss, cf1, ciou = 0.0, 0.0, 0.0
out["cand_rows"].append({
"order_id": sample["order_id"], "sample_index": int(idx), "name": str(cand["name"]),
"selected": str(cand["name"]) == selected, "hss": chss, "f1": cf1, "iou": ciou,
"n_v": int(len(cv)), "n_e": int(len(ce)),
"features": np.asarray(cand["features"], dtype=np.float64).tolist()})
try:
r = hss_fn(np.asarray(verts, dtype=float), list(edges), gt_v, gt_e)
except Exception as exc:
out["notes"].append(f"HSS FAILED ({type(exc).__name__}: {exc})")
r = HSSReturnType(hss=0.0, f1=0.0, iou=0.0)
out.update(hss=float(r.hss), f1=float(r.f1), iou=float(r.iou),
diag_hss=dict(out["diag_hss"]), diag_counts=dict(out["diag_counts"]))
return out
class _Worker:
"""The CPU side of every sample, in a worker process (see run_pipeline). Messages (name, idx, ...):
"pre" read + decode + stage-1 preprocess; "s2" stage-2 input build (union hull, else per seed);
"union" / "seed" merge with the stage-2 GPU result (per-seed fallback when the union hull yields no
member) and ensemble selection. Raw sample, COLMAP record and stage-1 cache stay here between the
steps; only scenes, stage-2 inputs and member wireframes cross the queues."""
def __init__(self, wid: int, out: "_Outbox", o: Dict[str, Any]):
self.wid, self.out, self.o, self.cfg = wid, out, o, o["cfg"]
self.hf = {k: ds.with_format("arrow") for k, ds in o["hf_splits"].items()}
self.st: Dict[int, Dict[str, Any]] = {}
_warmup_colmap(o["colmap_order"])
def handle(self, m) -> None:
try:
getattr(self, m[0])(*m[1:])
except Exception as exc: # per-sample CPU failure: the main process gives the sample the empty solution
s = self.st.pop(m[1], None)
extra = None
if self.o["sanity"] and s is not None:
ev, ee = empty_solution()
extra = _sanity_score(s["sample"], None, ev, ee, None, self.cfg, False, m[1])
self.out.put(("failed", m[1], m[0], f"{type(exc).__name__}: {exc}", traceback.format_exc(),
None if s is None else s["t"], extra))
def pre(self, idx: int, ref: tuple) -> None:
t0 = time.perf_counter()
if ref[0] == "tar":
files = read_tar_members(ref[1], ref[3])
t1 = time.perf_counter()
sample = decode_tar_sample(ref[2], files)
else:
row = self.hf[ref[1]][ref[2]].to_pylist()[0]
t1 = time.perf_counter()
sample = hf_row_images(row)
t2 = time.perf_counter()
s = self.st[idx] = {"sample": sample, "t": {"read": t1 - t0, "decode": t2 - t1, "s2_build": 0.0}}
pre = preprocess_sample(sample, self.o["n_pts"], self.o["use_depth"], 0.1, True,
colmap_order=self.o["colmap_order"])
s.update(rec=pre["colmap_rec"], cache=pre["cache"])
s["t"]["pre"] = time.perf_counter() - t2
self.out.put(("s1", idx, self.wid, pre["scene"]))
def s2(self, idx: int, s1_runs) -> None:
s = self.st[idx]
s["s1"] = s1_runs
t0 = time.perf_counter()
built = None
if self.cfg.ensemble_strategy == "union_hull" and self.cfg.ensemble_n > 1:
built = build_stage2_union_sample(s["sample"], s["rec"], s1_runs, self.cfg, s["cache"])
if built is None: # per-seed strategy, ensemble_n == 1, or no valid union hull
return self._per_seed(idx, 0, t0)
s["t"]["s2_build"] += time.perf_counter() - t0
self.out.put(("s2u", idx, _host_s2(built)))
def _per_seed(self, idx: int, enc_base: int, t0: float) -> None:
"""Released per-seed stage 2: one hull per stage-1 member; members with a valid hull go to the GPU
(stage-2 encode index enc_base + member), the others keep their stage-1 prediction."""
s = self.st[idx]
built = [build_stage2_seed_sample(s["sample"], s["rec"], v, e, self.cfg, s["cache"]) for v, e, _l in s["s1"]]
items = [(j, _host_s2(b)) for j, b in enumerate(built) if b is not None]
s["t"]["s2_build"] += time.perf_counter() - t0
if items:
self.out.put(("s2s", idx, enc_base, items))
else:
self.seed(idx, enc_base, {})
def union(self, idx: int, s2_runs) -> None:
t0 = time.perf_counter()
seed_results = merge_stage_members(self.st[idx]["s1"], s2_runs)
if seed_results:
self._finish(idx, seed_results, self.cfg.ensemble_n, t0)
else: # no usable union-hull member: released per-seed fallback
self._per_seed(idx, 1, t0)
def seed(self, idx: int, enc_base: int, runs: Dict[int, tuple]) -> None:
t0 = time.perf_counter()
s1 = self.st[idx]["s1"]
seed_results = merge_stage_members(s1, [runs[j] if j in runs else _NO_MEMBER for j in range(len(s1))])
self._finish(idx, seed_results, (self.cfg.ensemble_n if enc_base else 0) + len(runs), t0)
def _finish(self, idx: int, seed_results, n_hull_valid: int, t0: float) -> None:
s = self.st.pop(idx)
stats: Dict[str, int] = {}
diag = {} if self.o["diagnostics"] else None
verts, edges = select_ensemble(seed_results, s["s1"], n_hull_valid, self.cfg, s["sample"], s["rec"],
stats, diag)
edges = [(int(a), int(b)) for a, b in edges]
s["t"]["select"] = time.perf_counter() - t0
extra: Dict[str, Any] = {"stats": stats}
if self.o["sanity"]:
extra.update(_sanity_score(s["sample"], s["rec"], verts, edges, diag, self.cfg, self.o["dump"], idx))
self.out.put(("done", idx, np.asarray(verts, dtype=float).tolist(), edges, s["t"], extra))
class _Outbox:
"""Worker -> main messages, sent in order by a thread over this worker's own pipe: the worker does not
wait while the GPU loop is busy, and as only this process holds the write end, a worker that dies in
the middle of a message gives the main process EOF instead of a read that never completes."""
def __init__(self, conn):
self.q: queue.SimpleQueue = queue.SimpleQueue()
self.thread = threading.Thread(target=self._send_all, args=(conn,), daemon=True)
self.thread.start()
def _send_all(self, conn) -> None:
try:
for m in iter(self.q.get, None):
conn.send(m)
except BaseException: # a lost message would stall the run: die, the main process reports the dead worker
traceback.print_exc()
os._exit(1)
def put(self, m) -> None:
self.q.put(m)
def close(self) -> None:
self.q.put(None)
self.thread.join()
def _worker_main(wid: int, conn, out_conn) -> None:
"""Worker process: one "init" message, then sample messages until "stop"; stage-2 and selection
messages are served before queued preprocessing (they unblock the GPU loop)."""
signal.signal(signal.SIGINT, signal.SIG_IGN) # Ctrl-C reaches the whole process group; the main process stops us
torch.set_num_threads(1)
out = _Outbox(out_conn)
m = conn.recv()
if m[0] != "init":
raise RuntimeError(f"worker {wid}: expected 'init', got {m[0]!r}")
w = _Worker(wid, out, m[1])
hi: deque = deque()
lo: deque = deque()
busy = 0.0
while True:
if not hi and not lo:
m = conn.recv()
(lo if m[0] == "pre" else hi).append(m)
while conn.poll():
m = conn.recv()
(lo if m[0] == "pre" else hi).append(m)
m = hi.popleft() if hi else lo.popleft()
if m[0] == "stop":
out.put(("exit", wid, resource.getrusage(resource.RUSAGE_SELF).ru_maxrss, busy))
out.close()
return
t = time.perf_counter()
w.handle(m)
busy += time.perf_counter() - t
def start_workers(n: int):
"""n worker processes (spawn start method: safe with CUDA initialised in this process), each limited to
one OpenMP / BLAS thread. Returns [(process, input pipe, output pipe)], one pipe pair per worker.
The input pipes are written by the GPU loop's thread itself (an mp.Queue would add a feeder thread per
worker to this process, competing with the GPU loop for the GIL); their buffers are raised to 1 MB so
a send does not wait for a busy worker. This process closes its copies of the pipe ends the worker uses,
so a dead worker shows up as a broken pipe / EOF."""
ctx = mp.get_context("spawn")
saved = {k: os.environ.get(k) for k in _THREAD_ENV}
os.environ.update(dict.fromkeys(_THREAD_ENV, "1"))
try:
workers = []
for w in range(n):
rx, tx = ctx.Pipe(duplex=False)
out_rx, out_tx = ctx.Pipe(duplex=False)
fcntl.fcntl(tx.fileno(), fcntl.F_SETPIPE_SZ, 1 << 20)
p = ctx.Process(target=_worker_main, args=(w, rx, out_tx), name=f"s23dr-worker-{w}", daemon=True)
p.start()
rx.close()
out_tx.close()
workers.append((p, tx, out_rx))
finally:
for k, v in saved.items():
if v is None:
del os.environ[k]
else:
os.environ[k] = v
return workers
def check_workers(workers) -> None:
"""Raise if any worker process has exited."""
dead = [(w, p.exitcode) for w, (p, _tx, _rx) in enumerate(workers) if p.exitcode is not None]
if dead:
raise RuntimeError(f"pipeline worker(s) died (worker, exit code; -9 = SIGKILL, e.g. the OOM killer): "
f"{dead}; see the worker traceback above, if any")
def kill_workers(workers) -> None:
"""Error-path shutdown: SIGKILL (SIGTERM would make every worker print a native stack dump)."""
for p, _tx, _rx in workers: # kill before closing the pipes: a live worker would report the closed pipe
if p.is_alive():
p.kill()
for p, tx, rx in workers:
tx.close()
rx.close()
p.join(timeout=30)
def run_pipeline(workers, items, model, cfg: Stage2Config, device: torch.device, n_steps: int,
validity_thresh: float, args, report) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
"""All ``items`` (order_id, worker reference) through the workers and one GPU loop (this thread);
returns (predictions in item order, timing summary). Stops the workers at the end.
Per sample: worker "pre" -> GPU stage 1 -> worker "s2" -> GPU stage 2 (union hull: one item with
ensemble_n members; per seed: one item per member with a valid hull) -> worker merge + selection.
Seeding is per sample (order_id, --seed, stage), so outputs do not depend on batching or timing.
GPU batches hold S = --batch_samples samples (per-seed: S items); stage 2 runs before stage 1. A
batch of fewer than S runs only when no further input for that stage can arrive (--partial_batch
wait) or whenever the GPU would otherwise idle (pad). On CUDA it is padded to S by repeating its last
entry (results dropped), so every stage keeps one batch shape (one CUDA graph; bf16 results depend on
the shape, so an unpadded last batch would make them depend on arrival timing). At most
3*S + 2*n_workers samples are in flight (>= 3S - 2 makes a stall of the three GPU queues impossible),
each worker with at most 2 queued preprocessing tasks. ``report(i, order_id, verts, edges, times,
extra)`` runs once per finished sample (extra: worker extras, None if the sample failed unread)."""
pc = time.perf_counter
S, W, n = args.batch_samples, len(workers), len(items)
pad = device.type == "cuda"
readers = {rx: w for w, (_p, _tx, rx) in enumerate(workers)}
cap = 3 * S + 2 * W
oids = [o for o, _r in items]
ready: Dict[str, deque] = {"s1": deque(), "s2u": deque(), "s2s": deque()}
where: Dict[int, str] = {} # in-flight sample -> pre / s1 / build / s2u / s2s / post
count: Counter = Counter()
owner: Dict[int, int] = {}
npre = [0] * W
seeds: Dict[int, list] = {} # per-seed sample -> [enc_base, items left, {member: run}]
rec = [{"s1_gpu": 0.0, "s2_gpu": 0.0, "wait_s1": 0.0, "wait_s2": 0.0} for _ in range(n)]
results: List[Optional[Dict[str, Any]]] = [None] * n
wall: Counter = Counter()
batches: Counter = Counter()
padded: Counter = Counter()
stats: Counter = Counter()
failed: List[str] = []
nxt = n_done = 0
t_first = None
t_done: List[float] = []
bar = tqdm(total=n, desc="predict", unit="sample")
def send(w, m):
try:
workers[w][1].send(m)
except (BrokenPipeError, ConnectionResetError): # the worker is gone: say so
workers[w][0].join(timeout=5)
check_workers(workers)
raise
def recv(timeout: float) -> list:
"""The next message of every worker pipe readable within ``timeout`` (0: poll)."""
msgs = []
for rx in mp.connection.wait(list(readers), timeout):
try:
msgs.append(rx.recv())
except (EOFError, OSError): # a worker exited (possibly mid-message)
workers[readers[rx]][0].join(timeout=5)
check_workers(workers)
raise
return msgs
def stage(i, s):
if i in where:
count[where[i]] -= 1
where[i] = s
count[s] += 1
def admit():
nonlocal nxt
while nxt < n and len(where) < cap:
w = min(range(W), key=npre.__getitem__)
if npre[w] >= 2:
return
i, nxt = nxt, nxt + 1
owner[i] = w
npre[w] += 1
stage(i, "pre")
rec[i]["t_admit"] = pc()
send(w, ("pre", i, items[i][1]))
def finish(i, verts, edges, times, extra):
nonlocal n_done, t_first
count[where.pop(i)] -= 1
n_done += 1
t = pc()
t_first = t if t_first is None else t_first
t_done.append(t)
if times is not None:
rec[i].update(times)
rec[i]["latency"] = t - rec[i]["t_admit"]
rec[i]["done_s"] = t - t0
results[i] = {"order_id": oids[i], "wf_vertices": verts, "wf_edges": edges}
bar.update(1)
report(i, oids[i], verts, edges, rec[i], extra)
def on(m):
kind, i = m[0], m[1]
if kind == "s1":
npre[m[2]] -= 1
stage(i, "s1")
rec[i]["t_ready"] = pc()
ready["s1"].append((i, m[3]))
elif kind == "s2u":
stage(i, "s2u")
rec[i]["t_ready"] = pc()
ready["s2u"].append((i, _torch_s2(m[2])))
elif kind == "s2s":
stage(i, "s2s")
rec[i]["t_ready"] = pc()
seeds[i] = [m[2], len(m[3]), {}]
ready["s2s"].extend((i, j, m[2], _torch_s2(x)) for j, x in m[3])
elif kind == "done":
stats.update(m[5]["stats"])
finish(i, m[2], m[3], m[4], m[5])
elif kind == "failed":
if m[2] == "pre":
npre[owner[i]] -= 1
print(f"[predict] {oids[i]}: FAILED in '{m[2]}' ({m[3]}) β empty_solution\n{m[4]}", flush=True)
failed.append(oids[i])
ev, ee = empty_solution()
finish(i, np.asarray(ev, dtype=float).tolist(), [(int(a), int(b)) for a, b in ee], m[5], m[6])
else:
raise RuntimeError(f"unexpected worker message {kind!r}")
def runnable() -> Optional[str]:
more_s1 = nxt < n or count["pre"] > 0
more = {"s1": more_s1, "s2u": more_s1 or count["s1"] + count["build"] > 0}
more["s2s"] = more["s2u"] or count["s2u"] + count["post"] > 0
for s in ("s2u", "s2s", "s1"):
if len(ready[s]) >= S or (ready[s] and not more[s]):
return s
if args.partial_batch == "pad":
return next((s for s in ("s2u", "s2s", "s1") if ready[s]), None)
return None
def run(s):
q = ready[s]
take = [q.popleft() for _ in range(min(S, len(q)))]
full = take + [take[-1]] * (S - len(take)) if pad else take
batches[s] += 1
padded[s] += len(full) - len(take)
ids = [oids[x[0]] for x in full]
t0 = pc()
if s == "s1":
out = stage1_predict_batch(model, [x[1] for x in full], ids, cfg, n_steps, validity_thresh, device)
elif s == "s2u":
out = stage2_predict_batch(cfg, [x[1] for x in full], ids, [0] * len(full), device)
else:
out = stage2_predict_batch(cfg, [x[3] for x in full], ids, [x[2] + x[1] for x in full], device)
dt = pc() - t0
wall["gpu_" + s] += dt
for x, r in zip(take, out):
i = x[0]
rec[i]["s1_gpu" if s == "s1" else "s2_gpu"] += dt / len(take)
if s == "s1":
rec[i]["wait_s1"] = t0 - rec[i]["t_ready"]
stage(i, "build")
send(owner[i], ("s2", i, r))
elif s == "s2u":
rec[i]["wait_s2"] += t0 - rec[i]["t_ready"]
stage(i, "post")
send(owner[i], ("union", i, r))
else:
sd = seeds[i]
sd[2][x[1]] = r[0]
sd[1] -= 1
if sd[1] == 0:
del seeds[i]
rec[i]["wait_s2"] += t0 - rec[i]["t_ready"]
stage(i, "post")
send(owner[i], ("seed", i, sd[0], sd[2]))
t0, t0_wall = pc(), time.time()
last_msg = next_check = t0
while n_done < n:
if pc() >= next_check:
check_workers(workers)
next_check = pc() + 2.0
admit()
while msgs := recv(0):
for m in msgs:
on(m)
last_msg = pc()
s = runnable()
if s is not None:
run(s)
continue
tb = pc()
msgs = recv(1.0) # nothing to run: the GPU waits for the workers
wall["blocked"] += pc() - tb
for m in msgs:
on(m)
if msgs:
last_msg = pc()
elif pc() - last_msg > args.stall_timeout:
raise RuntimeError(f"pipeline stalled: no worker message for {args.stall_timeout:.0f} s with samples in "
f"flight {dict(count)}")
t1, t1_wall = pc(), time.time()
bar.close()
for w in range(W):
send(w, ("stop",))
exits: Dict[int, tuple] = {}
t_stop = pc()
while readers:
msgs = recv(1.0)
for m in msgs:
if m[0] != "exit":
raise RuntimeError(f"unexpected worker message after the last sample: {m[0]!r}")
exits[m[1]] = m[2:]
readers.pop(workers[m[1]][2])
if not msgs and pc() - t_stop > 60:
raise RuntimeError(f"workers {sorted(set(range(W)) - set(exits))} did not stop")
for p, _tx, _rx in workers:
p.join(timeout=60)
loop = t1 - t0
gpu = sum(v for k, v in wall.items() if k.startswith("gpu_"))
keys = ("read", "decode", "pre", "s2_build", "select", "s1_gpu", "s2_gpu", "wait_s1", "wait_s2", "latency")
summary = {
"n": n, "n_failed": len(failed), "failed": failed, "n_workers": W, "batch_samples": S,
"partial_batch": args.partial_batch, "padded_batches": pad, "max_in_flight": cap,
"t_loop": loop, "t_loop0": t0, "t_first_result": t_first, "loop_wall": (t0_wall, t1_wall),
"samples_per_s": n / loop,
# completions between 25 % and 75 % of the samples: no start-up (graph captures, JIT) and no drain
"samples_per_s_steady": (3 * n // 4 - n // 4) / (t_done[3 * n // 4] - t_done[n // 4]) if n >= 40 else None,
"per_sample_ms": {k: 1e3 * float(np.mean([r[k] for r in rec if k in r])) for k in keys},
"gpu_busy_frac": gpu / loop, "blocked_frac": wall["blocked"] / loop,
"main_overhead_frac": 1.0 - (gpu + wall["blocked"]) / loop,
"worker_busy_frac": sum(e[1] for e in exits.values()) / (W * loop),
"gpu_wall_s": {k: v for k, v in wall.items() if k.startswith("gpu_")},
"batches": dict(batches), "padded_slots": dict(padded), "selection_stats": dict(stats),
"peak_rss_main_mb": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024,
"peak_rss_workers_mb": [exits[w][0] / 1024 for w in range(W)],
"per_sample": [{"order_id": oids[i], **{k: v for k, v in rec[i].items() if not k.startswith("t_")}}
for i in range(n)],
}
if device.type == "cuda":
summary["gpu_mem_peak_mb"] = {"allocated": torch.cuda.max_memory_allocated(device) / 2 ** 20,
"reserved": torch.cuda.max_memory_reserved(device) / 2 ** 20}
print_pipeline_summary(summary)
return results, summary
def print_pipeline_summary(s: Dict[str, Any]) -> None:
"""Per-phase means and the loop split; what bounds the run."""
p = s["per_sample_ms"]
bound = ("CPU workers (more cores / --n_workers)" if s["worker_busy_frac"] > 0.85 else
"GPU" if s["gpu_busy_frac"] > 0.85 else
"main-process Python" if s["main_overhead_frac"] > 0.15 else
"neither saturated (batch latency)")
w_rss = s["peak_rss_workers_mb"]
steady = "" if s["samples_per_s_steady"] is None else f", middle half {s['samples_per_s_steady']:.2f}"
print(f"[pipeline] {s['n']} samples in {s['t_loop']:.1f} s = {s['samples_per_s']:.2f} samples/s{steady} "
f"(FAILED {s['n_failed']}; {s['n_workers']} workers, S={s['batch_samples']}, {s['partial_batch']})", flush=True)
print(f"[pipeline] per sample [ms], workers: read {p['read']:.1f} decode {p['decode']:.1f} "
f"stage-1 preprocess {p['pre']:.1f} stage-2 build {p['s2_build']:.1f} selection {p['select']:.1f}", flush=True)
print(f"[pipeline] per sample [ms], GPU loop: stage-1 GPU {p['s1_gpu']:.1f} stage-2 GPU {p['s2_gpu']:.1f} "
f"queue wait s1 {p['wait_s1']:.0f} s2 {p['wait_s2']:.0f} latency {p['latency']:.0f}", flush=True)
print(f"[pipeline] loop: GPU calls {100 * s['gpu_busy_frac']:.0f}% waiting for workers (GPU idle) "
f"{100 * s['blocked_frac']:.0f}% main-thread overhead {100 * s['main_overhead_frac']:.0f}% | workers busy "
f"{100 * s['worker_busy_frac']:.0f}% | batches {s['batches']} padded slots {s['padded_slots']}", flush=True)
print(f"[pipeline] peak RSS main {s['peak_rss_main_mb']:.0f} MB, workers {sum(w_rss):.0f} MB "
f"(max {max(w_rss):.0f})" + (f", GPU peak allocated {s['gpu_mem_peak_mb']['allocated']:.0f} MB reserved "
f"{s['gpu_mem_peak_mb']['reserved']:.0f} MB" if "gpu_mem_peak_mb" in s else "")
+ f" | selection {s['selection_stats']} | bound by: {bound}", flush=True)
def _print_prediction(i, order_id, verts, edges, times, extra) -> None:
print(f"[predict/stage2] {order_id}: {len(verts)}v {len(edges)}e (latency {times['latency']:.2f}s)", flush=True)
# ---------------------------------------------------------------------------
# Local sanity check (--sanity): val split, scored against GT
# ---------------------------------------------------------------------------
def run_sanity_check(workers, items, model, stage2_cfg: Stage2Config, device: torch.device,
n_steps: int, validity_thresh: float, args) -> Dict[str, Any]:
"""The inference pipeline on --sanity_split samples with GT; the workers score each prediction
(hoho2025.metric_helper.hss) and, with --sanity_ensemble_diagnostics / --ensemble_candidate_dump,
the ensemble alternatives. Prints per-sample and mean HSS / F1 / IoU; returns the pipeline summary
with the means."""
print(f"[sanity] dataset={args.sanity_data_dir or args.sanity_dataset} split={args.sanity_split} "
f"n={len(items)} n_sample_steps={n_steps} validity_thresh={validity_thresh}", flush=True)
print(f"[sanity] STAGE 2 enabled n_pts={stage2_cfg.n_pts} n_sample_steps={stage2_cfg.n_sample_steps} "
f"hull=(+{stage2_cfg.above_m:.2f}/-{stage2_cfg.below_m:.2f}/Β±{stage2_cfg.side_m:.2f})", flush=True)
diagnostics = args.sanity_ensemble_diagnostics or args.ensemble_candidate_dump is not None
if diagnostics and stage2_cfg.ensemble_n > 1:
print("[diag] enabled: scoring single/member0, medoid pick, confidence pick, final fused, and oracle-best "
"member", flush=True)
scores: Dict[str, List[float]] = {"hss": [], "f1": [], "iou": []}
diag_hss: Dict[str, List[float]] = defaultdict(list)
diag_counts: Dict[str, List[int]] = defaultdict(list)
cand_rows: Dict[int, List[dict]] = {}
def report(i, order_id, verts, edges, times, extra):
if extra is None: # failed before its GT was read
extra = {"hss": 0.0, "f1": 0.0, "iou": 0.0, "gt_nv": -1, "gt_ne": -1, "notes": ["no GT read"],
"diag_line": "", "cand_rows": [], "diag_hss": {}, "diag_counts": {}}
for note in extra["notes"]:
print(f"[sanity] {order_id}: {note}", flush=True)
for k in scores:
scores[k].append(extra[k])
for k, v in extra["diag_hss"].items():
diag_hss[k].extend(v)
for k, v in extra["diag_counts"].items():
diag_counts[k].extend(v)
cand_rows[i] = extra["cand_rows"]
g = lambda k: times[k] if k in times else float("nan")
print(f"[sanity] [{i:03d}] {order_id} pred={len(verts)}v/{len(edges)}e gt={extra['gt_nv']}v/{extra['gt_ne']}e "
f"HSS={extra['hss']:.3f} F1={extra['f1']:.3f} IoU={extra['iou']:.3f} | pre={g('pre'):.2f}s "
f"s1={g('s1_gpu'):.3f}s s2build={g('s2_build'):.3f}s s2={g('s2_gpu'):.3f}s sel={g('select'):.3f}s "
f"latency={times['latency']:.2f}s{extra['diag_line']}", flush=True)
_results, summary = run_pipeline(workers, items, model, stage2_cfg, device, n_steps, validity_thresh,
args, report)
def mean_std(xs):
arr = np.asarray(xs, dtype=np.float64)
return (float(arr.mean()), float(arr.std())) if arr.size else (0.0, 0.0)
print("=" * 60, flush=True)
print(f"[sanity] samples={len(scores['hss'])}", flush=True)
for k, name in (("hss", "HSS "), ("f1", "F1 "), ("iou", "IoU ")):
m, sd = mean_std(scores[k])
summary[f"sanity_{k}"] = m
print(f"[sanity] {name} mean={m:.4f} std={sd:.4f}", flush=True)
if diag_hss:
print("[diag] HSS means:", flush=True)
for name in ("single", "member", "medoid_pick", "confidence_pick", "final", "oracle"):
if name in diag_hss:
m, sd = mean_std(diag_hss[name])
print(f"[diag] {name:15s} mean={m:.4f} std={sd:.4f}", flush=True)
if "oracle" in diag_hss and "final" in diag_hss:
gap = np.asarray(diag_hss["oracle"]) - np.asarray(diag_hss["final"])
print(f"[diag] oracle-final mean={float(gap.mean()):+.4f} std={float(gap.std()):.4f}", flush=True)
for name in ("single", "medoid_pick", "confidence_pick", "final"):
if f"{name}_v" in diag_counts:
v_m, v_s = mean_std(diag_counts[f"{name}_v"])
e_m, e_s = mean_std(diag_counts[f"{name}_e"])
print(f"[diag] {name:15s} size={v_m:.1f}Β±{v_s:.1f}v/{e_m:.1f}Β±{e_s:.1f}e", flush=True)
st = summary["selection_stats"]
print(f"[sanity] stage-2 used={st.get('stage2_used', 0)} stage-1 fallback={st.get('stage1_fallback', 0)} "
f"empty fallback={st.get('empty_fallback', 0)}", flush=True)
if args.ensemble_candidate_dump is not None:
with open(args.ensemble_candidate_dump, "w") as f:
for i in sorted(cand_rows):
for row in cand_rows[i]:
f.write(json.dumps(row, separators=(",", ":")) + "\n")
print(f"[ranker/dump] wrote {sum(map(len, cand_rows.values()))} candidate rows to "
f"{args.ensemble_candidate_dump}", flush=True)
print("=" * 60, flush=True)
return summary
# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
def _build_stage2_cfg(args, params: Dict[str, Any], device: torch.device) -> Stage2Config:
"""Resolve --stage2_ckpt / env / params, load the Stage2Diffusion model,
and assemble a ``Stage2Config``. The two-stage pipeline is mandatory;
``resolve_stage2_ckpt_path`` raises if no ckpt is configured."""
ckpt_path = resolve_stage2_ckpt_path(args.stage2_ckpt, params)
model, s2_args = load_stage2_model(ckpt_path, device)
n_pts = (args.stage2_n_pts if args.stage2_n_pts is not None
else s2_args.get("n_pts", 16384))
k_verts = s2_args.get("k_verts", 64)
n_sample_steps = (args.stage2_n_sample_steps if args.stage2_n_sample_steps is not None
else s2_args.get("n_sample_steps", 20))
validity_thresh = (args.stage2_validity_thresh if args.stage2_validity_thresh is not None
else s2_args.get("validity_thresh", 0.0))
# Keep stage-2 inference on the original random sampler. Earlier FPS
# experiments added extra plumbing here, but the current submission/eval
# path intentionally does not switch sampling modes from CLI or ckpt args.
sampling = "random"
# Oversample budgets: random uses a smaller candidate pool; voxel is left
# as a code path for old experiments but is not selected by this script.
def _default_oversample(s: str) -> int:
if s == "voxel":
return 16_000
return 10_000
n_col_oversample = (args.stage2_n_col_oversample
if args.stage2_n_col_oversample is not None
else _default_oversample(sampling))
n_dep_oversample = (args.stage2_n_dep_oversample
if args.stage2_n_dep_oversample is not None
else _default_oversample(sampling))
fps_max_exact_iters = None
bf16_ok = device.type == "cuda" and torch.cuda.is_bf16_supported(including_emulation=False)
if device.type == "cuda" and not bf16_ok and (args.encoder_bf16 or args.denoiser_bf16):
print(f"[gpu] {torch.cuda.get_device_name(device)} has no native bf16: --encoder_bf16/--denoiser_bf16 "
f"DISABLED, running those parts in fp32", flush=True)
cfg = Stage2Config(
model=model,
n_pts=n_pts,
k_verts=k_verts,
n_sample_steps=n_sample_steps,
validity_thresh=validity_thresh,
above_m=args.stage2_above_m,
below_m=args.stage2_below_m,
side_m=args.stage2_side_m,
n_col_oversample=n_col_oversample,
n_dep_oversample=n_dep_oversample,
n_depth_per_image_cap=args.stage2_n_depth_per_image_cap,
sampling=sampling,
density_voxel_size_m=args.stage2_density_voxel_size_m,
density_kernel_radius=args.stage2_density_kernel_radius,
density_kernel_axis=args.stage2_density_kernel_axis,
density_response_power=args.stage2_density_response_power,
density_planarity_suppression=args.stage2_density_planarity_suppression,
density_planarity_radius=args.stage2_density_planarity_radius,
density_planarity_min_points=args.stage2_density_planarity_min_points,
density_min_per_voxel=args.stage2_density_min_per_voxel,
ensemble_n=args.ensemble_n,
ensemble_merge_m=args.ensemble_merge_m,
ensemble_mode=args.ensemble_mode,
ensemble_strategy=args.ensemble_strategy,
ensemble_refine_positions=(not args.no_position_refine),
ensemble_refine_agg=args.ensemble_refine_agg,
ensemble_top_k=args.ensemble_top_k,
ensemble_edge_vote=(not args.no_edge_vote),
ensemble_edge_vote_frac=args.ensemble_edge_vote_frac,
ensemble_vertex_vote_frac=args.ensemble_vertex_vote_frac,
ensemble_stage2_last_k=args.ensemble_stage2_last_k,
ensemble_selector=args.ensemble_selector,
ensemble_ranker_path=args.ensemble_ranker_path,
ensemble_ranker=(
_load_ensemble_ranker(args.ensemble_ranker_path)
if args.ensemble_selector == "ranker" else None
),
ensemble_fixed_candidate=args.ensemble_fixed_candidate,
ensemble_topk_fuse=args.ensemble_topk_fuse,
fps_max_exact_iters=fps_max_exact_iters,
seed=args.seed,
encoder_bf16=args.encoder_bf16 and bf16_ok,
denoiser_bf16=args.denoiser_bf16 and bf16_ok,
cuda_graph=args.cuda_graph and device.type == "cuda",
compile=args.compile and device.type == "cuda",
)
if device.type != "cuda" and (args.encoder_bf16 or args.denoiser_bf16 or args.tf32 or args.cuda_graph
or args.compile or args.fps_kernel != "torch"):
print(f"[gpu] device={device.type}: --encoder_bf16/--denoiser_bf16/--tf32/--cuda_graph/--compile/"
f"--fps_kernel triton are CUDA-only and DISABLED here; running fp32 eager with the torch FPS loop",
flush=True)
if device.type == "cuda" and args.fps_kernel == "triton":
try:
from models import fps_triton # noqa: F401 (imports triton)
except ImportError as exc:
raise SystemExit(f"[gpu] --fps_kernel triton (the default) needs the 'triton' package, which failed to "
f"import ({exc}); install triton or run with --fps_kernel torch (same anchors, "
f"slower)") from exc
torch.backends.cuda.matmul.allow_tf32 = args.tf32 and device.type == "cuda"
models.scene_encoder.FPS_BACKEND = args.fps_kernel if device.type == "cuda" else "torch"
torch.backends.cuda.enable_cudnn_sdp(args.cudnn_sdpa)
print(f"[gpu] seed={cfg.seed} encoder_bf16={cfg.encoder_bf16} denoiser_bf16={cfg.denoiser_bf16} "
f"tf32={torch.backends.cuda.matmul.allow_tf32} cuda_graph={cfg.cuda_graph} compile={cfg.compile} "
f"fps_kernel={models.scene_encoder.FPS_BACKEND} cudnn_sdpa={args.cudnn_sdpa}", flush=True)
extra = ""
if cfg.sampling == "voxel":
extra = (f" density(voxel={cfg.density_voxel_size_m:.2f}m "
f"kernel={cfg.density_kernel_axis}:r{cfg.density_kernel_radius} "
f"planarity_supp={cfg.density_planarity_suppression:.2f})")
elif cfg.sampling == "fps":
extra = (f" fps_max_exact_iters="
f"{'full' if cfg.fps_max_exact_iters is None else cfg.fps_max_exact_iters}")
print(f"[stage2] enabled n_pts={cfg.n_pts} steps={cfg.n_sample_steps} "
f"sampling={cfg.sampling} oversample={cfg.n_col_oversample}+{cfg.n_dep_oversample} "
f"hull=(+{cfg.above_m:.2f}/-{cfg.below_m:.2f}/Β±{cfg.side_m:.2f}){extra}",
flush=True)
if cfg.ensemble_n > 1:
refine_str = (cfg.ensemble_refine_agg
if cfg.ensemble_refine_positions else "off")
topk_str = ("all" if cfg.ensemble_top_k == 0
else f"top{cfg.ensemble_top_k}")
edge_str = (f"vote>={cfg.ensemble_edge_vote_frac:.2f}"
if cfg.ensemble_edge_vote else "picked")
vdrop_str = (f"vote>={cfg.ensemble_vertex_vote_frac:.2f}"
if cfg.ensemble_vertex_vote_frac > 0.0 else "off")
print(f"[ensemble] N={cfg.ensemble_n} strategy={cfg.ensemble_strategy} "
f"mode={cfg.ensemble_mode} tau={cfg.ensemble_merge_m:.2f}m "
f"refine={refine_str} members={topk_str} edges={edge_str} "
f"vdrop={vdrop_str} s2_lastk={cfg.ensemble_stage2_last_k} "
f"selector={cfg.ensemble_selector}", flush=True)
return cfg
def parse_args(argv=None):
p = argparse.ArgumentParser(description="S23DR 2026 submission script (trained model)")
p.add_argument("--ckpt", default=None,
help="Checkpoint path; falls back to $S23DR_CKPT, params['ckpt'], "
"then ./test_checkpoint.pth")
p.add_argument("--params", default="params.json")
p.add_argument("--n_sample_steps", type=int, default=50,
help="Stage-1 diffusion ODE steps at inference (default: 50).")
p.add_argument("--n_pts", type=int, default=None,
help="Stage-1 scene points at inference (default: ckpt args / 8192)")
p.add_argument("--validity_thresh", type=float, default=0.0,
help="Drop predicted vertices below this validity logit "
"(default: 0.0)")
p.add_argument("--device", default="cuda")
# ---- data + pipeline ----------------------------------------------------
p.add_argument("--data_dir", default="/tmp/data",
help="Test-server data dir (*public*/**/*.tar, *private*/**/*.tar, loader script); "
"downloaded with snapshot_download(params['dataset']) when missing.")
p.add_argument("--loader", choices=["tar", "hf"], default="tar",
help="'tar': read the samples straight from the tars (rows equal to the loader script's; "
"members it does not read are skipped, as it skips them). 'hf': datasets.load_dataset on "
"the loader script, as released (Arrow build first); rows are decoded in the workers "
"either way.")
p.add_argument("--colmap_order", choices=["pycolmap", "file"], default="pycolmap",
help="COLMAP point / image order: 'pycolmap' = exact released preprocessing (emulates "
"pycolmap's libstdc++ hash-map order); 'file' = portable file order (perturbs the "
"subsampled scenes like a different random draw).")
p.add_argument("--n_workers", type=int, default=max(1, min(8, len(os.sched_getaffinity(0)) - 2)),
help="CPU worker processes (tar read, preprocessing, stage-2 build, selection), ~1 GB RAM "
"each. Default: CPUs in this process's affinity minus 2, at most 8 (more did not "
"speed up an H200), at least 1.")
p.add_argument("--batch_samples", type=int, default=1,
help="Samples per GPU batch S (stage 1: S*ensemble_n trajectories). Larger is faster on a "
"big GPU: ~10 GB GPU memory at 8, ~20 GB at 16 (with CUDA graphs each stage captures "
"one graph for this shape). With bf16 / TF32 the predictions depend on S.")
p.add_argument("--partial_batch", choices=["wait", "pad"], default="wait",
help="Fewer than --batch_samples ready while more are coming: 'wait' for a full batch "
"(partial batches only at the end of the data); 'pad' runs them as soon as the GPU "
"would idle.")
p.add_argument("--stall_timeout", type=float, default=600.0,
help="Abort when no worker reports anything for this many seconds while samples are in flight.")
# ---- GPU numerics / seeding --------------------------------------------
p.add_argument("--seed", type=int, default=0,
help="Per-sample torch seed base: the x0 draws of every sample are reseeded "
"from sha1(order_id/seed/stage/n), so outputs do not depend on batching.")
p.add_argument("--encoder_bf16", action=argparse.BooleanOptionalAction, default=True,
help="bf16 autocast in the scene encoders (FPS anchors and the encoder output stay "
"fp32). CUDA only.")
p.add_argument("--denoiser_bf16", action=argparse.BooleanOptionalAction, default=True,
help="bf16 autocast in the denoiser blocks (ODE state, residual stream, embedding "
"and output heads stay fp32). CUDA only.")
p.add_argument("--tf32", action=argparse.BooleanOptionalAction, default=True,
help="TF32 tensor cores for the remaining fp32 matmuls. CUDA only.")
p.add_argument("--cuda_graph", action=argparse.BooleanOptionalAction, default=True,
help="Capture each denoiser ODE loop as a CUDA graph per batch shape (same kernels, no "
"launch overhead; one capture per new shape). CUDA only.")
p.add_argument("--compile", action=argparse.BooleanOptionalAction, default=False,
help="torch.compile the denoiser step (fused elementwise kernels); compiles once per "
"model and batch shape on first use (tens of seconds). CUDA only.")
p.add_argument("--cudnn_sdpa", action=argparse.BooleanOptionalAction, default=True,
help="Allow PyTorch's cuDNN attention backend (bf16; runtime-compiled kernels per new "
"shape, cached on disk). --no-cudnn_sdpa uses the flash / memory-efficient backends.")
p.add_argument("--fps_kernel", choices=["torch", "triton"], default="triton",
help="Scene-encoder anchor FPS: 'torch' loop (~6 launches per anchor) or one fused "
"Triton kernel per call (identical indices). CUDA only.")
p.add_argument("--output", default="submission.json")
p.add_argument("--limit", type=int, default=0,
help="If >0, only process the first N samples per split (debug)")
# ---- stage-2 refinement (optional) -----------------------------------
p.add_argument("--stage2_ckpt", default=None,
help="Stage-2 refinement checkpoint. Falls back to "
"$S23DR_STAGE2_CKPT then params['stage2_ckpt']. "
"When unset, runs stage-1 only.")
p.add_argument("--stage2_n_pts", type=int, default=None,
help="Stage-2 scene points (default: ckpt args / 16384).")
p.add_argument("--stage2_n_sample_steps", type=int, default=50,
help="Stage-2 ODE steps (default: 50 β 2.5x training, "
"inference oversampling).")
p.add_argument("--stage2_validity_thresh", type=float, default=0.0,
help="Stage-2 validity logit threshold (default: 0.0).")
p.add_argument("--stage2_above_m", type=float, default=0.5,
help="Hull inflation upward (metres). Default 0.5.")
p.add_argument("--stage2_below_m", type=float, default=0.5,
help="Hull inflation downward (metres). Default 0.5.")
p.add_argument("--stage2_side_m", type=float, default=0.5,
help="Hull inflation laterally in X/Y (metres). Default 0.5.")
p.add_argument("--stage2_n_col_oversample", type=int, default=None,
help="Stage-2 COLMAP oversample before sampling drops to n_pts//2. "
"Default: 10k for random sampling.")
p.add_argument("--stage2_n_dep_oversample", type=int, default=None,
help="Stage-2 depth oversample before sampling drops to n_pts//2. "
"Default: 10k for random sampling.")
p.add_argument("--stage2_n_depth_per_image_cap", type=int, default=30_000,
help="Cap on per-image depth pixels considered before the hull test.")
p.add_argument("--stage2_sampling", choices=["random"], default="random",
help="Stage-2 scene sampling mode. The eval/submission path "
"is locked to random sampling.")
p.add_argument("--stage2_fps_max_exact_iters", type=int, default=None,
help=argparse.SUPPRESS)
# ---- stage-2 density-contrast hyperparams (only used when --stage2_sampling=voxel) -
p.add_argument("--stage2_density_voxel_size_m", type=float, default=0.25)
p.add_argument("--stage2_density_kernel_radius", type=int, default=3)
p.add_argument("--stage2_density_kernel_axis",
choices=["cube", "x", "y", "z"], default="cube")
p.add_argument("--stage2_density_response_power", type=float, default=1.0)
p.add_argument("--stage2_density_planarity_suppression", type=float, default=1.0)
p.add_argument("--stage2_density_planarity_radius", type=int, default=1)
p.add_argument("--stage2_density_planarity_min_points", type=int, default=12)
p.add_argument("--stage2_density_min_per_voxel", type=int, default=0)
# ---- inference-time ensembling ---------------------------------------
p.add_argument("--ensemble_n", type=int, default=16,
help="Run N stage-1 random-init trajectories and combine "
"them per --ensemble_mode. Default 16 (paired with "
"--ensemble_strategy union_hull this is ~1.2x wall "
"since stage-2 shares one encoder pass at B=N). "
"Set to 1 to disable.")
p.add_argument("--ensemble_merge_m", type=float, default=0.5,
help="Vertex match threshold in metres for ensemble "
"selection (medoid Hungarian distance, position "
"refinement correspondents, consensus clustering). "
"Default 0.5 β matches the HSS metric's vert_thresh.")
p.add_argument("--ensemble_strategy",
choices=["union_hull", "per_seed"], default="union_hull",
help="How stage-2 is run across the N ensemble members. "
"'union_hull' (default) builds ONE stage-2 scene "
"from the union of all stage-1 vertex predictions, "
"encodes once, and runs a B=N denoiser batch with "
"per-slot init_verts. 'per_seed' runs N independent "
"(build β encode β denoise) passes; slower but more "
"robust if union-hull occasionally fails.")
p.add_argument("--ensemble_mode",
choices=["medoid", "consensus", "confidence"],
default="medoid",
help="How to combine the N ensemble runs. "
"'medoid' (default) picks the run most similar to "
"the others by Hungarian-matched distance. "
"'confidence' picks the run with the highest mean "
"validity logit. 'consensus' merges vertices and "
"majority-votes edges (lost recall in earlier tests).")
p.add_argument("--no_position_refine", action="store_true",
help="Disable position refinement. By default, after the "
"selector (medoid / confidence) picks a run, each "
"vertex of that run is replaced with the per-axis "
"aggregate (see --ensemble_refine_agg) of itself "
"and its Hungarian-matched correspondents in the "
"other N-1 runs (within --ensemble_merge_m). "
"Topology unchanged; only vertex positions denoised.")
p.add_argument("--ensemble_refine_agg", choices=["median", "mean", "wmean"],
default="mean",
help="Aggregator for position refinement. 'mean' "
"(default) has lower variance under iid noise; "
"'median' is robust to outlier correspondents; "
"'wmean' is a softmax-of-logit weighted mean (each "
"correspondent contributes proportional to "
"exp(validity_logit), so high-confidence runs "
"dominate). 'wmean' only kicks in when validity "
"logits are non-trivial β falls back to plain mean "
"when weights are uniform or missing.")
p.add_argument("--ensemble_top_k", type=int, default=0,
help="Soft-medoid: restrict the correspondent / voter set "
"used by position refinement and edge voting to the "
"K most central runs (lowest pairwise Hungarian "
"distance). 0 (default) = use all N. Typical values "
"for N=16: 5-8. The picked run (medoid) is always "
"included.")
p.add_argument("--no_edge_vote", action="store_true", default=True,
help="Keep the picked medoid/confidence run's edges "
"verbatim. This is the default.")
p.add_argument("--edge_vote", action="store_false", dest="no_edge_vote",
help="Enable edge majority voting: after selection each "
"non-picked run's edges are relabelled into the picked "
"run's vertex index space via the same Hungarian match "
"used for position refinement, and edges with >= "
"--ensemble_edge_vote_frac of votes survive.")
p.add_argument("--ensemble_edge_vote_frac", type=float, default=0.5,
help="Edge vote fraction (default 0.5 = strict majority). "
"An edge (i,j) in picked-vertex space is kept iff at "
"least ceil(M * frac) runs vote for it, where M is "
"the active voter set (top_k if set, else N).")
p.add_argument("--ensemble_vertex_vote_frac", type=float, default=0.0,
help="Vertex consensus drop fraction (default 0.0 = off). "
"When > 0, a picked-run vertex survives iff at least "
"ceil(M * frac) voter runs have a Hungarian "
"correspondent within tau. The picked run itself is "
"always one voter (self-vote). Tightens precision by "
"dropping spurious one-run-only detections β "
"complements --ensemble_edge_vote. Used by both "
"medoid/confidence modes (picked-then-refine) and "
"consensus mode (sets the cluster-support threshold).")
p.add_argument("--ensemble_stage2_last_k", type=int, default=1,
help="Average the last K stage-2 denoiser steps' "
"predictions (positions + validity / edge logits) "
"before thresholding. 1 (default) = use only the "
"final step (current behaviour). 3-5 mildly smooths "
"ODE jitter near the trajectory endpoint at zero "
"extra compute.")
p.add_argument("--ensemble_selector", choices=["legacy", "ranker", "fixed"],
default="legacy",
help="Final ensemble chooser. 'legacy' (default) keeps the "
"medoid/confidence/consensus path with no reranker. "
"'ranker' builds "
"raw/refined/voted/additive-edge candidates and picks "
"with --ensemble_ranker_path if present, otherwise a "
"small built-in heuristic. 'fixed' picks a named "
"candidate family.")
p.add_argument("--ensemble_fixed_candidate", default="confidence_mean_add",
help="Candidate name used by --ensemble_selector fixed. "
"Default confidence_mean_add, falling back to "
"medoid_mean_add when the confidence candidate is "
"identical to the medoid and therefore absent.")
p.add_argument("--ensemble_topk_fuse", type=int, default=3,
help="Top-K ranker-scored candidates to fuse (mean-refine "
"positions + edge-vote union) when "
"--ensemble_selector=ranker. 1 disables fusion and "
"keeps the argmax candidate.")
p.add_argument("--ensemble_ranker_path", default="ensemble_ranker_v5.npz",
help="NPZ produced by --train_ensemble_ranker_jsonl. Used "
"only when --ensemble_selector=ranker. If missing, "
"ranker mode falls back to a heuristic scorer.")
p.add_argument("--ensemble_candidate_dump", default=None,
help="In --sanity mode, write ranker candidate features "
"and GT HSS labels as JSONL for fast selector training.")
p.add_argument("--train_ensemble_ranker_jsonl", default=None,
help="Train the tiny NumPy ridge ranker from a candidate "
"JSONL dump and exit. No model checkpoint/GPU needed.")
p.add_argument("--ensemble_ranker_out", default="ensemble_ranker.npz",
help="Output path for --train_ensemble_ranker_jsonl.")
p.add_argument("--ensemble_ranker_l2", type=float, default=1e-2,
help="Ridge L2 for --train_ensemble_ranker_jsonl.")
# ---- local sanity check (no submission) ------------------------------
p.add_argument("--sanity", action="store_true",
help="Local pre-submission sanity check: load default ckpt, "
"run the inference pipeline on validation samples of the "
"public trainval dataset, score against GT, print HSS, and "
"exit. Writes no submission.json.")
p.add_argument("--sanity_n", type=int, default=0,
help="Number of val samples to score in --sanity mode (the first N of the split). "
"0 (default) means score the entire split. Without --sanity_data_dir, N > 0 streams "
"only those samples from the Hub; 0 downloads the whole split.")
p.add_argument("--sanity_split", default="validation",
help="Split to draw sanity samples from (default 'validation').")
p.add_argument("--sanity_dataset", default="usm3d/hoho22k_2026_trainval",
help="HF dataset id with GT used for --sanity scoring (gated: accept its terms on the "
"Hub and log in with 'hf auth login').")
p.add_argument("--sanity_cache_dir", default="cache",
help="Cache dir for --sanity data: <dir>/<dataset>/data/<split>/ holds the full shards "
"(--sanity_n 0), <dir>/<dataset>/stream/<split>/ the streamed sample prefixes; later "
"runs that need no more samples reuse them offline.")
p.add_argument("--sanity_data_dir", default=None,
help="Use the *.tar files below this dir (GT included) instead of downloading.")
p.add_argument("--sanity_ensemble_diagnostics", action="store_true",
help="In --sanity mode, score ensemble alternatives: "
"member0, medoid pick, confidence pick, final fused, "
"and oracle-best member. Diagnostic only; normal "
"predictions are unchanged.")
return p.parse_args(argv)
def main(argv=None) -> Optional[Dict[str, Any]]:
"""Returns the pipeline summary (``run_pipeline``; with the sanity means in --sanity mode)."""
args = parse_args(argv)
if args.train_ensemble_ranker_jsonl:
train_ensemble_ranker_jsonl(
args.train_ensemble_ranker_jsonl,
args.ensemble_ranker_out,
l2=args.ensemble_ranker_l2,
)
return None
if args.batch_samples < 1 or args.n_workers < 1:
raise SystemExit("--batch_samples and --n_workers must be >= 1")
# Workers start first: their imports and warm-up overlap with the dataset indexing and model loads.
# SIGINT is ignored while they are spawned, so each worker ignores it from its first instruction on.
previous = signal.signal(signal.SIGINT, signal.SIG_IGN)
workers = start_workers(args.n_workers)
def on_sigint(_signum, _frame): # Ctrl-C: stop now (a running download's threads would keep the process alive)
print("[interrupt] stopping", flush=True)
kill_workers(workers)
os._exit(130)
signal.signal(signal.SIGINT, on_sigint)
try:
return _main(args, workers)
except BaseException:
kill_workers(workers)
raise
finally:
signal.signal(signal.SIGINT, previous)
def _main(args, workers) -> Dict[str, Any]:
hf_splits: Dict[str, Any] = {}
if args.sanity:
# --sanity needs neither the test data nor params.json: score the public trainval GT.
params: Dict[str, Any] = {}
if Path(args.params).exists():
with open(args.params) as f:
params = json.load(f)
items = sanity_items(args)
else:
print("------------ Loading dataset ------------", flush=True)
with open(args.params) as f:
params = json.load(f)
print(params, flush=True)
print("pwd:", flush=True); os.system("pwd")
os.system("ls -lahtr")
print(f"{args.data_dir}/"); os.system(f"ls -lahtr {shlex.quote(args.data_dir)}/ 2>/dev/null")
print(f"{args.data_dir}/data"); os.system(f"ls -lahtrR {shlex.quote(args.data_dir)}/data 2>/dev/null")
data_path = resolve_data_dir(args.data_dir, params)
files = split_tars(data_path)
if args.loader == "tar":
items = tar_items(files, args.limit)
else:
items, hf_splits = hf_items(data_path, files, args.limit)
print(f"[data] {len(items)} samples (--loader {args.loader}, --limit {args.limit})", flush=True)
# ---- model: loaded ONCE -----------------------------------------------
ckpt_path = resolve_ckpt_path(args.ckpt, params)
if args.device == "cuda" and not torch.cuda.is_available():
if hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
device = torch.device("mps")
else:
device = torch.device("cpu")
else:
device = torch.device(args.device)
if device.type == "cpu":
print("[warn] CUDA/MPS unavailable β running on CPU; this will be slow.", flush=True)
if device.type == "cuda":
# This process's CPU work is now only the GPU loop's small batch copies: torch's 16-thread OpenMP
# pool made them slower (stage-2 batch assembly +15 ms/sample, measured), so one thread.
torch.set_num_threads(1)
model, ckpt_args = load_model(ckpt_path, device)
n_pts = (args.n_pts if args.n_pts is not None
else ckpt_args.get("n_pts", 8192))
use_depth = ckpt_args.get("use_depth", True)
n_sample_steps = (args.n_sample_steps if args.n_sample_steps is not None
else ckpt_args.get("n_sample_steps", 50))
validity_thresh = (args.validity_thresh if args.validity_thresh is not None
else ckpt_args.get("validity_thresh", 0.0))
print(f"[infer] n_pts={n_pts} use_depth={use_depth} "
f"n_sample_steps={n_sample_steps} validity_thresh={validity_thresh} "
f"torch_threads={torch.get_num_threads()} n_workers={args.n_workers} batch_samples={args.batch_samples} partial_batch={args.partial_batch} "
f"colmap_order={args.colmap_order}", flush=True)
stage2_cfg = _build_stage2_cfg(args, params, device)
host_cfg = copy.copy(stage2_cfg) # what the workers need: every knob except the GPU model
host_cfg.model = None
opts = {"n_pts": n_pts, "use_depth": use_depth, "colmap_order": args.colmap_order, "cfg": host_cfg,
"hf_splits": hf_splits, "sanity": args.sanity,
"diagnostics": args.sanity and (args.sanity_ensemble_diagnostics or args.ensemble_candidate_dump is not None),
"dump": args.sanity and args.ensemble_candidate_dump is not None}
for p, tx, _rx in workers:
try:
tx.send(("init", opts))
except (BrokenPipeError, ConnectionResetError): # a worker died during start-up
p.join(timeout=5)
check_workers(workers)
raise
if args.sanity:
return run_sanity_check(workers, items, model, stage2_cfg, device, n_sample_steps, validity_thresh,
args)
# ---- inference --------------------------------------------------------
print("------------ Running inference ------------", flush=True)
solution, summary = run_pipeline(workers, items, model, stage2_cfg, device, n_sample_steps,
validity_thresh, args, _print_prediction)
print("------------ Saving results ------------", flush=True)
with open(args.output, "w") as f:
json.dump(solution, f)
print(f"[done] wrote {len(solution)} predictions β {args.output} (FAILED: {summary['n_failed']})", flush=True)
return summary
if __name__ == "__main__":
summary = main()
if summary is not None and summary["n_failed"]:
print(f"[done] {summary['n_failed']} of {summary['n']} samples FAILED (see '[predict] ... FAILED' above); "
f"their predictions are empty solutions. Exit code 1.", flush=True)
sys.exit(1)
"""S23DR 2026 β submission script (trained WireframeDiffusion).
HF Competitions entry point: the test runner executes ``python script.py``
in the submission repo's working directory. We therefore:
* Load ``params.json`` (mirrors ``usm3d/empty_submission_2026``).
* Resolve the dataset (test server: ``/tmp/data``; local: snapshot_download).
* Read the samples straight from the webdataset tars (``--loader tar``; or
through the HF loader script, ``--loader hf``), **load the diffusion model
exactly once** on CUDA, run inference, and write ``submission.json``.
Online preprocessing
--------------------
Uses V10 online preprocessing by default β ``build_scene_input`` produces
the V10 feature point cloud (COLMAP+camera tokens + depth-unprojected
tokens, per-point RGB, soft top-2 gestalt). Matches the cache layout the
model was trained on.
Efficiency notes
----------------
* Models live only in the main process, which runs one GPU loop over batches
of ``--batch_samples`` samples (stage 1, then stage 2; fixed batch shape).
* All CPU work (tar read, COLMAP parse, scene build, stage-2 hull crop,
ensemble selection) runs in ``--n_workers`` spawned worker processes with one
BLAS thread each; the worker that preprocessed a sample keeps its stage-1
cache and does that sample's stage-2 build and selection (see run_pipeline).
* A sample whose CPU work raises gets the empty solution and is reported as
FAILED (counted at the end); a GPU error or a dead / stalled worker stops
the run.
Specifying the checkpoint
-------------------------
Resolution order (first hit wins):
1. ``--ckpt PATH`` (CLI, for local testing)
2. ``S23DR_CKPT`` env var (set by SLURM / docker entrypoint)
3. ``params['ckpt']`` (extra field in params.json)
4. ``./test_checkpoint.pth`` (default β what you'd commit to the
submission repo)
The script auto-resolves model architecture (small vs. large) from the
``args`` dict embedded in the checkpoint, so the same script handles both.
Local sanity check
------------------
Before pushing a submission repo, run::
python script.py --sanity
This loads the public ``usm3d/hoho22k_2026_trainval`` dataset (which has
GT wireframes), runs the trained model on a few validation samples, and
prints per-sample + mean HSS / F1 / IoU. It writes no submission.json β
its only job is to verify that the checkpoint loads, the V10 online
preprocessing path works end-to-end, and the model produces sane output
before you submit.
"""
from __future__ import annotations
import argparse
import copy
import fcntl
import hashlib
import io
import json
import multiprocessing as mp
import multiprocessing.connection
import os
import signal
import queue
import resource
import shlex
import sys
import threading
import time
import traceback
import zipfile
from collections import Counter, defaultdict, deque
from contextlib import contextmanager
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Tuple
import numpy as np
import torch
try:
from datasets import load_dataset
except ModuleNotFoundError:
load_dataset = None
from tqdm import tqdm
# --- our project imports ----------------------------------------------------
from data.preprocess import (
read_colmap_zip,
_cam_matrix_from_image,
build_scene_input,
_image_to_rgb_array,
gestalt_img_to_ids,
_camera_for_image,
_resolve_colmap_image,
GESTALT_CLASSES,
)