AntonioJun commited on
Commit
e40672f
·
verified ·
1 Parent(s): 6507d60

Update workspace code without replacing data

Browse files
encoder/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Spatial-code encoder package."""
encoder/adapters.py CHANGED
@@ -15,6 +15,7 @@ of those representations cross this file boundary.
15
  import gzip
16
  import os
17
  import pickle
 
18
 
19
  import numpy as np
20
 
@@ -92,6 +93,74 @@ def _load_masks(path):
92
  raise FileNotFoundError(f"no SAM3 cache found at {path}")
93
 
94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  def _backproject(depth, K, c2w, mask, conf=None):
96
  ys, xs = np.nonzero(mask)
97
  z = depth[ys, xs]
@@ -105,23 +174,26 @@ def _backproject(depth, K, c2w, mask, conf=None):
105
  return Xw.astype(np.float32), cf
106
 
107
 
108
- def adapt_da3_sam3(root=None, da3_path=None, sam3_path=None, **_):
109
- """Flat DA3 and SAM3 cache files -> the canonical geometry dict."""
 
 
 
110
  if da3_path is None:
111
  da3_path = os.path.join(root, "da3.npz") if root else None
112
  if sam3_path is None:
113
  sam3_path = root
114
  if not da3_path:
115
  raise ValueError("da3_path is required")
116
- d = np.load(da3_path)
117
- depth, intr, c2w = d["depth"], d["intr"], d["c2w"]
118
- conf = d["conf"] if "conf" in d and d["conf"].size else None
119
- ft = (
120
- d["frame_times"]
121
- if "frame_times" in d
122
- else np.arange(len(depth), dtype=np.float32)
123
- )
124
- per = _load_masks(sam3_path)
125
  instances, stats = {}, {}
126
  for cls, frames in per.items():
127
  by_id = {}
@@ -198,16 +270,106 @@ def adapt_da3_sam3(root=None, da3_path=None, sam3_path=None, **_):
198
  # ==========================================================================================
199
 
200
 
201
- def adapt_segvggt(root=None, path=None, **_):
202
- """Translate an existing SegVGGT NPZ export to canonical geometry."""
203
- path = path or root
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
  if path is None:
205
  raise ValueError("SegVGGT cache path is required")
206
  if os.path.isdir(path):
207
- path = os.path.join(path, "geometry.npz")
208
  if not os.path.exists(path):
209
  raise FileNotFoundError(f"SegVGGT raw cache does not exist: {path}")
210
- d = np.load(path, allow_pickle=True)
 
 
 
211
  world, masks = (
212
  np.asarray(d["world_points"], np.float32),
213
  np.asarray(d["instance_masks"], bool),
@@ -256,3 +418,24 @@ def adapt_segvggt(root=None, path=None, **_):
256
  "cameras": d["camera_positions"] if "camera_positions" in d else None,
257
  }
258
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  import gzip
16
  import os
17
  import pickle
18
+ import sys
19
 
20
  import numpy as np
21
 
 
93
  raise FileNotFoundError(f"no SAM3 cache found at {path}")
94
 
95
 
96
+ def _load_native_sam3(path):
97
+ """Decode the raw, per-frame SAM3 image-processor responses without tracking."""
98
+ try:
99
+ import torch
100
+ except ImportError as exc:
101
+ raise RuntimeError("PyTorch is required to read a raw SAM3 .pt cache") from exc
102
+ responses = torch.load(path, map_location="cpu", weights_only=False)
103
+ if not isinstance(responses, list):
104
+ raise ValueError(f"invalid SAM3 raw cache {path}; expected a response list")
105
+ class_name = os.environ.get("VSI_SAM3_PROMPT", "object")
106
+ frames = {}
107
+ for frame_index, response in enumerate(responses):
108
+ if not isinstance(response, dict):
109
+ raise ValueError(
110
+ f"invalid SAM3 response at frame {frame_index}; expected a dict"
111
+ )
112
+ masks = response.get("masks")
113
+ if masks is None and isinstance(response.get("outputs"), dict):
114
+ masks = response["outputs"].get("masks")
115
+ if masks is None:
116
+ raise ValueError(f"SAM3 response at frame {frame_index} has no masks")
117
+ masks = masks.detach().cpu().numpy() if hasattr(masks, "detach") else np.asarray(masks)
118
+ if masks.ndim == 2:
119
+ masks = masks[None]
120
+ if masks.ndim == 4 and masks.shape[1] == 1:
121
+ masks = masks[:, 0]
122
+ if masks.ndim != 3:
123
+ raise ValueError(
124
+ f"SAM3 masks at frame {frame_index} must be [N,H,W], got {masks.shape}"
125
+ )
126
+ frames[frame_index] = {
127
+ object_id: mask.astype(bool) for object_id, mask in enumerate(masks)
128
+ }
129
+ return {class_name: frames}
130
+
131
+
132
+ def _load_native_da3(path):
133
+ """Decode DA3's exact pickled Prediction object into projection inputs."""
134
+ model_root = os.environ.get("VSI_DA3_ROOT", "/root/models/depth-anything-3")
135
+ source_root = os.path.join(model_root, "src")
136
+ if source_root not in sys.path:
137
+ sys.path.insert(0, source_root)
138
+ with open(path, "rb") as stream:
139
+ prediction = pickle.load(stream)
140
+
141
+ def field(name, required=True):
142
+ value = getattr(prediction, name, None)
143
+ if value is None and isinstance(prediction, dict):
144
+ value = prediction.get(name)
145
+ if required and value is None:
146
+ raise ValueError(f"DA3 Prediction in {path} has no {name}")
147
+ return value
148
+
149
+ depth = np.asarray(field("depth"), np.float32)
150
+ intr = np.asarray(field("intrinsics"), np.float32)
151
+ extr = np.asarray(field("extrinsics"), np.float32)
152
+ if extr.shape[-2:] == (3, 4):
153
+ homogeneous = np.broadcast_to(np.eye(4, dtype=np.float32), extr.shape[:-2] + (4, 4)).copy()
154
+ homogeneous[..., :3, :] = extr
155
+ extr = homogeneous
156
+ if extr.shape[-2:] != (4, 4):
157
+ raise ValueError(f"DA3 extrinsics must end in [3,4] or [4,4], got {extr.shape}")
158
+ c2w = np.linalg.inv(extr).astype(np.float32)
159
+ conf_value = field("conf", required=False)
160
+ conf = np.asarray(conf_value, np.float32) if conf_value is not None else None
161
+ return depth, intr, c2w, conf
162
+
163
+
164
  def _backproject(depth, K, c2w, mask, conf=None):
165
  ys, xs = np.nonzero(mask)
166
  z = depth[ys, xs]
 
174
  return Xw.astype(np.float32), cf
