-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo_relaxflow_batch.py
More file actions
1627 lines (1472 loc) · 58.9 KB
/
Copy pathdemo_relaxflow_batch.py
File metadata and controls
1627 lines (1472 loc) · 58.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
RelaxFlow Batch Runner.
Manifest format (JSON/JSONL):
[
{
"id": "sample_0001",
"image": "/abs/path/to/image.png",
"mask": "/abs/path/to/mask.png",
"prior_images": ["/abs/path/to/prior.png"],
"prior_masks": ["/abs/path/to/prior_mask.png"],
"prior_text": "a wooden chair",
"gt_mesh": "/abs/path/to/gt_mesh.obj",
"gt_pointcloud": "/abs/path/to/gt_points.npy",
"gt_images": ["/abs/path/to/gt_view_00.png", "..."],
"gt_render_dir": "/abs/path/to/gt_views_dir"
}
]
"""
import argparse
import math
import json
import os
import shutil
import sys
import time
import warnings
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import imageio.v2 as imageio
import numpy as np
from loguru import logger
from omegaconf import OmegaConf
from hydra.utils import instantiate
from PIL import Image
import torch
import trimesh
from typing import Any
sys.path.append("notebook")
from inference import ( # noqa: E402
load_image,
load_mask,
infer_mask_from_image,
check_hydra_safety,
WHITELIST_FILTERS,
BLACKLIST_FILTERS,
)
from sam3d_objects.pipeline.relaxflow_config import (
RELAXFLOWConfig,
add_relaxflow_arguments,
print_config_summary,
)
from sam3d_objects.utils.relaxflow_eval_utils import (
CLIPImageSimilarity,
CLIPScoreCalculator,
FIDCalculator,
KIDCalculator,
compute_3d_metrics_from_pointclouds,
cov_mmd_from_sets,
fps_downsample,
has_2d_metrics,
save_batch_npz_files,
compute_pfid_with_pointe,
)
from sam3d_objects.model.backbone.tdfy_dit.utils import render_utils
from sam3d_objects.model.backbone.tdfy_dit.representations.mesh.cube2mesh import MeshExtractResult
PIPELINE_TARGET_RELAXFLOW = (
"sam3d_objects.pipeline.inference_pipeline_relaxflow.InferencePipelineRELAXFLOW"
)
PIPELINE_TARGET_BASE = (
"sam3d_objects.pipeline.inference_pipeline_pointmap.InferencePipelinePointMap"
)
try:
from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
_HAS_LPIPS = True
except Exception:
_HAS_LPIPS = False
def _default_cache_root() -> str:
env_cache = os.environ.get("RELAXFLOW_CACHE_ROOT")
if env_cache:
return env_cache
return str(Path("outputs") / "cache")
def _path_is_under(path: str, root: Path) -> bool:
try:
return Path(path).resolve().as_posix().startswith(root.resolve().as_posix())
except Exception:
return False
def _set_cache_env(cache_root: Optional[str]) -> None:
if not cache_root:
return
resolved_root = Path(cache_root).expanduser()
if not resolved_root.is_absolute():
resolved_root = (Path.cwd() / resolved_root).resolve()
else:
resolved_root = resolved_root.resolve()
resolved_root.mkdir(parents=True, exist_ok=True)
hf_home = resolved_root / "hf_cache"
hub_cache = hf_home / "hub"
datasets_cache = hf_home / "datasets"
torch_home = resolved_root / "torch_cache"
point_e_cache = resolved_root / "point_e_cache"
tmp_dir = resolved_root / "tmp"
for path in (hf_home, hub_cache, datasets_cache, torch_home, point_e_cache, tmp_dir):
path.mkdir(parents=True, exist_ok=True)
home_root = Path.home()
def _set_env(name: str, value: Path) -> None:
current = os.environ.get(name)
if not current or _path_is_under(current, home_root):
os.environ[name] = str(value)
_set_env("HF_HOME", hf_home)
_set_env("HUGGINGFACE_HUB_CACHE", hub_cache)
_set_env("TRANSFORMERS_CACHE", hub_cache)
_set_env("HF_DATASETS_CACHE", datasets_cache)
_set_env("TORCH_HOME", torch_home)
_set_env("POINT_E_CACHE_DIR", point_e_cache)
_set_env("TMPDIR", tmp_dir)
_set_env("TEMP", tmp_dir)
_set_env("TMP", tmp_dir)
def _expand_list(value) -> List[str]:
if value is None:
return []
if isinstance(value, (list, tuple)):
return list(value)
if isinstance(value, str):
if "," in value:
return [v for v in value.split(",") if v]
if " " in value.strip():
return [v for v in value.strip().split(" ") if v]
return [value]
return [value]
def _resolve_path(path: Optional[str], base_dir: Path, data_root: Optional[Path]) -> Optional[str]:
if path is None:
return None
path_obj = Path(path)
if path_obj.is_absolute():
return str(path_obj)
if data_root is not None:
return str(data_root / path_obj)
return str(base_dir / path_obj)
def _load_manifest(manifest_path: Path) -> List[Dict]:
if manifest_path.suffix.lower() == ".jsonl":
samples = []
with open(manifest_path, "r", encoding="utf-8") as handle:
for line in handle:
line = line.strip()
if not line:
continue
samples.append(json.loads(line))
return samples
with open(manifest_path, "r", encoding="utf-8") as handle:
data = json.load(handle)
if isinstance(data, dict) and "samples" in data:
return list(data["samples"])
if isinstance(data, list):
return data
raise ValueError("Manifest must be a JSON list or contain a 'samples' list.")
def _resize_mask(mask_arr: np.ndarray, target_image: np.ndarray) -> np.ndarray:
h, w = target_image.shape[:2]
if mask_arr.shape[0] == h and mask_arr.shape[1] == w:
return mask_arr.astype(bool)
mask_img = Image.fromarray(mask_arr.astype(np.uint8) * 255)
mask_img = mask_img.resize((w, h), resample=Image.Resampling.NEAREST)
return (np.array(mask_img) > 0).astype(bool)
def _mask_too_small(mask: np.ndarray, min_size: int = 2) -> bool:
if mask is None:
return True
ys, xs = np.where(mask)
if ys.size == 0 or xs.size == 0:
return True
width = xs.max() - xs.min() + 1
height = ys.max() - ys.min() + 1
return width < min_size or height < min_size
def _crop_and_center_object(image: np.ndarray, bg_threshold: int = 5) -> np.ndarray:
if image is None:
return image
img = image
if img.ndim == 2:
img = np.stack([img, img, img], axis=-1)
if img.shape[-1] == 4:
alpha = img[..., 3]
mask = alpha > 0
img = img[..., :3]
else:
mask = img.sum(axis=-1) > bg_threshold
ys, xs = np.where(mask)
if ys.size == 0 or xs.size == 0:
return img
y0, y1 = ys.min(), ys.max() + 1
x0, x1 = xs.min(), xs.max() + 1
crop = img[y0:y1, x0:x1]
h, w = crop.shape[:2]
size = max(h, w)
out = np.zeros((size, size, 3), dtype=crop.dtype)
y_off = (size - h) // 2
x_off = (size - w) // 2
out[y_off : y_off + h, x_off : x_off + w] = crop
return out
def _resize_image(image: np.ndarray, size: int = 224) -> np.ndarray:
if image is None:
return image
pil_img = Image.fromarray(image)
pil_img = pil_img.resize((size, size), resample=Image.Resampling.BICUBIC)
return np.array(pil_img)
def _prep_lpips_tensor(image: np.ndarray, size: int = 224) -> torch.Tensor:
resized = _resize_image(image, size=size).astype(np.float32) / 255.0
if resized.ndim == 2:
resized = np.stack([resized, resized, resized], axis=-1)
if resized.shape[-1] == 4:
resized = resized[..., :3]
tensor = torch.from_numpy(resized).permute(2, 0, 1).unsqueeze(0)
return tensor
def _resolve_obs_object_image(
entry: Dict,
base_dir: Path,
data_root: Optional[Path],
image_path: Optional[str],
) -> Optional[str]:
for key in ("obs_object_image", "rendered", "full_object_image"):
if entry.get(key):
return _resolve_path(entry.get(key), base_dir, data_root)
if image_path:
img_dir = Path(image_path).parent
candidate = img_dir / "rendered.png"
if candidate.exists():
return str(candidate)
return None
def _load_inputs(entry: Dict, data_root: Optional[Path], base_dir: Path):
image_path = _resolve_path(entry.get("image"), base_dir, data_root)
if image_path is None:
raise ValueError("Each entry must define an 'image' path.")
image = load_image(image_path)
mask_path = _resolve_path(entry.get("mask"), base_dir, data_root)
if mask_path:
mask = load_mask(mask_path)
mask = _resize_mask(mask, image)
else:
mask = infer_mask_from_image(image)
prior_images = _expand_list(entry.get("prior_images") or entry.get("prior_image"))
if not prior_images:
logger.warning("No prior_images provided; defaulting to input image for {}", image_path)
prior_images = [image_path]
prior_image_paths = [_resolve_path(p, base_dir, data_root) for p in prior_images]
prior_images = [load_image(p) for p in prior_image_paths]
prior_masks = _expand_list(entry.get("prior_masks") or entry.get("prior_mask"))
prior_mask_paths: List[str] = []
if prior_masks:
prior_mask_paths = [_resolve_path(p, base_dir, data_root) for p in prior_masks]
if len(prior_mask_paths) == 1 and len(prior_images) > 1:
base_mask = load_mask(prior_mask_paths[0])
prior_masks = [_resize_mask(base_mask, pi) for pi in prior_images]
elif len(prior_mask_paths) != len(prior_images):
raise ValueError(
f"prior_masks length must be 1 or match prior_images ({len(prior_images)})."
)
else:
prior_masks = [
_resize_mask(load_mask(p), pi) for p, pi in zip(prior_mask_paths, prior_images)
]
else:
prior_masks = [infer_mask_from_image(pi) for pi in prior_images]
return (
image_path,
mask_path,
image,
mask,
prior_images,
prior_masks,
prior_image_paths,
prior_mask_paths,
)
def _save_mask_array(mask: np.ndarray, path: Path) -> None:
mask_u8 = (mask.astype(np.uint8) * 255)
imageio.imwrite(str(path), mask_u8)
def _copy_inputs(
input_dir: Path,
image_path: Optional[str],
mask_path: Optional[str],
mask: np.ndarray,
prior_image_paths: List[str],
prior_mask_paths: List[str],
prior_masks: List[np.ndarray],
) -> None:
input_dir.mkdir(parents=True, exist_ok=True)
if image_path and Path(image_path).exists():
shutil.copy2(image_path, input_dir / "image.png")
if mask_path and Path(mask_path).exists():
shutil.copy2(mask_path, input_dir / "mask.png")
else:
_save_mask_array(mask, input_dir / "mask.png")
for idx, prior_path in enumerate(prior_image_paths):
suffix = Path(prior_path).suffix or ".png"
dst_path = input_dir / f"prior_{idx:02d}{suffix}"
if prior_path and Path(prior_path).exists():
shutil.copy2(prior_path, dst_path)
if prior_mask_paths:
for idx, prior_mask_path in enumerate(prior_mask_paths):
suffix = Path(prior_mask_path).suffix or ".png"
dst_path = input_dir / f"prior_mask_{idx:02d}{suffix}"
if prior_mask_path and Path(prior_mask_path).exists():
shutil.copy2(prior_mask_path, dst_path)
else:
for idx, prior_mask in enumerate(prior_masks):
_save_mask_array(prior_mask, input_dir / f"prior_mask_{idx:02d}.png")
def _to_pil_rgb(image) -> Image.Image:
if isinstance(image, Image.Image):
img = image
else:
img = Image.fromarray(image)
if img.mode == "RGBA":
bg = Image.new("RGBA", img.size, (255, 255, 255, 255))
img = Image.alpha_composite(bg, img).convert("RGB")
else:
img = img.convert("RGB")
return img
def _render_standard_views(
sample,
out_dir: Path,
resolution: int,
backend: str,
bg_color=(0, 0, 0),
) -> List[np.ndarray]:
out_dir.mkdir(parents=True, exist_ok=True)
yaws = [0.0, 0.5 * np.pi, 1.0 * np.pi, 1.5 * np.pi]
pitchs = [30.0 * np.pi / 180.0] * 4
extrinsics, intrinsics = render_utils.yaw_pitch_r_fov_to_extrinsics_intrinsics(
yaws, pitchs, rs=2.0, fovs=40.0
)
render_options = {"resolution": resolution, "bg_color": bg_color, "backend": backend}
res = render_utils.render_frames_rgba(
sample, extrinsics, intrinsics, render_options, verbose=False
)
views = res.get("color", [])
for i, view in enumerate(views):
imageio.imwrite(str(out_dir / f"view_{i:02d}.png"), view)
return views
def _load_rendered_frames(frames_dir: Path) -> List[np.ndarray]:
if not frames_dir.exists():
return []
paths = sorted(
[p for p in frames_dir.iterdir() if p.suffix.lower() in {".png", ".jpg", ".jpeg"}]
)
if not paths:
return []
frames: List[np.ndarray] = []
for path in paths:
try:
frames.append(np.array(imageio.imread(str(path))))
except Exception:
continue
return frames
def _select_evenly_spaced(items: List[Any], count: int) -> List[Any]:
if not items:
return []
if count <= 0 or len(items) <= count:
return list(items)
indices = np.linspace(0, len(items) - 1, num=count, dtype=int).tolist()
selected: List[Any] = []
last_idx = None
for idx in indices:
if last_idx is None or idx != last_idx:
selected.append(items[idx])
last_idx = idx
return selected
def _save_frames_and_video(
frames: List[np.ndarray],
frames_dir: Path,
video_path: Path,
fps: int = 15,
frame_stride: int = 1,
) -> None:
if not frames:
return
frames_dir.mkdir(parents=True, exist_ok=True)
stride = max(1, int(frame_stride))
saved_frames: List[np.ndarray] = []
for idx, frame in enumerate(frames):
if idx % stride != 0:
continue
imageio.imwrite(str(frames_dir / f"frame_{idx:04d}.png"), frame)
saved_frames.append(frame)
if not saved_frames:
return
with imageio.get_writer(str(video_path), fps=fps) as writer:
for frame in saved_frames:
if frame.ndim == 2:
rgb_frame = np.stack([frame, frame, frame], axis=-1)
elif frame.shape[-1] == 4:
rgb_frame = frame[:, :, :3]
else:
rgb_frame = frame
writer.append_data(rgb_frame)
def _format_duration(seconds: float) -> str:
if seconds is None or seconds < 0:
return "n/a"
total = int(seconds)
hours = total // 3600
minutes = (total % 3600) // 60
secs = total % 60
if hours:
return f"{hours:d}h{minutes:02d}m{secs:02d}s"
if minutes:
return f"{minutes:d}m{secs:02d}s"
return f"{secs:d}s"
def _render_spiral_views(
sample,
resolution: int,
backend: str,
num_frames: int,
bg_color=(1, 1, 1),
yaw_start_deg: float = -90.0,
pitch_deg: float = 0.0,
pitch_span_deg: float = 30.0,
radius: float = 2.0,
radius_span: float = 0.3,
fov_deg: float = 40.0,
) -> List[np.ndarray]:
yaws = torch.linspace(0, 2 * torch.pi, num_frames)
t_vals = torch.linspace(0, 2 * torch.pi, num_frames)
pitchs = (0.25 + 0.5 * torch.sin(t_vals)).tolist()
radii = [radius] * num_frames
extr, intr = render_utils.yaw_pitch_r_fov_to_extrinsics_intrinsics(
yaws.tolist(), pitchs, radii, fov_deg
)
render_options = {
"resolution": resolution,
"bg_color": bg_color,
"backend": backend,
}
res = render_utils.render_frames_rgba(sample, extr, intr, render_options, verbose=False)
return res.get("color", [])
def _render_turntable_views(
sample,
resolution: int,
backend: str,
num_frames: int,
bg_color=(0, 0, 0),
yaw_start_deg: float = -90.0,
pitch_deg: float = 0.0,
radius: float = 2.0,
fov_deg: float = 40.0,
) -> List[np.ndarray]:
"""Render turntable (fixed pitch) views around the object."""
yaws = (
torch.linspace(0, 2 * torch.pi, num_frames)
+ math.radians(yaw_start_deg)
).tolist()
pitchs = [math.radians(pitch_deg)] * num_frames
radii = [radius] * num_frames
extr, intr = render_utils.yaw_pitch_r_fov_to_extrinsics_intrinsics(
yaws, pitchs, radii, fov_deg
)
render_options = {
"resolution": resolution,
"bg_color": bg_color,
"backend": backend,
}
res = render_utils.render_frames_rgba(sample, extr, intr, render_options, verbose=False)
return res.get("color", [])
def _load_gt_images(
entry: Dict, data_root: Optional[Path], base_dir: Path
) -> Tuple[List[np.ndarray], List[str]]:
gt_images = _expand_list(entry.get("gt_images"))
gt_render_dir = entry.get("gt_render_dir")
paths: List[str] = []
if gt_images:
paths = [_resolve_path(p, base_dir, data_root) for p in gt_images]
elif gt_render_dir:
render_dir = Path(_resolve_path(gt_render_dir, base_dir, data_root))
paths = sorted(
str(p)
for ext in ("*.png", "*.jpg", "*.jpeg")
for p in render_dir.glob(ext)
)
if not paths:
return [], []
images = []
for p in paths:
try:
images.append(np.array(imageio.imread(p)))
except Exception:
continue
return images, paths
def _copy_gt_images(paths: List[str], dst_dir: Path, frame_stride: int = 1) -> None:
if not paths:
return
dst_dir.mkdir(parents=True, exist_ok=True)
stride = max(1, int(frame_stride))
for idx, p in enumerate(paths):
if idx % stride != 0:
continue
src = Path(p)
if not src.exists():
continue
shutil.copy2(src, dst_dir / src.name)
def _load_pointcloud(path: Optional[str]) -> Optional[np.ndarray]:
if path is None:
return None
path_obj = Path(path)
if not path_obj.exists():
return None
if path_obj.suffix == ".npy":
return np.load(str(path_obj))
if path_obj.suffix == ".pth":
data = torch.load(str(path_obj), map_location="cpu")
if isinstance(data, dict):
data = data.get("points") or data.get("pc") or data.get("pointcloud")
if isinstance(data, torch.Tensor):
return data.cpu().numpy()
if isinstance(data, np.ndarray):
return data
return None
def _mesh_to_pointcloud(mesh, device: str, points: int = 4096) -> Optional[torch.Tensor]:
if mesh is None:
return None
if isinstance(mesh, trimesh.Scene):
if not mesh.geometry:
return None
mesh = trimesh.util.concatenate(tuple(mesh.geometry.values()))
if hasattr(mesh, "vertices"):
verts = mesh.vertices
if isinstance(verts, torch.Tensor):
verts = verts.detach().cpu().numpy()
verts = np.asarray(verts)
else:
return None
if verts.ndim != 2 or verts.shape[1] != 3:
return None
pts = torch.from_numpy(verts).float().unsqueeze(0)
pts = pts.to(device)
pts = fps_downsample(pts, points)
return pts
def _atomic_json_dump(path: Path, payload: Dict) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp_path = path.with_suffix(path.suffix + ".tmp")
with tmp_path.open("w", encoding="utf-8") as handle:
json.dump(payload, handle, indent=2)
os.replace(tmp_path, path)
def _write_text_file(path: Path, content: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp_path = path.with_suffix(path.suffix + ".tmp")
tmp_path.write_text(content, encoding="utf-8")
os.replace(tmp_path, path)
def _mean_metrics(metric_dicts: List[Dict[str, float]]) -> Dict[str, float]:
if not metric_dicts:
return {}
keys = set().union(*[m.keys() for m in metric_dicts])
avg: Dict[str, float] = {}
for key in keys:
vals = [m[key] for m in metric_dicts if key in m and not np.isnan(m[key])]
if vals:
avg[key] = float(np.mean(vals))
return avg
def _run_vis_pass(
pipeline,
output: Dict,
branch_name: str,
save_dir: Path,
render_backend: str,
render_resolution: int,
render_num_frames: int,
render_frame_stride: int,
) -> None:
"""Run visualization rendering for a single branch output."""
branch_out = output.get("relaxflow") if branch_name == "relaxflow" else output.get(branch_name)
if branch_out is None:
logger.warning("Missing branch output {} for visualization", branch_name)
return
gs = branch_out.get("gs") or (branch_out.get("gaussian") or [None])[0]
if gs is None:
logger.warning("Missing gaussian output for {}", branch_name)
return
branch_dir = save_dir / branch_name
branch_dir.mkdir(parents=True, exist_ok=True)
# Render spiral views (transparent background)
try:
spiral_frames = _render_spiral_views(
gs,
render_resolution,
render_backend,
render_num_frames,
bg_color=(0, 0, 0), # transparent bg
)
if spiral_frames:
spiral_frames_dir = branch_dir / "spiral_frames_rgba"
_save_frames_and_video(
spiral_frames,
spiral_frames_dir,
branch_dir / f"{branch_name}_spiral.mp4",
fps=15,
frame_stride=render_frame_stride,
)
logger.info("Saved spiral video for {}", branch_name)
except Exception as exc:
logger.warning("Spiral render failed for {}: {}", branch_name, exc)
# Render turntable views (transparent background)
try:
turntable_frames = _render_turntable_views(
gs,
render_resolution,
render_backend,
render_num_frames,
bg_color=(0, 0, 0), # transparent bg
)
if turntable_frames:
turntable_frames_dir = branch_dir / "turntable_frames_rgba"
_save_frames_and_video(
turntable_frames,
turntable_frames_dir,
branch_dir / f"{branch_name}_turntable.mp4",
fps=15,
frame_stride=render_frame_stride,
)
logger.info("Saved turntable video for {}", branch_name)
except Exception as exc:
logger.warning("Turntable render failed for {}: {}", branch_name, exc)
# Save mesh if available
mesh_list = branch_out.get("mesh")
glb_data = branch_out.get("glb")
if mesh_list:
try:
mesh = mesh_list[0] if isinstance(mesh_list, (list, tuple)) else mesh_list
if hasattr(mesh, "vertices"):
mesh_path = branch_dir / f"{branch_name}.ply"
if isinstance(mesh, trimesh.Trimesh):
mesh.export(str(mesh_path))
elif hasattr(mesh, "save"):
mesh.save(str(mesh_path))
except Exception as exc:
logger.warning("Mesh save failed for {}: {}", branch_name, exc)
if glb_data is not None:
try:
glb_path = branch_dir / f"{branch_name}.glb"
if hasattr(glb_data, "export"):
glb_data.export(str(glb_path))
elif isinstance(glb_data, bytes):
glb_path.write_bytes(glb_data)
except Exception as exc:
logger.warning("GLB save failed for {}: {}", branch_name, exc)
def build_pipeline(config_path: str, compile_model: bool, prior_mode: str, run_obs_only: bool = False):
config = OmegaConf.load(config_path)
config.rendering_engine = "pytorch3d"
config.compile_model = compile_model
config.workspace_dir = os.path.dirname(config_path)
# Use base pipeline (no prior images needed) when run_obs_only is True
config["_target_"] = PIPELINE_TARGET_BASE if run_obs_only else PIPELINE_TARGET_RELAXFLOW
# Only add RELAXFLOW-specific parameters when not running obs_only mode
if not run_obs_only:
if "prior_blur_sigma" not in config:
config.prior_blur_sigma = 2.5
if "blur_attn_type" not in config:
config.blur_attn_type = "self"
config.pop("prior_mode", None)
if prior_mode == "cropped":
config.prior_use_cropped_only = True
config.prior_only_cropped_img_and_mask = False
elif prior_mode == "full":
config.prior_use_cropped_only = False
config.prior_only_cropped_img_and_mask = False
elif prior_mode == "cropped_and_mask":
config.prior_use_cropped_only = False
config.prior_only_cropped_img_and_mask = True
else:
for key in ["prior_blur_sigma", "blur_attn_type", "prior_mode",
"prior_use_cropped_only", "prior_only_cropped_img_and_mask"]:
config.pop(key, None)
check_hydra_safety(config, WHITELIST_FILTERS, BLACKLIST_FILTERS)
return instantiate(config)
def parse_args():
parser = argparse.ArgumentParser(
description="Batch RelaxFlow runner.",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=__doc__,
)
io_group = parser.add_argument_group("Input/Output")
io_group.add_argument(
"--config",
default="checkpoints/hf/checkpoints/pipeline.yaml",
help="Path to the pipeline config file.",
)
io_group.add_argument(
"--dataset",
required=True,
help="Path to dataset manifest (JSON/JSONL).",
)
io_group.add_argument(
"--data-root",
default=None,
help="Optional root directory to resolve relative paths in the manifest.",
)
io_group.add_argument(
"--output-dir",
type=str,
default="outputs/relaxflow_batch",
help="Output directory.",
)
io_group.add_argument(
"--output-name",
type=str,
default="run",
help="Output name prefix.",
)
io_group.add_argument(
"--world-size",
type=int,
default=1,
help="Number of workers for sharded evaluation.",
)
io_group.add_argument(
"--rank",
type=int,
default=0,
help="Worker rank in [0, world_size).",
)
io_group.add_argument(
"--max-samples",
type=int,
default=-1,
help="Optional limit of samples to process after sharding (-1 for all).",
)
pipeline_group = parser.add_argument_group("Pipeline Options")
pipeline_group.add_argument(
"--image-as",
type=str,
default="part",
choices=["scene", "part"],
help="Route observed image into 'part' or 'scene' condition slot.",
)
pipeline_group.add_argument(
"--only-cropped-img",
action="store_true",
help="Use only cropped image token as condition.",
)
pipeline_group.add_argument(
"--only-cropped-img-and-mask",
action="store_true",
help="Use cropped image and mask tokens as condition.",
)
pipeline_group.add_argument(
"--stage1-only",
action="store_true",
help="Skip Stage 2 (SLAT) and output sparse structure only.",
)
pipeline_group.add_argument(
"--compile",
action="store_true",
help="Compile the pipeline for faster inference.",
)
pipeline_group.add_argument(
"--compute-original",
action="store_true",
help="Also sample the original (non-relaxflow) branch.",
)
pipeline_group.add_argument(
"--compute-blend-prior-slat",
action="store_true",
help="Also decode the blend_prior_slat branch.",
)
pipeline_group.add_argument(
"--attn-blur-type",
choices=["cross", "self", "both"],
default="cross",
help="Alias for --blur-attn-type (Stage 1). If set, also applies to Stage 2 unless overridden.",
)
pipeline_group.add_argument(
"--stage2-attn-blur-type",
choices=["cross", "self", "both"],
default="cross",
help="Alias for --stage2-blur-attn-type (Stage 2).",
)
pipeline_group.add_argument(
"--run-obs-only",
action="store_true",
default=False,
help="Run only the obs_only branch (vanilla SAM3D), skip RELAXFLOW blending.",
)
vis_group = parser.add_argument_group("Visualization Mode")
vis_group.add_argument(
"--vis",
action="store_true",
default=True,
help="Enable visualization mode: run both blurred and no-blur, render spiral+turntable, skip metrics.",
)
render_group = parser.add_argument_group("Rendering Options")
render_group.add_argument(
"--render-backend",
default="inria",
choices=["inria", "gsplat"],
help="Rendering backend for turntable video.",
)
render_group.add_argument(
"--render-resolution",
type=int,
default=512,
help="Resolution for standard view renders.",
)
render_group.add_argument(
"--render-num-frames",
type=int,
default=120,
help="Frames for turntable video.",
)
render_group.add_argument(
"--render-frame-stride",
type=int,
default=2,
help="Stride for saving rendered frames (e.g. 2 saves every other frame).",
)
render_group.add_argument(
"--use-vertex-color",
dest="use_vertex_color",
action="store_true",
default=True,
help="Use vertex color baking for mesh.",
)
render_group.add_argument(
"--no-vertex-color",
dest="use_vertex_color",
action="store_false",
help="Skip vertex color baking.",
)
eval_group = parser.add_argument_group("Evaluation")
eval_group.add_argument(
"--eval-branches",
nargs="+",
default=["relaxflow", "blend_obs_slat", "obs_only"],
help="Branches to evaluate.",
)
eval_group.add_argument(
"--metrics-device",
default="cuda",
help="Device for metric computation.",
)
eval_group.add_argument(
"--clip-text-model",
default="openai/clip-vit-base-patch32",
help="Model name for image-text CLIPScore.",
)
eval_group.add_argument(
"--clip-image-model",
default="openai/clip-vit-base-patch32",
help="Model name for image-image CLIP similarity.",
)
eval_group.add_argument(
"--omit-point-level-metrics",
dest="omit_point_level_metrics",
action="store_true",
default=True,
help="Omit point-level 3D metrics (default: enabled).",
)
eval_group.add_argument(
"--keep-point-level-metrics",
dest="omit_point_level_metrics",
action="store_false",
help="Enable point-level 3D metrics (Chamfer, F-score, voxel IoU, COV/MMD).",
)
eval_group.add_argument(
"--eval-frames",
type=int,
default=10,
help="Evenly spaced frames per branch for CLIP/LPIPS metrics.",
)
eval_group.add_argument(
"--skip-pfid",
action="store_true",
help="Skip Point-E P-FID computation.",
)
eval_group.add_argument(
"--cache-root",
default=_default_cache_root(),
help="Cache directory for HF and temp files.",
)
add_relaxflow_arguments(parser)
return parser.parse_args()
def main() -> None:
args = parse_args()
if args.attn_blur_type is not None:
args.blur_attn_type = args.attn_blur_type
if args.stage2_attn_blur_type is None:
args.stage2_blur_attn_type = args.attn_blur_type
if args.stage2_attn_blur_type is not None:
args.stage2_blur_attn_type = args.stage2_attn_blur_type
if args.vis:
logger.info("Visualization mode enabled: skipping metrics, rendering spiral+turntable")
args.render_num_frames = 120
args.render_frame_stride = 1
run_obs_only = getattr(args, "run_obs_only", False)
if run_obs_only:
logger.info("Running obs_only mode: using base pipeline (no RELAXFLOW), only vanilla SAM3D.")
args.eval_branches = ["obs_only"]
args.compute_original = False
args.compute_blend_prior_slat = False
warnings.filterwarnings(
"ignore",
message="Bin size was too small in the coarse rasterization phase.*",
)
_set_cache_env(args.cache_root)