H1W0XXX commited on
Commit
5fbc173
·
1 Parent(s): ec20773

Fix evaluation persistence and update leaderboard with DeepSeek and GLM results

Browse files
.gitignore CHANGED
@@ -37,6 +37,7 @@ desktop.ini
37
 
38
  # Project specific
39
  eval_result_*.json
 
40
 
41
  # Helper Scripts
42
- push_all.ps1
 
37
 
38
  # Project specific
39
  eval_result_*.json
40
+ runs/
41
 
42
  # Helper Scripts
43
+ push_all.ps1
README.md CHANGED
@@ -164,14 +164,12 @@ $$
164
 
165
  ## 📊 评测榜单 (Leaderboard)
166
 
167
- | 模型 (Model) | 加权准确率 (Weighted Acc) | 备注 (Notes) |
168
- | :--- | :---: | :--- |
169
- | **Qwen3.5-35B-A3B** | 40.23% | Retries: 3 |
170
- | **Qwen3-VL-32B-Instruct** | 35.16% | Retries: 3 |
171
- | **gemma-4-31B-it** | 33.98% | Retries: 3 |
172
- | **GLM-4.5V-INT8** | 19.53% | Retries: 3 |
173
-
174
- *注:数据更新于 2026.4.5,基于 v1.0 数据集 (25题).*
175
 
176
  ## 许可证
177
 
 
164
 
165
  ## 📊 评测榜单 (Leaderboard)
166
 
167
+ | 模型 (Model) | 梁 (Beam) | 刚架 (Frame) | 桁架 (Truss) | 总得分 (Score) | 加权准确率 (Weighted Acc) |
168
+ | :--- | :---: | :---: | :---: | :---: | :---: |
169
+ | **deepseek-v4.1-flash** | 100.00% | 50.00% | 100.00% | 50.50 / 64 | **78.91%** |
170
+ | **glm-5.3-flash** | 100.00% | 46.30% | 100.00% | 49.50 / 64 | **77.34%** |
171
+
172
+ *注:数据更新于 2026-10-21,基于 v1.0 数据集,共 25 题(梁 5 题、刚架 10 题、桁架 10 题),总难度权重 64。评测参数:输出额度 32,768 tokens(包含思考与最终答案),reasoning_effort=high,每个模型并发 8,最多重试 2 次(每题最多请求 3 次)。各类别准确率均按难度加权计算。*
 
 
173
 
174
  ## 许可证
175
 
README_EN.md CHANGED
@@ -143,14 +143,12 @@ $$
143
 
144
  ## 📊 Leaderboard
145
 
146
- | Model | Weighted Accuracy | Notes |
147
- | :--- | :---: | :--- |
148
- | **Qwen3.5-35B-A3B** | 40.23% | Retries: 3 |
149
- | **Qwen3-VL-32B-Instruct** | 35.16% | Retries: 3 |
150
- | **gemma-4-31B-it** | 33.98% | Retries: 3 |
151
- | **GLM-4.5V-INT8** | 19.53% | Retries: 3 |
152
-
153
- *Note: Data updated on 2026.4.5, based on v1.0 dataset (25 tasks).*
154
 
155
  ## License
156
 
 
143
 
144
  ## 📊 Leaderboard
145
 
146
+ | Model | Beam | Frame | Truss | Score | Weighted Accuracy |
147
+ | :--- | :---: | :---: | :---: | :---: | :---: |
148
+ | **deepseek-v4.1-flash** | 100.00% | 50.00% | 100.00% | 50.50 / 64 | **78.91%** |
149
+ | **glm-5.3-flash** | 100.00% | 46.30% | 100.00% | 49.50 / 64 | **77.34%** |
150
+
151
+ *Note: Updated on 2026-10-21 using the v1.0 dataset: 25 tasks (5 beam, 10 frame, and 10 truss), with a total difficulty weight of 64. Evaluation settings: 32,768 output tokens (including reasoning and the final answer), reasoning_effort=high, concurrency of 8 per model, and up to 2 retries (3 attempts per task). Category accuracies are also weighted by difficulty.*
 
 
152
 
153
  ## License
154
 
run_eval.py CHANGED
@@ -15,6 +15,7 @@ from src.solver_bridge import TrussSolver
15
  from src.metrics import compute_score
16
  from src.data_loader import BenchmarkDataLoader
17
  from src.prompts import PROMPT_REGISTRY
 
18
 
19
  # 尝试引入 json_repair,如果没有安装则退化到 json
20
  try:
@@ -60,9 +61,31 @@ def extract_json(response_text):
60
  match = re.search(r'```(.*?)```', response_text, re.DOTALL)
61
  if match: return match.group(1).strip()
62
 
63
- # 5. 找最外层大括号
64
- match = re.search(r'\{.*?\}', response_text, re.DOTALL)
65
- if match: return match.group(0).strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
  return None
68
 
@@ -77,23 +100,46 @@ def short_text(text, max_len=160):
77
  return compact[:max_len - 3] + "..."
78
 
79
 
80
- def run_chat_completion(client, model_name, messages, temperature=0.2, stream_output=False):
 
 
81
  """封装 API 调用,默认只收集完整回复,不逐 token 打印。"""
 
 
 
 
 
 
 
82
  try:
83
  if stream_output:
84
  print(f"\n[Model Output Start]:")
85
 
 
 
 
86
  stream = client.chat.completions.create(
87
  model=model_name,
88
  messages=messages,
89
  temperature=temperature,
90
- max_tokens=8192,
91
- stream=True
 
 
92
  )
93
 
94
  full_content = []
95
  for chunk in stream:
 
 
 
 
 
96
  if chunk.choices:
 
 
 
 
97
  delta = chunk.choices[0].delta.content
98
  if delta:
99
  if stream_output:
@@ -106,8 +152,14 @@ def run_chat_completion(client, model_name, messages, temperature=0.2, stream_ou
106
  return "".join(full_content)
107
 
108
  except Exception as e:
 
109
  print(f"\n[API Error] {e}")
110
  return None
 
 
 
 
 
111
 
112
 
113
  def keep_best_retry_score(
@@ -244,7 +296,8 @@ def evaluate_task(task, args, current_system_prompt):
244
 
245
  loader = BenchmarkDataLoader()
246
  solver = TrussSolver("bin/framecalc.wasm")
247
- client = OpenAI(api_key=args.api_key, base_url=args.api_base) if not args.debug else None
 
248
 
249
  # Load Raw GT Model for diagnosis
250
  gt_raw_json = loader.load_raw_model_by_id(task_id)
@@ -296,12 +349,19 @@ def evaluate_task(task, args, current_system_prompt):
296
  messages = base_messages + retry_context
297
 
298
  tqdm.write(f"[{task_id}] attempt {attempts_used}/{args.max_retries + 1}: requesting API")
 
299
  response_text = run_chat_completion(
300
  client,
301
  args.model,
302
  messages,
303
  temperature=current_temp,
304
- stream_output=args.verbose_response
 
 
 
 
 
 
305
  )
306
  attempt_log = {
307
  "attempt": attempts_used,
@@ -313,13 +373,26 @@ def evaluate_task(task, args, current_system_prompt):
313
  "details": {},
314
  "failure": None
315
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
316
 
317
  if not response_text:
318
- fail_reason = "API Failure"
319
  attempt_log["failure"] = fail_reason
320
  attempt_logs.append(attempt_log)
321
- tqdm.write(f"[{task_id}] attempt {attempts_used}: API failure")
322
- break
323
 
324
  json_str = extract_json(response_text)
325
  attempt_log["extracted_json"] = json_str
@@ -416,7 +489,7 @@ def evaluate_task(task, args, current_system_prompt):
416
  return result
417
 
418
 
419
- def run_task_batch(tasks, concurrency, task_runner, show_progress=True):
420
  """
421
  题目级调度。并发完成顺序可能不同,但返回结果始终保持输入任务顺序。
422
  """
@@ -427,7 +500,13 @@ def run_task_batch(tasks, concurrency, task_runner, show_progress=True):
427
  iterator = enumerate(tasks)
428
  if show_progress:
429
  iterator = tqdm(iterator, total=len(tasks), desc="Evaluating", ascii=True)
430
- return [task_runner(index, task) for index, task in iterator]
 
 
 
 
 
 
431
 
432
  results = [None] * len(tasks)
433
  with ThreadPoolExecutor(max_workers=concurrency) as executor:
@@ -441,6 +520,8 @@ def run_task_batch(tasks, concurrency, task_runner, show_progress=True):
441
  for future in iterator:
442
  index = future_to_index[future]
443
  results[index] = future.result()
 
 
444
 
445
  return results
446
 
@@ -457,10 +538,20 @@ def main():
457
  parser.add_argument("--filter", type=str, default=None, help="Filter tasks")
458
  parser.add_argument("--verbose-response", action="store_true", help="Print full streaming model responses to console")
459
  parser.add_argument("--concurrency", type=int, default=1, help="Number of tasks to evaluate concurrently")
 
 
 
 
 
 
460
 
461
  args = parser.parse_args()
462
  if args.concurrency < 1:
463
  parser.error("--concurrency must be >= 1")
 
 
 
 
464
 
465
  # 1. System Prompt
466
  current_system_prompt = PROMPT_REGISTRY.get(args.prompt_type)
@@ -482,11 +573,22 @@ def main():
482
  if args.concurrency > 1 and args.verbose_response:
483
  print("[Warning] --verbose-response output may interleave when --concurrency > 1.")
484
 
485
- results = run_task_batch(
486
- tasks,
 
 
 
 
 
 
 
 
 
487
  args.concurrency,
488
  lambda index, task: evaluate_task(task, args, current_system_prompt),
 
489
  )
 
490
 
491
  # Summary
492
  total_score = sum(r['score'] for r in results)
@@ -529,9 +631,7 @@ def main():
529
  print(f"{'OVERALL':<15} | {len(results):<8} | {total_score:<10.2f} | {total_possible:<10.0f} | {weighted_acc:<9.2f}%")
530
  print("=" * 60)
531
 
532
- output_filename = f"eval_result_{'DEBUG' if args.debug else args.model.replace('/', '_')}.json"
533
- with open(output_filename, "w") as f:
534
- json.dump(results, f, indent=2)
535
  print(f"Results saved to {output_filename}")
536
 
537
  if __name__ == "__main__":
 
15
  from src.metrics import compute_score
16
  from src.data_loader import BenchmarkDataLoader
17
  from src.prompts import PROMPT_REGISTRY
18
+ from src.checkpoint import CheckpointStore, StreamProgress, append_event, atomic_json
19
 
20
  # 尝试引入 json_repair,如果没有安装则退化到 json
21
  try:
 
61
  match = re.search(r'```(.*?)```', response_text, re.DOTALL)
62
  if match: return match.group(1).strip()
63
 
64
+ # 5. 按括号层级提取完整对象,忽略字符串内部的括号与转义引号。
65
+ start = response_text.find('{')
66
+ if start >= 0:
67
+ depth = 0
68
+ in_string = False
69
+ escaped = False
70
+ for index in range(start, len(response_text)):
71
+ char = response_text[index]
72
+ if in_string:
73
+ if escaped:
74
+ escaped = False
75
+ elif char == '\\':
76
+ escaped = True
77
+ elif char == '"':
78
+ in_string = False
79
+ elif char == '"':
80
+ in_string = True
81
+ elif char == '{':
82
+ depth += 1
83
+ elif char == '}':
84
+ depth -= 1
85
+ if depth == 0:
86
+ return response_text[start:index + 1].strip()
87
+ # 保留完整的未闭合片段供 json_repair 尝试恢复。
88
+ return response_text[start:].strip()
89
 
90
  return None
91
 
 
100
  return compact[:max_len - 3] + "..."
101
 
102
 
103
+ def run_chat_completion(client, model_name, messages, temperature=0.2, stream_output=False,
104
+ max_tokens=8192, metadata=None, reasoning_effort=None,
105
+ progress_label=None, events_path=None, progress_interval=15):
106
  """封装 API 调用,默认只收集完整回复,不逐 token 打印。"""
107
+ if metadata is None:
108
+ metadata = {}
109
+ metadata.update(finish_reason=None, usage=None, reasoning_chars=0, error=None)
110
+ progress = StreamProgress(progress_label, events_path, progress_interval) if progress_label else None
111
+ if progress:
112
+ progress.start()
113
+ stream = None
114
  try:
115
  if stream_output:
116
  print(f"\n[Model Output Start]:")
117
 
118
+ request_options = {}
119
+ if reasoning_effort:
120
+ request_options['reasoning_effort'] = reasoning_effort
121
  stream = client.chat.completions.create(
122
  model=model_name,
123
  messages=messages,
124
  temperature=temperature,
125
+ max_tokens=max_tokens,
126
+ stream=True,
127
+ stream_options={"include_usage": True},
128
+ **request_options,
129
  )
130
 
131
  full_content = []
132
  for chunk in stream:
133
+ if progress:
134
+ delta = chunk.choices[0].delta if chunk.choices else None
135
+ progress.received(getattr(delta, 'content', None), getattr(delta, 'reasoning_content', None))
136
+ if chunk.usage:
137
+ metadata['usage'] = chunk.usage.model_dump()
138
  if chunk.choices:
139
+ choice = chunk.choices[0]
140
+ if choice.finish_reason:
141
+ metadata['finish_reason'] = choice.finish_reason
142
+ metadata['reasoning_chars'] += len(getattr(choice.delta, 'reasoning_content', None) or '')
143
  delta = chunk.choices[0].delta.content
144
  if delta:
145
  if stream_output:
 
152
  return "".join(full_content)
153
 
154
  except Exception as e:
155
+ metadata['error'] = str(e)
156
  print(f"\n[API Error] {e}")
157
  return None
158
+ finally:
159
+ if stream is not None and hasattr(stream, 'close'):
160
+ stream.close()
161
+ if progress:
162
+ progress.close()
163
 
164
 
165
  def keep_best_retry_score(
 
296
 
297
  loader = BenchmarkDataLoader()
298
  solver = TrussSolver("bin/framecalc.wasm")
299
+ client = OpenAI(api_key=args.api_key, base_url=args.api_base, timeout=args.api_timeout,
300
+ max_retries=0) if not args.debug else None
301
 
302
  # Load Raw GT Model for diagnosis
303
  gt_raw_json = loader.load_raw_model_by_id(task_id)
 
349
  messages = base_messages + retry_context
350
 
351
  tqdm.write(f"[{task_id}] attempt {attempts_used}/{args.max_retries + 1}: requesting API")
352
+ response_metadata = {}
353
  response_text = run_chat_completion(
354
  client,
355
  args.model,
356
  messages,
357
  temperature=current_temp,
358
+ stream_output=args.verbose_response,
359
+ max_tokens=args.max_tokens,
360
+ metadata=response_metadata,
361
+ reasoning_effort=args.reasoning_effort,
362
+ progress_label=f'{task_id} attempt {attempts_used}',
363
+ events_path=args.events_path,
364
+ progress_interval=args.progress_interval,
365
  )
366
  attempt_log = {
367
  "attempt": attempts_used,
 
373
  "details": {},
374
  "failure": None
375
  }
376
+ attempt_log.update(response_metadata)
377
+ # 保存原始回复后再调用求解器;即使本地诊断中断也有可审计记录。
378
+ append_event(args.events_path, dict(event='attempt_response', task_id=task_id, **attempt_log))
379
+ tqdm.write(f"[{task_id}] attempt {attempts_used}: finish={response_metadata['finish_reason']}, "
380
+ f"content_chars={len(response_text or '')}, reasoning_chars={response_metadata['reasoning_chars']}, "
381
+ f"usage={response_metadata['usage']}")
382
+
383
+ if response_metadata['finish_reason'] == 'length':
384
+ fail_reason = "Output Token Limit"
385
+ attempt_log['failure'] = fail_reason
386
+ attempt_logs.append(attempt_log)
387
+ tqdm.write(f"[{task_id}] attempt {attempts_used}: output limit reached ({args.max_tokens} tokens)")
388
+ continue
389
 
390
  if not response_text:
391
+ fail_reason = "API Failure" if response_metadata['error'] else "Empty Response"
392
  attempt_log["failure"] = fail_reason
393
  attempt_logs.append(attempt_log)
394
+ tqdm.write(f"[{task_id}] attempt {attempts_used}: {fail_reason}")
395
+ continue
396
 
397
  json_str = extract_json(response_text)
398
  attempt_log["extracted_json"] = json_str
 
489
  return result
490
 
491
 
492
+ def run_task_batch(tasks, concurrency, task_runner, show_progress=True, on_result=None):
493
  """
494
  题目级调度。并发完成顺序可能不同,但返回结果始终保持输入任务顺序。
495
  """
 
500
  iterator = enumerate(tasks)
501
  if show_progress:
502
  iterator = tqdm(iterator, total=len(tasks), desc="Evaluating", ascii=True)
503
+ results = []
504
+ for index, task in iterator:
505
+ result = task_runner(index, task)
506
+ if on_result:
507
+ on_result(result)
508
+ results.append(result)
509
+ return results
510
 
511
  results = [None] * len(tasks)
512
  with ThreadPoolExecutor(max_workers=concurrency) as executor:
 
520
  for future in iterator:
521
  index = future_to_index[future]
522
  results[index] = future.result()
523
+ if on_result:
524
+ on_result(results[index])
525
 
526
  return results
527
 
 
538
  parser.add_argument("--filter", type=str, default=None, help="Filter tasks")
539
  parser.add_argument("--verbose-response", action="store_true", help="Print full streaming model responses to console")
540
  parser.add_argument("--concurrency", type=int, default=1, help="Number of tasks to evaluate concurrently")
541
+ parser.add_argument("--max-tokens", type=int, default=8192, help="Output token budget including reasoning")
542
+ parser.add_argument("--output", type=str, default=None, help="Result JSON path")
543
+ parser.add_argument("--reasoning-effort", choices=["low", "medium", "high"], default=None, help="Requested reasoning effort")
544
+ parser.add_argument("--resume", action="store_true", help="Skip durably completed tasks from matching checkpoint")
545
+ parser.add_argument("--progress-interval", type=float, default=15, help="Stream heartbeat interval in seconds")
546
+ parser.add_argument("--api-timeout", type=float, default=120, help="API socket inactivity timeout in seconds")
547
 
548
  args = parser.parse_args()
549
  if args.concurrency < 1:
550
  parser.error("--concurrency must be >= 1")
551
+ if args.max_tokens < 1:
552
+ parser.error("--max-tokens must be >= 1")
553
+ if args.progress_interval <= 0 or args.api_timeout <= 0:
554
+ parser.error("progress interval and API timeout must be positive")
555
 
556
  # 1. System Prompt
557
  current_system_prompt = PROMPT_REGISTRY.get(args.prompt_type)
 
573
  if args.concurrency > 1 and args.verbose_response:
574
  print("[Warning] --verbose-response output may interleave when --concurrency > 1.")
575
 
576
+ output_filename = args.output or f"eval_result_{'DEBUG' if args.debug else args.model.replace('/', '_')}.json"
577
+ config = dict(model=args.model, api_base=args.api_base, max_tokens=args.max_tokens,
578
+ reasoning_effort=args.reasoning_effort, prompt_type=args.prompt_type,
579
+ system_prompt=current_system_prompt, max_retries=args.max_retries, debug=args.debug,
580
+ task_ids=[t['id'] for t in tasks])
581
+ checkpoint = CheckpointStore(output_filename, config, resume=args.resume)
582
+ args.events_path = str(checkpoint.directory / 'events.jsonl')
583
+ pending = [t for t in tasks if t['id'] not in checkpoint.results]
584
+ print(f"Checkpoint: {len(checkpoint.results)}/{len(tasks)} completed; {len(pending)} pending", flush=True)
585
+ run_task_batch(
586
+ pending,
587
  args.concurrency,
588
  lambda index, task: evaluate_task(task, args, current_system_prompt),
589
+ on_result=checkpoint.save,
590
  )
591
+ results = [checkpoint.results[t['id']] for t in tasks]
592
 
593
  # Summary
594
  total_score = sum(r['score'] for r in results)
 
631
  print(f"{'OVERALL':<15} | {len(results):<8} | {total_score:<10.2f} | {total_possible:<10.0f} | {weighted_acc:<9.2f}%")
632
  print("=" * 60)
633
 
634
+ atomic_json(output_filename, results)
 
 
635
  print(f"Results saved to {output_filename}")
636
 
637
  if __name__ == "__main__":
src/checkpoint.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Durable task results and stream heartbeats, independent of API credentials."""
2
+ import datetime
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+ import threading
7
+ import time
8
+
9
+
10
+ def atomic_json(path, value):
11
+ path = Path(path)
12
+ path.parent.mkdir(parents=True, exist_ok=True)
13
+ temporary = path.with_suffix(path.suffix + '.tmp')
14
+ with temporary.open('w', encoding='utf-8') as handle:
15
+ json.dump(value, handle, ensure_ascii=False, indent=2)
16
+ handle.flush()
17
+ os.fsync(handle.fileno())
18
+ os.replace(temporary, path)
19
+
20
+
21
+ class CheckpointStore:
22
+ def __init__(self, output, config, resume=False):
23
+ self.output = Path(output)
24
+ self.directory = Path(str(output) + '.checkpoint')
25
+ self.directory.mkdir(parents=True, exist_ok=True)
26
+ manifest = self.directory / 'config.json'
27
+ if manifest.exists():
28
+ if not resume:
29
+ raise ValueError('Checkpoint exists; use --resume or a new --output')
30
+ if json.loads(manifest.read_text(encoding='utf-8')) != config:
31
+ raise ValueError('Resume configuration does not match checkpoint')
32
+ else:
33
+ if self.output.exists():
34
+ raise ValueError('Output exists without a checkpoint; choose a new --output')
35
+ atomic_json(manifest, config)
36
+ self.ids = config['task_ids']
37
+ self.results = {}
38
+ for index, task_id in enumerate(self.ids):
39
+ path = self.directory / f'{index:04d}.json'
40
+ if path.exists():
41
+ result = json.loads(path.read_text(encoding='utf-8'))
42
+ if result['id'] != task_id:
43
+ raise ValueError('Checkpoint task ID mismatch')
44
+ self.results[task_id] = result
45
+
46
+ def save(self, result):
47
+ index = self.ids.index(result['id'])
48
+ atomic_json(self.directory / f'{index:04d}.json', result)
49
+ self.results[result['id']] = result
50
+ atomic_json(self.output, [self.results[k] for k in self.ids if k in self.results])
51
+
52
+
53
+ _event_lock = threading.Lock()
54
+
55
+
56
+ def append_event(path, event):
57
+ if path is None:
58
+ return
59
+ event = dict(event, timestamp=datetime.datetime.now().astimezone().isoformat())
60
+ with _event_lock:
61
+ with open(path, 'a', encoding='utf-8') as handle:
62
+ handle.write(json.dumps(event, ensure_ascii=False) + '\n')
63
+ handle.flush()
64
+ os.fsync(handle.fileno())
65
+
66
+
67
+ class StreamProgress:
68
+ def __init__(self, label, path=None, interval=15):
69
+ self.label = label
70
+ self.path = path
71
+ self.interval = interval
72
+ self.started = time.monotonic()
73
+ self.last_chunk = None
74
+ self.chunks = self.content_chars = self.reasoning_chars = 0
75
+ self.lock = threading.Lock()
76
+ self.stopped = threading.Event()
77
+ self.thread = threading.Thread(target=self._heartbeat, daemon=True)
78
+
79
+ def emit(self, phase):
80
+ with self.lock:
81
+ current = time.monotonic()
82
+ event = dict(label=self.label, phase=phase, elapsed_s=round(current - self.started, 1),
83
+ idle_s=round(current - (self.last_chunk or self.started), 1), chunks=self.chunks,
84
+ content_chars=self.content_chars, reasoning_chars=self.reasoning_chars)
85
+ print(f"[{self.label}] stream {phase}: elapsed={event['elapsed_s']}s idle={event['idle_s']}s "
86
+ f"chunks={event['chunks']} content_chars={event['content_chars']} reasoning_chars={event['reasoning_chars']}", flush=True)
87
+ append_event(self.path, event)
88
+
89
+ def start(self):
90
+ self.emit('connecting')
91
+ self.thread.start()
92
+
93
+ def received(self, content='', reasoning=''):
94
+ with self.lock:
95
+ self.chunks += 1
96
+ first = self.chunks == 1
97
+ self.last_chunk = time.monotonic()
98
+ self.content_chars += len(content or '')
99
+ self.reasoning_chars += len(reasoning or '')
100
+ if first:
101
+ self.emit('first_chunk')
102
+
103
+ def _heartbeat(self):
104
+ while not self.stopped.wait(self.interval):
105
+ self.emit('receiving')
106
+
107
+ def close(self):
108
+ self.stopped.set()
109
+ self.thread.join()
110
+ self.emit('closed')
tools/checkpoint_selftest.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from pathlib import Path
3
+ import sys
4
+ import tempfile
5
+ import time
6
+ import unittest
7
+
8
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
9
+ from src.checkpoint import CheckpointStore, StreamProgress
10
+ from run_eval import run_task_batch
11
+
12
+
13
+ class CheckpointSelfTest(unittest.TestCase):
14
+ def test_completed_task_survives_later_failure_and_resumes(self):
15
+ with tempfile.TemporaryDirectory() as temp:
16
+ output = Path(temp) / 'result.json'
17
+ config = {'task_ids': ['a', 'b'], 'max_tokens': 32768}
18
+ store = CheckpointStore(output, config)
19
+ def runner(index, task):
20
+ if task == 'b':
21
+ raise RuntimeError('interrupted')
22
+ return {'id': task, 'ratio': 1}
23
+ with self.assertRaises(RuntimeError):
24
+ run_task_batch(['a', 'b'], 1, runner, show_progress=False, on_result=store.save)
25
+ self.assertEqual(json.loads(output.read_text())[0]['id'], 'a')
26
+ resumed = CheckpointStore(output, config, resume=True)
27
+ pending = [t for t in config['task_ids'] if t not in resumed.results]
28
+ self.assertEqual(pending, ['b'])
29
+ run_task_batch(pending, 2, lambda i, t: {'id': t, 'ratio': 0.5}, show_progress=False, on_result=resumed.save)
30
+ self.assertEqual([r['id'] for r in json.loads(output.read_text())], ['a', 'b'])
31
+
32
+ def test_resume_rejects_changed_config_and_no_resume_overwrite(self):
33
+ with tempfile.TemporaryDirectory() as temp:
34
+ output = Path(temp) / 'result.json'
35
+ config = {'task_ids': ['a'], 'max_tokens': 32768}
36
+ CheckpointStore(output, config)
37
+ with self.assertRaises(ValueError):
38
+ CheckpointStore(output, config)
39
+ with self.assertRaises(ValueError):
40
+ CheckpointStore(output, dict(config, max_tokens=8192), resume=True)
41
+
42
+ def test_heartbeat_records_idle_and_stream_activity(self):
43
+ with tempfile.TemporaryDirectory() as temp:
44
+ events = Path(temp) / 'events.jsonl'
45
+ progress = StreamProgress('task attempt 1', events, interval=0.01)
46
+ progress.start()
47
+ try:
48
+ progress.received('abc', 'thinking')
49
+ time.sleep(0.04)
50
+ finally:
51
+ progress.close()
52
+ records = [json.loads(s) for s in events.read_text().splitlines()]
53
+ self.assertIn('receiving', [r['phase'] for r in records])
54
+ self.assertEqual(records[-1]['content_chars'], 3)
55
+ self.assertEqual(records[-1]['reasoning_chars'], 8)
56
+ self.assertEqual(records[-1]['chunks'], 1)
57
+
58
+
59
+ if __name__ == '__main__':
60
+ unittest.main(verbosity=2)
tools/response_selftest.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from pathlib import Path
3
+ from types import SimpleNamespace
4
+ import sys
5
+ import unittest
6
+ from unittest.mock import Mock
7
+
8
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
9
+ from run_eval import extract_json, run_chat_completion
10
+
11
+
12
+ class ResponseSelfTest(unittest.TestCase):
13
+ def test_nested_bare_json_with_escaped_strings(self):
14
+ model = {'points': [{'id': 'P1', 'label': 'a } { " \\ b'}], 'links': [], 'supports': [], 'loads': []}
15
+ text = json.dumps(model)
16
+ self.assertEqual(json.loads(extract_json(text)), model)
17
+ self.assertEqual(json.loads(extract_json('Answer:\n' + text + '\nDone.')), model)
18
+
19
+ def test_existing_wrappers(self):
20
+ text = '{"points": [{"id": "P1"}], "links": []}'
21
+ for wrapped in [f'<json>{text}</json>', f'```json\n{text}\n```', f'```\n{text}\n```', f'<|begin_of_box|>{text}<|end_of_box|>']:
22
+ self.assertEqual(extract_json(wrapped), text)
23
+
24
+ def test_no_json(self):
25
+ self.assertIsNone(extract_json('No answer'))
26
+
27
+ def test_stream_records_reasoning_limit_and_usage(self):
28
+ client = Mock()
29
+ usage = Mock()
30
+ usage.model_dump.return_value = {'completion_tokens': 32768}
31
+ client.chat.completions.create.return_value = [
32
+ SimpleNamespace(usage=None, choices=[SimpleNamespace(finish_reason=None, delta=SimpleNamespace(content=None, reasoning_content='thinking'))]),
33
+ SimpleNamespace(usage=None, choices=[SimpleNamespace(finish_reason='length', delta=SimpleNamespace(content=None))]),
34
+ SimpleNamespace(usage=usage, choices=[]),
35
+ ]
36
+ metadata = {}
37
+ self.assertEqual(run_chat_completion(client, 'model', [], max_tokens=32768, metadata=metadata, reasoning_effort='high'), '')
38
+ self.assertEqual(metadata['finish_reason'], 'length')
39
+ self.assertEqual(metadata['reasoning_chars'], 8)
40
+ self.assertEqual(metadata['usage']['completion_tokens'], 32768)
41
+ self.assertEqual(client.chat.completions.create.call_args.kwargs['max_tokens'], 32768)
42
+ self.assertEqual(client.chat.completions.create.call_args.kwargs['reasoning_effort'], 'high')
43
+
44
+ def test_api_exception_is_distinct_from_empty_response(self):
45
+ client = Mock()
46
+ client.chat.completions.create.side_effect = RuntimeError('test failure')
47
+ metadata = {}
48
+ self.assertIsNone(run_chat_completion(client, 'model', [], metadata=metadata))
49
+ self.assertEqual(metadata['error'], 'test failure')
50
+
51
+
52
+ if __name__ == '__main__':
53
+ unittest.main(verbosity=2)
tools/run_pair.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run both models concurrently; restart interrupted workers from task checkpoints."""
2
+ import argparse
3
+ from collections import Counter
4
+ import datetime
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ import runpy
9
+ import subprocess
10
+ import sys
11
+ import time
12
+
13
+ ROOT = Path(__file__).resolve().parents[1]
14
+ sys.path.insert(0, str(ROOT))
15
+ from src.checkpoint import atomic_json
16
+
17
+ MODELS = ['neolink/deepseek-v4.1-flash', 'neolink/glm-5.3-flash']
18
+
19
+
20
+ def now():
21
+ return datetime.datetime.now().astimezone().isoformat()
22
+
23
+
24
+ def main():
25
+ parser = argparse.ArgumentParser()
26
+ parser.add_argument('--run-dir', required=True)
27
+ parser.add_argument('--worker', choices=MODELS)
28
+ args = parser.parse_args()
29
+ run = Path(args.run_dir).resolve()
30
+ run.mkdir(parents=True, exist_ok=True)
31
+ os.chdir(ROOT)
32
+ if args.worker:
33
+ output = run / ('eval_result_' + args.worker.replace('/', '_') + '.json')
34
+ sys.argv = [str(ROOT / 'run_eval.py'), '--model', args.worker,
35
+ '--api-base', 'https://vnet.neolink.com/api/v1',
36
+ '--api-key', os.environ['STRUCTURAL_EVAL_API_KEY'],
37
+ '--concurrency', '8', '--max-retries', '2', '--max-tokens', '32768',
38
+ '--reasoning-effort', 'high', '--output', str(output), '--resume',
39
+ '--progress-interval', '15', '--api-timeout', '120']
40
+ runpy.run_path(str(ROOT / 'run_eval.py'), run_name='__main__')
41
+ return
42
+
43
+ state = dict(started_at=now(), launcher_pid=os.getpid(), max_tokens=32768,
44
+ reasoning_effort='high', concurrency_per_model=8, models=[])
45
+ processes = {}
46
+ def launch(model, entry):
47
+ log_path = run / (model.replace('/', '_') + '.log')
48
+ with log_path.open('a', encoding='utf-8') as log:
49
+ log.write(f'\n=== launch {now()} (resume enabled) ===\n')
50
+ log.flush()
51
+ process = subprocess.Popen([sys.executable, '-u', str(Path(__file__).resolve()),
52
+ '--run-dir', str(run), '--worker', model],
53
+ stdout=log, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL)
54
+ processes[model] = process
55
+ entry.update(pid=process.pid, status='running', log=str(log_path))
56
+ for model in MODELS:
57
+ entry = dict(model=model, restarts=0, started_at=now())
58
+ state['models'].append(entry)
59
+ launch(model, entry)
60
+ while True:
61
+ active = False
62
+ for entry in state['models']:
63
+ model = entry['model']
64
+ output = run / ('eval_result_' + model.replace('/', '_') + '.json')
65
+ if output.exists():
66
+ results = json.loads(output.read_text(encoding='utf-8'))
67
+ entry['completed_tasks'] = len(results)
68
+ entry['result'] = str(output)
69
+ entry['reasons'] = dict(Counter(r['reason'] for r in results))
70
+ entry['weighted_accuracy_on_completed'] = 100 * sum(r['score'] for r in results) / sum(r['difficulty'] for r in results) if results else 0
71
+ code = processes[model].poll()
72
+ if code is None:
73
+ active = True
74
+ elif entry['status'] == 'running':
75
+ if code != 0 and entry['restarts'] < 2:
76
+ entry['restarts'] += 1
77
+ launch(model, entry)
78
+ active = True
79
+ else:
80
+ entry.update(exit_code=code, finished_at=now(),
81
+ status='completed' if code == 0 and entry.get('completed_tasks') == 25 else 'failed')
82
+ state['updated_at'] = now()
83
+ if not active:
84
+ state['finished_at'] = now()
85
+ atomic_json(run / 'status.json', state)
86
+ if not active:
87
+ if any(e['status'] != 'completed' for e in state['models']):
88
+ raise SystemExit(1)
89
+ break
90
+ time.sleep(15)
91
+
92
+
93
+ if __name__ == '__main__':
94
+ main()