175
 
176
 
177
+ def adapt_da3_sam3(root=None, da3_path=None, sam3_path=None, scene=None, **_):
178
+ """Fuse raw DA3 geometry and raw per-frame SAM3 masks into canonical geometry."""
179
+ if root and scene:
180
+ da3_path = da3_path or os.path.join(root, "depth-anything-3", f"{scene}.pkl")
181
+ sam3_path = sam3_path or os.path.join(root, "sam3", f"{scene}.pt")
182
  if da3_path is None:
183
  da3_path = os.path.join(root, "da3.npz") if root else None
184
  if sam3_path is None:
185
  sam3_path = root
186
  if not da3_path:
187
  raise ValueError("da3_path is required")
188
+ if str(da3_path).endswith(".pkl"):
189
+ depth, intr, c2w, conf = _load_native_da3(da3_path)
190
+ ft = np.arange(len(depth), dtype=np.float32)
191
+ else:
192
+ d = np.load(da3_path)
193
+ depth, intr, c2w = d["depth"], d["intr"], d["c2w"]
194
+ conf = d["conf"] if "conf" in d and d["conf"].size else None
195
+ ft = d["frame_times"] if "frame_times" in d else np.arange(len(depth), dtype=np.float32)
196
+ per = _load_native_sam3(sam3_path) if str(sam3_path).endswith(".pt") else _load_masks(sam3_path)
197
  instances, stats = {}, {}
198
  for cls, frames in per.items():
199
  by_id = {}
 
270
  # ==========================================================================================
271
 
272
 
273
+ SEGVGGT_CLASSES = """wall|floor|chair|table|door|couch|cabinet|shelf|desk|office chair|bed|pillow|sink|picture|window|toilet|bookshelf|monitor|curtain|book|armchair|coffee table|box|refrigerator|lamp|kitchen cabinet|towel|clothes|tv|nightstand|counter|dresser|stool|cushion|plant|ceiling|bathtub|end table|dining table|keyboard|bag|backpack|toilet paper|printer|tv stand|whiteboard|blanket|shower curtain|trash can|closet|stairs|microwave|stove|shoe|computer tower|bottle|bin|ottoman|bench|board|washing machine|mirror|copier|basket|sofa chair|file cabinet|fan|laptop|shower|paper|person|paper towel dispenser|oven|blinds|rack|plate|blackboard|piano|suitcase|rail|radiator|recycling bin|container|wardrobe|soap dispenser|telephone""".split("|")
274
+
275
+
276
+ def _decode_segvggt_raw(path):
277
+ """Decode the official SegVGGT.forward tensor dictionary for this adapter."""
278
+ import sys
279
+
280
+ try:
281
+ import torch
282
+ import torch.nn.functional as functional
283
+ except ImportError as exc:
284
+ raise RuntimeError("PyTorch is required to read a SegVGGT .pt cache") from exc
285
+
286
+ model_root = os.environ.get("VSI_SEGVGGT_ROOT", "/root/models/SegVGGT")
287
+ if model_root not in sys.path:
288
+ sys.path.insert(0, model_root)
289
+ try:
290
+ from eval.instance_eval_common import predict_by_feat_instance
291
+ from segvggt.utils.pose_enc import pose_encoding_to_extri_intri
292
+ except ImportError as exc:
293
+ raise RuntimeError(
294
+ "SegVGGT is required to decode its native prediction dictionary"
295
+ ) from exc
296
+
297
+ raw = torch.load(path, map_location="cpu", weights_only=False)
298
+ required = {"world_points", "instance_maps", "instance_labels", "pose_enc"}
299
+ if not isinstance(raw, dict) or not required.issubset(raw):
300
+ missing = sorted(required - set(raw)) if isinstance(raw, dict) else sorted(required)
301
+ raise ValueError(f"invalid SegVGGT raw cache {path}; missing keys: {missing}")
302
+
303
+ logits = raw["instance_maps"][0]
304
+ query_count, frame_total, height, width = logits.shape
305
+ masks, label_ids, _ = predict_by_feat_instance(
306
+ raw["instance_labels"][0],
307
+ logits.reshape(query_count, -1),
308
+ mask_thr=float(os.environ.get("VSI_MASK_THR", "0.4")),
309
+ npoint_thr=1,
310
+ )
311
+ masks = masks.reshape(-1, frame_total, height, width).cpu().numpy()
312
+ label_ids = label_ids.cpu().numpy()
313
+ keep = [index for index, label in enumerate(label_ids) if int(label) >= 2]
314
+
315
+ world = raw["world_points"][0].float()
316
+ if tuple(world.shape[1:3]) != (height, width):
317
+ world = (
318
+ functional.interpolate(
319
+ world.permute(0, 3, 1, 2),
320
+ (height, width),
321
+ mode="nearest",
322
+ )
323
+ .permute(0, 2, 3, 1)
324
+ )
325
+ world = world.cpu().numpy()
326
+
327
+ if "images" in raw:
328
+ image_size = raw["images"].shape[-2:]
329
+ elif "depth" in raw:
330
+ image_size = raw["depth"].shape[2:4]
331
+ else:
332
+ image_size = (height, width)
333
+ extrinsics, _ = pose_encoding_to_extri_intri(
334
+ raw["pose_enc"].float(), image_size
335
+ )
336
+ extrinsics = extrinsics[0].cpu().numpy()
337
+ rotations = extrinsics[:, :3, :3]
338
+ translations = extrinsics[:, :3, 3]
339
+ cameras = -np.einsum("sji,sj->si", rotations, translations)
340
+ labels = np.asarray(
341
+ [
342
+ SEGVGGT_CLASSES[int(label_ids[index])]
343
+ if int(label_ids[index]) < len(SEGVGGT_CLASSES)
344
+ else f"class {int(label_ids[index])}"
345
+ for index in keep
346
+ ],
347
+ dtype=object,
348
+ )
349
+ return {
350
+ "world_points": world,
351
+ "instance_masks": masks[keep].astype(bool),
352
+ "labels": labels,
353
+ "camera_positions": cameras.astype(np.float32),
354
+ }
355
+
356
+
357
+ def adapt_segvggt(root=None, path=None, scene=None, **_):
358
+ """Translate a raw-preserving SegVGGT cache to canonical geometry."""
359
+ if path is None and root and scene:
360
+ path = os.path.join(root, "segvggt", f"{scene}.pt")
361
+ else:
362
+ path = path or root
363
  if path is None:
364
  raise ValueError("SegVGGT cache path is required")
365
  if os.path.isdir(path):
366
+ path = os.path.join(path, f"{scene}.pt" if scene else "geometry.pt")
367
  if not os.path.exists(path):
368
  raise FileNotFoundError(f"SegVGGT raw cache does not exist: {path}")
