H1W0XXX commited on
Commit
13c9dd5
·
1 Parent(s): 17d233c

Improve retry scoring logs and tests

Browse files
run_eval.py CHANGED
@@ -66,10 +66,22 @@ def extract_json(response_text):
66
  return None
67
 
68
 
69
- def run_chat_completion(client, model_name, messages, temperature=0.2):
70
- """封装 API 调用 (支持流式输出)"""
 
 
 
 
 
 
 
 
 
 
71
  try:
72
- print(f"\n[Model Output Start]:")
 
 
73
  stream = client.chat.completions.create(
74
  model=model_name,
75
  messages=messages,
@@ -83,10 +95,13 @@ def run_chat_completion(client, model_name, messages, temperature=0.2):
83
  if chunk.choices:
84
  delta = chunk.choices[0].delta.content
85
  if delta:
86
- print(delta, end="", flush=True)
 
87
  full_content.append(delta)
88
-
89
- print(f"\n[Model Output End]\n{'-'*40}")
 
 
90
  return "".join(full_content)
91
 
92
  except Exception as e:
@@ -94,6 +109,24 @@ def run_chat_completion(client, model_name, messages, temperature=0.2):
94
  return None
95
 
96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
  # --- 诊断相关函数 ---
98
 
99
  def apply_standard_load(model):
@@ -213,6 +246,7 @@ def main():
213
  parser.add_argument("--debug", action="store_true", help="Run sanity check using Ground Truth JSON (No AI)")
214
  parser.add_argument("--prompt-type", type=str, default="standard", choices=PROMPT_REGISTRY.keys())
215
  parser.add_argument("--filter", type=str, default=None, help="Filter tasks")
 
216
 
217
  args = parser.parse_args()
218
 
@@ -237,7 +271,7 @@ def main():
237
  print(f"Starting evaluation on {len(tasks)} tasks.")
238
  results = []
239
 
240
- for task in tqdm(tasks, desc="Evaluating"):
241
  task_id = task['id']
242
  gt_solution = task['gt_solution']
243
  if isinstance(gt_solution, list) and len(gt_solution) > 0: gt_solution = gt_solution[0]
@@ -249,9 +283,12 @@ def main():
249
  final_details = {}
250
  fail_reason = "Unknown"
251
  attempts_used = 0
 
 
252
 
253
  # --- Debug Mode ---
254
  if args.debug:
 
255
  ai_json = gt_raw_json
256
  if not ai_json:
257
  fail_reason = "GT JSON Missing"
@@ -262,6 +299,7 @@ def main():
262
  else:
263
  score, details = compute_score(ai_solution, gt_solution)
264
  best_score = score
 
265
  final_details = details
266
  fail_reason = "Success" if score == 1.0 else "Wrong Answer"
267
 
@@ -287,19 +325,40 @@ def main():
287
  # 构造本次请求的消息列表
288
  messages = base_messages + retry_context
289
 
290
- print(f"\n[Attempt {attempts_used}] Requesting API...")
291
- response_text = run_chat_completion(client, args.model, messages, temperature=current_temp)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
292
 
293
  if not response_text:
294
  fail_reason = "API Failure"
 
 
 
295
  break
296
 
297
  json_str = extract_json(response_text)
 
298
  error_feedback = ""
299
 
300
  if not json_str:
301
  error_feedback = "I cannot find valid JSON. Please output standard JSON inside <json> tags."
302
  fail_reason = "Parse Error"
 
303
  else:
304
  try:
305
  ai_json = JSON_LIB.loads(json_str)
@@ -308,41 +367,61 @@ def main():
308
  if solver_error:
309
  error_feedback = f"Solver Error: {solver_error}. Check connectivity."
310
  fail_reason = "Solver Crashed"
 
311
  elif not ai_solution:
312
  error_feedback = "Unstable structure (empty result)."
313
  fail_reason = "Unstable"
 
314
  else:
315
  score, details = compute_score(ai_solution, gt_solution)
 
 
316
 
317
  if score == 1.0:
318
  best_score = 1.0
 
319
  final_details = details
320
  fail_reason = "Success"
 
 
 
321
  break # Perfect!
322
  else:
323
  # ❌ 计算结果不对,启动诊断
324
  fail_reason = "Wrong Answer"
325
  final_details = details
 
326
 
327
  # 只有当存在 GT Raw Model 时才能诊断
328
  if gt_raw_json:
329
  partial_score, diag_feedback = diagnose_failure(solver, ai_json, gt_raw_json)
330
  error_feedback = f"Result incorrect. Diagnostic: {diag_feedback}"
 
331
 
332
- # 如果是最后一次尝试,记录诊断得分为最终得分
333
- if attempt == args.max_retries:
334
- best_score = partial_score
335
- fail_reason = f"Partial: {diag_feedback}"
 
 
 
 
 
 
336
  else:
337
  error_feedback = "Result incorrect (Reaction forces mismatch)."
338
 
339
  except Exception as e:
340
  error_feedback = f"JSON Syntax Error: {e}"
341
  fail_reason = "Syntax Error"
 
 
 
 
342
 
343
  # Retry Logic: 只保留最近一次的错误
344
  if attempt < args.max_retries and error_feedback:
345
- print(f" -> Feedback: {error_feedback}")
346
  # 更新 retry_context,覆盖掉旧的错误历史
347
  retry_context = [
348
  {"role": "assistant", "content": response_text},
@@ -359,8 +438,11 @@ def main():
359
  "difficulty": task.get("difficulty", 1),
360
  "reason": fail_reason,
361
  "attempts_used": attempts_used,
362
- "details": final_details
 
 
363
  })
 
