Insta360-Research commited on
Commit
1ba04d7
·
verified ·
1 Parent(s): 68c2f9e

Upload 3 files

Browse files
scripts/infer_unisharp.py ADDED
@@ -0,0 +1,814 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import logging
6
+ import math
7
+ import os
8
+ import re
9
+ import sys
10
+ from pathlib import Path
11
+ from typing import Any, Literal
12
+
13
+ import numpy as np
14
+ import torch
15
+ from PIL import Image, ImageOps
16
+
17
+ REPO_ROOT = Path(__file__).resolve().parents[1]
18
+ sys.path.insert(0, str(REPO_ROOT))
19
+
20
+ from unisharp.cli.unified_trainer import UnifiedTrainer # noqa: E402
21
+ from unisharp.models.unisharp_feature import UnisharpFeatureConfig, UnisharpFeatureModel # noqa: E402
22
+ from unisharp.utils.camera_utils import transform_gaussians_to_world # noqa: E402
23
+ from unisharp.utils.color_space import linearRGB2sRGB # noqa: E402
24
+ from unisharp.utils.fisheye_geer import render_gaussians_fisheye624 # noqa: E402
25
+ from unisharp.utils.gaussians import save_ply # noqa: E402
26
+ from unisharp.utils.gsplat import GSplatRenderer # noqa: E402
27
+ from unisharp.utils.camera_projection import build_extrinsics_w2c # noqa: E402
28
+ from unisharp.utils.rayfit_camera import fit_fisheye624_params_from_rays, fit_pinhole_intrinsics_from_rays # noqa: E402
29
+
30
+
31
+ LOGGER = logging.getLogger("infer_unisharp")
32
+ IMAGE_SUFFIXES = {".png", ".jpg", ".jpeg", ".webp", ".PNG", ".JPG", ".JPEG", ".WEBP"}
33
+ CameraKind = Literal["perspective", "fisheye", "panorama"]
34
+ FACE_NAMES = ["up", "back", "left", "front", "right", "down"]
35
+
36
+
37
+ def _configure_torchhub_cache() -> None:
38
+ torchhub_dir = REPO_ROOT / "checkpoints" / "torchhub"
39
+ torchhub_dir.mkdir(parents=True, exist_ok=True)
40
+ os.environ["TORCH_HOME"] = str(torchhub_dir)
41
+ torch.hub.set_dir(str(torchhub_dir))
42
+
43
+
44
+ def _feature_config_from_checkpoint(checkpoint_path: Path, ckpt: dict[str, Any]) -> UnisharpFeatureConfig:
45
+ cfg = UnisharpFeatureConfig()
46
+ merged: dict[str, Any] = {}
47
+ cfg_payload = ckpt.get("config", {})
48
+ if isinstance(cfg_payload, dict):
49
+ merged.update(cfg_payload)
50
+ for key in cfg.__dict__.keys():
51
+ if key in ckpt:
52
+ merged[key] = ckpt[key]
53
+ config_path = checkpoint_path.parent / "config.json"
54
+ if config_path.exists():
55
+ try:
56
+ sidecar = json.loads(config_path.read_text(encoding="utf-8"))
57
+ except Exception:
58
+ sidecar = None
59
+ if isinstance(sidecar, dict):
60
+ merged.update({k: v for k, v in sidecar.items() if k in cfg.__dict__})
61
+ for key in cfg.__dict__.keys():
62
+ if key in merged:
63
+ setattr(cfg, key, merged[key])
64
+ return cfg
65
+
66
+
67
+ def _load_model(checkpoint_path: Path, device: torch.device) -> tuple[UnisharpFeatureModel, int]:
68
+ try:
69
+ ckpt = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
70
+ except TypeError:
71
+ ckpt = torch.load(checkpoint_path, map_location="cpu")
72
+ if not isinstance(ckpt, dict):
73
+ raise ValueError(f"Expected checkpoint dict, got {type(ckpt)} from {checkpoint_path}")
74
+ cfg = _feature_config_from_checkpoint(checkpoint_path, ckpt)
75
+ model = UnisharpFeatureModel(cfg).to(device)
76
+ missing, unexpected = model.load_from_checkpoint(str(checkpoint_path), strict=False)
77
+ if missing or unexpected:
78
+ LOGGER.warning("Loaded checkpoint with missing=%s unexpected=%s", missing[:20], unexpected[:20])
79
+ model.eval()
80
+ return model, int(ckpt.get("step", 0))
81
+
82
+
83
+ def _collect_image_paths(args: argparse.Namespace) -> list[Path]:
84
+ paths: list[Path] = []
85
+ if args.image is not None:
86
+ paths.append(Path(args.image))
87
+ if args.image_list is not None:
88
+ for raw in Path(args.image_list).read_text(encoding="utf-8").splitlines():
89
+ line = raw.strip()
90
+ if line and not line.startswith("#"):
91
+ paths.append(Path(line))
92
+ if args.image_dir is not None:
93
+ root = Path(args.image_dir)
94
+ paths.extend(sorted(p for p in root.iterdir() if p.is_file() and p.suffix in IMAGE_SUFFIXES))
95
+ if not paths:
96
+ raise ValueError("Provide --image, --image-list, or --image-dir.")
97
+ return paths[: int(args.max_images)] if int(args.max_images) > 0 else paths
98
+
99
+
100
+ def _load_rgb_u8(image_path: Path, max_long_edge: int) -> torch.Tensor:
101
+ with Image.open(image_path) as raw:
102
+ image = ImageOps.exif_transpose(raw).convert("RGB")
103
+ if int(max_long_edge) > 0:
104
+ w, h = image.size
105
+ scale = min(1.0, float(max_long_edge) / float(max(h, w)))
106
+ if scale < 1.0:
107
+ image = image.resize(
108
+ (max(1, int(round(w * scale))), max(1, int(round(h * scale)))),
109
+ resample=Image.BILINEAR,
110
+ )
111
+ arr = np.asarray(image, dtype=np.uint8).copy()
112
+ return torch.from_numpy(arr).permute(2, 0, 1).contiguous()
113
+
114
+
115
+ def _to_u8_hwc(img_chw: torch.Tensor) -> np.ndarray:
116
+ if img_chw.dtype == torch.uint8:
117
+ return img_chw.permute(1, 2, 0).detach().cpu().numpy()
118
+ x = img_chw.detach().to(torch.float32).clamp(0.0, 1.0)
119
+ return (x * 255.0).round().to(torch.uint8).permute(1, 2, 0).cpu().numpy()
120
+
121
+
122
+ def _crop_border_u8(frame: np.ndarray, fraction: float) -> np.ndarray:
123
+ if float(fraction) <= 0.0:
124
+ return frame
125
+ if frame.ndim < 2:
126
+ return frame
127
+ h, w = int(frame.shape[0]), int(frame.shape[1])
128
+ crop_y = int(round(float(h) * float(fraction)))
129
+ crop_x = int(round(float(w) * float(fraction)))
130
+ if crop_y <= 0 and crop_x <= 0:
131
+ return frame
132
+ if crop_y * 2 >= h or crop_x * 2 >= w:
133
+ return frame
134
+ return frame[crop_y : h - crop_y, crop_x : w - crop_x].copy()
135
+
136
+
137
+ def _save_gif(frames: list[np.ndarray], out_file: Path, duration_ms: int) -> None:
138
+ if not frames:
139
+ raise ValueError(f"No frames to save for {out_file}")
140
+ out_file.parent.mkdir(parents=True, exist_ok=True)
141
+ pil_frames = [Image.fromarray(frame) for frame in frames]
142
+ pil_frames[0].save(
143
+ out_file,
144
+ save_all=True,
145
+ append_images=pil_frames[1:],
146
+ duration=int(duration_ms),
147
+ loop=0,
148
+ disposal=2,
149
+ )
150
+
151
+
152
+ def _slug_from_path(image_path: Path) -> str:
153
+ raw = f"{image_path.parent.name}_{image_path.stem}"
154
+ return re.sub(r"[^A-Za-z0-9_.-]+", "_", raw)
155
+
156
+
157
+ def _normalize_rays(rays: torch.Tensor) -> torch.Tensor:
158
+ rays_f = rays.detach().to(torch.float32)
159
+ return rays_f / torch.linalg.vector_norm(rays_f, dim=1, keepdim=True).clamp(min=1e-6)
160
+
161
+
162
+ def _angular_span_deg(a: np.ndarray) -> float:
163
+ a = a[np.isfinite(a)]
164
+ if a.size < 2:
165
+ return 0.0
166
+ return float(np.degrees(np.nanpercentile(a, 99.0) - np.nanpercentile(a, 1.0)))
167
+
168
+
169
+ def _angle_between_deg(a: np.ndarray, b: np.ndarray) -> float:
170
+ denom = max(float(np.linalg.norm(a) * np.linalg.norm(b)), 1e-8)
171
+ return float(np.degrees(np.arccos(np.clip(float(np.dot(a, b)) / denom, -1.0, 1.0))))
172
+
173
+
174
+ def _ray_fov_stats(rays_b3hw: torch.Tensor) -> dict[str, float]:
175
+ rays = _normalize_rays(rays_b3hw)[0].detach().cpu().numpy()
176
+ _, h, w = rays.shape
177
+ rows = [max(0, min(h - 1, int(round(h * q)))) for q in (0.25, 0.5, 0.75)]
178
+ cols = [max(0, min(w - 1, int(round(w * q)))) for q in (0.25, 0.5, 0.75)]
179
+ h_spans = []
180
+ for row in rows:
181
+ lon = np.unwrap(np.arctan2(rays[0, row], rays[2, row]))
182
+ h_spans.append(_angular_span_deg(lon))
183
+ v_spans = []
184
+ for col in cols:
185
+ x = rays[0, :, col]
186
+ y = rays[1, :, col]
187
+ z = rays[2, :, col]
188
+ lat = np.arctan2(y, np.sqrt(x * x + z * z))
189
+ v_spans.append(_angular_span_deg(lat))
190
+ corners = [rays[:, 0, 0], rays[:, 0, w - 1], rays[:, h - 1, 0], rays[:, h - 1, w - 1]]
191
+ diag = max(_angle_between_deg(corners[i], corners[j]) for i in range(4) for j in range(i + 1, 4))
192
+ return {
193
+ "horizontal_fov_deg": float(np.median(h_spans)),
194
+ "vertical_fov_deg": float(np.median(v_spans)),
195
+ "diagonal_fov_deg": float(diag),
196
+ "aspect": float(w) / float(max(h, 1)),
197
+ }
198
+
199
+
200
+ def _classify_camera(stats: dict[str, float], args: argparse.Namespace) -> CameraKind:
201
+ forced = str(args.camera).strip().lower()
202
+ if forced != "auto":
203
+ return {"pinhole": "perspective", "erp": "panorama"}.get(forced, forced) # type: ignore[return-value]
204
+ aspect = float(stats["aspect"])
205
+ h_fov = float(stats["horizontal_fov_deg"])
206
+ v_fov = float(stats["vertical_fov_deg"])
207
+ diag_fov = float(stats["diagonal_fov_deg"])
208
+ if (
209
+ float(args.panorama_aspect_min) <= aspect <= float(args.panorama_aspect_max)
210
+ and h_fov >= float(args.panorama_hfov_threshold_deg)
211
+ and v_fov >= float(args.panorama_vfov_threshold_deg)
212
+ ):
213
+ return "panorama"
214
+ fishlike_aspect = aspect <= float(args.fisheye_max_aspect)
215
+ fishlike_fov = (
216
+ max(h_fov, v_fov) >= float(args.fisheye_fov_threshold_deg)
217
+ or (diag_fov >= float(args.fisheye_diag_threshold_deg) and v_fov >= float(args.fisheye_vfov_min_deg))
218
+ )
219
+ if fishlike_aspect and fishlike_fov:
220
+ return "fisheye"
221
+ return "perspective"
222
+
223
+
224
+ def _empty_ray_stats() -> dict[str, float]:
225
+ return {
226
+ "horizontal_fov_deg": float("nan"),
227
+ "vertical_fov_deg": float("nan"),
228
+ "diagonal_fov_deg": float("nan"),
229
+ "aspect": float("nan"),
230
+ }
231
+
232
+
233
+ def _pinhole_intrinsics_from_values(values: list[float] | None, *, device: torch.device) -> torch.Tensor | None:
234
+ if values is None:
235
+ return None
236
+ vals = [float(v) for v in values]
237
+ if len(vals) == 4:
238
+ fx, fy, cx, cy = vals
239
+ k = torch.tensor(
240
+ [[fx, 0.0, cx], [0.0, fy, cy], [0.0, 0.0, 1.0]],
241
+ dtype=torch.float32,
242
+ device=device,
243
+ )
244
+ elif len(vals) == 9:
245
+ k = torch.tensor(vals, dtype=torch.float32, device=device).reshape(3, 3)
246
+ else:
247
+ raise ValueError("--camera-intrinsics expects 4 values (fx fy cx cy) or 9 row-major K values.")
248
+ return k.unsqueeze(0)
249
+
250
+
251
+ def _fisheye624_params_from_values(values: list[float] | None, *, device: torch.device) -> torch.Tensor | None:
252
+ if values is None:
253
+ return None
254
+ vals = [float(v) for v in values]
255
+ if len(vals) == 8:
256
+ vals = vals + [0.0] * 8
257
+ if len(vals) != 16:
258
+ raise ValueError("--camera-params expects 8 or 16 Fisheye624 values.")
259
+ return torch.tensor(vals, dtype=torch.float32, device=device).reshape(1, 16)
260
+
261
+
262
+ def _load_camera_json(path: Path | None) -> Any:
263
+ if path is None:
264
+ return None
265
+ payload = json.loads(Path(path).read_text(encoding="utf-8"))
266
+ if not isinstance(payload, dict):
267
+ raise ValueError("--camera-json must point to a JSON object.")
268
+ return payload
269
+
270
+
271
+ def _camera_json_for_image(payload: Any, image_path: Path) -> dict[str, Any] | None:
272
+ if not isinstance(payload, dict):
273
+ return None
274
+ images = payload.get("images", None)
275
+ if isinstance(images, dict):
276
+ keys = [
277
+ str(image_path),
278
+ image_path.as_posix(),
279
+ image_path.name,
280
+ image_path.stem,
281
+ ]
282
+ for key in keys:
283
+ value = images.get(key, None)
284
+ if isinstance(value, dict):
285
+ base = payload.get("default", {})
286
+ merged = dict(base) if isinstance(base, dict) else {}
287
+ merged.update(value)
288
+ return merged
289
+ if isinstance(payload.get("default", None), dict):
290
+ return dict(payload["default"])
291
+ return dict(payload)
292
+
293
+
294
+ def _values_from_camera_json(entry: dict[str, Any] | None, *names: str) -> list[float] | None:
295
+ if not isinstance(entry, dict):
296
+ return None
297
+ for name in names:
298
+ value = entry.get(name, None)
299
+ if value is None:
300
+ continue
301
+ if isinstance(value, dict):
302
+ if all(k in value for k in ("fx", "fy", "cx", "cy")):
303
+ return [float(value["fx"]), float(value["fy"]), float(value["cx"]), float(value["cy"])]
304
+ if "K" in value:
305
+ value = value["K"]
306
+ else:
307
+ continue
308
+ if isinstance(value, (list, tuple)):
309
+ if len(value) == 3 and all(isinstance(row, (list, tuple)) for row in value):
310
+ flat = [float(x) for row in value for x in row]
311
+ else:
312
+ flat = [float(x) for x in value]
313
+ return flat
314
+ return None
315
+
316
+
317
+ def _camera_name_from_json(entry: dict[str, Any] | None) -> str | None:
318
+ if not isinstance(entry, dict):
319
+ return None
320
+ value = entry.get("camera", entry.get("camera_model", entry.get("type", None)))
321
+ return str(value).strip().lower() if value is not None and str(value).strip() else None
322
+
323
+
324
+ @torch.no_grad()
325
+ def _predict_unik3d_rays(
326
+ model: UnisharpFeatureModel,
327
+ image_u8: torch.Tensor,
328
+ *,
329
+ image_h: int,
330
+ image_w: int,
331
+ ) -> torch.Tensor:
332
+ model.feature_extractor.forward(
333
+ rgb_u8=image_u8,
334
+ target_h=int(image_h),
335
+ target_w=int(image_w),
336
+ use_predicted_rays=True,
337
+ )
338
+ output = model.feature_extractor._unisharp_last_unik3d_output
339
+ if not isinstance(output, dict) or not torch.is_tensor(output.get("rays", None)):
340
+ raise RuntimeError("UniK3D did not return predicted rays for camera classification.")
341
+ return output["rays"]
342
+
343
+
344
+ def _build_forward_poses(num_views: int, distance_m: float, device: torch.device) -> list[torch.Tensor]:
345
+ poses = []
346
+ r_c2w = torch.eye(3, dtype=torch.float32, device=device)
347
+ views = max(1, int(num_views))
348
+ for idx in range(views):
349
+ alpha = float(idx + 1) / float(views)
350
+ eye = torch.tensor([0.0, 0.0, float(distance_m) * alpha], dtype=torch.float32, device=device)
351
+ poses.append(build_extrinsics_w2c(r_c2w, eye, "c2w"))
352
+ return poses
353
+
354
+
355
+ def _build_rotate_poses(num_views: int, radius_m: float, device: torch.device) -> list[torch.Tensor]:
356
+ poses = []
357
+ src_r_c2w = torch.eye(3, dtype=torch.float32, device=device)
358
+ views = max(1, int(num_views))
359
+ for idx in range(views):
360
+ theta = -2.0 * math.pi * float(idx) / float(views)
361
+ eye = torch.tensor(
362
+ [
363
+ float(radius_m) * math.sin(theta),
364
+ float(radius_m) * math.cos(theta),
365
+ 0.0,
366
+ ],
367
+ dtype=torch.float32,
368
+ device=device,
369
+ )
370
+ poses.append(build_extrinsics_w2c(src_r_c2w, eye, "c2w"))
371
+ return poses
372
+
373
+
374
+ def _render_pinhole_frame(
375
+ renderer: GSplatRenderer,
376
+ gaussians: Any,
377
+ *,
378
+ extr_w2c: torch.Tensor,
379
+ intrinsics: torch.Tensor,
380
+ image_h: int,
381
+ image_w: int,
382
+ ) -> np.ndarray:
383
+ out = renderer(
384
+ gaussians,
385
+ extrinsics=extr_w2c[None],
386
+ intrinsics=intrinsics[None],
387
+ image_width=int(image_w),
388
+ image_height=int(image_h),
389
+ )
390
+ alpha = out.alpha.detach().to(torch.float32).clamp(0.0, 1.0)
391
+ rgb = linearRGB2sRGB((out.color / alpha.clamp(min=1e-4)).clamp(0.0, 1.0)).clamp(0.0, 1.0)
392
+ return _to_u8_hwc(rgb[0])
393
+
394
+
395
+ def _render_fisheye_frame(
396
+ gaussians: Any,
397
+ *,
398
+ extr_w2c: torch.Tensor,
399
+ camera_params: torch.Tensor,
400
+ image_h: int,
401
+ image_w: int,
402
+ ) -> np.ndarray:
403
+ out = render_gaussians_fisheye624(
404
+ gaussians,
405
+ extrinsics_w2c=extr_w2c[None],
406
+ camera_params=camera_params,
407
+ image_h=int(image_h),
408
+ image_w=int(image_w),
409
+ valid_mask=None,
410
+ )
411
+ alpha = out["alpha"].detach().to(torch.float32).clamp(0.0, 1.0)
412
+ rgb = linearRGB2sRGB((out["color"] / alpha.clamp(min=1e-4)).clamp(0.0, 1.0)).clamp(0.0, 1.0)
413
+ return _to_u8_hwc(rgb[0])
414
+
415
+
416
+ def _render_panorama_frame_and_faces(
417
+ trainer: UnifiedTrainer,
418
+ gaussians: Any,
419
+ *,
420
+ extr_w2c: torch.Tensor,
421
+ equ_h: int,
422
+ equ_w: int,
423
+ face_w: int,
424
+ ) -> tuple[np.ndarray, dict[str, np.ndarray]]:
425
+ cube_color, _, cube_alpha = trainer._render_cubemap(gaussians, extr_w2c, face_w=int(face_w))
426
+ erp_color = trainer._cube_to_erp(cube_color, equ_h=int(equ_h), equ_w=int(equ_w), face_w=int(face_w))
427
+ erp_alpha = trainer._cube_to_erp(cube_alpha, equ_h=int(equ_h), equ_w=int(equ_w), face_w=int(face_w))
428
+ erp = linearRGB2sRGB((erp_color / erp_alpha.clamp(min=1e-4)).clamp(0.0, 1.0)).clamp(0.0, 1.0)
429
+ face_views: dict[str, np.ndarray] = {}
430
+ for face_idx, face_name in enumerate(FACE_NAMES):
431
+ face = linearRGB2sRGB(
432
+ (cube_color[face_idx : face_idx + 1] / cube_alpha[face_idx : face_idx + 1].clamp(min=1e-4)).clamp(0.0, 1.0)
433
+ ).clamp(0.0, 1.0)
434
+ face_views[face_name] = _to_u8_hwc(face[0])
435
+ return _to_u8_hwc(erp[0]), face_views
436
+
437
+
438
+ @torch.no_grad()
439
+ def _run_model_pinhole(
440
+ model: UnisharpFeatureModel,
441
+ image: torch.Tensor,
442
+ image_u8: torch.Tensor,
443
+ *,
444
+ intrinsics: torch.Tensor,
445
+ distance_init_cap_m: float,
446
+ ) -> dict[str, Any]:
447
+ return model(
448
+ image=image,
449
+ image_u8=image_u8,
450
+ camera_intrinsics=intrinsics,
451
+ camera_params=None,
452
+ camera_model="pinhole",
453
+ depth_gt=None,
454
+ distance_init_cap_m=(float(distance_init_cap_m) if float(distance_init_cap_m) > 0.0 else None),
455
+ return_aux=True,
456
+ )
457
+
458
+
459
+ @torch.no_grad()
460
+ def _run_model_fisheye(
461
+ model: UnisharpFeatureModel,
462
+ image: torch.Tensor,
463
+ image_u8: torch.Tensor,
464
+ *,
465
+ camera_params: torch.Tensor,
466
+ distance_init_cap_m: float,
467
+ ) -> dict[str, Any]:
468
+ return model(
469
+ image=image,
470
+ image_u8=image_u8,
471
+ camera_intrinsics=None,
472
+ camera_params=camera_params,
473
+ camera_model="fisheye624",
474
+ depth_gt=None,
475
+ distance_init_cap_m=(float(distance_init_cap_m) if float(distance_init_cap_m) > 0.0 else None),
476
+ return_aux=True,
477
+ )
478
+
479
+
480
+ @torch.no_grad()
481
+ def _run_model_panorama(
482
+ model: UnisharpFeatureModel,
483
+ image: torch.Tensor,
484
+ image_u8: torch.Tensor,
485
+ *,
486
+ distance_init_cap_m: float,
487
+ ) -> dict[str, Any]:
488
+ return model(
489
+ image=image,
490
+ image_u8=image_u8,
491
+ camera_intrinsics=None,
492
+ camera_params=None,
493
+ camera_model="spherical",
494
+ depth_gt=None,
495
+ distance_init_cap_m=(float(distance_init_cap_m) if float(distance_init_cap_m) > 0.0 else None),
496
+ return_aux=True,
497
+ )
498
+
499
+
500
+ def _save_ply_if_requested(gaussians: Any, path: Path, f_px: float, image_h: int, image_w: int, enabled: bool) -> None:
501
+ if not enabled:
502
+ return
503
+ path.parent.mkdir(parents=True, exist_ok=True)
504
+ save_ply(gaussians, f_px=float(f_px), image_shape=(int(image_h), int(image_w)), path=path)
505
+
506
+
507
+ @torch.no_grad()
508
+ def _process_one(
509
+ *,
510
+ model: UnisharpFeatureModel,
511
+ renderer: GSplatRenderer,
512
+ train_renderer: UnifiedTrainer,
513
+ image_path: Path,
514
+ out_root: Path,
515
+ step: int,
516
+ args: argparse.Namespace,
517
+ ) -> None:
518
+ rgb_u8 = _load_rgb_u8(image_path, max_long_edge=int(args.max_long_edge))
519
+ _, h, w = rgb_u8.shape
520
+ if h < 4 or w < 4:
521
+ raise ValueError(f"Invalid image size for {image_path}: {tuple(rgb_u8.shape)}")
522
+
523
+ device = next(model.parameters()).device
524
+ image_u8 = rgb_u8.unsqueeze(0).to(device=device)
525
+ image = image_u8.to(torch.float32) / 255.0
526
+
527
+ camera_json_entry = _camera_json_for_image(getattr(args, "_camera_json_data", None), image_path)
528
+ json_camera_name = _camera_name_from_json(camera_json_entry)
529
+ json_intrinsics = _values_from_camera_json(camera_json_entry, "intrinsics", "camera_intrinsics", "K")
530
+ json_camera_params = _values_from_camera_json(camera_json_entry, "camera_params", "fisheye624_params", "params")
531
+ explicit_intrinsics = _pinhole_intrinsics_from_values(json_intrinsics or args.camera_intrinsics, device=device)
532
+ explicit_camera_params = _fisheye624_params_from_values(json_camera_params or args.camera_params, device=device)
533
+ if explicit_intrinsics is not None and explicit_camera_params is not None:
534
+ raise ValueError("Use only one of --camera-intrinsics or --camera-params.")
535
+
536
+ rays: torch.Tensor | None
537
+ render_intrinsics: torch.Tensor | None = None
538
+ render_camera_params: torch.Tensor | None = None
539
+ if explicit_intrinsics is not None:
540
+ camera_kind: CameraKind = "panorama" if json_camera_name in {"panorama", "erp", "spherical"} else "perspective"
541
+ render_intrinsics = explicit_intrinsics
542
+ if camera_kind == "panorama":
543
+ out = _run_model_panorama(model, image, image_u8, distance_init_cap_m=float(args.distance_init_cap_m))
544
+ else:
545
+ out = _run_model_pinhole(
546
+ model,
547
+ image,
548
+ image_u8,
549
+ intrinsics=explicit_intrinsics,
550
+ distance_init_cap_m=float(args.distance_init_cap_m),
551
+ )
552
+ rays = out.get("geometry_rays", out.get("unik3d_gt_rays", out.get("unik3d_rays", None)))
553
+ stats = _ray_fov_stats(rays) if torch.is_tensor(rays) else _empty_ray_stats()
554
+ elif explicit_camera_params is not None:
555
+ camera_kind = "fisheye"
556
+ render_camera_params = explicit_camera_params
557
+ out = _run_model_fisheye(
558
+ model,
559
+ image,
560
+ image_u8,
561
+ camera_params=explicit_camera_params,
562
+ distance_init_cap_m=float(args.distance_init_cap_m),
563
+ )
564
+ rays = out.get("geometry_rays", out.get("unik3d_gt_rays", out.get("unik3d_rays", None)))
565
+ stats = _ray_fov_stats(rays) if torch.is_tensor(rays) else _empty_ray_stats()
566
+ else:
567
+ rays = _predict_unik3d_rays(model, image_u8, image_h=h, image_w=w)
568
+ stats = _ray_fov_stats(rays)
569
+ if json_camera_name in {"panorama", "erp", "spherical"}:
570
+ camera_kind = "panorama"
571
+ elif json_camera_name in {"fisheye", "fisheye624", "opencv_fisheye"}:
572
+ camera_kind = "fisheye"
573
+ elif json_camera_name in {"perspective", "pinhole"}:
574
+ camera_kind = "perspective"
575
+ else:
576
+ camera_kind = _classify_camera(stats, args)
577
+ if camera_kind == "panorama":
578
+ out = _run_model_panorama(model, image, image_u8, distance_init_cap_m=float(args.distance_init_cap_m))
579
+ elif camera_kind == "fisheye":
580
+ render_camera_params = fit_fisheye624_params_from_rays(rays).detach().to(device=device, dtype=torch.float32)
581
+ out = _run_model_fisheye(
582
+ model,
583
+ image,
584
+ image_u8,
585
+ camera_params=render_camera_params,
586
+ distance_init_cap_m=float(args.distance_init_cap_m),
587
+ )
588
+ else:
589
+ render_intrinsics = fit_pinhole_intrinsics_from_rays(rays).detach().to(device=device, dtype=torch.float32)
590
+ out = _run_model_pinhole(
591
+ model,
592
+ image,
593
+ image_u8,
594
+ intrinsics=render_intrinsics,
595
+ distance_init_cap_m=float(args.distance_init_cap_m),
596
+ )
597
+
598
+ LOGGER.info(
599
+ "%s -> %s | hfov=%.1f vfov=%.1f diag=%.1f aspect=%.3f",
600
+ image_path,
601
+ camera_kind,
602
+ stats["horizontal_fov_deg"],
603
+ stats["vertical_fov_deg"],
604
+ stats["diagonal_fov_deg"],
605
+ stats["aspect"],
606
+ )
607
+
608
+ src_w2c = torch.eye(4, dtype=torch.float32, device=device)
609
+ gaussians_world = transform_gaussians_to_world(out["gaussians"], src_w2c)
610
+ forward_poses = _build_forward_poses(
611
+ num_views=int(args.forward_views),
612
+ distance_m=float(args.forward_distance_m),
613
+ device=device,
614
+ )
615
+ rotate_poses = _build_rotate_poses(
616
+ num_views=int(args.rotate_views),
617
+ radius_m=float(args.rotate_radius_m),
618
+ device=device,
619
+ )
620
+
621
+ sample_dir = out_root / _slug_from_path(image_path)
622
+ sample_dir.mkdir(parents=True, exist_ok=True)
623
+ output_crop_border_fraction = 0.0 if camera_kind == "panorama" else 0.05
624
+ Image.fromarray(_crop_border_u8(_to_u8_hwc(rgb_u8), output_crop_border_fraction)).save(sample_dir / "input.png")
625
+
626
+ forward_frames: list[np.ndarray] = []
627
+ rotate_frames: list[np.ndarray] = []
628
+
629
+ if camera_kind == "panorama":
630
+ face_w = int(args.face_w) if int(args.face_w) > 0 else max(16, int(min(h, w // 4)))
631
+ forward_dir = sample_dir / "forward_erp"
632
+ rotate_dir = sample_dir / "rotate_erp"
633
+ rotate_faces_dir = sample_dir / "rotate_cubemap_faces"
634
+ forward_dir.mkdir(parents=True, exist_ok=True)
635
+ rotate_dir.mkdir(parents=True, exist_ok=True)
636
+ for face_name in FACE_NAMES:
637
+ (rotate_faces_dir / face_name).mkdir(parents=True, exist_ok=True)
638
+ for pose in forward_poses:
639
+ erp_u8, _ = _render_panorama_frame_and_faces(
640
+ train_renderer,
641
+ gaussians_world,
642
+ extr_w2c=pose,
643
+ equ_h=h,
644
+ equ_w=w,
645
+ face_w=face_w,
646
+ )
647
+ forward_dir.joinpath(f"forward_{len(forward_frames):02d}.png").parent.mkdir(parents=True, exist_ok=True)
648
+ Image.fromarray(erp_u8).save(forward_dir / f"forward_{len(forward_frames):02d}.png")
649
+ forward_frames.append(erp_u8)
650
+ for pose in rotate_poses:
651
+ erp_u8, face_views = _render_panorama_frame_and_faces(
652
+ train_renderer,
653
+ gaussians_world,
654
+ extr_w2c=pose,
655
+ equ_h=h,
656
+ equ_w=w,
657
+ face_w=face_w,
658
+ )
659
+ frame_idx = len(rotate_frames)
660
+ Image.fromarray(erp_u8).save(rotate_dir / f"rotate_{frame_idx:02d}.png")
661
+ for face_name, face_u8 in face_views.items():
662
+ Image.fromarray(face_u8).save(rotate_faces_dir / face_name / f"rotate_{frame_idx:02d}_{face_name}.png")
663
+ rotate_frames.append(erp_u8)
664
+ f_px = float(w) / (2.0 * math.pi)
665
+ elif camera_kind == "fisheye":
666
+ if render_camera_params is None:
667
+ if not torch.is_tensor(rays):
668
+ raise RuntimeError("Fisheye ray fitting requires model rays.")
669
+ render_camera_params = fit_fisheye624_params_from_rays(rays)
670
+ params = render_camera_params
671
+ params = params.detach().to(device=device, dtype=torch.float32)
672
+ for pose in forward_poses:
673
+ forward_frames.append(_render_fisheye_frame(gaussians_world, extr_w2c=pose, camera_params=params, image_h=h, image_w=w))
674
+ for pose in rotate_poses:
675
+ rotate_frames.append(_render_fisheye_frame(gaussians_world, extr_w2c=pose, camera_params=params, image_h=h, image_w=w))
676
+ f_px = float(0.5 * (float(params[0, 0].detach().cpu()) + float(params[0, 1].detach().cpu())))
677
+ else:
678
+ if render_intrinsics is None:
679
+ if not torch.is_tensor(rays):
680
+ raise RuntimeError("Pinhole ray fitting requires model rays.")
681
+ render_intrinsics = fit_pinhole_intrinsics_from_rays(rays)
682
+ intrinsics = render_intrinsics
683
+ k3 = intrinsics.detach().to(device=device, dtype=torch.float32)[0]
684
+ for pose in forward_poses:
685
+ forward_frames.append(_render_pinhole_frame(renderer, gaussians_world, extr_w2c=pose, intrinsics=k3, image_h=h, image_w=w))
686
+ for pose in rotate_poses:
687
+ rotate_frames.append(_render_pinhole_frame(renderer, gaussians_world, extr_w2c=pose, intrinsics=k3, image_h=h, image_w=w))
688
+ f_px = float(0.5 * (float(k3[0, 0].detach().cpu()) + float(k3[1, 1].detach().cpu())))
689
+
690
+ if output_crop_border_fraction > 0.0:
691
+ forward_frames = [_crop_border_u8(frame, output_crop_border_fraction) for frame in forward_frames]
692
+ rotate_frames = [_crop_border_u8(frame, output_crop_border_fraction) for frame in rotate_frames]
693
+
694
+ _save_gif(forward_frames, sample_dir / "forward_0p2m.gif", duration_ms=int(args.gif_duration_ms))
695
+ _save_gif(rotate_frames, sample_dir / "rotate_0p1m.gif", duration_ms=int(args.gif_duration_ms))
696
+ _save_ply_if_requested(gaussians_world, sample_dir / "gaussians.ply", f_px=f_px, image_h=h, image_w=w, enabled=bool(args.save_ply))
697
+
698
+ metadata = {
699
+ "checkpoint": str(args.checkpoint),
700
+ "checkpoint_step": int(step),
701
+ "image": str(image_path),
702
+ "camera_kind": camera_kind,
703
+ "ray_stats": stats,
704
+ "camera_json": str(args.camera_json) if args.camera_json is not None else None,
705
+ "camera_json_entry": camera_json_entry,
706
+ "explicit_camera_intrinsics": args.camera_intrinsics,
707
+ "explicit_camera_params": args.camera_params,
708
+ "forward_distance_m": float(args.forward_distance_m),
709
+ "rotate_radius_m": float(args.rotate_radius_m),
710
+ "rotate_path": "clockwise_camera_xy_orbit_fixed_source_orientation",
711
+ "panorama_renderer": "unisharp.cli.unified_trainer.UnifiedTrainer._render_cubemap/_cube_to_erp",
712
+ "low_pass_filter_eps": float(args.low_pass_filter_eps),
713
+ "output_crop_border_fraction": float(output_crop_border_fraction),
714
+ "height": int(h),
715
+ "width": int(w),
716
+ }
717
+ (sample_dir / "metadata.json").write_text(json.dumps(metadata, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
718
+ LOGGER.info("Saved outputs -> %s", sample_dir)
719
+
720
+
721
+ def _build_argparser() -> argparse.ArgumentParser:
722
+ p = argparse.ArgumentParser(description="UniSharp single-image inference with automatic camera-type detection.")
723
+ p.add_argument("--checkpoint", type=Path, required=True)
724
+ p.add_argument("--image", type=Path, default=None)
725
+ p.add_argument("--image-list", type=Path, default=None)
726
+ p.add_argument("--image-dir", type=Path, default=None)
727
+ p.add_argument("--out-dir", type=Path, default=REPO_ROOT / "outputs" / "inference")
728
+ p.add_argument("--device", type=str, default="cuda:0" if torch.cuda.is_available() else "cpu")
729
+ p.add_argument("--max-images", type=int, default=0)
730
+ p.add_argument("--max-long-edge", type=int, default=768)
731
+ p.add_argument("--forward-views", type=int, default=10)
732
+ p.add_argument("--forward-distance-m", type=float, default=0.2)
733
+ p.add_argument("--rotate-views", type=int, default=10)
734
+ p.add_argument("--rotate-radius-m", type=float, default=0.1)
735
+ p.add_argument("--gif-duration-ms", type=int, default=300)
736
+ p.add_argument("--face-w", type=int, default=0, help="Panorama cubemap face width. 0 uses min(H, W/4).")
737
+ p.add_argument("--distance-init-cap-m", type=float, default=0.0)
738
+ p.add_argument("--save-ply", action="store_true")
739
+ p.add_argument(
740
+ "--camera-json",
741
+ type=Path,
742
+ default=None,
743
+ help="JSON file with calibrated camera parameters. Supports a global object or an images mapping keyed by path/name/stem.",
744
+ )
745
+ p.add_argument(
746
+ "--camera-intrinsics",
747
+ type=float,
748
+ nargs="+",
749
+ default=None,
750
+ help="Explicit pinhole intrinsics. Pass fx fy cx cy or 9 row-major K values. If omitted, intrinsics are fitted from rays.",
751
+ )
752
+ p.add_argument(
753
+ "--camera-params",
754
+ type=float,
755
+ nargs="+",
756
+ default=None,
757
+ help="Explicit Fisheye624 parameters. Pass 8 values (fx fy cx cy k1 k2 k3 k4) or all 16 values. If omitted, parameters are fitted from rays.",
758
+ )
759
+ p.add_argument(
760
+ "--camera",
761
+ type=str,
762
+ default="auto",
763
+ choices=["auto", "perspective", "pinhole", "fisheye", "panorama", "erp"],
764
+ help="Override automatic ray-range camera classification.",
765
+ )
766
+ p.add_argument("--fisheye-fov-threshold-deg", type=float, default=95.0)
767
+ p.add_argument("--fisheye-diag-threshold-deg", type=float, default=130.0)
768
+ p.add_argument("--fisheye-vfov-min-deg", type=float, default=70.0)
769
+ p.add_argument("--fisheye-max-aspect", type=float, default=1.65)
770
+ p.add_argument("--panorama-hfov-threshold-deg", type=float, default=260.0)
771
+ p.add_argument("--panorama-vfov-threshold-deg", type=float, default=120.0)
772
+ p.add_argument("--panorama-aspect-min", type=float, default=1.75)
773
+ p.add_argument("--panorama-aspect-max", type=float, default=2.25)
774
+ p.add_argument("--low-pass-filter-eps", type=float, default=0.0)
775
+ return p
776
+
777
+
778
+ def main() -> None:
779
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
780
+ _configure_torchhub_cache()
781
+ args = _build_argparser().parse_args()
782
+ args._camera_json_data = _load_camera_json(args.camera_json)
783
+ device = torch.device(str(args.device))
784
+ model, step = _load_model(Path(args.checkpoint), device=device)
785
+ renderer = GSplatRenderer(
786
+ color_space="sRGB",
787
+ background_color="black",
788
+ low_pass_filter_eps=float(args.low_pass_filter_eps),
789
+ ).to(device)
790
+ train_renderer = UnifiedTrainer(
791
+ model=model,
792
+ renderer=renderer,
793
+ loss_fn=None,
794
+ device=device,
795
+ )
796
+ image_paths = _collect_image_paths(args)
797
+ Path(args.out_dir).mkdir(parents=True, exist_ok=True)
798
+ LOGGER.info("Rendering %d image(s) to %s", len(image_paths), args.out_dir)
799
+ for image_path in image_paths:
800
+ _process_one(
801
+ model=model,
802
+ renderer=renderer,
803
+ train_renderer=train_renderer,
804
+ image_path=Path(image_path),
805
+ out_root=Path(args.out_dir),
806
+ step=int(step),
807
+ args=args,
808
+ )
809
+ if device.type == "cuda":
810
+ torch.cuda.empty_cache()
811
+
812
+
813
+ if __name__ == "__main__":
814
+ main()
scripts/train.sh ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
5
+ REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
6
+
7
+ CONDA_SH="${CONDA_SH:-/media/home/smx/miniconda3/bin/conda}"
8
+ CONDA_ENV="${CONDA_ENV:-unisharp}"
9
+ if [[ -x "${CONDA_SH}" ]]; then
10
+ eval "$("${CONDA_SH}" shell.bash hook)"
11
+ conda activate "${CONDA_ENV}"
12
+ fi
13
+
14
+ export PYTHONPATH="${REPO_ROOT}:${PYTHONPATH:-}"
15
+ export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION="${PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION:-python}"
16
+
17
+ export OUT_ROOT="${OUT_ROOT:-${REPO_ROOT}/outputs}"
18
+ export RUN_NAME="${RUN_NAME:-unisharp_$(date +%Y%m%d_%H%M%S)}"
19
+
20
+ export SEED="${SEED:-260602}"
21
+
22
+ export STEPS="${STEPS:-1000000}"
23
+ export WARMUP="${WARMUP:-75000}"
24
+ export BATCH_SIZE="${BATCH_SIZE:-2}"
25
+ export NUM_WORKERS="${NUM_WORKERS:-1}"
26
+ export GPU_IDS="${GPU_IDS:-0,1,2,3,4,5,6,7}"
27
+ export MASTER_PORT="${MASTER_PORT:-29531}"
28
+ export DEVICE="${DEVICE:-cuda}"
29
+ export DDP_TIMEOUT_HOURS="${DDP_TIMEOUT_HOURS:-8}"
30
+
31
+ export LR0="${LR0:-1.2e-4}"
32
+ export LR1="${LR1:-1.6e-5}"
33
+ export UNIK3D_DECODER_LR0="${UNIK3D_DECODER_LR0:-2.5e-5}"
34
+ export UNIK3D_DECODER_LR1="${UNIK3D_DECODER_LR1:-2.5e-6}"
35
+ export UNIK3D_ENCODER_LR0="${UNIK3D_ENCODER_LR0:-1.5e-6}"
36
+ export UNIK3D_ENCODER_LR1="${UNIK3D_ENCODER_LR1:-1.5e-7}"
37
+ export GRAD_CLIP_NORM="${GRAD_CLIP_NORM:-1.0}"
38
+ export MAX_STEP_GRAD_NORM="${MAX_STEP_GRAD_NORM:-100000.0}"
39
+
40
+ export INITIALIZER_STRIDE="${INITIALIZER_STRIDE:-1}"
41
+ export INITIALIZER_SCALE_FACTOR="${INITIALIZER_SCALE_FACTOR:-1.5}"
42
+ export DELTA_RHO_LIMIT="${DELTA_RHO_LIMIT:-2.0}"
43
+
44
+ export MAX_INDEX_GAP="${MAX_INDEX_GAP:-10}"
45
+ export MAX_DEPTH_M="${MAX_DEPTH_M:-100.0}"
46
+ export PINHOLE_TRAIN_SIZE="${PINHOLE_TRAIN_SIZE:-0}"
47
+ export TRAIN_RESIZE_MULTIPLE="${TRAIN_RESIZE_MULTIPLE:-256}"
48
+ export SIM_MAX_LONG_EDGE="${SIM_MAX_LONG_EDGE:-0}"
49
+ export RE10K_PSEUDO_FAR_DEPTH_INVALID_M="${RE10K_PSEUDO_FAR_DEPTH_INVALID_M:-30.0}"
50
+ export SIM_FAR_DEPTH_INVALID_M="${SIM_FAR_DEPTH_INVALID_M:-30.0}"
51
+ export SIM_FAR_DEPTH_INVALID_MAX_FRAC="${SIM_FAR_DEPTH_INVALID_MAX_FRAC:-1.0}"
52
+ export SCANETPP_FISHEYE_FAR_DEPTH_INVALID_M="${SCANETPP_FISHEYE_FAR_DEPTH_INVALID_M:-30.0}"
53
+
54
+ export LAMBDA_COLOR="${LAMBDA_COLOR:-1.0}"
55
+ export LAMBDA_ALPHA="${LAMBDA_ALPHA:-1.5}"
56
+ export LAMBDA_PERCEP="${LAMBDA_PERCEP:-1.0}"
57
+ export LAMBDA_DEPTH="${LAMBDA_DEPTH:-0.5}"
58
+ export LAMBDA_TV="${LAMBDA_TV:-1.0}"
59
+ export LAMBDA_GRAD="${LAMBDA_GRAD:-1.0}"
60
+ export LAMBDA_GRAD_IMG="${LAMBDA_GRAD_IMG:-0.2}"
61
+ export LAMBDA_EDGE_RGB="${LAMBDA_EDGE_RGB:-0.0}"
62
+ export LAMBDA_DELTA="${LAMBDA_DELTA:-1.0}"
63
+ export LAMBDA_DELTA_RHO="${LAMBDA_DELTA_RHO:-0.01}"
64
+ export LAMBDA_SPLAT="${LAMBDA_SPLAT:-1.0}"
65
+ export LAMBDA_EDGE_SPLAT="${LAMBDA_EDGE_SPLAT:-0.0}"
66
+ export LAMBDA_GRID="${LAMBDA_GRID:-0.05}"
67
+ export LAMBDA_AUX_RAY="${LAMBDA_AUX_RAY:-3.0}"
68
+ export LAMBDA_AUX_DEPTH_SCALE="${LAMBDA_AUX_DEPTH_SCALE:-3.0}"
69
+ export LAMBDA_AUX_DEPTH2_SCALE="${LAMBDA_AUX_DEPTH2_SCALE:-1.0}"
70
+
71
+ export SAVE_EVERY="${SAVE_EVERY:-5000}"
72
+ export VIS_EVERY="${VIS_EVERY:-500}"
73
+ export LOG_EVERY="${LOG_EVERY:-50}"
74
+
75
+
76
+ export DATASET_WEIGHT_RE10K="${DATASET_WEIGHT_RE10K:-1.0}"
77
+ export DATASET_WEIGHT_HM3D="${DATASET_WEIGHT_HM3D:-1.0}"
78
+ export DATASET_WEIGHT_SIM="${DATASET_WEIGHT_SIM:-1.0}"
79
+ export DATASET_WEIGHT_WILDRGBD="${DATASET_WEIGHT_WILDRGBD:-1.0}"
80
+ export DATASET_WEIGHT_DL3DV="${DATASET_WEIGHT_DL3DV:-1.0}"
81
+ export DATASET_WEIGHT_SCANETPP="${DATASET_WEIGHT_SCANETPP:-0.0}"
82
+
83
+ export DATA_ROOT_RE10K="${DATA_ROOT_RE10K:-/media/team_data/ML4_team/datasets/re10k}"
84
+ export RE10K_PSEUDO_DEPTH_ROOT="${RE10K_PSEUDO_DEPTH_ROOT:-/media/team_data/ML4_team/datasets/re10k_depth}"
85
+ export DATA_ROOT_HM3D="${DATA_ROOT_HM3D:-/media/team_data/ML4_team/datasets/panogs}"
86
+ export DATA_ROOT_SIM="${DATA_ROOT_SIM:-/media/team_data/ML4_team/datasets/omnirooms}"
87
+ export SIM_POSE_ROOT="${SIM_POSE_ROOT:-/media/team_data/ML4_team/datasets/omnirooms/pose}"
88
+ export DATA_ROOT_DL3DV="${DATA_ROOT_DL3DV:-/media/team_data/ML4_team/datasets/DL3DV-ALL-960P}"
89
+ export DATA_ROOT_DL3DV_DEPTH="${DATA_ROOT_DL3DV_DEPTH:-/media/team_data/ML4_team/datasets/DL3DV-ALL-960P_depth}"
90
+ export DATA_ROOT_SCANETPP="${DATA_ROOT_SCANETPP:-/media/team_data/ML4_team/datasets/scan}"
91
+
92
+ DEFAULT_DATASET_MANIFEST_DIR="${REPO_ROOT}/dataset_manifests"
93
+ if [[ -d "${REPO_ROOT}/../dataset_manifests" ]]; then
94
+ DEFAULT_DATASET_MANIFEST_DIR="${REPO_ROOT}/../dataset_manifests"
95
+ fi
96
+ export DATASET_MANIFEST_DIR="${DATASET_MANIFEST_DIR:-${DEFAULT_DATASET_MANIFEST_DIR}}"
97
+ if [[ ! -f "${DATASET_MANIFEST_DIR}/omnirooms.txt" && -f "${REPO_ROOT}/../dataset_manifests/omnirooms.txt" ]]; then
98
+ export DATASET_MANIFEST_DIR="${REPO_ROOT}/../dataset_manifests"
99
+ fi
100
+ export WILD_ROOTS_FILE="${WILD_ROOTS_FILE:-${DATASET_MANIFEST_DIR}/wildrgbd_roots.txt}"
101
+
102
+ export CUDA_VISIBLE_DEVICES="${GPU_IDS}"
103
+ export NCCL_NET="${NCCL_NET:-Socket}"
104
+ export NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-1}"
105
+ export TORCH_NCCL_ASYNC_ERROR_HANDLING="${TORCH_NCCL_ASYNC_ERROR_HANDLING:-1}"
106
+
107
+ IFS=',' read -r -a GPU_ID_ARR <<< "${GPU_IDS}"
108
+ if [[ "${#GPU_ID_ARR[@]}" -gt 1 ]]; then
109
+ LAUNCH_CMD=(torchrun --nproc_per_node="${#GPU_ID_ARR[@]}" --master_port="${MASTER_PORT}")
110
+ else
111
+ LAUNCH_CMD=(python)
112
+ fi
113
+
114
+ echo "UniSharp training: run=${RUN_NAME} out=${OUT_ROOT} gpu=${GPU_IDS}"
115
+ echo " branch=gt-override scratch_unik3d_pretrained"
116
+ echo " datasets: re10k=${DATASET_WEIGHT_RE10K} hm3d=${DATASET_WEIGHT_HM3D} omnirooms=${DATASET_WEIGHT_SIM} wildrgbd=${DATASET_WEIGHT_WILDRGBD} dl3dv=${DATASET_WEIGHT_DL3DV} scanetpp=${DATASET_WEIGHT_SCANETPP}"
117
+
118
+ exec "${LAUNCH_CMD[@]}" -m unisharp.cli train-feature \
119
+ --out-root "${OUT_ROOT}" \
120
+ --run-name "${RUN_NAME}" \
121
+ --steps "${STEPS}" \
122
+ --warmup "${WARMUP}" \
123
+ --lr0 "${LR0}" \
124
+ --lr1 "${LR1}" \
125
+ --unik3d-lr0 "${UNIK3D_DECODER_LR0}" \
126
+ --unik3d-lr1 "${UNIK3D_DECODER_LR1}" \
127
+ --unik3d-encoder-lr0 "${UNIK3D_ENCODER_LR0}" \
128
+ --unik3d-encoder-lr1 "${UNIK3D_ENCODER_LR1}" \
129
+ --grad-clip-norm "${GRAD_CLIP_NORM}" \
130
+ --max-step-grad-norm "${MAX_STEP_GRAD_NORM}" \
131
+ --batch-size "${BATCH_SIZE}" \
132
+ --num-workers "${NUM_WORKERS}" \
133
+ --device "${DEVICE}" \
134
+ --ddp-timeout-hours "${DDP_TIMEOUT_HOURS}" \
135
+ --max-index-gap "${MAX_INDEX_GAP}" \
136
+ --max-depth-m "${MAX_DEPTH_M}" \
137
+ --sim-far-depth-invalid-m "${SIM_FAR_DEPTH_INVALID_M}" \
138
+ --sim-far-depth-invalid-max-frac "${SIM_FAR_DEPTH_INVALID_MAX_FRAC}" \
139
+ --sim-max-long-edge "${SIM_MAX_LONG_EDGE}" \
140
+ --pinhole-train-size "${PINHOLE_TRAIN_SIZE}" \
141
+ --train-resize-multiple "${TRAIN_RESIZE_MULTIPLE}" \
142
+ --scanetpp-fisheye-far-depth-invalid-m "${SCANETPP_FISHEYE_FAR_DEPTH_INVALID_M}" \
143
+ --initializer-stride "${INITIALIZER_STRIDE}" \
144
+ --initializer-scale-factor "${INITIALIZER_SCALE_FACTOR}" \
145
+ --delta-rho-limit "${DELTA_RHO_LIMIT}" \
146
+ --lambda-color "${LAMBDA_COLOR}" \
147
+ --lambda-alpha "${LAMBDA_ALPHA}" \
148
+ --lambda-percep "${LAMBDA_PERCEP}" \
149
+ --lambda-depth "${LAMBDA_DEPTH}" \
150
+ --lambda-tv "${LAMBDA_TV}" \
151
+ --lambda-grad "${LAMBDA_GRAD}" \
152
+ --lambda-grad-img "${LAMBDA_GRAD_IMG}" \
153
+ --lambda-edge-rgb "${LAMBDA_EDGE_RGB}" \
154
+ --lambda-delta "${LAMBDA_DELTA}" \
155
+ --lambda-delta-rho "${LAMBDA_DELTA_RHO}" \
156
+ --lambda-splat "${LAMBDA_SPLAT}" \
157
+ --lambda-edge-splat "${LAMBDA_EDGE_SPLAT}" \
158
+ --lambda-grid "${LAMBDA_GRID}" \
159
+ --lambda-aux-ray "${LAMBDA_AUX_RAY}" \
160
+ --lambda-aux-depth-scale "${LAMBDA_AUX_DEPTH_SCALE}" \
161
+ --lambda-aux-depth2-scale "${LAMBDA_AUX_DEPTH2_SCALE}" \
162
+ --dataset-weight-re10k "${DATASET_WEIGHT_RE10K}" \
163
+ --dataset-weight-hm3d "${DATASET_WEIGHT_HM3D}" \
164
+ --dataset-weight-sim "${DATASET_WEIGHT_SIM}" \
165
+ --dataset-weight-wildrgbd "${DATASET_WEIGHT_WILDRGBD}" \
166
+ --dataset-weight-dl3dv "${DATASET_WEIGHT_DL3DV}" \
167
+ --dataset-weight-scanetpp "${DATASET_WEIGHT_SCANETPP}" \
168
+ --data-root-re10k "${DATA_ROOT_RE10K}" \
169
+ --re10k-pseudo-depth-root "${RE10K_PSEUDO_DEPTH_ROOT}" \
170
+ --re10k-pseudo-far-depth-invalid-m "${RE10K_PSEUDO_FAR_DEPTH_INVALID_M}" \
171
+ --data-root-hm3d "${DATA_ROOT_HM3D}" \
172
+ --data-root-sim "${DATA_ROOT_SIM}" \
173
+ --sim-pose-root "${SIM_POSE_ROOT}" \
174
+ --wild-roots-file "${WILD_ROOTS_FILE}" \
175
+ --data-root-dl3dv "${DATA_ROOT_DL3DV}" \
176
+ --data-root-dl3dv-depth "${DATA_ROOT_DL3DV_DEPTH}" \
177
+ --data-root-scanetpp "${DATA_ROOT_SCANETPP}" \
178
+ --dataset-manifest-dir "${DATASET_MANIFEST_DIR}" \
179
+ --save-every "${SAVE_EVERY}" \
180
+ --vis-every "${VIS_EVERY}" \
181
+ --log-every "${LOG_EVERY}" \
182
+ --seed "${SEED}"
scripts/validate_unisharp.sh ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
5
+ REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
6
+
7
+ CONDA_SH="${CONDA_SH:-/media/home/smx/miniconda3/bin/conda}"
8
+ CONDA_ENV="${CONDA_ENV:-unisharp}"
9
+ if [[ -x "${CONDA_SH}" ]]; then
10
+ eval "$("${CONDA_SH}" shell.bash hook)"
11
+ conda activate "${CONDA_ENV}"
12
+ fi
13
+
14
+ export PYTHONPATH="${REPO_ROOT}:${PYTHONPATH:-}"
15
+ export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION="${PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION:-python}"
16
+
17
+ CHECKPOINT="${CHECKPOINT:-${1:-}}"
18
+ if [[ -z "${CHECKPOINT}" || ! -f "${CHECKPOINT}" ]]; then
19
+ echo "ERROR: pass a checkpoint as arg1 or set CHECKPOINT=/path/to/step_XXXXXXX.pt" >&2
20
+ exit 1
21
+ fi
22
+
23
+ export OUT_ROOT="${OUT_ROOT:-${REPO_ROOT}/outputs/validation}"
24
+ export RUN_NAME="${RUN_NAME:-unisharp_validation_$(date +%Y%m%d_%H%M%S)}"
25
+ RUN_DIR="${OUT_ROOT}/${RUN_NAME}"
26
+ mkdir -p "${RUN_DIR}"
27
+
28
+ export GPU_IDS="${GPU_IDS:-0}"
29
+ export VALIDATION_JOBS_PER_GPU="${VALIDATION_JOBS_PER_GPU:-1}"
30
+ export VALIDATION_BATCH_SIZE="${VALIDATION_BATCH_SIZE:-1}"
31
+ export VALIDATION_FAST_METRICS="${VALIDATION_FAST_METRICS:-1}"
32
+ export VALIDATION_MAX_GROUPS="${VALIDATION_MAX_GROUPS:-0}"
33
+ export SEED="${SEED:-42}"
34
+ export MAX_INDEX_GAP="${MAX_INDEX_GAP:-10}"
35
+ export PAIR_MAX_TRANSLATION_M="${PAIR_MAX_TRANSLATION_M:-0.5}"
36
+ export PAIR_MIN_OVERLAP="${PAIR_MIN_OVERLAP:-0.6}"
37
+ export PANO_POSE_FLIP_CONVENTION="${PANO_POSE_FLIP_CONVENTION:-flip_yz_negate_rel_z}"
38
+
39
+ DEFAULT_VALIDATION_MANIFEST_DIR="${REPO_ROOT}/validation_manifests"
40
+ if [[ -d "${REPO_ROOT}/../validation_manifests" ]]; then
41
+ DEFAULT_VALIDATION_MANIFEST_DIR="${REPO_ROOT}/../validation_manifests"
42
+ fi
43
+ export VALIDATION_MANIFEST_DIR="${VALIDATION_MANIFEST_DIR:-${DEFAULT_VALIDATION_MANIFEST_DIR}}"
44
+ export VALIDATION_PSEUDO_DEPTH_ROOT="${VALIDATION_PSEUDO_DEPTH_ROOT:-/media/team_data/ML4_team/datasets/validation_depth}"
45
+ export RE10K_PSEUDO_DEPTH_ROOT="${RE10K_PSEUDO_DEPTH_ROOT:-/media/team_data/ML4_team/datasets/re10k_depth/test}"
46
+
47
+ export DATA_ROOT_RE10K="${DATA_ROOT_RE10K:-/media/team_data/ML4_team/datasets/re10k}"
48
+ export DATA_ROOT_DL3DV="${DATA_ROOT_DL3DV:-/media/team_data/ML4_team/datasets/DL3DV-ALL-960P}"
49
+ export DATA_ROOT_HM3D="${DATA_ROOT_HM3D:-/media/team_data/ML4_team/datasets/hm3d}"
50
+ export DATA_ROOT_REPLICA="${DATA_ROOT_REPLICA:-/media/team_data/ML4_team/datasets/replica}"
51
+ export DATA_ROOT_SIM="${DATA_ROOT_SIM:-/media/team_data/ML4_team/datasets/omnirooms}"
52
+ export SIM_POSE_ROOT="${SIM_POSE_ROOT:-/media/team_data/ML4_team/datasets/omnirooms/pose}"
53
+ DEFAULT_DATASET_MANIFEST_DIR="${REPO_ROOT}/dataset_manifests"
54
+ if [[ -d "${REPO_ROOT}/../dataset_manifests" ]]; then
55
+ DEFAULT_DATASET_MANIFEST_DIR="${REPO_ROOT}/../dataset_manifests"
56
+ fi
57
+ export WILD_ROOTS_FILE="${WILD_ROOTS_FILE:-${DEFAULT_DATASET_MANIFEST_DIR}/wildrgbd_roots.txt}"
58
+ export DATA_ROOT_SCANNETPP="${DATA_ROOT_SCANNETPP:-/media/team_data/ML4_team/datasets/scannetpp}"
59
+ export DATA_ROOT_SCANETPP_FISHEYE="${DATA_ROOT_SCANETPP_FISHEYE:-/media/team_data/ML4_team/datasets/scan}"
60
+ export DATA_ROOT_TAT="${DATA_ROOT_TAT:-/media/team_data/ML4_team/datasets/TAT/tanks_and_temples}"
61
+
62
+ DATASETS_CSV="${DATASETS:-re10k,dl3dv,hm3d,omnirooms,wildrgbd}"
63
+ IFS=',' read -r -a DATASET_ARR <<< "${DATASETS_CSV}"
64
+ IFS=',' read -r -a GPU_ID_ARR <<< "${GPU_IDS}"
65
+ if [[ "${VALIDATION_JOBS_PER_GPU}" -lt 1 ]]; then
66
+ echo "ERROR: VALIDATION_JOBS_PER_GPU must be >= 1" >&2
67
+ exit 1
68
+ fi
69
+
70
+ data_root_for_dataset() {
71
+ case "$1" in
72
+ re10k) echo "${DATA_ROOT_RE10K}" ;;
73
+ dl3dv) echo "${DATA_ROOT_DL3DV}" ;;
74
+ hm3d)
75
+ if [[ -d "${DATA_ROOT_HM3D}/test" ]]; then
76
+ echo "${DATA_ROOT_HM3D}/test"
77
+ else
78
+ echo "${DATA_ROOT_HM3D}"
79
+ fi
80
+ ;;
81
+ replica) echo "${DATA_ROOT_REPLICA}" ;;
82
+ omnirooms) echo "${DATA_ROOT_SIM}" ;;
83
+ wildrgbd) echo "${WILD_ROOTS_FILE}" ;;
84
+ scannetpp) echo "${DATA_ROOT_SCANNETPP}" ;;
85
+ scanetpp_fisheye) echo "${DATA_ROOT_SCANETPP_FISHEYE}" ;;
86
+ omnirooms_wide) echo "${DATA_ROOT_SIM}" ;;
87
+ tat) echo "${DATA_ROOT_TAT}" ;;
88
+ *) echo "Unknown dataset: $1" >&2; return 1 ;;
89
+ esac
90
+ }
91
+
92
+ extra_args_for_dataset() {
93
+ case "$1" in
94
+ re10k) echo "--re10k-pseudo-depth-root ${RE10K_PSEUDO_DEPTH_ROOT}" ;;
95
+ omnirooms) echo "--sim-pose-root ${SIM_POSE_ROOT}" ;;
96
+ *) echo "" ;;
97
+ esac
98
+ }
99
+
100
+ run_dataset() {
101
+ local gpu_id="$1"
102
+ local dataset="$2"
103
+ local data_root
104
+ local out_dir
105
+ local manifest
106
+
107
+ data_root="$(data_root_for_dataset "${dataset}")"
108
+ out_dir="${RUN_DIR}/${dataset}"
109
+ manifest="${VALIDATION_MANIFEST_DIR}/${dataset}.txt"
110
+
111
+ local cmd=(
112
+ python -m unisharp.validation.run_validation
113
+ --checkpoint "${CHECKPOINT}"
114
+ --dataset "${dataset}"
115
+ --data-root "${data_root}"
116
+ --device "cuda:0"
117
+ --out-dir "${out_dir}"
118
+ --validation-batch-size "${VALIDATION_BATCH_SIZE}"
119
+ --validation-pseudo-depth-root "${VALIDATION_PSEUDO_DEPTH_ROOT}"
120
+ --max-index-gap "${MAX_INDEX_GAP}"
121
+ --pair-max-translation-m "${PAIR_MAX_TRANSLATION_M}"
122
+ --pair-min-overlap "${PAIR_MIN_OVERLAP}"
123
+ --seed "${SEED}"
124
+ )
125
+ if [[ -f "${manifest}" ]]; then
126
+ cmd+=(--manifest-file "${manifest}")
127
+ fi
128
+ if [[ "${VALIDATION_MAX_GROUPS}" != "0" ]]; then
129
+ cmd+=(--manifest-max-groups "${VALIDATION_MAX_GROUPS}")
130
+ fi
131
+ if [[ "${VALIDATION_FAST_METRICS}" == "1" ]]; then
132
+ cmd+=(--fast-metrics)
133
+ fi
134
+ read -r -a extra_args <<< "$(extra_args_for_dataset "${dataset}")"
135
+ if [[ "${#extra_args[@]}" -gt 0 && -n "${extra_args[0]:-}" ]]; then
136
+ cmd+=("${extra_args[@]}")
137
+ fi
138
+
139
+ echo "Validating ${dataset} on GPU ${gpu_id}"
140
+ CUDA_VISIBLE_DEVICES="${gpu_id}" PANO_POSE_FLIP_CONVENTION="${PANO_POSE_FLIP_CONVENTION}" "${cmd[@]}"
141
+ }
142
+
143
+ worker() {
144
+ local worker_id="$1"
145
+ local gpu_index=$(( worker_id % ${#GPU_ID_ARR[@]} ))
146
+ local gpu_id="${GPU_ID_ARR[${gpu_index}]}"
147
+ local total_workers=$(( ${#GPU_ID_ARR[@]} * VALIDATION_JOBS_PER_GPU ))
148
+ local idx
149
+ for idx in "${!DATASET_ARR[@]}"; do
150
+ if (( idx % total_workers == worker_id )); then
151
+ run_dataset "${gpu_id}" "${DATASET_ARR[${idx}]}"
152
+ fi
153
+ done
154
+ }
155
+
156
+ echo "UniSharp validation"
157
+ echo " CHECKPOINT=${CHECKPOINT}"
158
+ echo " RUN_DIR=${RUN_DIR}"
159
+ echo " DATASETS=${DATASETS_CSV}"
160
+ echo " GPU_IDS=${GPU_IDS}"
161
+
162
+ TOTAL_WORKERS=$(( ${#GPU_ID_ARR[@]} * VALIDATION_JOBS_PER_GPU ))
163
+ PIDS=()
164
+ for worker_id in $(seq 0 $((TOTAL_WORKERS - 1))); do
165
+ worker "${worker_id}" &
166
+ PIDS+=("$!")
167
+ done
168
+
169
+ STATUS=0
170
+ for pid in "${PIDS[@]}"; do
171
+ wait "${pid}" || STATUS=1
172
+ done
173
+
174
+ if [[ "${STATUS}" -ne 0 ]]; then
175
+ echo "One or more validation workers failed." >&2
176
+ exit "${STATUS}"
177
+ fi
178
+
179
+ echo "Validation finished."
180
+ echo "Outputs: ${RUN_DIR}"