369
+ if str(path).endswith(".pt"):
370
+ d = _decode_segvggt_raw(path)
371
+ else:
372
+ d = np.load(path, allow_pickle=True)
373
  world, masks = (
374
  np.asarray(d["world_points"], np.float32),
375
  np.asarray(d["instance_masks"], bool),
 
418
  "cameras": d["camera_positions"] if "camera_positions" in d else None,
419
  }
420
  )
421
+
422
+
423
+ RAW_ADAPTERS = {
424
+ "da3_sam3": adapt_da3_sam3,
425
+ "segvggt": adapt_segvggt,
426
+ }
427
+
428
+
429
+ def available_models():
430
+ """Return raw model formats supported by the encoder."""
431
+ return tuple(sorted(RAW_ADAPTERS))
432
+
433
+
434
+ def adapt(model, **raw_cache):
435
+ """Dispatch one model's native cache to its isolated format adapter."""
436
+ adapter = RAW_ADAPTERS.get(model)
437
+ if adapter is None:
438
+ raise KeyError(
439
+ f"no raw encoder adapter for {model!r}; expected one of {available_models()}"
440
+ )
441
+ return validate(adapter(**raw_cache))
encoder/config.py CHANGED
@@ -13,15 +13,11 @@ DATA_ROOT = Path(os.environ.get("VSI_DATA_ROOT", "/workspace/data"))
13
  VSI_ROOT = Path(os.environ.get("VSI_ROOT", "/root/data/VSI-Bench"))
14
  JSONL = Path(os.environ.get("VSI_JSONL", VSI_ROOT / "test.jsonl"))
15
  CACHE_ROOT = Path(os.environ.get("VSI_CACHE_ROOT", "/root/data/caches"))
16
- CODES_ROOT = Path(os.environ.get("VSI_CODES", DATA_ROOT / "spatial codes"))
 
 
17
  VIDEO_DATASETS = ("scannet", "scannetpp", "arkitscenes")
18
 
19
- ADAPTERS = {
20
- "da3_sam3": "adapt_da3_sam3",
21
- "segvggt": "adapt_segvggt",
22
- }
23
-
24
-
25
  def video_path(scene: str, dataset: str | None = None) -> str:
26
  """Return the unique MP4 for ``scene`` from the VSI-Bench dataset folders."""
27
  scene = str(scene)
@@ -56,15 +52,15 @@ def cache_file(scene: str, model: str | None = None) -> str:
56
 
57
 
58
  def segvggt_cache_file(scene: str, model: str | None = None) -> str:
59
- return str(Path(model_cache_dir(model or "segvggt")) / f"{scene}.npz")
60
 
61
 
62
  def da3_cache_file(scene: str, model: str | None = None) -> str:
63
- return str(Path(model_cache_dir(model or "da3_sam3")) / f"{scene}.da3.npz")
64
 
65
 
66
  def sam3_cache_file(scene: str, model: str | None = None) -> str:
67
- return str(Path(model_cache_dir(model or "da3_sam3")) / f"{scene}.sam3.pkl.gz")
68
 
69
 
70
  def spatial_code_path(scene: str) -> str:
 
13
  VSI_ROOT = Path(os.environ.get("VSI_ROOT", "/root/data/VSI-Bench"))
14
  JSONL = Path(os.environ.get("VSI_JSONL", VSI_ROOT / "test.jsonl"))
15
  CACHE_ROOT = Path(os.environ.get("VSI_CACHE_ROOT", "/root/data/caches"))
16
+ CODES_ROOT = Path(
17
+ os.environ.get("VSI_CODES", DATA_ROOT / "spatial codes" / "segvggt")
18
+ )
19
  VIDEO_DATASETS = ("scannet", "scannetpp", "arkitscenes")
20
 
 
 
 
 
 
 
21
  def video_path(scene: str, dataset: str | None = None) -> str:
22
  """Return the unique MP4 for ``scene`` from the VSI-Bench dataset folders."""
23
  scene = str(scene)
 
52
 
53
 
54
  def segvggt_cache_file(scene: str, model: str | None = None) -> str:
55
+ return str(Path(model_cache_dir(model or "segvggt")) / f"{scene}.pt")
56
 
57
 
58
  def da3_cache_file(scene: str, model: str | None = None) -> str:
59
+ return str(Path(model_cache_dir(model or "depth-anything-3")) / f"{scene}.pkl")
60
 
61
 
62
  def sam3_cache_file(scene: str, model: str | None = None) -> str:
63
+ return str(Path(model_cache_dir(model or "sam3")) / f"{scene}.pt")
64
 
65
 
66
  def spatial_code_path(scene: str) -> str:
encoder/geometric.py CHANGED
@@ -179,12 +179,19 @@ def room_gravity(
179
 
180
 
181
  def pos3(rec):
182
- """[floor_x, floor_y, height_above_floor] from a spatial-code instance record's named position."""
183
  p = rec.get("position") or {}
 
 
 
 
 
 
 
184
  return [
185
- p.get("floor_x_meters", 0.0),
186
- p.get("floor_y_meters", 0.0),
187
- p.get("height_above_floor_meters", 0.0),
188
  ]
189
 
190
 
@@ -210,6 +217,26 @@ def _floor_basis(up_vec):
210
  return u, v, g
211
 
212
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
  def _object_records(insts, count, u, v, g, floor_level):
214
  """Up to `count` instances, strongest-evidence first (most observed points = best-segmented,
215
  closest, most geometry). `count` (peak co-visibility) decides HOW MANY; total observed points
@@ -1114,8 +1141,7 @@ def build_spatial_code_raw(depth, intr, c2w, conf, ftimes, per):
1114
  up_vec
1115
  ) # shared gravity floor frame (bu,bv horizontal, bg up)
1116
  P = np.concatenate([i["pts"] for cl in inst.values() for i in cl], 0)
1117
- # floor = robust bottom of observed geometry along gravity (low percentile).
1118
- floor_level = float(np.percentile(P @ bg, 2))
1119
  fa = compute_floor_area(depth, intr, c2w, conf, None, up_vec=up_vec)
1120
  code = to_spatial_code(inst, stats, fa, up_ax, up_vec, floor_level)
1121
  cls = list(inst.keys())
@@ -1473,7 +1499,7 @@ def build_spatial_code(scene):
1473
  all_points = np.concatenate(
1474
  [i["pts"] for values in inst.values() for i in values], 0
1475
  )
1476
- floor_level = float(np.percentile(all_points @ g, 2))
1477
  objects = {}
1478
  for cls, items in inst.items():
1479
  requested_count = max(0, int(stats[cls].get("peak", len(items))))
 
179
 
180
 
181
  def pos3(rec):
182
+ """Read either legacy numeric or current unit-string position formatting."""
183
  p = rec.get("position") or {}
184
+
185
+ def meters(current, legacy):
186
+ value = p.get(current, p.get(legacy, 0.0))
187
+ if isinstance(value, str):
188
+ value = value.removesuffix(" meters").strip()
189
+ return float(value)
190
+
191
  return [
192
+ meters("x coordinate", "floor_x_meters"),
193
+ meters("y coordinate", "floor_y_meters"),
194
+ meters("height above floor", "height_above_floor_meters"),
195
  ]
196
 
197
 
 
217
  return u, v, g
218
 
219
 
220
+ def _floor_level(points, gravity, v2=None):
221
+ """Reference floor estimator shared by every model representation.
222
+
223
+ The supplied geometry uses the densest gravity-height slab for its reproducible v1
224
+ behavior and the robust second percentile for v2. Keep that switch here, after model
225
+ adapters have produced world points, so it cannot become model-specific.
226
+ """
227
+ heights = np.asarray(points, np.float64) @ np.asarray(gravity, np.float64)
228
+ heights = heights[np.isfinite(heights)]
229
+ if not len(heights):
230
+ return 0.0
231
+ if v2 is None:
232
+ v2 = os.environ.get("VSI_CODE_V2") == "1"
233
+ if v2:
234
+ return float(np.percentile(heights, 2))
235
+ counts, edges = np.histogram(heights, bins=80)
236
+ index = int(counts.argmax())
237
+ return float(0.5 * (edges[index] + edges[index + 1]))
238
+
239
+
240
  def _object_records(insts, count, u, v, g, floor_level):
241
  """Up to `count` instances, strongest-evidence first (most observed points = best-segmented,
242
  closest, most geometry). `count` (peak co-visibility) decides HOW MANY; total observed points
 
1141
  up_vec
1142
  ) # shared gravity floor frame (bu,bv horizontal, bg up)
