gpcv_incontext_bench / inference_k2.py
insomnia7's picture
Add files using upload-large-folder tool
2c986a2 verified
Raw
History Blame Contribute Delete
7.88 kB
import os
import json
import re
from pathlib import Path
from vllm import LLM, SamplingParams
from transformers import AutoProcessor
from PIL import Image
# --- 1. 环境与硬件配置 ---
os.environ["VLLM_USE_V1"] = "0"
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
os.environ["CUDA_VISIBLE_DEVICES"] = "0,1,2,3"
os.environ["PYTHONNOUSERSITE"] = "1"
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
def extract_bboxes_from_response(response_text):
"""从模型回复中提取 bbox 坐标,兼容两种格式:
GT格式: {"bboxes": ["<x1><y1><x2><y2>", ...]}
模型输出: [{"bbox": ["<bbox_start><x1><y1><x2><y2><bbox_end>", ...]}]
"""
try:
response_clean = response_text.strip()
if response_clean.startswith('"') and response_clean.endswith('"'):
try:
response_clean = json.loads(response_clean)
except Exception:
pass
if isinstance(response_clean, str):
if not (response_clean.startswith('{') or response_clean.startswith('[')):
match = re.search(r'[\{\[].*[\}\]]', response_clean, re.DOTALL)
if match:
response_clean = match.group()
data = json.loads(response_clean)
else:
data = response_clean
pattern = r'<x(\d+)><y(\d+)><x(\d+)><y(\d+)>'
# 格式1: [{"bbox": [...]}] — 模型输出
if isinstance(data, list):
all_bbox_strs = []
for item in data:
all_bbox_strs.extend(item.get("bbox", []))
# 格式2: {"bboxes": [...]} — GT
elif isinstance(data, dict):
all_bbox_strs = data.get("bboxes", [])
else:
return []
bboxes = []
for bbox_str in all_bbox_strs:
match = re.search(pattern, bbox_str)
if match:
x1, y1, x2, y2 = map(int, match.groups())
bboxes.append([x1, y1, x2, y2])
return bboxes
except Exception:
return []
def load_conversation_data(data_file, max_samples=None):
"""加载对话格式的 .jsonl 数据"""
data_list = []
if not os.path.exists(data_file):
print(f"错误: 找不到文件 {data_file}")
return []
with open(data_file, 'r', encoding='utf-8') as f:
for idx, line in enumerate(f):
if max_samples and idx >= max_samples:
break
try:
data = json.loads(line.strip())
convs = data['conversations']
if isinstance(convs, str):
convs = json.loads(convs)
human_val = next((c['value'] for c in convs if c['from'] == 'human'), None)
gpt_val = next((c['value'] for c in convs if c['from'] == 'gpt'), None)
if human_val:
data_list.append({
'image': data['image'],
'prompt': human_val,
'ground_truth': gpt_val or ""
})
except Exception as e:
print(f"解析第 {idx} 行失败: {e}")
print(f"成功加载了 {len(data_list)} 条数据")
return data_list
def run_vllm_inference(model_path, data_list, output_file, temperature=0.0):
"""核心推理函数"""
print(f"\n正在初始化 vLLM 模型: {model_path}")
# 加载 processor 用于生成正确的 prompt 格式
processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
# 初始化 LLM 引擎
llm = LLM(
model=model_path,
tensor_parallel_size=4,
trust_remote_code=True,
max_model_len=8192,
gpu_memory_utilization=0.85,
dtype="bfloat16",
enforce_eager=True,
limit_mm_per_prompt={"image": 1},
)
sampling_params = SamplingParams(
temperature=temperature,
top_p=0.9 if temperature > 0 else 1.0,
max_tokens=2048,
stop=["</s>", "<|im_end|>", "<|endoftext|>"],
skip_special_tokens=False,
)
# 构建 vLLM 输入
vllm_inputs = []
for item in data_list:
# 使用 processor 构建正确的消息格式
messages = [
{
"role": "user",
"content": [
{"type": "image", "image": item['image']},
{"type": "text", "text": item['prompt']}
]
}
]
# 应用 chat template,生成带图片占位符的 prompt
prompt_text = processor.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True
)
# 加载图片
image = Image.open(item['image'])
vllm_inputs.append({
"prompt": prompt_text,
"multi_modal_data": {"image": image}
})
print(f"开始执行 Batch 推理 (共 {len(data_list)} 个样本)...")
print(f"Prompt 示例: {vllm_inputs[0]['prompt'][:200]}...")
# 分批处理
batch_size = 2
all_results = []
for i in range(0, len(vllm_inputs), batch_size):
batch_inputs = vllm_inputs[i:i+batch_size]
batch_data = data_list[i:i+batch_size]
print(f"处理批次 {i//batch_size + 1}/{(len(vllm_inputs)-1)//batch_size + 1}")
outputs = llm.generate(batch_inputs, sampling_params)
for idx, (item, output) in enumerate(zip(batch_data, outputs)):
res_text = output.outputs[0].text
pred_boxes = extract_bboxes_from_response(res_text)
gt_boxes = extract_bboxes_from_response(item['ground_truth'])
all_results.append({
'index': i + idx,
'image': item['image'],
'prompt': item['prompt'],
'model_response': res_text,
'ground_truth': item['ground_truth'],
'pred_bboxes': pred_boxes,
'gt_bboxes': gt_boxes,
'num_pred': len(pred_boxes),
'num_gt': len(gt_boxes),
})
if (i + idx + 1) % 5 == 0:
print(f"进度: {i + idx + 1}/{len(data_list)}")
# 保存完整结果
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(all_results, f, ensure_ascii=False, indent=2)
# 保存简化结果用于计算 IoU
simplified_path = str(output_file).replace(".json", "_simplified.json")
simplified = [{"image": r['image'], "gt_bboxes": r['gt_bboxes'], "pred_bboxes": r['pred_bboxes']} for r in all_results]
with open(simplified_path, 'w', encoding='utf-8') as f:
json.dump(simplified, f, ensure_ascii=False, indent=2)
print(f"\n推理完成!")
print(f"完整结果: {output_file}")
print(f"简化结果: {simplified_path}")
return all_results
def main():
MODEL_PATH = "/home/disk2/hjl/ICL_QWEN/ckpt_0409_iter_26916"
DATA_FILE = "/home/disk2/hjl/ICL_QWEN/ICL_benchmark/fewshot_data/conversation/conversation_k2.jsonl"
OUTPUT_DIR = Path("/home/disk2/hjl/ICL_QWEN/new_test")
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
IS_TEST = False
if IS_TEST:
print(">>> 进入测试模式 (Sample=10)")
data = load_conversation_data(DATA_FILE, max_samples=10)
output_name = "test_results_k2.json"
else:
print(">>> 进入全量推理模式")
data = load_conversation_data(DATA_FILE)
output_name = "full_results_k2.json"
if data:
run_vllm_inference(MODEL_PATH, data, OUTPUT_DIR / output_name, temperature=0.0)
else:
print("未加载到有效数据,请检查路径。")
if __name__ == "__main__":
main()