364
 
365
  # Summary
366
  total_score = sum(r['score'] for r in results)
@@ -370,7 +452,7 @@ def main():
370
  weighted_acc = (total_score / total_possible) * 100 if total_possible else 0
371
 
372
  print("\n" + "=" * 60)
373
- print(f"📊 Evaluation Report: {args.model}")
374
  print(f"Filter: {args.filter if args.filter else 'None'} | Max Retries: {args.max_retries}")
375
  print("-" * 60)
376
  print(f"{'Category':<15} | {'Tasks':<8} | {'Score':<10} | {'Max Score':<10} | {'Accuracy':<10}")
 
66
  return None
67
 
68
 
69
+ def short_text(text, max_len=160):
70
+ """压缩日志文本,避免控制台输出太长。"""
71
+ if not text:
72
+ return ""
73
+ compact = " ".join(str(text).split())
74
+ if len(compact) <= max_len:
75
+ return compact
76
+ return compact[:max_len - 3] + "..."
77
+
78
+
79
+ def run_chat_completion(client, model_name, messages, temperature=0.2, stream_output=False):
80
+ """封装 API 调用,默认只收集完整回复,不逐 token 打印。"""
81
  try:
82
+ if stream_output:
83
+ print(f"\n[Model Output Start]:")
84
+
85
  stream = client.chat.completions.create(
86
  model=model_name,
87
  messages=messages,
 
95
  if chunk.choices:
96
  delta = chunk.choices[0].delta.content
97
  if delta:
98
+ if stream_output:
99
+ print(delta, end="", flush=True)
100
  full_content.append(delta)
101
+
102
+ if stream_output:
103
+ print(f"\n[Model Output End]\n{'-'*40}")
104
+
105
  return "".join(full_content)
106
 
107
  except Exception as e:
 
109
  return None
110
 
111
 
112
+ def keep_best_retry_score(
113
+ best_score,
114
+ best_attempt,
115
+ final_details,
116
+ fail_reason,
117
+ candidate_score,
118
+ candidate_attempt,
119
+ candidate_details,
120
+ candidate_reason,
121
+ ):
122
+ """
123
+ Retry 评分策略:保留历史最高分;同分时保留更早的尝试,便于结果稳定。
124
+ """
125
+ if best_attempt == 0 or candidate_score > best_score:
126
+ return candidate_score, candidate_attempt, candidate_details, candidate_reason
127
+ return best_score, best_attempt, final_details, fail_reason
128
+
129
+
130
  # --- 诊断相关函数 ---
131
 
132
  def apply_standard_load(model):
 
246
  parser.add_argument("--debug", action="store_true", help="Run sanity check using Ground Truth JSON (No AI)")
247
  parser.add_argument("--prompt-type", type=str, default="standard", choices=PROMPT_REGISTRY.keys())
248
  parser.add_argument("--filter", type=str, default=None, help="Filter tasks")
249
+ parser.add_argument("--verbose-response", action="store_true", help="Print full streaming model responses to console")
250
 
251
  args = parser.parse_args()
252
 
 
271
  print(f"Starting evaluation on {len(tasks)} tasks.")
272
  results = []
273
 
274
+ for task in tqdm(tasks, desc="Evaluating", ascii=True):
275
  task_id = task['id']
276
  gt_solution = task['gt_solution']
277
  if isinstance(gt_solution, list) and len(gt_solution) > 0: gt_solution = gt_solution[0]
 
283
  final_details = {}
284
  fail_reason = "Unknown"
285
  attempts_used = 0
286
+ best_attempt = 0
287
+ attempt_logs = []
288
 
289
  # --- Debug Mode ---
290
  if args.debug:
291
+ attempts_used = 1
292
  ai_json = gt_raw_json
293
  if not ai_json:
294
  fail_reason = "GT JSON Missing"
 
299
  else:
300
  score, details = compute_score(ai_solution, gt_solution)
301
  best_score = score
302
+ best_attempt = 1
303
  final_details = details
304
  fail_reason = "Success" if score == 1.0 else "Wrong Answer"
305
 
 
325
  # 构造本次请求的消息列表
326
  messages = base_messages + retry_context
327
 
328
+ tqdm.write(f"[{task_id}] attempt {attempts_used}/{args.max_retries + 1}: requesting API")
329
+ response_text = run_chat_completion(
330
+ client,
331
+ args.model,
332
+ messages,
333
+ temperature=current_temp,
334
+ stream_output=args.verbose_response
335
+ )
336
+ attempt_log = {
337
+ "attempt": attempts_used,
338
+ "temperature": current_temp,
339
+ "response_text": response_text,
340
+ "extracted_json": None,
341
+ "feedback": "",
342
+ "score": None,
343
+ "details": {},
344
+ "failure": None
345
+ }
346
 
347
  if not response_text:
348
  fail_reason = "API Failure"
349
+ attempt_log["failure"] = fail_reason
350
+ attempt_logs.append(attempt_log)
351
+ tqdm.write(f"[{task_id}] attempt {attempts_used}: API failure")
352
  break
353
 
354
  json_str = extract_json(response_text)
355
+ attempt_log["extracted_json"] = json_str
356
  error_feedback = ""
357
 
358
  if not json_str:
359
  error_feedback = "I cannot find valid JSON. Please output standard JSON inside <json> tags."
360
  fail_reason = "Parse Error"
361
+ attempt_log["failure"] = fail_reason
362
  else:
363
  try:
364
  ai_json = JSON_LIB.loads(json_str)
 
367
  if solver_error:
368
  error_feedback = f"Solver Error: {solver_error}. Check connectivity."
369
  fail_reason = "Solver Crashed"
370
+ attempt_log["failure"] = fail_reason
371
  elif not ai_solution:
372
  error_feedback = "Unstable structure (empty result)."
373
  fail_reason = "Unstable"
374
+ attempt_log["failure"] = fail_reason
375
  else:
376
  score, details = compute_score(ai_solution, gt_solution)
377
+ attempt_log["score"] = score
378
+ attempt_log["details"] = details
379
 
380
  if score == 1.0:
381
  best_score = 1.0
382
+ best_attempt = attempts_used
383
  final_details = details
384
  fail_reason = "Success"
385
+ attempt_log["failure"] = None
386
+ attempt_logs.append(attempt_log)
387
+ tqdm.write(f"[{task_id}] attempt {attempts_used}: success")
388
  break # Perfect!
389
  else:
390
  # ❌ 计算结果不对,启动诊断
391
  fail_reason = "Wrong Answer"
392
  final_details = details
393
+ attempt_log["failure"] = fail_reason
394
 
395
  # 只有当存在 GT Raw Model 时才能诊断
396
  if gt_raw_json:
397
  partial_score, diag_feedback = diagnose_failure(solver, ai_json, gt_raw_json)
398
  error_feedback = f"Result incorrect. Diagnostic: {diag_feedback}"
399
+ attempt_log["diagnostic_score"] = partial_score
400
 
401
+ best_score, best_attempt, final_details, fail_reason = keep_best_retry_score(
402
+ best_score,
403
+ best_attempt,
404
+ final_details,
405
+ fail_reason,
406
+ partial_score,
407
+ attempts_used,
408
+ details,
409
+ f"Partial: {diag_feedback}",
410
+ )
411
  else:
412
  error_feedback = "Result incorrect (Reaction forces mismatch)."
413
 
414
  except Exception as e:
415
  error_feedback = f"JSON Syntax Error: {e}"
416
  fail_reason = "Syntax Error"
417
+ attempt_log["failure"] = fail_reason
418
+
419
+ attempt_log["feedback"] = error_feedback
420
+ attempt_logs.append(attempt_log)
421
 
422
  # Retry Logic: 只保留最近一次的错误
423
  if attempt < args.max_retries and error_feedback:
424
+ tqdm.write(f"[{task_id}] attempt {attempts_used}: {short_text(error_feedback)}")
425
  # 更新 retry_context,覆盖掉旧的错误历史
426
  retry_context = [
427
  {"role": "assistant", "content": response_text},
 
438
  "difficulty": task.get("difficulty", 1),
439
  "reason": fail_reason,
440
  "attempts_used": attempts_used,
441
+ "best_attempt": best_attempt,
442
+ "details": final_details,
443
+ "attempt_logs": attempt_logs
444
  })