1143
  P = np.concatenate([i["pts"] for cl in inst.values() for i in cl], 0)
1144
+ floor_level = _floor_level(P, bg)
 
1145
  fa = compute_floor_area(depth, intr, c2w, conf, None, up_vec=up_vec)
1146
  code = to_spatial_code(inst, stats, fa, up_ax, up_vec, floor_level)
1147
  cls = list(inst.keys())
 
1499
  all_points = np.concatenate(
1500
  [i["pts"] for values in inst.values() for i in values], 0
1501
  )
1502
+ floor_level = _floor_level(all_points, g)
1503
  objects = {}
1504
  for cls, items in inst.items():
1505
  requested_count = max(0, int(stats[cls].get("peak", len(items))))
encoder/launch.py CHANGED
@@ -8,10 +8,16 @@ import argparse
8
  import json
9
  import multiprocessing as mp
10
  import os
 
11
  import subprocess
 
12
  import traceback
13
 
14
- import config as C
 
 
 
 
15
 
16
 
17
  def _scenes():
@@ -39,7 +45,7 @@ def _visible_gpus():
39
  def _worker(task_queue, result_queue, model, rebuild, gpu):
40
  if gpu is not None:
41
  os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu)
42
- import render
43
 
44
  while True:
45
  scene = task_queue.get()
 
8
  import json
9
  import multiprocessing as mp
10
  import os
11
+ from pathlib import Path
12
  import subprocess
13
+ import sys
14
  import traceback
15
 
16
+ WORKSPACE_ROOT = Path(__file__).resolve().parent.parent
17
+ if str(WORKSPACE_ROOT) not in sys.path:
18
+ sys.path.insert(0, str(WORKSPACE_ROOT))
19
+
20
+ from encoder import config as C
21
 
22
 
23
  def _scenes():
 
45
  def _worker(task_queue, result_queue, model, rebuild, gpu):
46
  if gpu is not None:
47
  os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu)
48
+ from encoder import render
49
 
50
  while True:
51
  scene = task_queue.get()
encoder/render.py CHANGED
@@ -4,9 +4,9 @@ from __future__ import annotations
4
 
5
  import os
6
 
7
- import config as C
8
- import geometric as geometry_math
9
- import run as perceive
10
 
11
 
12
  def build_spatial_code_for(scene, model=None, rebuild=False):
 
4
 
5
  import os
6
 
7
+ from encoder import config as C
8
+ from encoder import geometric as geometry_math
9
+ from encoder import run as perceive
10
 
11
 
12
  def build_spatial_code_for(scene, model=None, rebuild=False):
encoder/run.py CHANGED
@@ -5,22 +5,16 @@ from __future__ import annotations
5
  import argparse
6
  import gzip
7
  import os
 
8
  import pickle
 
9
 
10
- import adapters
11
- import config as C
 
12
 
13
-
14
- def _adapter_kwargs(scene: str, model: str) -> dict:
15
- if model == "segvggt":
16
- return {"scene": scene, "path": C.segvggt_cache_file(scene, model)}
17
- if model == "da3_sam3":
18
- return {
19
- "scene": scene,
20
- "da3_path": C.da3_cache_file(scene, model),
21
- "sam3_path": C.sam3_cache_file(scene, model),
22
- }
23
- return {"scene": scene, "root": C.model_cache_dir(model)}
24
 
25
 
26
  def cache_or_load(scene: str, model: str | None = None, rebuild: bool = False):
@@ -31,12 +25,12 @@ def cache_or_load(scene: str, model: str | None = None, rebuild: bool = False):
31
  with gzip.open(path, "rb") as f:
32
  return adapters.validate(pickle.load(f)), "loaded"
33
 
34
- adapter_name = C.ADAPTERS.get(model)
35
- if adapter_name is None:
36
- raise KeyError(f"no adapter configured for {model!r}")
37
- kwargs = _adapter_kwargs(scene, model)
38
- kwargs["rebuild"] = rebuild
39
- geometry = adapters.validate(getattr(adapters, adapter_name)(**kwargs))
40
  os.makedirs(os.path.dirname(path), exist_ok=True)
41
  with gzip.open(path, "wb") as f:
42
  pickle.dump(geometry, f, protocol=pickle.HIGHEST_PROTOCOL)
@@ -54,7 +48,7 @@ def main() -> None:
54
  print(
55
  f"[{a.scene}] model={a.model} cache={how} classes={len(geometry['instances'])} instances={count}"
56
  )
57
- import render
58
 
59
  _, _, path = render.write_spatial_code_for(a.scene, a.model, False)
60
  print(f"[{a.scene}] spatial_code={path}")
 
5
  import argparse
6
  import gzip
7
  import os
8
+ from pathlib import Path
9
  import pickle
10
+ import sys
11
 
12
+ WORKSPACE_ROOT = Path(__file__).resolve().parent.parent
13
+ if str(WORKSPACE_ROOT) not in sys.path:
14
+ sys.path.insert(0, str(WORKSPACE_ROOT))
15
 
