Repository navigation
Expand file tree
/
Copy pathrun_inference.py
More file actions
426 lines (368 loc) · 15 KB
/
Copy pathrun_inference.py
File metadata and controls
426 lines (368 loc) · 15 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
"""
SAM 3D Objects Inference Script
Supports both single-view and multi-view 3D reconstruction
Usage:
# Multi-view inference (mask_prompt=None, images and masks in same directory, use all images)
python run_inference.py --input_path ./data/images_and_masks
# Single-view inference (specify a single image name)
python run_inference.py --input_path ./data/images_and_masks --image_names image1
# Multi-view inference (mask_prompt!=None, images in images/, masks in specified folder)
python run_inference.py --input_path ./data --mask_prompt stuffed_toy
# Specify multiple image names (can be any filename without extension)
python run_inference.py --input_path ./data --mask_prompt stuffed_toy --image_names image1,view_a,2
"""
import sys
import argparse
from pathlib import Path
from typing import List, Optional
from loguru import logger
# 导入推理代码
sys.path.append("notebook")
from inference import Inference
from load_images_and_masks import load_images_and_masks_from_path
from sam3d_objects.utils.cross_attention_logger import CrossAttentionLogger
def parse_image_names(image_names_str: Optional[str]) -> Optional[List[str]]:
"""
Parse image names string
Args:
image_names_str: Image names string, e.g., "image1,view_a" or "1,2" or "image1"
Can be any filename (without extension) or numbers
Returns:
image_names: List of image names (without extension), None means use all available images
"""
if image_names_str is None or image_names_str == "":
return None
names = [x.strip() for x in image_names_str.split(",") if x.strip()]
return names if names else None
def parse_attention_layers(layers_str: Optional[str]) -> Optional[List[int]]:
"""
Parse attention layer indices from CLI string.
"""
if layers_str is None:
return None
tokens = [token.strip() for token in layers_str.split(",") if token.strip()]
if not tokens:
return None
indices: List[int] = []
for token in tokens:
try:
indices.append(int(token))
except ValueError as exc:
raise ValueError(f"Invalid attention layer index: {token}") from exc
return indices
def resolve_attention_stages(stage_str: Optional[str]) -> List[str]:
"""
Normalize stage selection argument.
"""
if stage_str is None or stage_str.lower() == "both":
return ["ss", "slat"]
stage_str = stage_str.lower()
if stage_str not in {"ss", "slat"}:
raise ValueError(f"Invalid attention_stage: {stage_str}")
return [stage_str]
def get_output_dir(
input_path: Path,
mask_prompt: Optional[str] = None,
image_names: Optional[List[str]] = None,
is_single_view: bool = False
) -> Path:
"""
Create output directory based on input path and parameters
Args:
input_path: Input path
mask_prompt: Mask folder name (if using separated directory structure)
image_names: List of image names
is_single_view: Whether it's single-view inference
Returns:
output_dir: Path to visualization/{mask_prompt_or_dirname}_{image_names}/ directory
"""
visualization_dir = Path("visualization")
visualization_dir.mkdir(exist_ok=True)
if mask_prompt:
dir_name = mask_prompt
else:
dir_name = input_path.name if input_path.is_dir() else input_path.parent.name
if is_single_view:
if image_names and len(image_names) == 1:
safe_name = image_names[0].replace("/", "_").replace("\\", "_")
dir_name = f"{dir_name}_{safe_name}"
else:
dir_name = f"{dir_name}_single"
elif image_names:
if len(image_names) == 1:
safe_name = image_names[0].replace("/", "_").replace("\\", "_")
dir_name = f"{dir_name}_{safe_name}"
else:
safe_names = [name.replace("/", "_").replace("\\", "_") for name in image_names]
dir_name = f"{dir_name}_{'_'.join(safe_names[:3])}"
if len(safe_names) > 3:
dir_name += f"_and_{len(safe_names)-3}_more"
else:
dir_name = f"{dir_name}_multiview"
output_dir = visualization_dir / dir_name
output_dir.mkdir(parents=True, exist_ok=True)
logger.info(f"Output directory: {output_dir}")
return output_dir
def run_inference(
input_path: Path,
mask_prompt: Optional[str] = None,
image_names: Optional[List[str]] = None,
seed: int = 42,
stage1_steps: int = 50,
stage2_steps: int = 25,
decode_formats: List[str] = None,
model_tag: str = "hf",
save_attention: bool = False,
attention_stage: Optional[str] = None,
attention_layers: Optional[List[int]] = None,
save_coords: bool = False,
):
"""
Run inference
Args:
input_path: Input path
mask_prompt: Mask folder name, if None then images and masks are in the same directory
image_names: List of image names (without extension), e.g., ["image1", "view_a"] or ["1", "2"],
None means use all available images
seed: Random seed
stage1_steps: Stage 1 inference steps
stage2_steps: Stage 2 inference steps
decode_formats: List of decode formats
model_tag: Model tag
save_attention: Whether to record cross-attention weights
attention_stage: Stage selector ('ss', 'slat', or 'both')
attention_layers: Layer indices to record (supports negative indices)
save_coords: Whether to save 3D spatial coordinates in SLAT attention files
"""
config_path = f"checkpoints/{model_tag}/pipeline.yaml"
if not Path(config_path).exists():
raise FileNotFoundError(f"Model config file not found: {config_path}")
logger.info(f"Loading model: {config_path}")
inference = Inference(config_path, compile=False)
if hasattr(inference._pipeline, 'rendering_engine'):
if inference._pipeline.rendering_engine != "pytorch3d":
logger.warning(f"Rendering engine is set to {inference._pipeline.rendering_engine}, changing to pytorch3d")
inference._pipeline.rendering_engine = "pytorch3d"
logger.info(f"Loading data: {input_path}")
if mask_prompt:
logger.info(f"Mask prompt: {mask_prompt} (images in images/, masks in {mask_prompt}/)")
else:
logger.info("Mask prompt: None (images and masks in same directory)")
view_images, view_masks, loaded_image_names = load_images_and_masks_from_path(
input_path=input_path,
mask_prompt=mask_prompt,
image_names=image_names,
)
num_views = len(view_images)
logger.info(f"Successfully loaded {num_views} views: {loaded_image_names}")
is_single_view = num_views == 1
output_dir = get_output_dir(input_path, mask_prompt, image_names, is_single_view)
# 将日志写入输出目录中的 inference.log,方便后续分析
log_file = output_dir / "inference.log"
logger.add(
log_file,
format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {name}:{function}:{line} - {message}",
level="INFO",
)
decode_formats = decode_formats or ["gaussian", "mesh"]
attention_logger: Optional[CrossAttentionLogger] = None
if save_attention:
stages = resolve_attention_stages(attention_stage)
attention_dir = output_dir / "attention"
attention_logger = CrossAttentionLogger(
attention_dir,
enabled_stages=stages,
layer_indices=attention_layers,
save_coords=save_coords,
)
attention_logger.attach_to_pipeline(inference._pipeline)
logger.info(
f"Cross-attention logging enabled → stages={stages}, layers={attention_layers or 'default (-1)'}, "
f"save_coords={save_coords}"
)
if is_single_view:
logger.info("Single-view inference mode")
image = view_images[0]
mask = view_masks[0] if view_masks else None
result = inference._pipeline.run(
image,
mask,
seed=seed,
stage1_only=False,
with_mesh_postprocess=False,
with_texture_baking=False,
use_vertex_color=True,
stage1_inference_steps=stage1_steps,
stage2_inference_steps=stage2_steps,
decode_formats=decode_formats,
attention_logger=attention_logger,
)
else:
logger.info("Multi-view inference mode")
result = inference._pipeline.run_multi_view(
view_images=view_images,
view_masks=view_masks,
seed=seed,
mode="multidiffusion",
stage1_inference_steps=stage1_steps,
stage2_inference_steps=stage2_steps,
decode_formats=decode_formats,
with_mesh_postprocess=False,
with_texture_baking=False,
use_vertex_color=True,
attention_logger=attention_logger,
)
saved_files = []
print(f"\n{'='*60}")
print(f"Inference completed!")
print(f"Generated coordinates: {result['coords'].shape[0] if 'coords' in result else 'N/A'}")
print(f"{'='*60}")
if 'glb' in result and result['glb'] is not None:
output_path = output_dir / "result.glb"
result['glb'].export(str(output_path))
saved_files.append("result.glb")
print(f"✓ GLB file saved to: {output_path}")
if 'gs' in result:
output_path = output_dir / "result.ply"
result['gs'].save_ply(str(output_path))
saved_files.append("result.ply")
print(f"✓ Gaussian Splatting (PLY) saved to: {output_path}")
elif 'gaussian' in result:
if isinstance(result['gaussian'], list) and len(result['gaussian']) > 0:
output_path = output_dir / "result.ply"
result['gaussian'][0].save_ply(str(output_path))
saved_files.append("result.ply")
print(f"✓ Gaussian Splatting (PLY) saved to: {output_path}")
if 'mesh' in result:
print(f"✓ Mesh information generated (included in GLB)")
print(f"\n{'='*60}")
print(f"All output files saved to: {output_dir}")
print(f"Saved files: {', '.join(saved_files)}")
print(f"{'='*60}")
if attention_logger is not None:
attention_logger.close()
print(f"\nFile descriptions:")
print(f"- PLY file: Gaussian Splatting format with position and color information")
print(f" * Recommended to use specialized Gaussian Splatting viewers")
print(f"- GLB file: Complete 3D mesh model, can be viewed in Blender, Three.js, etc.")
def main():
parser = argparse.ArgumentParser(
description="SAM 3D Objects Inference Script - Supports single-view and multi-view 3D reconstruction",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Multi-view inference (mask_prompt=None, images and masks in same directory, use all images)
python run_inference.py --input_path ./data/images_and_masks
# Single-view inference (specify a single image name)
python run_inference.py --input_path ./data/images_and_masks --image_names image1
# Multi-view inference (mask_prompt!=None, images in images/, masks in specified folder)
python run_inference.py --input_path ./data --mask_prompt stuffed_toy
# Specify multiple image names (can be any filename without extension)
python run_inference.py --input_path ./data --mask_prompt stuffed_toy --image_names image1,view_a,2
"""
)
parser.add_argument(
"--input_path",
type=str,
required=True,
help="Input path. If mask_prompt=None, images and masks are in this directory; "
"if mask_prompt!=None, images are in input_path/images/, masks in input_path/{mask_prompt}/"
)
parser.add_argument(
"--mask_prompt",
type=str,
default=None,
help="Mask folder name. If None, images and masks are in the same directory "
"(naming format: xxxx.png and xxxx_mask.png); "
"if not None, images are in input_path/images/, masks in input_path/{mask_prompt}/"
)
parser.add_argument(
"--image_names",
type=str,
default=None,
help="Image names (without extension), e.g., 'image1,view_a' or '1,2' or 'image1'. "
"Can specify multiple, comma-separated. If not specified, use all available images"
)
parser.add_argument(
"--seed",
type=int,
default=42,
help="Random seed (default: 42)"
)
parser.add_argument(
"--stage1_steps",
type=int,
default=50,
help="Stage 1 inference steps (default: 50)"
)
parser.add_argument(
"--stage2_steps",
type=int,
default=25,
help="Stage 2 inference steps (default: 25)"
)
parser.add_argument(
"--decode_formats",
type=str,
default="gaussian,mesh",
help="Decode formats, comma-separated, e.g., 'gaussian,mesh' or 'gaussian' (default: gaussian,mesh)"
)
parser.add_argument(
"--model_tag",
type=str,
default="hf",
help="Model tag (default: hf)"
)
parser.add_argument(
"--save_attention",
action="store_true",
help="Enable saving cross-attention weights for analysis",
)
parser.add_argument(
"--attention_stage",
type=str,
default="both",
choices=["ss", "slat", "both"],
help="Which stage(s) to record: ss, slat, or both (default)",
)
parser.add_argument(
"--attention_layers",
type=str,
default="-1",
help="Comma-separated layer indices to record (supports negative indices, default: -1)",
)
parser.add_argument(
"--save_coords",
action="store_true",
help="Save 3D spatial coordinates in SLAT attention files (default: False)",
)
args = parser.parse_args()
input_path = Path(args.input_path)
if not input_path.exists():
raise FileNotFoundError(f"Input path does not exist: {input_path}")
image_names = parse_image_names(args.image_names)
decode_formats = [fmt.strip() for fmt in args.decode_formats.split(",") if fmt.strip()]
if not decode_formats:
decode_formats = ["gaussian", "mesh"]
try:
run_inference(
input_path=input_path,
mask_prompt=args.mask_prompt,
image_names=image_names,
seed=args.seed,
stage1_steps=args.stage1_steps,
stage2_steps=args.stage2_steps,
decode_formats=decode_formats,
model_tag=args.model_tag,
save_attention=args.save_attention,
attention_stage=args.attention_stage,
attention_layers=parse_attention_layers(args.attention_layers),
save_coords=args.save_coords,
)
except Exception as e:
logger.error(f"Inference failed: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
if __name__ == "__main__":
main()