445
+ tqdm.write(f"[{task_id}] done: ratio={best_score:.2f}, reason={fail_reason}, attempts={attempts_used}")
446
 
447
  # Summary
448
  total_score = sum(r['score'] for r in results)
 
452
  weighted_acc = (total_score / total_possible) * 100 if total_possible else 0
453
 
454
  print("\n" + "=" * 60)
455
+ print(f"Evaluation Report: {args.model}")
456
  print(f"Filter: {args.filter if args.filter else 'None'} | Max Retries: {args.max_retries}")
457
  print("-" * 60)
458
  print(f"{'Category':<15} | {'Tasks':<8} | {'Score':<10} | {'Max Score':<10} | {'Accuracy':<10}")
tools/diagnose_selftest.py CHANGED
@@ -1,8 +1,12 @@
1
  import copy
2
  import json
 
 
3
  import unittest
4
  from pathlib import Path
5
 
 
 
6
  from run_eval import diagnose_failure
7
  from src.solver_bridge import TrussSolver
8
 
 
1
  import copy
2
  import json
3
+ import os
4
+ import sys
5
  import unittest
6
  from pathlib import Path
7
 
8
+ sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
9
+
10
  from run_eval import diagnose_failure
11
  from src.solver_bridge import TrussSolver
12
 