16
+ from encoder import adapters
17
+ from encoder import config as C
 
 
 
 
 
 
 
 
 
18
 
19
 
20
  def cache_or_load(scene: str, model: str | None = None, rebuild: bool = False):
 
25
  with gzip.open(path, "rb") as f:
26
  return adapters.validate(pickle.load(f)), "loaded"
27
 
28
+ geometry = adapters.adapt(
29
+ model,
30
+ scene=scene,
31
+ root=str(C.CACHE_ROOT),
32
+ rebuild=rebuild,
33
+ )
34
  os.makedirs(os.path.dirname(path), exist_ok=True)
35
  with gzip.open(path, "wb") as f:
36
  pickle.dump(geometry, f, protocol=pickle.HIGHEST_PROTOCOL)
 
48
  print(
49
  f"[{a.scene}] model={a.model} cache={how} classes={len(geometry['instances'])} instances={count}"
50
  )
51
+ from encoder import render
52
 
53
  _, _, path = render.write_spatial_code_for(a.scene, a.model, False)
54
  print(f"[{a.scene}] spatial_code={path}")
inference/__init__.py CHANGED
@@ -1 +1,40 @@
1
- """Model inference that produces raw geometry caches for the encoder."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Self-contained configuration and helpers for model inference."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from pathlib import Path
7
+
8
+ FRAMES_PER_VIDEO = int(os.environ.get("VSI_FRAMES_PER_VIDEO", "32"))
9
+ VSI_ROOT = Path(os.environ.get("VSI_ROOT", "/root/data/VSI-Bench"))
10
+ JSONL = Path(os.environ.get("VSI_JSONL", VSI_ROOT / "test.jsonl"))
11
+ CACHE_ROOT = Path(os.environ.get("VSI_CACHE_ROOT", "/root/data/caches"))
12
+ VIDEO_DATASETS = ("scannet", "scannetpp", "arkitscenes")
13
+
14
+
15
+ def video_path(scene: str, dataset: str | None = None) -> str:
16
+ """Return the unique VSI-Bench video for a scene."""
17
+ scene = str(scene)
18
+ datasets = (dataset,) if dataset else VIDEO_DATASETS
19
+ matches: list[Path] = []
20
+ for name in datasets:
21
+ if name not in VIDEO_DATASETS:
22
+ raise ValueError(
23
+ f"unknown VSI dataset {name!r}; expected one of {VIDEO_DATASETS}"
24
+ )
25
+ candidate = VSI_ROOT / name / f"{scene}.mp4"
26
+ if candidate.is_file():
27
+ matches.append(candidate)
28
+ if not matches:
29
+ searched = ", ".join(str(VSI_ROOT / name / f"{scene}.mp4") for name in datasets)
30
+ raise FileNotFoundError(
31
+ f"video for scene {scene!r} not found; searched: {searched}"
32
+ )
33
+ if len(matches) > 1:
34
+ raise RuntimeError(f"scene {scene!r} exists in multiple datasets: {matches}")
35
+ return str(matches[0])
36
+
37
+
38
+ def model_cache_dir(model: str) -> str:
39
+ """Return the inference cache directory for a model."""
40
+ return str(CACHE_ROOT / model)
inference/adapters.py CHANGED
@@ -1,10 +1,11 @@
1
- """Model-specific inference adapters that write encoder-compatible raw caches."""
2
 
3
  from __future__ import annotations
4
 
5
  from abc import ABC, abstractmethod
6
  import os
7
  from pathlib import Path
 
8
  import sys
9
 
10
  import numpy as np
@@ -13,7 +14,7 @@ import numpy as np
13
  class InferenceAdapter(ABC):
14
  """Common interface implemented by every inference backend."""
15
 
16
- output_suffix = ".npz"
17
 
18
  @abstractmethod
19
  def load_model(self, device: str) -> None:
@@ -21,11 +22,13 @@ class InferenceAdapter(ABC):
21
 
22
  @abstractmethod
23
  def run_scene(self, video_path: str, output_path: str, frame_count: int) -> None:
24
- """Run one video and atomically write a raw encoder cache."""
25
 
26
 
27
  class SegVGGTAdapter(InferenceAdapter):
28
- """SegVGGT inference producing the NPZ fields consumed by encoder/adapters.py."""
 
 
29
 
30
  classes = """wall|floor|chair|table|door|couch|cabinet|shelf|desk|office chair|bed|pillow|sink|picture|window|toilet|bookshelf|monitor|curtain|book|armchair|coffee table|box|refrigerator|lamp|kitchen cabinet|towel|clothes|tv|nightstand|counter|dresser|stool|cushion|plant|ceiling|bathtub|end table|dining table|keyboard|bag|backpack|toilet paper|printer|tv stand|whiteboard|blanket|shower curtain|trash can|closet|stairs|microwave|stove|shoe|computer tower|bottle|bin|ottoman|bench|board|washing machine|mirror|copier|basket|sofa chair|file cabinet|fan|laptop|shower|paper|person|paper towel dispenser|oven|blinds|rack|plate|blackboard|piano|suitcase|rail|radiator|recycling bin|container|wardrobe|soap dispenser|telephone""".split(
31
  "|"
@@ -52,15 +55,8 @@ class SegVGGTAdapter(InferenceAdapter):
52
  sys.path.insert(0, str(self.model_root))
53
  try:
54
  import torch
55
- import torch.nn.functional as functional
56
- from eval.instance_eval_common import predict_by_feat_instance
57
  from hydra import compose, initialize_config_dir
58
  from hydra.utils import instantiate
59
- from segvggt.utils.geometry import (
60
- closed_form_inverse_se3,
61
- unproject_depth_map_to_point_map,
62
- )
63
- from segvggt.utils.pose_enc import pose_encoding_to_extri_intri
64
  except ImportError as exc:
65
  raise RuntimeError(
66
  f"missing SegVGGT dependency ({exc}); install {self.model_root}/requirements.txt"
@@ -84,14 +80,7 @@ class SegVGGTAdapter(InferenceAdapter):
84
  state["model"] if "model" in state else state, strict=False
85
  )
86
  self.model = model.to(self.device).to(self.dtype).eval()
87
- self.runtime = (
88
- torch,
89
- functional,
90
- predict_by_feat_instance,
91
- unproject_depth_map_to_point_map,
92
- closed_form_inverse_se3,
93
- pose_encoding_to_extri_intri,
94
- )
95
 
96
  @staticmethod
97
  def _read_video(path, frame_count):
@@ -131,8 +120,8 @@ class SegVGGTAdapter(InferenceAdapter):
131
  def run_scene(self, video_path, output_path, frame_count):
132
  if self.model is None or self.runtime is None:
133
  raise RuntimeError("load_model() must be called before run_scene()")
134
- torch, functional, predict, unproject, inverse, decode_pose = self.runtime
135
- frames, times = self._read_video(video_path, frame_count)
136
  images = (
137
  torch.from_numpy(frames)
138
  .permute(0, 3, 1, 2)
@@ -146,58 +135,181 @@ class SegVGGTAdapter(InferenceAdapter):
146
  torch.autocast(device_type=self.device.type, dtype=self.dtype),
147
  ):
148
  prediction = self.model(images)
149
- logits = prediction["instance_maps"][0]
150
- query_count, frame_total, height, width = logits.shape
151
- masks, labels, _ = predict(
152
- prediction["instance_labels"][0],
153
- logits.reshape(query_count, -1),
154
- mask_thr=float(os.environ.get("VSI_MASK_THR", "0.4")),
155
- npoint_thr=1,
156
- )
157
- masks = masks.reshape(-1, frame_total, height, width).detach().cpu().numpy()
158
- labels = labels.detach().cpu().numpy()
159
- depth = prediction["depth"][0].float().cpu()
160
- extrinsics, intrinsics = decode_pose(
161
- prediction["pose_enc"].float(), depth.shape[1:3]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
162
  )
163
- extrinsics = extrinsics[0].detach().cpu().numpy()
164
- intrinsics = intrinsics[0].detach().cpu().numpy()
165
- world = unproject(depth.numpy(), extrinsics, intrinsics)
166
- world = (
167
- functional.interpolate(
168
- torch.from_numpy(world).permute(0, 3, 1, 2),
169
- (height, width),
170
- mode="nearest",
171
  )
172
- .permute(0, 2, 3, 1)
173
- .numpy()
174
  )
175
- cameras = inverse(extrinsics)[:, :3, 3]
176
- keep = [index for index, label in enumerate(labels) if int(label) >= 2]
177
- names = np.asarray(
178
- [
179
- self.classes[int(labels[index])]
180
- if int(labels[index]) < len(self.classes)
181
- else f"class {int(labels[index])}"
182
- for index in keep
183
- ],
184
- dtype=object,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
  )
186
  output = Path(output_path)
187
  output.parent.mkdir(parents=True, exist_ok=True)
188
- temporary = output.with_suffix(output.suffix + ".tmp.npz")
189
- np.savez_compressed(
190
- temporary,
191
- world_points=world.astype(np.float32),
192
- instance_masks=masks[keep].astype(bool),
193
- labels=names,
194
- frame_times=times,
195
- camera_positions=cameras.astype(np.float32),
 
 
 
 
 
 
196
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
  os.replace(temporary, output)
198
 
199
 
200
- _ADAPTERS = {"segvggt": SegVGGTAdapter}
 
 
 
 
201
 
202
 
203
  def available_models():
@@ -213,3 +325,13 @@ def get_adapter(model, **config):
213
  f"unknown inference model {model!r}; expected one of {available_models()}"
214
  )
215
  return adapter_type(**config)
 
 
 
 
 
 
 
 
 
 
 
1
+ """Model-specific inference adapters that preserve native outputs in model caches."""
2
 
3
  from __future__ import annotations
4
 
5
  from abc import ABC, abstractmethod
6
  import os
7
  from pathlib import Path
8
+ import pickle
9
  import sys
10
 
11
  import numpy as np
 
14
  class InferenceAdapter(ABC):
15
  """Common interface implemented by every inference backend."""
16
 
17
+ output_suffix: str
18
 
19
  @abstractmethod
20
  def load_model(self, device: str) -> None:
 
22
 
23
  @abstractmethod
24
  def run_scene(self, video_path: str, output_path: str, frame_count: int) -> None:
25
+ """Run one video and atomically preserve the model's native output."""
26
 
