hyin-ustc commited on
Commit
c9bbed5
·
verified ·
1 Parent(s): 3870e03

Add files using upload-large-folder tool

Browse files
spatial-model/GeoThinker/assets/.DS_Store ADDED
Binary file (6.15 kB). View file
 
spatial-model/GeoThinker/scripts/evaluation/eval.sh ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ set -e
2
+ export LMMS_EVAL_LAUNCHER="accelerate"
3
+ export CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7
4
+ export NCCL_NVLS_ENABLE=0
5
+
6
+ output_path=logs/$(TZ="Asia/Shanghai" date "+%Y%m%d")
7
+ model_path=GeoThinker-8B
8
+
9
+ benchmark=vsibench
10
+
11
+ accelerate launch --num_processes=8 --main_process_port 29505 -m lmms_eval \
12
+ --model geothinker \
13
+ --model_args pretrained=$model_path,use_flash_attention_2=true,max_num_frames=32,max_length=12800,max_pixels=451584,min_pixels=12544 \
14
+ --tasks ${benchmark} \
15
+ --batch_size 1 \
16
+ --output_path $output_path
spatial-model/GeoThinker/scripts/train/train_sr_qwen25vl.sh ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Complete QwenVL Training Launch Script with Full Parameter Documentation
3
+
4
+ # Qwen2.5VL works on transformers=4.50.0, and may not work on transformers=4.57.0
5
+ pip install transformers==4.50.0
6
+
7
+ # ======================
8
+ # Distributed Configuration
9
+ # ======================
10
+ MASTER_ADDR="127.0.0.1" # [Required] Master node IP for multi-GPU training
11
+ MASTER_PORT=$(shuf -i 20000-29999 -n 1) # Random port to avoid conflicts
12
+ NPROC_PER_NODE=8 # Automatically detects available GPUs
13
+ export CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7
14
+
15
+ # ======================
16
+ # Path Configuration
17
+ # ======================
18
+ MODEL_PATH="Qwen/Qwen2.5-VL-7B-Instruct/" # [ModelArguments] Pretrained model path
19
+ GEOMETRY_ENCODER_TYPE="vggt"
20
+ GEOMETRY_ENCODER_PATH="facebook/VGGT-1B"
21
+ OUTPUT_DIR="PATH_TO_OUTPUT_DIR" # Directory for saving checkpoints
22
+ CACHE_DIR="./cache" # [TrainingArguments] Cache directory for models
23
+ mkdir -p $OUTPUT_DIR
24
+
25
+ # ======================
26
+ # Model Configuration
27
+ # ======================
28
+ DATASETS="llava_hound_64k_32frame,spar_234k,vsi_590k_32frame,vlm3r_vsi_205k_32frames,vlm3r_vst_132k_32frames,phygames_140k,mindcube_10k,cambrian_s_3m_subset_32frame"
29
+
30
+ # ======================
31
+ # Training Hyperparameters
32
+ # ======================
33
+ LR=1e-5
34
+ total_batch_size=64
35
+ GRADIENT_ACCUMULATION_STEPS=$(($total_batch_size / $NPROC_PER_NODE))
36
+
37
+ torchrun --nproc_per_node=$NPROC_PER_NODE \
38
+ --master_addr=$MASTER_ADDR \
39
+ --master_port=$MASTER_PORT \
40
+ src/qwen_vl/train/train_qwen.py \
41
+ --model_name_or_path $MODEL_PATH \
42
+ --tune_mm_llm True \
43
+ --tune_mm_vision False \
44
+ --tune_mm_mlp False \
45
+ --dataset_use $DATASETS \
46
+ --output_dir $OUTPUT_DIR \
47
+ --cache_dir $CACHE_DIR \
48
+ --bf16 \
49
+ --per_device_train_batch_size 1 \
50
+ --gradient_accumulation_steps $GRADIENT_ACCUMULATION_STEPS \
51
+ --learning_rate $LR \
52
+ --mm_projector_lr 1e-5 \
53
+ --vision_tower_lr 1e-6 \
54
+ --optim adamw_torch \
55
+ --model_max_length 12800 \
56
+ --data_flatten False \
57
+ --max_pixels $((576*28*28)) \
58
+ --min_pixels $((16*28*28)) \
59
+ --base_interval 2 \
60
+ --video_max_frames 8 \
61
+ --video_min_frames 4 \
62
+ --video_max_frame_pixels $((1664*28*28)) \
63
+ --video_min_frame_pixels $((256*28*28)) \
64
+ --num_train_epochs 1 \
65
+ --warmup_ratio 0.03 \
66
+ --lr_scheduler_type "cosine" \
67
+ --weight_decay 0.01 \
68
+ --logging_steps 50 \
69
+ --save_steps 1000 \
70
+ --save_total_limit 1 \
71
+ --deepspeed "scripts/zero2_opt.json" \
72
+ --gradient_checkpointing \
73
+ --dataloader_num_workers 4 \
74
+ --group_by_modality_length true \
75
+ --seed 0 \
76
+ --report_to "none" \
77
+ --use_geometry_encoder true \
78
+ --geometry_encoder_type $GEOMETRY_ENCODER_TYPE \
79
+ --geometry_encoder_path $GEOMETRY_ENCODER_PATH \
80
+ --feature_fusion_method "zero" \
81
+ --geo_cross_attn True \
82
+ --geo_importance_gate True \
83
+ --depart_smi_token True \
84
+ > ${OUTPUT_DIR}/train.log 2>&1
spatial-model/GeoThinker/scripts/train/train_sr_qwen3vl.sh ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Complete QwenVL Training Launch Script with Full Parameter Documentation
3
+
4
+ # Qwen3VL works on transformers=4.57.0
5
+ pip install transformers==4.57.0
6
+
7
+ # ======================
8
+ # Distributed Configuration
9
+ # ======================
10
+ MASTER_ADDR="127.0.0.1" # [Required] Master node IP for multi-GPU training
11
+ MASTER_PORT=$(shuf -i 20000-29999 -n 1) # Random port to avoid conflicts
12
+ NPROC_PER_NODE=8 # Automatically detects available GPUs
13
+ export CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7
14
+
15
+ # ======================
16
+ # Path Configuration
17
+ # ======================
18
+ MODEL_PATH="Qwen/Qwen3-VL-8B-Instruct/" # [ModelArguments] Pretrained model path
19
+ GEOMETRY_ENCODER_TYPE="vggt"
20
+ GEOMETRY_ENCODER_PATH="facebook/VGGT-1B"
21
+ OUTPUT_DIR="PATH_TO_OUTPUT_DIR" # Directory for saving checkpoints
22
+ CACHE_DIR="./cache" # [TrainingArguments] Cache directory for models
23
+ mkdir -p $OUTPUT_DIR
24
+
25
+ # ======================
26
+ # Model Configuration
27
+ # ======================
28
+ DATASETS="llava_hound_64k_32frame,spar_234k,vsi_590k_32frame,vlm3r_vsi_205k_32frames,vlm3r_vst_132k_32frames,phygames_140k,mindcube_10k,cambrian_s_3m_subset_32frame"
29
+
30
+ # ======================
31
+ # Training Hyperparameters
32
+ # ======================
33
+ LR=1e-5
34
+ total_batch_size=64
35
+ GRADIENT_ACCUMULATION_STEPS=$(($total_batch_size / $NPROC_PER_NODE))
36
+
37
+ torchrun --nproc_per_node=$NPROC_PER_NODE \
38
+ --master_addr=$MASTER_ADDR \
39
+ --master_port=$MASTER_PORT \
40
+ src/qwen_vl/train/train_qwen.py \
41
+ --model_name_or_path $MODEL_PATH \
42
+ --tune_mm_llm True \
43
+ --tune_mm_vision False \
44
+ --tune_mm_mlp False \
45
+ --dataset_use $DATASETS \
46
+ --output_dir $OUTPUT_DIR \
47
+ --cache_dir $CACHE_DIR \
48
+ --bf16 \
49
+ --per_device_train_batch_size 1 \
50
+ --gradient_accumulation_steps $GRADIENT_ACCUMULATION_STEPS \
51
+ --learning_rate $LR \
52
+ --mm_projector_lr 1e-5 \
53
+ --vision_tower_lr 1e-6 \
54
+ --optim adamw_torch \
55
+ --model_max_length 12800 \
56
+ --data_flatten False \
57
+ --max_pixels $((576*28*28)) \
58
+ --min_pixels $((16*28*28)) \
59
+ --base_interval 2 \
60
+ --video_max_frames 8 \
61
+ --video_min_frames 4 \
62
+ --video_max_frame_pixels $((1664*28*28)) \
63
+ --video_min_frame_pixels $((256*28*28)) \
64
+ --num_train_epochs 1 \
65
+ --warmup_ratio 0.03 \
66
+ --lr_scheduler_type "cosine" \
67
+ --weight_decay 0.01 \
68
+ --logging_steps 50 \
69
+ --save_steps 1000 \
70
+ --save_total_limit 1 \
71
+ --deepspeed "scripts/zero2_opt.json" \
72
+ --gradient_checkpointing \
73
+ --dataloader_num_workers 4 \
74
+ --group_by_modality_length true \
75
+ --seed 0 \
76
+ --report_to "none" \
77
+ --use_geometry_encoder true \
78
+ --geometry_encoder_type $GEOMETRY_ENCODER_TYPE \
79
+ --geometry_encoder_path $GEOMETRY_ENCODER_PATH \
80
+ --feature_fusion_method "zero" \
81
+ --geo_cross_attn True \
82
+ --geo_importance_gate True \
83
+ --depart_smi_token True \
84
+ > ${OUTPUT_DIR}/train.log 2>&1
spatial-model/GeoThinker/scripts/zero2.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "fp16": {
3
+ "enabled": "auto",
4
+ "loss_scale": 0,
5
+ "loss_scale_window": 1000,
6
+ "initial_scale_power": 16,
7
+ "hysteresis": 2,
8
+ "min_loss_scale": 1
9
+ },
10
+ "bf16": {
11
+ "enabled": "auto"
12
+ },
13
+ "train_micro_batch_size_per_gpu": "auto",
14
+ "train_batch_size": "auto",
15
+ "gradient_accumulation_steps": "auto",
16
+ "zero_optimization": {
17
+ "stage": 2,
18
+ "overlap_comm": true,
19
+ "contiguous_gradients": true,
20
+ "sub_group_size": 1e9,
21
+ "reduce_bucket_size": "auto"
22
+ }
23
+ }
spatial-model/GeoThinker/scripts/zero2_opt.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "fp16": {
3
+ "enabled": "auto",
4
+ "loss_scale": 0,
5
+ "loss_scale_window": 1000,
6
+ "initial_scale_power": 16,
7
+ "hysteresis": 2,
8
+ "min_loss_scale": 1
9
+ },
10
+ "bf16": {
11
+ "enabled": "auto"
12
+ },
13
+ "train_micro_batch_size_per_gpu": "auto",
14
+ "train_batch_size": "auto",
15
+ "gradient_accumulation_steps": "auto",
16
+ "zero_optimization": {
17
+ "stage": 2,
18
+ "overlap_comm": false,
19
+ "contiguous_gradients": true,
20
+ "sub_group_size": 1e9,
21
+ "reduce_bucket_size": 5e7,
22
+ "allgather_bucket_size": 5e7,
23
+ "round_robin_gradients": true
24
+ },
25
+ "activation_checkpointing": {
26
+ "partition_activations": true,
27
+ "cpu_checkpointing": true,
28
+ "contiguous_memory_optimization": true,
29
+ "number_checkpoints": null,
30
+ "synchronize_checkpoint_boundary": true,
31
+ "profile": false
32
+ }
33
+ }
spatial-model/VLM-3R/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA-CLIP-18B.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1536,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 48,
6
+ "width": 5120,
7
+ "head_width": 128,
8
+ "mlp_ratio": 5,
9
+ "patch_size": 14,
10
+ "eva_model_name": "eva-clip-18b-14-x",
11
+ "drop_path_rate": 0,
12
+ "qkv_bias": false,
13
+ "xattn": true,
14
+ "postnorm": true,
15
+ "fusedLN": false,
16
+ "use_rms_norm": true
17
+ },
18
+ "text_cfg": {
19
+ "context_length": 77,
20
+ "vocab_size": 49408,
21
+ "width": 1280,
22
+ "heads": 20,
23
+ "layers": 32,
24
+ "xattn": false,
25
+ "fusedLN": false
26
+ }
27
+ }
spatial-model/VLM-3R/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA-CLIP-8B-plus.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1280,
3
+ "vision_cfg": {
4
+ "image_size": 448,
5
+ "layers": 32,
6
+ "width": 4096,
7
+ "head_width": 128,
8
+ "mlp_ratio": 5,
9
+ "patch_size": 14,
10
+ "eva_model_name": "eva-clip-8b-14-plus-x",
11
+ "drop_path_rate": 0,
12
+ "qkv_bias": false,
13
+ "xattn": true,
14
+ "postnorm": false,
15
+ "fusedLN": false,
16
+ "use_rms_norm": true
17
+ },
18
+ "text_cfg": {
19
+ "context_length": 77,
20
+ "vocab_size": 49408,
21
+ "width": 1280,
22
+ "heads": 20,
23
+ "layers": 32,
24
+ "xattn": false,
25
+ "fusedLN": false
26
+ }
27
+ }
spatial-model/VLM-3R/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA-CLIP-8B.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1280,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 32,
6
+ "width": 4096,
7
+ "head_width": 128,
8
+ "mlp_ratio": 5,
9
+ "patch_size": 14,
10
+ "eva_model_name": "eva-clip-8b-14-x",
11
+ "drop_path_rate": 0,
12
+ "qkv_bias": false,
13
+ "xattn": true,
14
+ "postnorm": false,
15
+ "fusedLN": false,
16
+ "use_rms_norm": true
17
+ },
18
+ "text_cfg": {
19
+ "context_length": 77,
20
+ "vocab_size": 49408,
21
+ "width": 1280,
22
+ "heads": 20,
23
+ "layers": 32,
24
+ "xattn": false,
25
+ "fusedLN": false
26
+ }
27
+ }
spatial-model/VLM-3R/scripts/extract_spatial_features.py ADDED
@@ -0,0 +1,593 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import sys # Added for path manipulation
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.multiprocessing as mp # Added for multiprocessing
7
+ from tqdm import tqdm
8
+ import json
9
+ import re
10
+ import math
11
+ import random
12
+ import yaml
13
+ from PIL import Image, ImageFile
14
+ import numpy as np
15
+ import copy
16
+ from transformers import AutoProcessor # Added import
17
+ from glob import glob # For finding video files
18
+ from pathlib import Path # For path manipulation
19
+ import traceback # For error reporting in subprocesses
20
+ import h5py # Added for potential HDF5 saving (though not used currently for point clouds)
21
+
22
+ # Assume necessary imports from llava are available in the PYTHONPATH
23
+ # You might need to adjust imports based on your project structure
24
+ from llava.utils import process_video_with_decord # Or other video processing functions used
25
+ from llava.utils import rank0_print # Use rank0_print for controlled output
26
+ from llava.train.train import DataArguments # Re-use DataArguments for consistency
27
+ from llava.constants import DEFAULT_IMAGE_TOKEN
28
+ from llava.model.multimodal_encoder.siglip_encoder import SigLipImageProcessor # Added direct import
29
+
30
+ # Add imports for direct spatial tower loading
31
+ from llava.model.multimodal_spatial_encoder.cut3r_spatial_encoder import Cut3rSpatialConfig, Cut3rEncoder
32
+ from src.dust3r.model import ARCroco3DStereo # Import CUT3R model class
33
+
34
+ ImageFile.LOAD_TRUNCATED_IMAGES = True
35
+
36
+ # --- Constants ---
37
+ VIDEO_EXTENSIONS = ['.mp4', '.avi', '.mov', '.mkv'] # Add more if needed
38
+
39
+ # --- Image/Video Loading and Preprocessing ---
40
+ # (Adapted from LazySupervisedDataset and encode_spatial_features)
41
+
42
+ def load_image(image_path):
43
+ try:
44
+ image = Image.open(image_path).convert("RGB")
45
+ return image
46
+ except Exception as e:
47
+ rank0_print(f"Error loading image {image_path}: {e}") # Use rank0_print
48
+ return None
49
+
50
+ def preprocess_image_for_spatial(image, processor, target_size=(432, 432)):
51
+ """Preprocesses a single PIL image for spatial feature extraction using the provided processor."""
52
+ # Process using the vision model's processor
53
+ try:
54
+ processed_output = processor(images=image, return_tensors='pt')
55
+ image_tensor = processed_output['pixel_values'].squeeze(0) # Shape (C, H_proc, W_proc)
56
+ except Exception as e:
57
+ rank0_print(f"Error processing image with processor: {e}") # Use rank0_print
58
+ return None
59
+
60
+ # Resize to the target size expected by the spatial tower (if different)
61
+ c, h_proc, w_proc = image_tensor.shape
62
+ if h_proc != target_size[0] or w_proc != target_size[1]:
63
+ image_scaled = nn.functional.interpolate(
64
+ image_tensor.unsqueeze(0), # Add batch dim for interpolate
65
+ size=target_size,
66
+ mode='bilinear',
67
+ align_corners=False
68
+ ).squeeze(0) # Remove batch dim
69
+ else:
70
+ image_scaled = image_tensor
71
+
72
+ # Return shape (1, C, H_target, W_target) - batch dim added later before spatial tower
73
+ return image_scaled.unsqueeze(0)
74
+
75
+ # Old manual preprocessing:
76
+ # image_tensor = torch.from_numpy(np.array(image)).permute(2, 0, 1).float() / 255.0
77
+ # image_scaled = nn.functional.interpolate(image_tensor.unsqueeze(0), size=target_size, mode='bilinear', align_corners=False)
78
+ # return image_scaled # Output shape (1, C, H, W)
79
+
80
+ def load_and_preprocess_video_frames(video_path, data_args, processor, target_size=(432, 432), rank=0):
81
+ """
82
+ Loads video, samples frames, preprocesses them using the processor,
83
+ and returns a tensor of shape (F, C, H_target, W_target).
84
+ Includes rank for logging.
85
+ """
86
+ try:
87
+ # Use the same video processing function as in training
88
+ video_frames, video_time, frame_time, num_frames_to_sample = process_video_with_decord(video_path, data_args)
89
+
90
+ # Preprocess all frames together using the processor
91
+ try:
92
+ # Ensure video_frames is a list of PIL Images or compatible format
93
+ processed_output = processor.preprocess(images=video_frames, return_tensors="pt")
94
+ frames_tensor = processed_output['pixel_values'] # Shape (F, C, H_proc, W_proc)
95
+ except Exception as e:
96
+ rank0_print(f"[GPU {rank}] Error processing video frames with processor for {video_path}: {e}")
97
+ return None
98
+
99
+ # Resize frames to the target size if necessary
100
+ f, c, h_proc, w_proc = frames_tensor.shape
101
+ if h_proc != target_size[0] or w_proc != target_size[1]:
102
+ # Interpolate expects (B, C, H, W) or (C, H, W)
103
+ # Process frame by frame or reshape if possible, let's do frame by frame for simplicity
104
+ frames_scaled_list = []
105
+ for i in range(f):
106
+ frame_scaled = nn.functional.interpolate(
107
+ frames_tensor[i].unsqueeze(0), # Add batch dim
108
+ size=target_size,
109
+ mode='bilinear',
110
+ align_corners=False
111
+ ).squeeze(0) # Remove batch dim
112
+ frames_scaled_list.append(frame_scaled)
113
+ frames_scaled = torch.stack(frames_scaled_list) # Shape (F, C, H_target, W_target)
114
+ else:
115
+ frames_scaled = frames_tensor
116
+
117
+ # Return shape (F, C, H_target, W_target) - Batch dim added later during batching
118
+ return frames_scaled
119
+
120
+ except Exception as e:
121
+ rank0_print(f"[GPU {rank}] Error processing video {video_path}: {e}")
122
+ return None
123
+
124
+ # --- Main Extraction Logic ---
125
+
126
+ def find_video_files(input_dir):
127
+ """Recursively finds all video files in the input directory."""
128
+ video_files = []
129
+ rank0_print(f"Scanning for video files in {input_dir}...")
130
+ for ext in VIDEO_EXTENSIONS:
131
+ # Using Path for easier relative path calculation
132
+ input_path = Path(input_dir)
133
+ # **/*{ext} finds files in input_dir and subdirectories
134
+ video_files.extend(input_path.rglob(f"*{ext}"))
135
+ # Case-insensitive search for extensions
136
+ video_files.extend(input_path.rglob(f"*{ext.upper()}"))
137
+
138
+ # Remove duplicates if extensions overlap (e.g., .MP4 and .mp4)
139
+ unique_video_files = sorted(list(set(video_files)))
140
+ rank0_print(f"Found {len(unique_video_files)} potential video files.")
141
+ return [str(f) for f in unique_video_files] # Return as strings
142
+
143
+ def get_output_path(input_file_path: Path, input_base_dir: Path, output_base_dir: Path) -> Path:
144
+ """Calculates the output path for a given input file."""
145
+ try:
146
+ relative_path = input_file_path.relative_to(input_base_dir)
147
+ except ValueError:
148
+ rank0_print(f"Warning: Input file {input_file_path} is not within the specified base input directory {input_base_dir}. Outputting directly to {output_base_dir}.")
149
+ relative_path = input_file_path.name # Use only the filename
150
+
151
+ # Change extension to .pt
152
+ output_filename_path = output_base_dir / relative_path.with_suffix('.pt')
153
+ return output_filename_path
154
+
155
+ def get_point_cloud_output_path(input_file_path: Path, input_base_dir: Path, point_cloud_output_base_dir: Path) -> Path:
156
+ """Calculates the output path for the point cloud corresponding to an input file."""
157
+ try:
158
+ relative_path = input_file_path.relative_to(input_base_dir)
159
+ except ValueError:
160
+ rank0_print(f"Warning: Input file {input_file_path} is not within the specified base input directory {input_base_dir}. Outputting point cloud directly to {point_cloud_output_base_dir}.")
161
+ relative_path = input_file_path.name # Use only the filename
162
+
163
+ # Change extension to .ply
164
+ output_filename_path = point_cloud_output_base_dir / relative_path.with_suffix('.ply')
165
+ return output_filename_path
166
+
167
+ def get_preprocessed_frames_output_dir(input_file_path: Path, input_base_dir: Path, frames_output_base_dir: Path) -> Path:
168
+ """Calculates the output directory for the preprocessed frames corresponding to an input file."""
169
+ try:
170
+ relative_path = input_file_path.relative_to(input_base_dir)
171
+ except ValueError:
172
+ rank0_print(f"Warning: Input file {input_file_path} is not within the specified base input directory {input_base_dir}. Outputting frames directly under {frames_output_base_dir}.")
173
+ relative_path = input_file_path.stem # Use only the filename stem (no extension)
174
+
175
+ # Create a directory based on the relative path (without extension)
176
+ output_dir_path = frames_output_base_dir / relative_path.parent / relative_path.stem
177
+ return output_dir_path
178
+
179
+ # --- Worker Process Function ---
180
+ def process_videos_on_gpu(rank, gpu_id, args, video_files_chunk, input_base_dir, output_dir):
181
+ """
182
+ Worker function executed by each process to handle a chunk of videos on a specific GPU.
183
+ """
184
+ device = torch.device(f"cuda:{gpu_id}")
185
+ torch.cuda.set_device(device) # Ensure this process uses the assigned GPU
186
+
187
+ processed_count = 0
188
+ skipped_count = 0
189
+ total_files_in_chunk = len(video_files_chunk)
190
+ batch_size = args.batch_size
191
+
192
+ rank0_print(f"[GPU {gpu_id}] Worker started, assigned {total_files_in_chunk} files.")
193
+
194
+ # -- Load Model Components (within each worker process) --
195
+ try:
196
+ rank0_print(f"[GPU {gpu_id}] Loading CUT3R Spatial Tower...")
197
+ if not os.path.exists(args.cut3r_weights_path):
198
+ rank0_print(f"[GPU {gpu_id}] ERROR: CUT3R weights file not found at: {args.cut3r_weights_path}")
199
+ return 0, total_files_in_chunk # Return counts
200
+
201
+ # Pass point cloud config from args
202
+ cut3r_config = Cut3rSpatialConfig(
203
+ weights_path=args.cut3r_weights_path,
204
+ export_point_cloud=args.export_point_cloud,
205
+ point_cloud_output_dir=args.point_cloud_output_dir, # Pass base dir, specific file handled later
206
+ point_cloud_voxel_size=args.point_cloud_voxel_size
207
+ )
208
+ spatial_tower = Cut3rEncoder(config=cut3r_config)
209
+
210
+ model_dtype = torch.bfloat16 if args.precision == 'bf16' else torch.float16 if args.precision == 'fp16' else torch.float32
211
+ spatial_tower.to(device=device, dtype=model_dtype).eval()
212
+ rank0_print(f"[GPU {gpu_id}] CUT3R Spatial Tower loaded on {device}.")
213
+
214
+ # -- Load Image Processor Config and Initialize Processor --
215
+ rank0_print(f"[GPU {gpu_id}] Loading Processor config from {args.processor_config_path}...")
216
+ with open(args.processor_config_path, 'r') as f:
217
+ processor_config = json.load(f)
218
+
219
+ image_mean_list = processor_config.get("image_mean", (0.5, 0.5, 0.5))
220
+ image_std_list = processor_config.get("image_std", (0.5, 0.5, 0.5))
221
+ size_config = processor_config.get("size", {"height": 384, "width": 384})
222
+ size_tuple = (size_config["height"], size_config["width"])
223
+ resample_val = processor_config.get("resample", 3)
224
+ rescale_factor_val = processor_config.get("rescale_factor", 1/255.0)
225
+
226
+ image_processor = SigLipImageProcessor(
227
+ image_mean=image_mean_list,
228
+ image_std=image_std_list,
229
+ size=size_tuple,
230
+ resample=resample_val,
231
+ rescale_factor=rescale_factor_val
232
+ )
233
+ rank0_print(f"[GPU {gpu_id}] SigLipImageProcessor initialized.")
234
+
235
+ # Convert mean/std to tensors for de-normalization if saving frames
236
+ if args.save_preprocessed_frames:
237
+ mean_tensor = torch.tensor(image_mean_list, device=device).view(3, 1, 1)
238
+ std_tensor = torch.tensor(image_std_list, device=device).view(3, 1, 1)
239
+ else:
240
+ mean_tensor, std_tensor = None, None # Avoid unused variables
241
+
242
+ except Exception as e:
243
+ rank0_print(f"[GPU {gpu_id}] Error during initialization: {e}\n{traceback.format_exc()}")
244
+ return 0, total_files_in_chunk # Indicate all files skipped due to init error
245
+
246
+ # --- Load Dummy DataArguments ---
247
+ data_args = DataArguments(
248
+ video_fps=args.video_fps,
249
+ frames_upbound=args.frames_upbound,
250
+ force_sample=True
251
+ )
252
+
253
+ # --- Feature Extraction Loop for the Chunk (Batched Processing) ---
254
+ # Use tqdm only on rank 0 or manage it externally if needed
255
+ # Simple loop without per-process tqdm for now
256
+ for i in range(0, total_files_in_chunk, batch_size):
257
+ batch_paths_str = video_files_chunk[i:min(i + batch_size, total_files_in_chunk)]
258
+ batch_paths = [Path(p) for p in batch_paths_str]
259
+
260
+ # --- Batch Preprocessing ---
261
+ batch_data_to_process = [] # Stores (preprocessed_input, feature_output_filename, point_cloud_output_filename, video_full_path)
262
+ files_in_batch = 0
263
+ skipped_in_batch = 0
264
+ max_frames_in_batch = 0
265
+ point_cloud_base_dir = Path(args.point_cloud_output_dir) if args.export_point_cloud else None
266
+ frames_base_dir = Path(args.save_preprocessed_frames_dir) if args.save_preprocessed_frames else None
267
+
268
+ for video_full_path in batch_paths:
269
+ files_in_batch += 1
270
+ feature_output_filename_path = get_output_path(video_full_path, input_base_dir, output_dir)
271
+ feature_output_filename = str(feature_output_filename_path)
272
+
273
+ point_cloud_output_filename = None
274
+ if args.export_point_cloud and point_cloud_base_dir:
275
+ point_cloud_output_filename_path = get_point_cloud_output_path(video_full_path, input_base_dir, point_cloud_base_dir)
276
+ point_cloud_output_filename = str(point_cloud_output_filename_path)
277
+ # Ensure parent dir for point cloud exists
278
+ point_cloud_output_filename_path.parent.mkdir(parents=True, exist_ok=True)
279
+
280
+
281
+ # Check feature file existence
282
+ feature_output_filename_path.parent.mkdir(parents=True, exist_ok=True)
283
+ feature_exists = os.path.exists(feature_output_filename)
284
+
285
+ # Check point cloud existence (if exporting)
286
+ point_cloud_exists = False
287
+ if args.export_point_cloud and point_cloud_output_filename:
288
+ point_cloud_exists = os.path.exists(point_cloud_output_filename)
289
+
290
+ # Determine if skipping is needed
291
+ # Skip if NOT overwriting AND (feature exists AND (point cloud exists OR not exporting point cloud))
292
+ should_skip = not args.overwrite and (feature_exists and (point_cloud_exists or not args.export_point_cloud))
293
+
294
+ if should_skip:
295
+ skipped_in_batch += 1
296
+ continue
297
+
298
+
299
+ preprocessed_input = load_and_preprocess_video_frames(
300
+ str(video_full_path), data_args, image_processor, rank=gpu_id # Pass rank for logging
301
+ )
302
+
303
+ if preprocessed_input is not None and preprocessed_input.nelement() > 0:
304
+ # Store point cloud path only if exporting
305
+ pc_path_to_store = point_cloud_output_filename if args.export_point_cloud else None
306
+
307
+ # --- Save Preprocessed Frames (if enabled) ---
308
+ if args.save_preprocessed_frames and frames_base_dir is not None and mean_tensor is not None and std_tensor is not None:
309
+ try:
310
+ frames_output_dir_path = get_preprocessed_frames_output_dir(video_full_path, input_base_dir, frames_base_dir)
311
+ frames_output_dir_path.mkdir(parents=True, exist_ok=True)
312
+
313
+ # De-normalize and save each frame
314
+ # Move tensor to CPU for processing/saving if it isn't already
315
+ # Note: preprocessed_input is on CPU from load_and_preprocess...
316
+ preprocessed_input_float = preprocessed_input.float() # Ensure float32 for calculation
317
+ for frame_idx in range(preprocessed_input_float.shape[0]):
318
+ frame_tensor = preprocessed_input_float[frame_idx] # Shape (C, H, W)
319
+
320
+ # De-normalize: (tensor * std + mean) / rescale_factor
321
+ # Assuming rescale_factor = 1/255.0
322
+ # (tensor * std + mean) * 255.0
323
+ # Move mean/std to the frame's device (likely CPU here)
324
+ denormalized_frame = (frame_tensor * std_tensor.to(frame_tensor.device) + mean_tensor.to(frame_tensor.device)) / rescale_factor_val
325
+
326
+ # Clamp and convert to uint8
327
+ denormalized_frame = torch.clamp(denormalized_frame, 0, 255).to(torch.uint8)
328
+
329
+ # Convert to PIL Image (C, H, W) -> (H, W, C)
330
+ pil_image = Image.fromarray(denormalized_frame.permute(1, 2, 0).cpu().numpy())
331
+
332
+ # Construct filename
333
+ frame_filename = frames_output_dir_path / f"frame_{frame_idx:04d}.png"
334
+
335
+ # Save the image
336
+ pil_image.save(frame_filename)
337
+
338
+ except Exception as e_save_frame:
339
+ rank0_print(f"[GPU {gpu_id}] Error saving preprocessed frame for {video_full_path}, frame {frame_idx}: {e_save_frame}")
340
+ # Continue processing other frames/videos
341
+
342
+ # Append data for batch inference
343
+ batch_data_to_process.append((preprocessed_input, feature_output_filename, pc_path_to_store, video_full_path))
344
+ max_frames_in_batch = max(max_frames_in_batch, preprocessed_input.shape[0])
345
+ else:
346
+ rank0_print(f"[GPU {gpu_id}] Failed to load/preprocess {video_full_path}. Skipping.")
347
+ skipped_in_batch += 1
348
+
349
+ # --- Batch Inference (True Batching) ---
350
+ processed_in_batch = 0
351
+ if batch_data_to_process:
352
+ padded_tensors = []
353
+ output_info = [] # Stores (feature_output_filename, point_cloud_output_filename, video_full_path)
354
+
355
+ for preprocessed_input, feature_output_filename, point_cloud_output_filename, video_full_path in batch_data_to_process:
356
+ num_frames = preprocessed_input.shape[0]
357
+ padding_needed = max_frames_in_batch - num_frames
358
+ padded_tensor = torch.nn.functional.pad(
359
+ preprocessed_input,
360
+ (0, 0, 0, 0, 0, 0, 0, padding_needed),
361
+ mode='constant',
362
+ value=0
363
+ )
364
+ padded_tensors.append(padded_tensor)
365
+ output_info.append((feature_output_filename, point_cloud_output_filename, video_full_path))
366
+
367
+ # Stack padded tensors into a single batch
368
+ # Note: Cut3rEncoder expects input shape (B, F, C, H, W) or (F, C, H, W)
369
+ # Our load function returns (F, C, H, W), stack adds batch: (B, F, C, H, W) ? Check stack dim.
370
+ # torch.stack(tensors, dim=0) makes (B, F, C, H, W)
371
+ # Let's adjust the input format if needed, assuming Cut3rEncoder handles (B, F, C, H, W) or (F, C, H, W)
372
+ # If it expects (F, B, C, H, W), need permute. Sticking with (B, F, C, H, W) for now.
373
+ batch_tensor = torch.stack(padded_tensors, dim=1).to(device=device, dtype=model_dtype) # Shape (F_max, B, C, H, W)
374
+ point_cloud_paths_for_batch = [info[1] for info in output_info] if args.export_point_cloud else None
375
+
376
+ try:
377
+ with torch.no_grad():
378
+ # Pass batch_tensor directly. Cut3rEncoder handles iterating through frames internally.
379
+ # Expected input is (B, F, C, H, W) or (F, C, H, W)
380
+ # Expected output is (B * F, token_num, token_dim)
381
+ # Pass point cloud paths if exporting
382
+ camera_tokens_batch, patch_tokens_batch = spatial_tower(
383
+ batch_tensor,
384
+ point_cloud_output_paths=point_cloud_paths_for_batch # Pass the paths here
385
+ )
386
+
387
+
388
+ # Reshape the outputs to separate Batch and Frame dimensions
389
+ B = batch_tensor.shape[0] # Actual batch size processed
390
+ F_max = max_frames_in_batch
391
+ # Note: The Cut3rEncoder might flatten B*F in the output. Confirm expected output shape.
392
+ # Assuming output is (B * F_max, token_num, token_dim)
393
+ expected_output_len = B * F_max
394
+ if camera_tokens_batch.shape[0] != expected_output_len:
395
+ rank0_print(f"[GPU {gpu_id}] Warning: Output dimension mismatch. Expected {expected_output_len} but got {camera_tokens_batch.shape[0]}. Skipping save for this batch.")
396
+ skipped_in_batch += B # Mark all items in batch as skipped
397
+ else:
398
+ _, token_num_cam, token_dim_cam = camera_tokens_batch.shape
399
+ _, token_num_patch, token_dim_patch = patch_tokens_batch.shape
400
+
401
+ # View as (B, F_max, token_num, token_dim)
402
+ camera_tokens_reshaped = camera_tokens_batch.view(B, F_max, token_num_cam, token_dim_cam)
403
+ patch_tokens_reshaped = patch_tokens_batch.view(B, F_max, token_num_patch, token_dim_patch)
404
+
405
+ for idx, (feature_output_filename, point_cloud_output_filename, video_full_path) in enumerate(output_info):
406
+ try:
407
+ # Save features regardless
408
+ features_to_save = {
409
+ "camera_tokens": camera_tokens_reshaped[idx].cpu(),
410
+ "patch_tokens": patch_tokens_reshaped[idx].cpu()
411
+ }
412
+ torch.save(features_to_save, feature_output_filename)
413
+
414
+ # Point cloud saving is handled inside spatial_tower if enabled
415
+
416
+ processed_in_batch += 1
417
+ except Exception as e_save:
418
+ rank0_print(f"[GPU {gpu_id}] Error saving features for {video_full_path} (point cloud saving handled separately): {e_save}")
419
+ skipped_in_batch += 1
420
+ # Attempt to remove potentially corrupted feature file
421
+ if os.path.exists(feature_output_filename):
422
+ try: os.remove(feature_output_filename)
423
+ except OSError: rank0_print(f"Warning: Could not remove potentially corrupted file {feature_output_filename}")
424
+ # Note: Point cloud file removal isn't handled here as saving happens in the model
425
+
426
+ except Exception as e_batch:
427
+ rank0_print(f"[GPU {gpu_id}] Error during batch inference (features or point clouds): {e_batch}\n{traceback.format_exc()}")
428
+ skipped_in_batch += len(batch_data_to_process) - processed_in_batch
429
+
430
+ processed_count += processed_in_batch
431
+ skipped_count += skipped_in_batch
432
+
433
+ # Optional: Print progress per worker periodically
434
+ if (i // batch_size) % 10 == 0: # Print every 10 batches
435
+ rank0_print(f"[GPU {gpu_id}] Progress: Batch {i//batch_size+1}/{math.ceil(total_files_in_chunk/batch_size)}, Processed: {processed_count}, Skipped: {skipped_count}")
436
+
437
+
438
+ rank0_print(f"[GPU {gpu_id}] Worker finished. Processed: {processed_count}, Skipped: {skipped_count}")
439
+ return processed_count, skipped_count
440
+
441
+
442
+ # --- Main Execution ---
443
+ if __name__ == "__main__":
444
+ mp.set_start_method('spawn', force=True) # Recommended for CUDA with multiprocessing
445
+
446
+ parser = argparse.ArgumentParser(description="Extract Spatial Features using CUT3R (Multi-GPU)")
447
+ parser.add_argument("--cut3r-weights-path", type=str, required=True, help="Path to the CUT3R weights file (e.g., cut3r_512_dpt_4_64.pth)")
448
+ parser.add_argument("--input-dir", type=str, default=None, help="Root directory containing video files to process recursively (ignored if --input-file is provided)")
449
+ parser.add_argument("--input-file", type=str, default=None, help="Path to a single video file to process")
450
+ parser.add_argument("--output-dir", type=str, required=True, help="Root directory to save the extracted features, mirroring input structure")
451
+ parser.add_argument("--processor-config-path", type=str, required=True, help="Path to the processor_config.json file for SigLipImageProcessor")
452
+ # parser.add_argument("--device", type=str, default="cuda:0", help="Device to use (e.g., 'cuda:0', 'cpu')") # Replaced by gpu-ids
453
+ parser.add_argument("--gpu-ids", type=str, default="0", help="Comma-separated list of GPU IDs to use (e.g., '0,1,2') or 'all'")
454
+ parser.add_argument("--precision", type=str, default="fp16", choices=['fp16', 'bf16', 'fp32'], help="Computation precision")
455
+ parser.add_argument("--overwrite", action="store_true", help="Overwrite existing feature files")
456
+ parser.add_argument("--video-fps", type=int, default=1, help="FPS for video frame sampling")
457
+ parser.add_argument("--frames-upbound", type=int, default=10, help="Max frames to sample per video")
458
+ parser.add_argument("--batch-size", type=int, default=1, help="Number of videos to process per batch *per GPU*") # Clarified batch size scope
459
+ parser.add_argument("--export-point-cloud", action="store_true", help="Export generated point cloud for each video")
460
+ parser.add_argument("--point-cloud-output-dir", type=str, default="point_clouds", help="Directory to save exported point clouds (used if --export-point-cloud is set)")
461
+ parser.add_argument("--point-cloud-voxel-size", type=float, default=0.01, help="Voxel size for downsampling exported point clouds")
462
+ parser.add_argument("--save-preprocessed-frames", action="store_true", help="Save the preprocessed frames used for feature extraction as images")
463
+ parser.add_argument("--save-preprocessed-frames-dir", type=str, default="preprocessed_frames", help="Directory to save preprocessed frames (used if --save-preprocessed-frames is set)")
464
+
465
+ args = parser.parse_args()
466
+
467
+ # --- Validate Input Arguments ---
468
+ if not args.input_dir and not args.input_file:
469
+ parser.error("Either --input-dir or --input-file must be specified.")
470
+ if args.input_dir and args.input_file:
471
+ rank0_print("Warning: Both --input-dir and --input-file provided. --input-file will be used.")
472
+ args.input_dir = None # Prioritize input_file
473
+
474
+ # --- Determine GPUs to Use ---
475
+ if args.gpu_ids.lower() == 'all':
476
+ if torch.cuda.is_available():
477
+ num_gpus = torch.cuda.device_count()
478
+ gpu_ids = list(range(num_gpus))
479
+ if num_gpus == 0:
480
+ rank0_print("Error: 'all' GPUs requested, but no CUDA devices found.")
481
+ sys.exit(1)
482
+ rank0_print(f"Using all available GPUs: {gpu_ids}")
483
+ else:
484
+ rank0_print("Error: 'all' GPUs requested, but CUDA is not available.")
485
+ sys.exit(1)
486
+ else:
487
+ try:
488
+ gpu_ids = [int(id.strip()) for id in args.gpu_ids.split(',')]
489
+ # Validate GPU IDs
490
+ if torch.cuda.is_available():
491
+ num_gpus = torch.cuda.device_count()
492
+ for gpu_id in gpu_ids:
493
+ if gpu_id < 0 or gpu_id >= num_gpus:
494
+ rank0_print(f"Error: Invalid GPU ID {gpu_id}. Available GPUs: {list(range(num_gpus))}")
495
+ sys.exit(1)
496
+ else:
497
+ rank0_print(f"Warning: Specified GPU IDs {gpu_ids}, but CUDA is not available. Will attempt CPU if possible (not recommended/tested).")
498
+ # Or exit if CPU processing is not intended/supported
499
+ # sys.exit(1)
500
+ rank0_print(f"Using specified GPUs: {gpu_ids}")
501
+ except ValueError:
502
+ rank0_print(f"Error: Invalid format for --gpu-ids. Expected comma-separated integers (e.g., '0,1,2') or 'all'. Got: {args.gpu_ids}")
503
+ sys.exit(1)
504
+
505
+ if not gpu_ids:
506
+ rank0_print("Error: No valid GPUs specified or found.")
507
+ sys.exit(1)
508
+
509
+ num_workers = len(gpu_ids)
510
+
511
+ # --- Prepare Output Directory ---
512
+ output_dir = Path(args.output_dir)
513
+ output_dir.mkdir(parents=True, exist_ok=True) # Use Path.mkdir
514
+ if args.export_point_cloud:
515
+ pc_output_dir = Path(args.point_cloud_output_dir)
516
+ pc_output_dir.mkdir(parents=True, exist_ok=True)
517
+ rank0_print(f"Point clouds will be saved to: {args.point_cloud_output_dir}")
518
+ if args.save_preprocessed_frames:
519
+ frames_output_dir = Path(args.save_preprocessed_frames_dir)
520
+ frames_output_dir.mkdir(parents=True, exist_ok=True)
521
+ rank0_print(f"Preprocessed frames will be saved to: {args.save_preprocessed_frames_dir}")
522
+
523
+ # --- Determine Input Files ---
524
+ if args.input_file:
525
+ input_file_path = Path(args.input_file)
526
+ if not input_file_path.is_file():
527
+ rank0_print(f"Error: Provided --input-file '{args.input_file}' not found or is not a file.")
528
+ sys.exit(1)
529
+ all_video_files_paths = [input_file_path]
530
+ input_base_dir = Path(args.input_dir) if args.input_dir and input_file_path.is_relative_to(args.input_dir) else input_file_path.parent
531
+ rank0_print(f"Processing single input file: {args.input_file}")
532
+ elif args.input_dir:
533
+ input_base_dir = Path(args.input_dir)
534
+ # Find files needs Path objects
535
+ all_video_files_paths_str = find_video_files(args.input_dir)
536
+ all_video_files_paths = [Path(p) for p in all_video_files_paths_str] # Keep as Path objects
537
+ if not all_video_files_paths:
538
+ rank0_print(f"No video files found in {args.input_dir}. Exiting.")
539
+ sys.exit(0)
540
+ rank0_print(f"Found {len(all_video_files_paths)} video files in {args.input_dir}.")
541
+ else:
542
+ # This case should be caught by parser.error earlier
543
+ rank0_print("Error: No input specified.")
544
+ sys.exit(1)
545
+
546
+ # --- Distribute Files Among Workers ---
547
+ files_per_worker = [[] for _ in range(num_workers)]
548
+ for i, file_path in enumerate(all_video_files_paths):
549
+ worker_index = i % num_workers
550
+ # Pass file paths as strings to worker processes
551
+ files_per_worker[worker_index].append(str(file_path))
552
+
553
+ # --- Launch Worker Processes ---
554
+ rank0_print(f"Starting feature extraction with {num_workers} worker process(es) on GPUs {gpu_ids}...")
555
+ pool_args = []
556
+ for rank, gpu_id in enumerate(gpu_ids):
557
+ pool_args.append(
558
+ (rank, gpu_id, args, files_per_worker[rank], input_base_dir, output_dir)
559
+ )
560
+
561
+ total_processed = 0
562
+ total_skipped = 0
563
+ try:
564
+ with mp.Pool(processes=num_workers) as pool:
565
+ # Use starmap to pass multiple arguments to the worker function
566
+ results = pool.starmap(process_videos_on_gpu, pool_args)
567
+
568
+ # Aggregate results
569
+ for processed, skipped in results:
570
+ total_processed += processed
571
+ total_skipped += skipped
572
+
573
+ except Exception as e:
574
+ rank0_print(f"\n--- An error occurred during multiprocessing ---")
575
+ rank0_print(f"Error: {e}")
576
+ rank0_print(traceback.format_exc())
577
+ rank0_print("Feature extraction may be incomplete.")
578
+ # Ensure totals reflect potentially partial completion if some processes finished
579
+ if 'results' in locals():
580
+ for processed, skipped in results:
581
+ total_processed += processed
582
+ total_skipped += skipped
583
+ else: # If pool creation failed or starmap didn't even start
584
+ total_skipped = len(all_video_files_paths)
585
+
586
+
587
+ # --- Final Summary ---
588
+ rank0_print("-" * 30)
589
+ rank0_print(f"Feature extraction complete.")
590
+ rank0_print(f"Successfully processed: {total_processed}")
591
+ rank0_print(f"Skipped (exists or error): {total_skipped}")
592
+ rank0_print(f"Total files considered: {len(all_video_files_paths)}")
593
+ rank0_print(f"Features saved in: {args.output_dir}")
spatial-model/VLM-3R/scripts/qwen.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoModelForCausalLM, AutoTokenizer
2
+ import torch
3
+
4
+ device = "cuda" # the device to load the model onto
5
+
6
+ model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen1.5-MoE-A2.7B-Chat", torch_dtype=torch.bfloat16, device_map="auto")
7
+ tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen1.5-MoE-A2.7B-Chat")
8
+
9
+ prompt = "Give me a short introduction to large language model."
10
+ messages = [{"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": prompt}]
11
+ text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
12
+ model_inputs = tokenizer([text], return_tensors="pt").to(device)
13
+
14
+ generated_ids = model.generate(model_inputs.input_ids, max_new_tokens=512)
15
+ generated_ids = [output_ids[len(input_ids) :] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)]
16
+
17
+ response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
18
+
19
+ print(response)
spatial-model/VLM-3R/scripts/summarize_data.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from tqdm import tqdm
4
+
5
+ with open("/mnt/bn/vl-research/workspace/boli01/zzzprojects/LLaVA/playground/data/llava_v1_5_mix665k.json") as f:
6
+ llava_v1_5_mix665k = json.load(f) # 665298
7
+
8
+ with open("/mnt/bn/vl-research/workspace/boli01/zzzprojects/LLaVA/playground/data/llava_instruct_150k.json") as f:
9
+ llava_instruct_150k = json.load(f) # 157712
10
+
11
+ # Create sets of "id" fields
12
+ mix665k_ids = set()
13
+ for item in llava_v1_5_mix665k:
14
+ all_conv = ""
15
+ for cur_conversation in item["conversations"]:
16
+ all_conv += cur_conversation["value"]
17
+ mix665k_ids.add(f'{item["id"]}_{all_conv}')
18
+
19
+ instruct_150k_ids = set()
20
+ for item in llava_instruct_150k:
21
+ all_conv = ""
22
+ for cur_conversation in item["conversations"]:
23
+ all_conv += cur_conversation["value"]
24
+ instruct_150k_ids.add(f'{item["id"]}_{all_conv}')
25
+
26
+ share_gpt_ids = set()
27
+ for item in llava_v1_5_mix665k:
28
+ if "image" not in item:
29
+ all_conv = ""
30
+ for cur_conversation in item["conversations"]:
31
+ all_conv += cur_conversation["value"]
32
+ share_gpt_ids.add(f'{item["id"]}_{all_conv}') # 40688
33
+
34
+ # Get "id" fields that are in mix665k but not in instruct_150k and share_gpt
35
+ new_ids = mix665k_ids - instruct_150k_ids - share_gpt_ids # 466898
36
+
37
+ # Get "id" fields that are in mix665k but not in share_gpt
38
+ # new_ids = mix665k_ids - share_gpt_ids #624610
39
+
40
+ # import pdb; pdb.set_trace()
41
+
42
+ # Filter mix665k data based on new_ids
43
+ new_data = []
44
+ for item in llava_v1_5_mix665k:
45
+ all_conv = ""
46
+ for cur_conversation in item["conversations"]:
47
+ all_conv += cur_conversation["value"]
48
+ if f'{item["id"]}_{all_conv}' in new_ids:
49
+ new_data.append(item)
50
+
51
+ import pdb
52
+
53
+ pdb.set_trace()
54
+
55
+ with open("/mnt/bn/vl-research/workspace/boli01/zzzprojects/LLaVA/playground/data/mixtral_instruct_135K_of_158K_V1.5.json") as f:
56
+ new_mixtral_instruct = json.load(f)
57
+
58
+ # mixtral_instruct_50K_of_80K_V1.json@
59
+
60
+ # print(len(new_data))
61
+ # for _ in new_mixtral_instruct:
62
+ # # import pdb; pdb.set_trace()
63
+ # if "coco" not in _["image"]:
64
+ # _["image"] = f"coco/train2017/{_['image']}"
65
+ # new_data.append(_)
66
+
67
+ # print(len(instruct_150k_ids))
68
+ print(len(new_data))
69
+
70
+ # for _ in tqdm(new_data):
71
+ # if "image" in _:
72
+ # if "000000442654" in _["image"]:
73
+ # all_conv = ""
74
+ # for cur_conversation in _["conversations"]:
75
+ # all_conv += cur_conversation["value"]
76
+ # # if not os.path.exists(f'/mnt/bn/vl-research/workspace/boli01/data/playground/data/{_["image"]}'):
77
+ # import pdb; pdb.set_trace()
78
+
79
+ # Write new_data to a new JSON file
80
+ with open("/mnt/bn/vl-research/workspace/boli01/zzzprojects/LLaVA/playground/data/llava_v1_5_mix665k_minus_llava_instruct_150k_minus_sharegpt_plus_mixtral_instruct_135K_of_158K_V1.5.json", "w") as f:
81
+ json.dump(new_data, f)
spatial-model/VLM-3R/scripts/zero2.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "fp16": {
3
+ "enabled": "auto",
4
+ "loss_scale": 0,
5
+ "loss_scale_window": 1000,
6
+ "initial_scale_power": 16,
7
+ "hysteresis": 2,
8
+ "min_loss_scale": 1
9
+ },
10
+ "bf16": {
11
+ "enabled": "auto"
12
+ },
13
+ "optimizer": {
14
+ "type": "AdamW",
15
+ "params": {
16
+ "lr": "auto",
17
+ "betas": "auto",
18
+ "eps": "auto",
19
+ "weight_decay": "auto"
20
+ }
21
+ },
22
+ "zero_optimization": {
23
+ "stage": 2,
24
+ "offload_optimizer": {
25
+ "device": "none",
26
+ "pin_memory": true
27
+ },
28
+ "allgather_partitions": true,
29
+ "allgather_bucket_size": 2e8,
30
+ "overlap_comm": false,
31
+ "reduce_scatter": true,
32
+ "reduce_bucket_size": 2e8,
33
+ "contiguous_gradients": true
34
+ },
35
+ "gradient_accumulation_steps": "auto",
36
+ "gradient_clipping": "auto",
37
+ "steps_per_print": 100,
38
+ "train_batch_size": "auto",
39
+ "train_micro_batch_size_per_gpu": "auto",
40
+ "wall_clock_breakdown": false
41
+ }
spatial-model/VLM-3R/scripts/zero2_offload.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "fp16": {
3
+ "enabled": "auto",
4
+ "loss_scale": 0,
5
+ "loss_scale_window": 1000,
6
+ "initial_scale_power": 16,
7
+ "hysteresis": 2,
8
+ "min_loss_scale": 1
9
+ },
10
+ "bf16": {
11
+ "enabled": "auto"
12
+ },
13
+ "train_micro_batch_size_per_gpu": "auto",
14
+ "train_batch_size": "auto",
15
+ "gradient_accumulation_steps": "auto",
16
+ "zero_optimization": {
17
+ "stage": 2,
18
+ "offload_optimizer": {
19
+ "device": "cpu",
20
+ "pin_memory": true
21
+ },
22
+ "offload_param": {
23
+ "device": "cpu",
24
+ "pin_memory": true
25
+ },
26
+ "overlap_comm": true,
27
+ "contiguous_gradients": true,
28
+ "sub_group_size": 1e9,
29
+ "reduce_bucket_size": "auto"
30
+ }
31
+ }
spatial-model/VLM-3R/scripts/zero3.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "fp16": {
3
+ "enabled": "auto",
4
+ "loss_scale": 0,
5
+ "loss_scale_window": 1000,
6
+ "initial_scale_power": 16,
7
+ "hysteresis": 2,
8
+ "min_loss_scale": 1
9
+ },
10
+ "bf16": {
11
+ "enabled": "auto"
12
+ },
13
+
14
+ "zero_optimization": {
15
+ "stage": 3,
16
+ "offload_optimizer": {
17
+ "device": "none",
18
+ "pin_memory": true
19
+ },
20
+ "offload_param": {
21
+ "device": "none",
22
+ "pin_memory": true
23
+ },
24
+ "overlap_comm": true,
25
+ "contiguous_gradients": true,
26
+ "sub_group_size": 1e9,
27
+ "reduce_bucket_size": "auto",
28
+ "stage3_prefetch_bucket_size": "auto",
29
+ "stage3_param_persistence_threshold": "auto",
30
+ "stage3_max_live_parameters": 1e9,
31
+ "stage3_max_reuse_distance": 1e9,
32
+ "stage3_gather_16bit_weights_on_model_save": true
33
+ },
34
+
35
+ "gradient_accumulation_steps": "auto",
36
+ "gradient_clipping": "auto",
37
+ "steps_per_print": 100,
38
+ "train_batch_size": "auto",
39
+ "train_micro_batch_size_per_gpu": "auto",
40
+ "wall_clock_breakdown": false
41
+ }
spatial-model/VLM-3R/scripts/zero3_offload.json ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "fp16": {
3
+ "enabled": "auto",
4
+ "loss_scale": 0,
5
+ "loss_scale_window": 1000,
6
+ "initial_scale_power": 16,
7
+ "hysteresis": 2,
8
+ "min_loss_scale": 1
9
+ },
10
+ "bf16": {
11
+ "enabled": "auto"
12
+ },
13
+ "optimizer": {
14
+ "type": "AdamW",
15
+ "params": {
16
+ "lr": "auto",
17
+ "betas": "auto",
18
+ "eps": "auto",
19
+ "weight_decay": "auto"
20
+ }
21
+ },
22
+ "zero_optimization": {
23
+ "stage": 3,
24
+ "offload_optimizer": {
25
+ "device": "cpu",
26
+ "pin_memory": true
27
+ },
28
+ "offload_param": {
29
+ "device": "cpu",
30
+ "pin_memory": true
31
+ },
32
+ "overlap_comm": true,
33
+ "contiguous_gradients": true,
34
+ "sub_group_size": 1e9,
35
+ "reduce_bucket_size": "auto",
36
+ "stage3_prefetch_bucket_size": "auto",
37
+ "stage3_param_persistence_threshold": "auto",
38
+ "stage3_max_live_parameters": 1e9,
39
+ "stage3_max_reuse_distance": 1e9,
40
+ "gather_16bit_weights_on_model_save": true
41
+ },
42
+ "gradient_accumulation_steps": "auto",
43
+ "gradient_clipping": "auto",
44
+ "train_batch_size": "auto",
45
+ "train_micro_batch_size_per_gpu": "auto",
46
+ "steps_per_print": 1e5,
47
+ "wall_clock_breakdown": false
48
+ }
spatial-model/VLM-3R/scripts/zero3pp.json ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "fp16": {
3
+ "enabled": "auto",
4
+ "loss_scale": 0,
5
+ "loss_scale_window": 1000,
6
+ "initial_scale_power": 16,
7
+ "hysteresis": 2,
8
+ "min_loss_scale": 1
9
+ },
10
+ "bf16": {
11
+ "enabled": "auto"
12
+ },
13
+ "optimizer": {
14
+ "type": "AdamW",
15
+ "params": {
16
+ "lr": "auto",
17
+ "betas": "auto",
18
+ "eps": "auto",
19
+ "weight_decay": "auto"
20
+ }
21
+ },
22
+
23
+ "zero_optimization": {
24
+ "stage": 3,
25
+ "offload_optimizer": {
26
+ "device": "none",
27
+ "pin_memory": true
28
+ },
29
+ "offload_param": {
30
+ "device": "none",
31
+ "pin_memory": true
32
+ },
33
+ "overlap_comm": true,
34
+ "contiguous_gradients": true,
35
+ "zero_quantized_weights": true,
36
+ "zero_hpz_partition_size": 16,
37
+ "zero_quantized_gradients": true,
38
+ "sub_group_size": 1e9,
39
+ "reduce_bucket_size": "auto",
40
+ "stage3_prefetch_bucket_size": "auto",
41
+ "stage3_param_persistence_threshold": "auto",
42
+ "stage3_max_live_parameters": 1e9,
43
+ "stage3_max_reuse_distance": 1e9,
44
+ "stage3_gather_16bit_weights_on_model_save": true
45
+ },
46
+
47
+ "gradient_accumulation_steps": "auto",
48
+ "gradient_clipping": "auto",
49
+ "steps_per_print": 100,
50
+ "train_batch_size": "auto",
51
+ "train_micro_batch_size_per_gpu": "auto",
52
+ "wall_clock_breakdown": false
53
+ }
spatial-model/VLM-3R/thinking-in-space/tools/live_bench/live_bench/data_generator/live_bench_data.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datasets
2
+ from live_bench.data_generator.qa_generator import QAGenerator
3
+ from live_bench.data_generator.question_finalizer import QuestionFinalizer
4
+ from live_bench.data_generator.utils.extract_infomation import ImageInfomation
5
+ from live_bench.screen_shoter.screen import ScreenImage
6
+
7
+
8
+ class LiveBenchData(object):
9
+ SUBTASKS = ("Basic Understanding", "Contextual Analysis", "Deeper Implications", "Broader Implications", "Further Insights")
10
+
11
+ features = datasets.Features(
12
+ {
13
+ "id": datasets.Value("int32"),
14
+ "images": datasets.Sequence(datasets.Image()),
15
+ "website": datasets.Value("string"),
16
+ "question": datasets.Value("string"),
17
+ "answer": datasets.Value("string"),
18
+ "criteria": datasets.Value("string"),
19
+ "subtask": datasets.Value("string"),
20
+ "data_generator": datasets.Value("string"),
21
+ "checker": datasets.Value("string"),
22
+ "date_time": datasets.Value("string"),
23
+ "screen_shoter": datasets.Value("string"),
24
+ "screen_size": datasets.Value("string"),
25
+ "score": datasets.Value("int32"),
26
+ "reason": datasets.Value("string"),
27
+ "scorer_name": datasets.Value("string"),
28
+ }
29
+ )
30
+
31
+ def __init__(
32
+ self,
33
+ *,
34
+ screen: ScreenImage,
35
+ question: str,
36
+ answer: str,
37
+ criteria: str,
38
+ subtask: str,
39
+ data_generator: str,
40
+ infomation: ImageInfomation = None,
41
+ score: int = None,
42
+ reason: str = None,
43
+ checker: QAGenerator = None,
44
+ finalizer: QuestionFinalizer = None,
45
+ scorer_name=None,
46
+ scorer=None,
47
+ ):
48
+ self.screen = screen
49
+ self.question = question
50
+ self.answer = answer
51
+ self.criteria = criteria
52
+ self.subtask = subtask
53
+ self.data_generator = data_generator
54
+ self.infomation = infomation
55
+ self.checker = None
56
+ if checker:
57
+ response = checker.check(screen, question, answer, criteria, subtask, infomation=infomation)
58
+ if response.success:
59
+ formatted_response = checker.format_checked_response(response)
60
+ if formatted_response.question and formatted_response.answer and formatted_response.criteria:
61
+ self.question = formatted_response.question
62
+ self.answer = formatted_response.answer
63
+ self.criteria = formatted_response.criteria
64
+ if formatted_response.subtask:
65
+ self.subtask = formatted_response.subtask
66
+ else:
67
+ self.subtask = subtask
68
+ self.checker = checker.get_name()
69
+ if finalizer:
70
+ try:
71
+ qa = finalizer.finalize_question(self.question, self.answer, self.criteria, self.screen.images)
72
+ except Exception as e:
73
+ raise e
74
+ self.question = qa["question"]
75
+ self.answer = qa["answer"]
76
+ self.criteria = qa["criteria"]
77
+ if self.subtask:
78
+ for sub in LiveBenchData.SUBTASKS:
79
+ if sub.lower() in self.subtask.lower():
80
+ self.subtask = sub
81
+ break
82
+ else:
83
+ self.subtask = "Further Insights"
84
+ else:
85
+ self.subtask = "Not Specified"
86
+ if score is not None:
87
+ self.score = score
88
+ self.reason = reason
89
+ self.scorer_name = scorer_name
90
+ else:
91
+ score = scorer.get_score(question, answer, screen.images)
92
+ self.score = score.score
93
+ self.reason = score.reason
94
+ self.scorer_name = scorer.get_name()
95
+
96
+ def to_dict(self):
97
+ images = self.screen.images
98
+ website = self.screen.website.get_info()
99
+ question = self.question
100
+ answer = self.answer
101
+ subtask = self.subtask
102
+ data_generator = self.data_generator
103
+ date_time = self.screen.capture_datetime
104
+ screen_shoter = self.screen.shoter
105
+ screen_size = self.screen.screen_size
106
+ criteria = self.criteria
107
+ return {
108
+ "images": images,
109
+ "website": website,
110
+ "question": question,
111
+ "answer": answer,
112
+ "criteria": criteria,
113
+ "subtask": subtask,
114
+ "data_generator": data_generator,
115
+ "checker": self.checker,
116
+ "date_time": date_time,
117
+ "screen_shoter": screen_shoter,
118
+ "screen_size": screen_size,
119
+ "score": self.score,
120
+ "reason": self.reason,
121
+ "scorer_name": self.scorer_name,
122
+ }
123
+
124
+ def to_hf_dict(self):
125
+ return self.features.encode_example(self.to_dict())
126
+
127
+ def to_output_dict(self):
128
+ return {
129
+ "screen": self.screen.to_output_dict(),
130
+ "question": self.question,
131
+ "answer": self.answer,
132
+ "criteria": self.criteria,
133
+ "subtask": self.subtask,
134
+ "data_generator": self.data_generator,
135
+ "checker": self.checker,
136
+ "score": self.score,
137
+ "reason": self.reason,
138
+ "scorer_name": self.scorer_name,
139
+ }
spatial-model/VLM-3R/thinking-in-space/tools/live_bench/live_bench/data_generator/prompt.md ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ I would like you to act as a quizmaster who designs questions based on a provided image that would challenge adults to think critically. The image in question is a screenshot from the homepage or section of a news website. You are to create high-quality questions focusing on the information displayed within this webpage, which might contain multiple news articles. Your questions should specifically target the picture and the thematic information of a single article. Your question should be answerable, and checkable. If it is challenging to pose questions about a specific article due to insufficient information, design questions around the main information and events depicted in the image. Within your capabilities, try to make the questions more challenging.
2
+
3
+ A well-crafted question about an event should allow respondents to gain deeper insights by observing and analyzing the event, paying attention to the following aspects:
4
+
5
+ - Basic Understanding: Questions that require direct observation or recall of the information presented in the image. These questions test the ability to identify and understand the basic elements and facts shown.
6
+ - Contextual Analysis: Questions that delve into the context or setting of the information presented. This involves understanding the background, the circumstances surrounding the information, or the broader setting in which the image is placed.
7
+ - Deeper Implications: Questions that explore the underlying meanings, implications, or consequences of the information in the image. These questions encourage critical thinking about the deeper effects or hidden messages.
8
+ - Broader Implications: Questions that extend the discussion beyond the immediate context of the image to its wider impact on society, other fields, or global issues.
9
+ - Further Insights: Questions that prompt exploration of additional layers of understanding or connections to other knowledge and concepts not immediately apparent from the image.
10
+
11
+ Consider designing a multi-round Q&A process, progressively deepening the understanding of the event’s essence.
12
+
13
+ Please note that although the image may contain a lot of political content, try to avoid questions with any political bias when asking questions. Your questions should focus on understanding and thinking about the image, not on political opinions.
14
+
15
+ You should try to be innovative, and you may propose some difficult questions, as well as multiple-choice questions, fill-in-the-blank questions, or even image-text matching questions, and sequencing questions. Within your capabilities, try to make the questions more challenging.
16
+
17
+ At the same time, you need to generate how this question should be scored, that is, the criteria. Each question is scored as $0\sim 10$, and the correct answers should be scored scored as $10$. Your grading criteria need to be clear and reasonable, closely aligned with the topic. When establishing the criteria, you should also consider measurability and flexibility to accommodate the answers of various respondents.
spatial-model/VLM-3R/thinking-in-space/tools/live_bench/live_bench/data_generator/question_finalizer.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from abc import ABC, abstractmethod
4
+ from typing import List
5
+
6
+ import anthropic
7
+ import google.generativeai as genai
8
+ import openai
9
+ from live_bench.data_generator.qa_generator import QAData
10
+ from live_bench.data_generator.utils.claude import (
11
+ claude_generate_response,
12
+ format_claude_images,
13
+ )
14
+ from live_bench.data_generator.utils.gemini import gemini_generate_response
15
+ from live_bench.data_generator.utils.gpt4v import (
16
+ format_gpt4v_images,
17
+ gpt4v_generate_response,
18
+ )
19
+ from PIL import Image
20
+
21
+ REJECT_TO_ANSWER = "Reject to answer"
22
+
23
+
24
+ class AnswerGetter(ABC):
25
+ @abstractmethod
26
+ def get_answer(self, question: str, images: List[Image.Image]):
27
+ raise NotImplementedError("get_answer not implemented")
28
+
29
+
30
+ class GPT4VAnswerGetter(AnswerGetter):
31
+ def __init__(self, model: str = "gpt-4o", api_key=None):
32
+ self.model = model
33
+ if api_key is None:
34
+ self.api_key = os.getenv("OPENAI_API_KEY", None)
35
+ else:
36
+ self.api_key = api_key
37
+ self.client = openai.OpenAI(api_key=self.api_key)
38
+
39
+ def get_answer(self, question: str, images: List[Image.Image]):
40
+ messages = [{"role": "user", "content": format_gpt4v_images(images) + [{"type": "text", "text": question}]}]
41
+ response = gpt4v_generate_response(messages=messages, client=self.client, model=self.model)
42
+ if response.success:
43
+ return response.content
44
+ else:
45
+ return REJECT_TO_ANSWER
46
+
47
+
48
+ class ClaudeAnswerGetter(AnswerGetter):
49
+ def __init__(self, model: str = "claude-3-5-sonnet-20240620", api_key=None):
50
+ self.model = model
51
+ if api_key is None:
52
+ self.api_key = os.getenv("ANTHROPIC_API_KEY", None)
53
+ else:
54
+ self.api_key = api_key
55
+ self.client = anthropic.Anthropic(api_key=self.api_key)
56
+
57
+ def get_answer(self, question: str, images: List[Image.Image]):
58
+ messages = [{"role": "user", "content": format_claude_images(images) + [{"type": "text", "text": question}]}]
59
+ response = claude_generate_response(self.client, self.model, messages)
60
+ if response.success:
61
+ return response.content
62
+ else:
63
+ return REJECT_TO_ANSWER
64
+
65
+
66
+ class GeminiAnswerGetter(AnswerGetter):
67
+ def __init__(self, model: str = "gemini-1.5-pro", api_key=None):
68
+ self.model = model
69
+ self.client = genai.GenerativeModel(model)
70
+
71
+ def get_answer(self, question: str, images: List[Image.Image]):
72
+ response = gemini_generate_response(self.client, images + [question], max_tokens=2048)
73
+ if response.success:
74
+ return response.content
75
+ else:
76
+ return REJECT_TO_ANSWER
77
+
78
+
79
+ QUESTION_FINALIZER_PROMPT = """\
80
+ You are a question setter, and your task is to modify the following question, answer, and scoring criteria to ensure:
81
+
82
+ 1. The question is clear and unambiguous.
83
+ 2. The answer is correct and reasonable (although the original ground truth answer is mostly correct, it may not be perfect, and sometimes the answer maybe incorrect).
84
+ 3. The scoring criteria are rational and facilitate the accurate assessment of responses.
85
+ 4. The full score for the scoring criteria must be 10 points, and it must directly relate to the specific answer.
86
+ 5. Except for some multiple-choice questions or other questions with only one possible answer, the scoring criteria should not be an all-or-nothing system. Partially correct answers should receive proportional points.
87
+ 6. Ensure that the scoring system is flexible enough to accommodate slight variations in correct answers while still maintaining a standard for what is considered an acceptable answer.
88
+ 7. Clearly define what constitutes a full score, partial score, and zero score.
89
+ 8. The criteria should be as detailed as possible, even if a LLM without image understanding capabilities could still score the answer based on the criteria and ground truth answer correctly.
90
+
91
+ Your task is to finalize these standards, thus ensuring the correctness of the answer and the rationality of the scoring criteria.
92
+
93
+ Some tips:
94
+
95
+ 1. For some extremely hard open-ended questions where answers may vary, hitting all points perfectly may not be realistic. In such cases, you can relax the criteria slightly. For example, if there are five possible points in an answer, but answering three adequately could merit full points. An other option is to change the question to a multiple-choice / multi-select question. But remember, it only applies to extremely hard open-ended questions which are impossible to answer perfectly.
96
+ 2. For some questions, changing the format might be beneficial. You can consider transforming them into different types of questions such as essay, fill-in-the-blank, multiple-choice (or multiple-select), true/false, ranking (e.g., based on time, importance, etc.), or matching questions to enhance the difficulty and rationality of the scoring criteria.
97
+ """
98
+
99
+ FINALIZER_OUTPUT_FORMAT_PROMPT = """\
100
+ Please provide the final question, answer, and scoring criteria in the following json format:
101
+ {
102
+ "question": "The final question",
103
+ "answer": "The final answer",
104
+ "criteria": "The final scoring criteria"
105
+ }
106
+
107
+ One thing as a reminder is that if you want to add a new line in the json string, you should use the escape character "\\n" instead to represent the new line.
108
+ """
109
+
110
+
111
+ class QuestionFinalizer(object):
112
+ def __init__(self, gpt4v_model: str = "gpt-4o", claude_model: str = "claude-3-5-sonnet-20240620", gemini_model: str = "gemini-1.5-pro"):
113
+ self.models = {"GPT4V": GPT4VAnswerGetter(gpt4v_model), "Claude": ClaudeAnswerGetter(claude_model), "Gemini": GeminiAnswerGetter(gemini_model)}
114
+ self.client = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY", None))
115
+ # self.client = anthropic.Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY", None))
116
+
117
+ def finalize_question(self, question, answer, criteria, images: List[Image.Image]):
118
+ information = [f"[Original Question]\n{question}", f"[Original Answer]\n{answer}", f"[Original Criteria]\n{criteria}"]
119
+ information.append(
120
+ "Below are answers from three candidates for reference. These answers may not be correct but are reasonably credible (but mostly correct). If any candidate rejects to answer, consider whether there is an issue with the question (such as containing violent or graphic content, or having a clear political bias). If so, please make necessary modifications. For open-ended questions, also consider the reasonableness of these answers. If they are reasonable, you may need to adjust the scoring criteria or the answer itself."
121
+ )
122
+ for model_name, model in self.models.items():
123
+ information.append(f"[{model_name} Answer]\n{model.get_answer(question, images)}")
124
+ information.append(FINALIZER_OUTPUT_FORMAT_PROMPT)
125
+ prompt = "\n\n".join(information)
126
+ messages = [{"role": "user", "content": format_gpt4v_images(images) + [{"type": "text", "text": prompt}]}]
127
+ try:
128
+ response = gpt4v_generate_response(client=self.client, model="gpt-4o", messages=messages, system=QUESTION_FINALIZER_PROMPT)
129
+ if response.success:
130
+ data = json.loads(response.content)
131
+ return {
132
+ "question": data["question"],
133
+ "answer": data["answer"],
134
+ "criteria": data["criteria"],
135
+ }
136
+ except Exception as e:
137
+ print(f"Failed to generate response: {e}")
138
+ return None