H1W0XXX commited on
Commit ·
ec20773
1
Parent(s): 13c9dd5
Add task-level concurrency
Browse filesFiles changed (2)
- run_eval.py+220-176
- tools/concurrency_selftest.pyAdded+65
4 unmodified lines5678910225 unmodified lines2362372382392402415 unmodified lines2472482492502512522532541 unmodified line2562572582592602612622634 unmodified lines2682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484 unmodified linesimport argparseimport mimetypesimport copyfrom tqdm import tqdmfrom openai import OpenAIimport traceback225 unmodified linesreturn 0.50, "Geometry and supports are correct, but the member connection types (hinge/rigid) are incorrect."def main():parser = argparse.ArgumentParser(description="Structural AI Benchmark Evaluator")parser.add_argument("--model", type=str, default="debug-mode", help="Model name")5 unmodified linesparser.add_argument("--prompt-type", type=str, default="standard", choices=PROMPT_REGISTRY.keys())parser.add_argument("--filter", type=str, default=None, help="Filter tasks")parser.add_argument("--verbose-response", action="store_true", help="Print full streaming model responses to console")args = parser.parse_args()# 1. System Promptcurrent_system_prompt = PROMPT_REGISTRY.get(args.prompt_type)1 unmodified line# 2. Componentsloader = BenchmarkDataLoader()solver = TrussSolver("bin/framecalc.wasm")client = OpenAI(api_key=args.api_key, base_url=args.api_base) if not args.debug else None# 3. Taskstasks = loader.load_tasks_for_eval()4 unmodified linesif args.limit > 0:tasks = tasks[:args.limit]print(f"Starting evaluation on {len(tasks)} tasks.")results = []for task in tqdm(tasks, desc="Evaluating", ascii=True):task_id = task['id']gt_solution = task['gt_solution']if isinstance(gt_solution, list) and len(gt_solution) > 0: gt_solution = gt_solution[0]# Load Raw GT Model for diagnosisgt_raw_json = loader.load_raw_model_by_id(task_id)best_score = 0final_details = {}fail_reason = "Unknown"attempts_used = 0best_attempt = 0attempt_logs = []# --- Debug Mode ---if args.debug:attempts_used = 1ai_json = gt_raw_jsonif not ai_json:fail_reason = "GT JSON Missing"else:ai_solution, solver_error = solver.solve(ai_json)if solver_error:fail_reason = f"Physics Solver Crashed: {solver_error}"else:score, details = compute_score(ai_solution, gt_solution)best_score = scorebest_attempt = 1final_details = detailsfail_reason = "Success" if score == 1.0 else "Wrong Answer"# --- AI Mode ---else:base64_image = encode_image(task['image_path'])# 基础对话历史 (System + User/Image)base_messages = [{"role": "system", "content": current_system_prompt},{"role": "user", "content": [{"type": "text", "text": "Analyze the structure in this image and output the JSON definition."},{"type": "image_url", "image_url": {"url": base64_image}}]}]# 用于重试的上下文 (Last Assistant Response + Error)retry_context = []for attempt in range(args.max_retries + 1):attempts_used = attempt + 1current_temp = 0.6 if attempt == 0 else 0.7# 构造本次请求的消息列表messages = base_messages + retry_contexttqdm.write(f"[{task_id}] attempt {attempts_used}/{args.max_retries + 1}: requesting API")response_text = run_chat_completion(client,args.model,messages,temperature=current_temp,stream_output=args.verbose_response)attempt_log = {"attempt": attempts_used,"temperature": current_temp,"response_text": response_text,"extracted_json": None,"feedback": "","score": None,"details": {},"failure": None}if not response_text:fail_reason = "API Failure"attempt_log["failure"] = fail_reasonattempt_logs.append(attempt_log)tqdm.write(f"[{task_id}] attempt {attempts_used}: API failure")breakjson_str = extract_json(response_text)attempt_log["extracted_json"] = json_strerror_feedback = ""if not json_str:error_feedback = "I cannot find valid JSON. Please output standard JSON inside <json> tags."fail_reason = "Parse Error"attempt_log["failure"] = fail_reasonelse:try:ai_json = JSON_LIB.loads(json_str)ai_solution, solver_error = solver.solve(ai_json)if solver_error:error_feedback = f"Solver Error: {solver_error}. Check connectivity."fail_reason = "Solver Crashed"attempt_log["failure"] = fail_reasonelif not ai_solution:error_feedback = "Unstable structure (empty result)."fail_reason = "Unstable"attempt_log["failure"] = fail_reasonelse:score, details = compute_score(ai_solution, gt_solution)attempt_log["score"] = scoreattempt_log["details"] = detailsif score == 1.0:best_score = 1.0best_attempt = attempts_usedfinal_details = detailsfail_reason = "Success"attempt_log["failure"] = Noneattempt_logs.append(attempt_log)tqdm.write(f"[{task_id}] attempt {attempts_used}: success")break # Perfect!else:# ❌ 计算结果不对,启动诊断fail_reason = "Wrong Answer"final_details = detailsattempt_log["failure"] = fail_reason# 只有当存在 GT Raw Model 时才能诊断if gt_raw_json:partial_score, diag_feedback = diagnose_failure(solver, ai_json, gt_raw_json)error_feedback = f"Result incorrect. Diagnostic: {diag_feedback}"attempt_log["diagnostic_score"] = partial_scorebest_score, best_attempt, final_details, fail_reason = keep_best_retry_score(best_score,best_attempt,final_details,fail_reason,partial_score,attempts_used,details,f"Partial: {diag_feedback}",)else:error_feedback = "Result incorrect (Reaction forces mismatch)."except Exception as e:error_feedback = f"JSON Syntax Error: {e}"fail_reason = "Syntax Error"attempt_log["failure"] = fail_reasonattempt_log["feedback"] = error_feedbackattempt_logs.append(attempt_log)# Retry Logic: 只保留最近一次的错误if attempt < args.max_retries and error_feedback:tqdm.write(f"[{task_id}] attempt {attempts_used}: {short_text(error_feedback)}")# 更新 retry_context,覆盖掉旧的错误历史retry_context = [{"role": "assistant", "content": response_text},{"role": "user", "content": f"Error: {error_feedback} Fix the JSON."}]# Final Score Calculation: Difficulty * Ratiofinal_score = best_score * task.get("difficulty", 1)results.append({"id": task_id,"score": final_score, # Now this is weighted"ratio": best_score, # Store the raw ratio (0.0 - 1.0)"difficulty": task.get("difficulty", 1),"reason": fail_reason,"attempts_used": attempts_used,"best_attempt": best_attempt,"details": final_details,"attempt_logs": attempt_logs})tqdm.write(f"[{task_id}] done: ratio={best_score:.2f}, reason={fail_reason}, attempts={attempts_used}")# Summarytotal_score = sum(r['score'] for r in results)4 unmodified lines567891011225 unmodified lines2372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494505 unmodified lines4564574584594604614624634644654661 unmodified line4684694704714724734 unmodified lines4784794804814824834844854864874884894904914924 unmodified linesimport argparseimport mimetypesimport copyfrom concurrent.futures import ThreadPoolExecutor, as_completedfrom tqdm import tqdmfrom openai import OpenAIimport traceback225 unmodified linesreturn 0.50, "Geometry and supports are correct, but the member connection types (hinge/rigid) are incorrect."def evaluate_task(task, args, current_system_prompt):task_id = task['id']gt_solution = task['gt_solution']if isinstance(gt_solution, list) and len(gt_solution) > 0: gt_solution = gt_solution[0]loader = BenchmarkDataLoader()solver = TrussSolver("bin/framecalc.wasm")client = OpenAI(api_key=args.api_key, base_url=args.api_base) if not args.debug else None# Load Raw GT Model for diagnosisgt_raw_json = loader.load_raw_model_by_id(task_id)best_score = 0final_details = {}fail_reason = "Unknown"attempts_used = 0best_attempt = 0attempt_logs = []# --- Debug Mode ---if args.debug:attempts_used = 1ai_json = gt_raw_jsonif not ai_json:fail_reason = "GT JSON Missing"else:ai_solution, solver_error = solver.solve(ai_json)if solver_error:fail_reason = f"Physics Solver Crashed: {solver_error}"else:score, details = compute_score(ai_solution, gt_solution)best_score = scorebest_attempt = 1final_details = detailsfail_reason = "Success" if score == 1.0 else "Wrong Answer"# --- AI Mode ---else:base64_image = encode_image(task['image_path'])# 基础对话历史 (System + User/Image)base_messages = [{"role": "system", "content": current_system_prompt},{"role": "user", "content": [{"type": "text", "text": "Analyze the structure in this image and output the JSON definition."},{"type": "image_url", "image_url": {"url": base64_image}}]}]# 用于重试的上下文 (Last Assistant Response + Error)retry_context = []for attempt in range(args.max_retries + 1):attempts_used = attempt + 1current_temp = 0.6 if attempt == 0 else 0.7# 构造本次请求的消息列表messages = base_messages + retry_contexttqdm.write(f"[{task_id}] attempt {attempts_used}/{args.max_retries + 1}: requesting API")response_text = run_chat_completion(client,args.model,messages,temperature=current_temp,stream_output=args.verbose_response)attempt_log = {"attempt": attempts_used,"temperature": current_temp,"response_text": response_text,"extracted_json": None,"feedback": "","score": None,"details": {},"failure": None}if not response_text:fail_reason = "API Failure"attempt_log["failure"] = fail_reasonattempt_logs.append(attempt_log)tqdm.write(f"[{task_id}] attempt {attempts_used}: API failure")breakjson_str = extract_json(response_text)attempt_log["extracted_json"] = json_strerror_feedback = ""if not json_str:error_feedback = "I cannot find valid JSON. Please output standard JSON inside <json> tags."fail_reason = "Parse Error"attempt_log["failure"] = fail_reasonelse:try:ai_json = JSON_LIB.loads(json_str)ai_solution, solver_error = solver.solve(ai_json)if solver_error:error_feedback = f"Solver Error: {solver_error}. Check connectivity."fail_reason = "Solver Crashed"attempt_log["failure"] = fail_reasonelif not ai_solution:error_feedback = "Unstable structure (empty result)."fail_reason = "Unstable"attempt_log["failure"] = fail_reasonelse:score, details = compute_score(ai_solution, gt_solution)attempt_log["score"] = scoreattempt_log["details"] = detailsif score == 1.0:best_score = 1.0best_attempt = attempts_usedfinal_details = detailsfail_reason = "Success"attempt_log["failure"] = Noneattempt_logs.append(attempt_log)tqdm.write(f"[{task_id}] attempt {attempts_used}: success")break # Perfect!else:# ❌ 计算结果不对,启动诊断fail_reason = "Wrong Answer"final_details = detailsattempt_log["failure"] = fail_reason# 只有当存在 GT Raw Model 时才能诊断if gt_raw_json:partial_score, diag_feedback = diagnose_failure(solver, ai_json, gt_raw_json)error_feedback = f"Result incorrect. Diagnostic: {diag_feedback}"attempt_log["diagnostic_score"] = partial_scorebest_score, best_attempt, final_details, fail_reason = keep_best_retry_score(best_score,best_attempt,final_details,fail_reason,partial_score,attempts_used,details,f"Partial: {diag_feedback}",)else:error_feedback = "Result incorrect (Reaction forces mismatch)."except Exception as e:error_feedback = f"JSON Syntax Error: {e}"fail_reason = "Syntax Error"attempt_log["failure"] = fail_reasonattempt_log["feedback"] = error_feedbackattempt_logs.append(attempt_log)# Retry Logic: 只保留最近一次的错误if attempt < args.max_retries and error_feedback:tqdm.write(f"[{task_id}] attempt {attempts_used}: {short_text(error_feedback)}")# 更新 retry_context,覆盖掉旧的错误历史retry_context = [{"role": "assistant", "content": response_text},{"role": "user", "content": f"Error: {error_feedback} Fix the JSON."}]# Final Score Calculation: Difficulty * Ratiofinal_score = best_score * task.get("difficulty", 1)result = {"id": task_id,"score": final_score, # Now this is weighted"ratio": best_score, # Store the raw ratio (0.0 - 1.0)"difficulty": task.get("difficulty", 1),"reason": fail_reason,"attempts_used": attempts_used,"best_attempt": best_attempt,"details": final_details,"attempt_logs": attempt_logs}tqdm.write(f"[{task_id}] done: ratio={best_score:.2f}, reason={fail_reason}, attempts={attempts_used}")return resultdef run_task_batch(tasks, concurrency, task_runner, show_progress=True):"""题目级调度。并发完成顺序可能不同,但返回结果始终保持输入任务顺序。"""if concurrency < 1:raise ValueError("concurrency must be >= 1")if concurrency == 1:iterator = enumerate(tasks)if show_progress:iterator = tqdm(iterator, total=len(tasks), desc="Evaluating", ascii=True)return [task_runner(index, task) for index, task in iterator]results = [None] * len(tasks)with ThreadPoolExecutor(max_workers=concurrency) as executor:future_to_index = {executor.submit(task_runner, index, task): indexfor index, task in enumerate(tasks)}iterator = as_completed(future_to_index)if show_progress:iterator = tqdm(iterator, total=len(tasks), desc="Evaluating", ascii=True)for future in iterator:index = future_to_index[future]results[index] = future.result()return resultsdef main():parser = argparse.ArgumentParser(description="Structural AI Benchmark Evaluator")parser.add_argument("--model", type=str, default="debug-mode", help="Model name")5 unmodified linesparser.add_argument("--prompt-type", type=str, default="standard", choices=PROMPT_REGISTRY.keys())parser.add_argument("--filter", type=str, default=None, help="Filter tasks")parser.add_argument("--verbose-response", action="store_true", help="Print full streaming model responses to console")parser.add_argument("--concurrency", type=int, default=1, help="Number of tasks to evaluate concurrently")args = parser.parse_args()if args.concurrency < 1:parser.error("--concurrency must be >= 1")# 1. System Promptcurrent_system_prompt = PROMPT_REGISTRY.get(args.prompt_type)1 unmodified line# 2. Componentsloader = BenchmarkDataLoader()# 3. Taskstasks = loader.load_tasks_for_eval()4 unmodified linesif args.limit > 0:tasks = tasks[:args.limit]print(f"Starting evaluation on {len(tasks)} tasks. Concurrency: {args.concurrency}")if args.concurrency > 1 and args.verbose_response:print("[Warning] --verbose-response output may interleave when --concurrency > 1.")results = run_task_batch(tasks,args.concurrency,lambda index, task: evaluate_task(task, args, current_system_prompt),)# Summarytotal_score = sum(r['score'] for r in results)
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465import osimport sysimport threadingimport timeimport unittest
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
from run_eval import run_task_batch
class ConcurrencySelfTest(unittest.TestCase): def test_concurrent_results_keep_input_order(self): tasks = ["task-0", "task-1", "task-2", "task-3"]
def runner(index, task): time.sleep((len(tasks) - index) * 0.01) return {"id": task, "index": index}
results = run_task_batch(tasks, concurrency=4, task_runner=runner, show_progress=False)
self.assertEqual([r["id"] for r in results], tasks) self.assertEqual([r["index"] for r in results], list(range(len(tasks))))
def test_concurrency_runs_multiple_tasks_at_once(self): tasks = list(range(6)) lock = threading.Lock() active = 0 max_active = 0
def runner(index, task): nonlocal active, max_active with lock: active += 1 max_active = max(max_active, active) time.sleep(0.03) with lock: active -= 1 return task
results = run_task_batch(tasks, concurrency=3, task_runner=runner, show_progress=False)
self.assertEqual(results, tasks) self.assertGreater(max_active, 1)
def test_sequential_mode_still_works(self): tasks = ["a", "b", "c"] seen = []
def runner(index, task): seen.append((index, task)) return task.upper()
results = run_task_batch(tasks, concurrency=1, task_runner=runner, show_progress=False)
self.assertEqual(results, ["A", "B", "C"]) self.assertEqual(seen, [(0, "a"), (1, "b"), (2, "c")])
def test_invalid_concurrency_is_rejected(self): with self.assertRaises(ValueError): run_task_batch([], concurrency=0, task_runner=lambda index, task: task, show_progress=False)
if __name__ == "__main__": unittest.main(verbosity=2)run_eval.py+220-176
tools/concurrency_selftest.pyAdded+65