27
 
28
  class SegVGGTAdapter(InferenceAdapter):
29
+ """SegVGGT inference preserving native tensors plus derived encoder geometry."""
30
+
31
+ output_suffix = ".pt"
32
 
33
  classes = """wall|floor|chair|table|door|couch|cabinet|shelf|desk|office chair|bed|pillow|sink|picture|window|toilet|bookshelf|monitor|curtain|book|armchair|coffee table|box|refrigerator|lamp|kitchen cabinet|towel|clothes|tv|nightstand|counter|dresser|stool|cushion|plant|ceiling|bathtub|end table|dining table|keyboard|bag|backpack|toilet paper|printer|tv stand|whiteboard|blanket|shower curtain|trash can|closet|stairs|microwave|stove|shoe|computer tower|bottle|bin|ottoman|bench|board|washing machine|mirror|copier|basket|sofa chair|file cabinet|fan|laptop|shower|paper|person|paper towel dispenser|oven|blinds|rack|plate|blackboard|piano|suitcase|rail|radiator|recycling bin|container|wardrobe|soap dispenser|telephone""".split(
34
  "|"
 
55
  sys.path.insert(0, str(self.model_root))
56
  try:
57
  import torch
 
 
58
  from hydra import compose, initialize_config_dir
59
  from hydra.utils import instantiate
 
 
 
 
 
60
  except ImportError as exc:
61
  raise RuntimeError(
62
  f"missing SegVGGT dependency ({exc}); install {self.model_root}/requirements.txt"
 
80
  state["model"] if "model" in state else state, strict=False
81
  )
82
  self.model = model.to(self.device).to(self.dtype).eval()
83
+ self.runtime = torch
 
 
 
 
 
 
 
84
 
85
  @staticmethod
86
  def _read_video(path, frame_count):
 
120
  def run_scene(self, video_path, output_path, frame_count):
121
  if self.model is None or self.runtime is None:
122
  raise RuntimeError("load_model() must be called before run_scene()")
123
+ torch = self.runtime
124
+ frames, _ = self._read_video(video_path, frame_count)
125
  images = (
126
  torch.from_numpy(frames)
127
  .permute(0, 3, 1, 2)
 
135
  torch.autocast(device_type=self.device.type, dtype=self.dtype),
136
  ):
137
  prediction = self.model(images)
138
+ raw_prediction = _to_cpu(prediction)
139
+ output = Path(output_path)
140
+ output.parent.mkdir(parents=True, exist_ok=True)
141
+ temporary = output.with_suffix(output.suffix + ".tmp")
142
+ torch.save(raw_prediction, temporary)
143
+ os.replace(temporary, output)
144
+
145
+
146
+ def _to_cpu(value):
147
+ """Move tensors to CPU without changing dtype, shape, or nested structure."""
148
+ if hasattr(value, "detach") and hasattr(value, "cpu"):
149
+ return value.detach().cpu()
150
+ if isinstance(value, dict):
151
+ return {key: _to_cpu(item) for key, item in value.items()}
152
+ if isinstance(value, list):
153
+ return [_to_cpu(item) for item in value]
154
+ if isinstance(value, tuple):
155
+ return tuple(_to_cpu(item) for item in value)
156
+ return value
157
+
158
+
159
+ class DepthAnything3Adapter(InferenceAdapter):
160
+ """Run DA3's official API and preserve its native Prediction object."""
161
+
162
+ output_suffix = ".pkl"
163
+
164
+ def __init__(self, model_root=None, checkpoint=None):
165
+ self.model_root = Path(
166
+ model_root
167
+ or os.environ.get(
168
+ "VSI_DA3_ROOT", "/root/models/depth-anything-3"
169
+ )
170
  )
171
+ self.checkpoint = Path(
172
+ checkpoint
173
+ or os.environ.get(
174
+ "VSI_DA3_CHECKPOINT",
175
+ self.model_root / "checkpoints" / "DA3-LARGE-1.1",
 
 
 
176
  )
 
 
177
  )
178
+ self.model = self.device = None
179
+
180
+ def load_model(self, device: str) -> None:
181
+ source_root = self.model_root / "src"
182
+ if not source_root.is_dir():
183
+ raise FileNotFoundError(
184
+ f"Depth Anything 3 repository not found: {self.model_root}"
185
+ )
186
+ if not self.checkpoint.is_dir():
187
+ raise FileNotFoundError(
188
+ f"Depth Anything 3 checkpoint not found: {self.checkpoint}"
189
+ )
190
+ if str(source_root) not in sys.path:
191
+ sys.path.insert(0, str(source_root))
192
+ try:
193
+ from depth_anything_3.api import DepthAnything3
194
+ except ImportError as exc:
195
+ raise RuntimeError(
196
+ f"missing Depth Anything 3 dependency ({exc}); "
197
+ f"install {self.model_root}"
198
+ ) from exc
199
+ self.device = device
200
+ self.model = DepthAnything3.from_pretrained(
201
+ str(self.checkpoint), local_files_only=True
202
+ ).to(device)
203
+
204
+ @staticmethod
205
+ def _read_video(path, frame_count):
206
+ import cv2
207
+
208
+ capture = cv2.VideoCapture(path)
209
+ if not capture.isOpened():
210
+ raise RuntimeError(f"cannot open video: {path}")
211
+ try:
212
+ total = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
213
+ if total < frame_count:
214
+ raise ValueError(
215
+ f"{path} has {total} frames; {frame_count} are required"
216
+ )
217
+ frames = []
218
+ for index in np.linspace(0, total - 1, frame_count, dtype=int):
219
+ capture.set(cv2.CAP_PROP_POS_FRAMES, int(index))
220
+ ok, frame = capture.read()
221
+ if not ok:
222
+ raise RuntimeError(f"failed reading frame {index} from {path}")
223
+ frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
224
+ return frames
225
+ finally:
226
+ capture.release()
227
+
228
+ def run_scene(self, video_path, output_path, frame_count):
229
+ if self.model is None:
230
+ raise RuntimeError("load_model() must be called before run_scene()")
231
+ prediction = self.model.inference(
232
+ self._read_video(video_path, frame_count),
233
+ export_dir=None,
234
  )
235
  output = Path(output_path)
236
  output.parent.mkdir(parents=True, exist_ok=True)
237
+ temporary = output.with_suffix(output.suffix + ".tmp")
238
+ with open(temporary, "wb") as stream:
239
+ pickle.dump(prediction, stream, protocol=pickle.HIGHEST_PROTOCOL)
240
+ os.replace(temporary, output)
241
+
242
+
243
+ class SAM3Adapter(InferenceAdapter):
244
+ """Run SAM3 independently on sampled images, with no video tracking."""
245
+
246
+ output_suffix = ".pt"
247
+
248
+ def __init__(self, model_root=None, checkpoint=None, prompt=None):
249
+ self.model_root = Path(
250
+ model_root or os.environ.get("VSI_SAM3_ROOT", "/root/models/sam3")
251
  )
252
+ self.checkpoint = Path(
253
+ checkpoint
254
+ or os.environ.get(
255
+ "VSI_SAM3_CHECKPOINT",
256
+ self.model_root / "checkpoints" / "sam3.pt",
257
+ )
258
+ )
259
+ self.prompt = prompt or os.environ.get("VSI_SAM3_PROMPT", "object")
260
+ self.model = self.processor = self.runtime = None
261
+
262
+ def load_model(self, device: str) -> None:
263
+ if not self.model_root.is_dir():
264
+ raise FileNotFoundError(f"SAM3 repository not found: {self.model_root}")
265
+ if not self.checkpoint.is_file():
266
+ raise FileNotFoundError(f"SAM3 checkpoint not found: {self.checkpoint}")
267
+ if str(self.model_root) not in sys.path:
268
+ sys.path.insert(0, str(self.model_root))
269
+ try:
270
+ import torch
271
+ from sam3.model.sam3_image_processor import Sam3Processor
272
+ from sam3.model_builder import build_sam3_image_model
273
+ except ImportError as exc:
274
+ raise RuntimeError(
275
+ f"missing SAM3 dependency ({exc}); install {self.model_root}"
276
+ ) from exc
277
+ self.runtime = torch
278
+ self.model = build_sam3_image_model(
279
+ checkpoint_path=str(self.checkpoint),
280
+ load_from_HF=False,
281
+ device=device,
282
+ eval_mode=True,
283
+ enable_segmentation=True,
284
+ )
285
+ self.processor = Sam3Processor(self.model)
286
+
287
+ def run_scene(self, video_path, output_path, frame_count):
288
+ if self.model is None or self.processor is None or self.runtime is None:
289
+ raise RuntimeError("load_model() must be called before run_scene()")
290
+ from PIL import Image
291
+
292
+ frames = DepthAnything3Adapter._read_video(video_path, frame_count)
293
+ raw_outputs = []
294
+ with self.runtime.inference_mode():
295
+ for frame in frames:
296
+ state = self.processor.set_image(Image.fromarray(frame))
297
+ raw_outputs.append(
298
+ self.processor.set_text_prompt(state=state, prompt=self.prompt)
299
+ )
300
+ raw_outputs = _to_cpu(raw_outputs)
301
+ output = Path(output_path)
302
+ output.parent.mkdir(parents=True, exist_ok=True)
303
+ temporary = output.with_suffix(output.suffix + ".tmp")
304
+ self.runtime.save(raw_outputs, temporary)
305
  os.replace(temporary, output)
306
 
307
 
308
+ _ADAPTERS = {
309
+ "depth-anything-3": DepthAnything3Adapter,
310
+ "sam3": SAM3Adapter,
311
+ "segvggt": SegVGGTAdapter,
312
+ }
313
 
314
 
315
  def available_models():
 
325
  f"unknown inference model {model!r}; expected one of {available_models()}"
326
  )