tools/retry_scoring_selftest.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import unittest
4
+
5
+ sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
6
+
7
+ from run_eval import keep_best_retry_score
8
+
9
+
10
+ class RetryScoringSelfTest(unittest.TestCase):
11
+ def test_first_scored_attempt_is_recorded_even_when_zero(self):
12
+ details = {"attempt": 1}
13
+
14
+ score, attempt, final_details, reason = keep_best_retry_score(
15
+ best_score=0,
16
+ best_attempt=0,
17
+ final_details={},
18
+ fail_reason="Unknown",
19
+ candidate_score=0,
20
+ candidate_attempt=1,
21
+ candidate_details=details,
22
+ candidate_reason="Partial: geometry incorrect",
23
+ )
24
+
25
+ self.assertEqual(score, 0)
26
+ self.assertEqual(attempt, 1)
27
+ self.assertIs(final_details, details)
28
+ self.assertEqual(reason, "Partial: geometry incorrect")
29
+
30
+ def test_lower_later_score_does_not_replace_best(self):
31
+ best_details = {"attempt": 1}
32
+ candidate_details = {"attempt": 2}
33
+
34
+ score, attempt, final_details, reason = keep_best_retry_score(
35
+ best_score=0.5,
36
+ best_attempt=1,
37
+ final_details=best_details,
38
+ fail_reason="Partial: connection incorrect",
39
+ candidate_score=0.25,
40
+ candidate_attempt=2,
41
+ candidate_details=candidate_details,
42
+ candidate_reason="Partial: supports incorrect",
43
+ )
44
+
45
+ self.assertEqual(score, 0.5)
46
+ self.assertEqual(attempt, 1)
47
+ self.assertIs(final_details, best_details)
48
+ self.assertEqual(reason, "Partial: connection incorrect")
49
+
50
+ def test_higher_later_score_replaces_best(self):
51
+ best_details = {"attempt": 1}
52
+ candidate_details = {"attempt": 2}
53
+
54
+ score, attempt, final_details, reason = keep_best_retry_score(
55
+ best_score=0.25,
56
+ best_attempt=1,
57
+ final_details=best_details,
58
+ fail_reason="Partial: supports incorrect",
59
+ candidate_score=0.75,
60
+ candidate_attempt=2,
61
+ candidate_details=candidate_details,
62
+ candidate_reason="Partial: loads incorrect",
63
+ )
64
+
65
+ self.assertEqual(score, 0.75)
66
+ self.assertEqual(attempt, 2)
67
+ self.assertIs(final_details, candidate_details)
68
+ self.assertEqual(reason, "Partial: loads incorrect")
69
+
70
+ def test_equal_score_keeps_earlier_attempt(self):
71
+ best_details = {"attempt": 1}
72
+ candidate_details = {"attempt": 2}
73
+
74
+ score, attempt, final_details, reason = keep_best_retry_score(
75
+ best_score=0.5,
76
+ best_attempt=1,
77
+ final_details=best_details,
78
+ fail_reason="Partial: connection incorrect",
79
+ candidate_score=0.5,
80
+ candidate_attempt=2,
81
+ candidate_details=candidate_details,
82
+ candidate_reason="Partial: connection incorrect again",
83
+ )
84
+
85
+ self.assertEqual(score, 0.5)
86
+ self.assertEqual(attempt, 1)
87
+ self.assertIs(final_details, best_details)
88
+ self.assertEqual(reason, "Partial: connection incorrect")
89
+
90
+
91
+ if __name__ == "__main__":
92
+ unittest.main(verbosity=2)