327
  return adapter_type(**config)
328
+
329
+
330
+ def output_suffix(model):
331
+ """Return the native cache suffix owned by a registered model adapter."""
332
+ adapter_type = _ADAPTERS.get(model)
333
+ if adapter_type is None:
334
+ raise KeyError(
335
+ f"unknown inference model {model!r}; expected one of {available_models()}"
336
+ )
337
+ return adapter_type.output_suffix
inference/launch.py CHANGED
@@ -14,13 +14,11 @@ import traceback
14
 
15
  HERE = Path(__file__).resolve().parent
16
  WORKSPACE_ROOT = HERE.parent
17
- ENCODER_ROOT = WORKSPACE_ROOT / "encoder"
18
- for path in (WORKSPACE_ROOT, ENCODER_ROOT):
19
- if str(path) not in sys.path:
20
- sys.path.insert(0, str(path))
21
 
 
22
  from inference import adapters # noqa: E402
23
- import config as encoder_config # noqa: E402
24
 
25
 
26
  def _load_run_module():
@@ -33,7 +31,7 @@ def _load_run_module():
33
 
34
  def scenes():
35
  """Return unique manifest scenes in their original order."""
36
- with open(encoder_config.JSONL) as manifest:
37
  return list(
38
  dict.fromkeys(str(json.loads(line)["scene_name"]) for line in manifest)
39
  )
@@ -94,7 +92,7 @@ def main():
94
  parser.add_argument(
95
  "--model", default="segvggt", choices=adapters.available_models()
96
  )
97
- parser.add_argument("--frames", type=int, default=encoder_config.FRAMES_PER_VIDEO)
98
  parser.add_argument("--rebuild", action="store_true")
99
  args = parser.parse_args()
100
  selected = [args.scene] if args.scene else scenes()
 
14
 
15
  HERE = Path(__file__).resolve().parent
16
  WORKSPACE_ROOT = HERE.parent
17
+ if str(WORKSPACE_ROOT) not in sys.path:
18
+ sys.path.insert(0, str(WORKSPACE_ROOT))
 
 
19
 
20
+ import inference as inference_config # noqa: E402
21
  from inference import adapters # noqa: E402
 
22
 
23
 
24
  def _load_run_module():
 
31
 
32
  def scenes():
33
  """Return unique manifest scenes in their original order."""
34
+ with open(inference_config.JSONL) as manifest:
35
  return list(
36
  dict.fromkeys(str(json.loads(line)["scene_name"]) for line in manifest)
37
  )
 
92
  parser.add_argument(
93
  "--model", default="segvggt", choices=adapters.available_models()
94
  )
95
+ parser.add_argument("--frames", type=int, default=inference_config.FRAMES_PER_VIDEO)
96
  parser.add_argument("--rebuild", action="store_true")
97
  args = parser.parse_args()
98
  selected = [args.scene] if args.scene else scenes()
inference/run.py CHANGED
@@ -6,34 +6,34 @@ import argparse
6
  from pathlib import Path
7
  import sys
8
 
9
- HERE = Path(__file__).resolve().parent
10
- WORKSPACE_ROOT = HERE.parent
11
- ENCODER_ROOT = WORKSPACE_ROOT / "encoder"
12
- for path in (WORKSPACE_ROOT, ENCODER_ROOT):
13
- if str(path) not in sys.path:
14
- sys.path.insert(0, str(path))
15
 
 
16
  from inference import adapters # noqa: E402
17
- import config as encoder_config # noqa: E402
18
 
19
 
20
  def output_path(scene, model):
21
- """Return the flat raw-cache path for one scene and model."""
22
- return str(Path(encoder_config.model_cache_dir(model)) / f"{scene}.npz")
 
23
 
24
 
25
  def run_scene(
26
  scene, model="segvggt", frame_count=None, rebuild=False, adapter=None, device=None
27
  ):
28
  """Run one scene, optionally reusing an adapter already loaded by a batch worker."""
 
 
 
29
  destination = output_path(scene, model)
30
  if Path(destination).is_file() and not rebuild:
31
  return "skipped", destination
32
- frame_count = frame_count or encoder_config.FRAMES_PER_VIDEO
33
- if adapter is None:
34
- adapter = adapters.get_adapter(model)
35
  adapter.load_model(device or "cuda")
36
- adapter.run_scene(encoder_config.video_path(scene), destination, frame_count)
37
  return "built", destination
38
 
39
 
@@ -43,7 +43,7 @@ def main():
43
  parser.add_argument(
44
  "--model", default="segvggt", choices=adapters.available_models()
45
  )
46
- parser.add_argument("--frames", type=int, default=encoder_config.FRAMES_PER_VIDEO)
47
  parser.add_argument("--device", default="cuda")
48
  parser.add_argument("--rebuild", action="store_true")
49
  args = parser.parse_args()
 
6
  from pathlib import Path
7
  import sys
8
 
9
+ WORKSPACE_ROOT = Path(__file__).resolve().parent.parent
10
+ if str(WORKSPACE_ROOT) not in sys.path:
11
+ sys.path.insert(0, str(WORKSPACE_ROOT))
 
 
 
12
 
13
+ import inference as inference_config # noqa: E402
14
  from inference import adapters # noqa: E402
 
15
 
16
 
17
  def output_path(scene, model):
18
+ """Return the adapter-owned raw-cache path for one scene and model."""
19
+ suffix = adapters.output_suffix(model)
20
+ return str(Path(inference_config.model_cache_dir(model)) / f"{scene}{suffix}")
21
 
22
 
23
  def run_scene(
24
  scene, model="segvggt", frame_count=None, rebuild=False, adapter=None, device=None
25
  ):
26
  """Run one scene, optionally reusing an adapter already loaded by a batch worker."""
27
+ owns_adapter = adapter is None
28
+ if owns_adapter:
29
+ adapter = adapters.get_adapter(model)
30
  destination = output_path(scene, model)
31
  if Path(destination).is_file() and not rebuild:
32
  return "skipped", destination
33
+ frame_count = frame_count or inference_config.FRAMES_PER_VIDEO
34
+ if owns_adapter:
 
35
  adapter.load_model(device or "cuda")
36
+ adapter.run_scene(inference_config.video_path(scene), destination, frame_count)
37
  return "built", destination
38
 
39
 
 
43
  parser.add_argument(
44
  "--model", default="segvggt", choices=adapters.available_models()
45
  )
46
+ parser.add_argument("--frames", type=int, default=inference_config.FRAMES_PER_VIDEO)
47
  parser.add_argument("--device", default="cuda")
48
  parser.add_argument("--rebuild", action="store_true")
49
  args = parser.parse_args()