File size: 49,040 Bytes
cc1c573
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
#!/usr/bin/env python3
"""Mixed-pool DP evaluation for PaddleOCR-VL table recognition.

* K vLLM servers per GPU x G GPUs (DP = number of GPUs, K workers each).
* All cohorts are merged into one pool and interleaved, so every worker sees a
  mix of datasets instead of finishing one dataset before the next.
* Samples are pre-assigned to workers with greedy LPT on image pixel count, so
  each worker's total image resolution is about the same.
* Scoring overlaps inference: finished predictions are batched and scored by a
  ProcessPool (TEDS is ~n^3, so it needs many CPU workers) while inference
  continues. TEDS == 1 implies TEDS-S == 1.

Usage:
  eval_mix.py --model DIR --tag TAG --cohorts gate_pub_icdar gate_val_eval10k ...
"""
import argparse
import base64
import heapq
import json
import os
import pyarrow.parquet as pq
import queue
import random
import signal
import subprocess
import sys
import threading
import time
import urllib.request
from collections import defaultdict
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

V5 = "/autodl-fs/data/povl_v5"
sys.path.insert(0, "/autodl-fs/data/povl_optimization/protocol")
import canonical_teds as ct  # noqa: E402
from evaluation_policy import filter_evaluation,row_is_excluded,policy as evaluation_policy
from fullpage_evaluation_policy import filter_pack_rows,route_existing_curriculum

# 默认用**本地盘**的 vllm(2026-10-25): /autodl-fs 是网络盘,
# `import vllm` 实测 175 秒(其中 CPU 只有 19 秒 -> 89% 是 I/O 等待);
# 拷到本地 xfs 后只要 44 秒, 12 个 engine 一起起 14分47秒 -> 2分34秒。
_LOCAL_VLLM = "/root/autodl-tmp/vllm_local/bin/vllm"
VLLM = os.environ.get("POVL_VLLM",
                      _LOCAL_VLLM if os.path.exists(_LOCAL_VLLM)
                      else "/autodl-fs/data/vllm_env/bin/vllm")
PROMPT = "Table Recognition:"


def log(m):
    print(f"[{time.strftime('%m-%d %H:%M:%S')}] {m}", flush=True)


def apply_run_parallel_config(args):
    """Reload this run's evaluation layout at each invocation.

    Allows the active training controller to keep running while the next
    evaluation adopts the user's updated multi-instance configuration.
    Runs without this opt-in file retain their existing CLI behaviour.
    """
    root = os.environ.get('POVL_RUN_DIR')
    path = os.path.join(root, 'eval_parallel.json') if root else ''
    if not path or not os.path.isfile(path):
        return args
    with open(path, encoding='utf-8') as f:
        config = json.load(f)
    for key in ('per_gpu', 'conc_per_worker', 'score_workers'):
        value = config.get(key, getattr(args, key))
        if not isinstance(value, int) or isinstance(value, bool) or value <= 0:
            raise ValueError(f'Invalid evaluation parallel setting {key}={value!r}')
        setattr(args, key, value)
    log(f'Evaluation layout: {len(args.gpus)} GPUs x {args.per_gpu} vLLM instances '
        f'= {len(args.gpus) * args.per_gpu}; concurrency/instance={args.conc_per_worker}; '
        f'score_workers={args.score_workers}; config={path}')
    return args


# ----------------------------------------------------------------------------
# scoring
# ----------------------------------------------------------------------------
def _score_one_raw_impl(job):
    """消融路径: 不抽表格, 直接把模型原始输出丢进 TEDS。"""
    sid, pred, gt, gt_fmt = job
    out = {"sample_id": sid}
    if not isinstance(pred, str) or not pred.strip():
        out.update(teds=0.0, teds_s=0.0, status="empty")
        return out
    try:
        res = ct.score_pair(pred, gt, "otsl", gt_fmt)
    except Exception as e:
        out.update(teds=0.0, teds_s=0.0, status=f"score_exc:{type(e).__name__}")
        return out
    if res.get("status") == "metric_oversize":
        out.update(teds=0.0, teds_s=0.0, status="pred_oversize")
        return out
    if res.get("status") == "gt_error":
        out.update(teds=None, teds_s=None, status="gt_error")
        return out
    t, s = res["teds"], res["teds_structure"]
    if t is not None and t >= 1.0:
        s = 1.0
    out.update(teds=t, teds_s=s, status=res["status"])
    # 空 cell 表按用户定的口径以 TEDS 为准, 常规表以 TEDS-S 为准;
    # 汇报时按 primary_metric 分开, 不要把两种口径混在一张表里排序
    for k in ("gt_fill_ratio", "gt_structure_only", "primary_metric", "primary"):
        if k in res:
            out[k] = res[k]
    return out


def _score_one_impl(job):
    sid, pred, gt, gt_fmt = job
    out = {"sample_id": sid}
    if not isinstance(pred, str) or not pred.strip():
        out.update(teds=0.0, teds_s=0.0, status="empty")
        return out
    # 抽表格本体再算分: 模型被喂整页图时可能把页眉/正文一起吐出来, 那些不该进 TEDS。
    # prose_frac 同时是诊断量 —— 它直接说明模型是在读表还是在复述整页。
    #
    # fmt=None 自动识别方言。这里**不能**像以前那样硬编码 "otsl": 模型有时会吐
    # HTML, 那样 extract_table 会返回空 -> 直接判 0 分(实测自检 243/300 失败)。
    # 识别之后再把预测与 GT 统一归一到 canonical HTML, 两边同方言再比,
    # 消除 OTSL/HTML 的口径错配。
    try:
        pred_t, info = ct.extract_table(pred, None)
    except Exception as e:
        out.update(teds=0.0, teds_s=0.0, status=f"extract_exc:{type(e).__name__}")
        return out
    out.update(extracted_format=info["format"], prose_frac=info["prose_frac"])
    if not pred_t:
        out.update(teds=0.0, teds_s=0.0, status=f"no_table:{info['format']}")
        return out
    try:
        pred_html = ct.cells_to_canonical_html(ct.parse_table(pred_t, info["format"]))
        gt_html = ct.cells_to_canonical_html(ct.parse_table(gt, gt_fmt))
        res = ct.score_pair(pred_html, gt_html, "html", "html")
    except Exception as e:  # never let one pathological sample kill a batch
        out.update(teds=0.0, teds_s=0.0, status=f"score_exc:{type(e).__name__}")
        return out
    st = res.get("status")
    if st == "metric_oversize":
        try:
            g = ct.count_tree_nodes(ct.parse_table(gt_html, "html"))
        except Exception:
            g = 10 ** 9
        if g <= 4000:  # GT is scoreable; the prediction blew up -> model failure
            out.update(teds=0.0, teds_s=0.0, status="pred_oversize")
        else:
            out.update(teds=None, teds_s=None, status="gt_oversize")
        return out
    if st == "gt_error":
        out.update(teds=None, teds_s=None, status="gt_error")
        return out
    t, s = res["teds"], res["teds_structure"]
    if t is not None and t >= 1.0:
        s = 1.0
    out.update(teds=t, teds_s=s, status=st,
               merge_f1=res.get("merged_rect_f1"))
    return out


# ----------------------------------------------------------------------------
# servers
# ----------------------------------------------------------------------------
def gpu_free_bytes(gpu: int) -> int:
    """查某张卡的空闲显存; 查不到就返回一个保守估计。"""
    try:
        out = subprocess.check_output(
            ["nvidia-smi", "-i", str(gpu),
             "--query-gpu=memory.free", "--format=csv,noheader,nounits"],
            timeout=20)
        return int(out.decode().strip().splitlines()[0]) * 1024 ** 2
    except Exception:
        return 40 * 10 ** 9


def plan_workers(gpus, per_gpu_hint: int, util: float, reserve: float = 0.10):
    """按每卡空闲显存决定每卡几个 vLLM worker。

    规则(用户 2026-10-18): 每卡 2-4 个 worker, 按 gpu_memory_utilization 算,
    且**worker 往大来** —— 显存够就顶满 4 个, 不够再往下退, 低于 2 就退到 1。
    真正的 KV 预算在 start_servers 里按 util/per_gpu 再分一次。
    """
    need = 4 * 10 ** 9          # 每个 engine 的模型权重 + 激活 + 一点 KV
    plan = []
    for g in gpus:
        free = gpu_free_bytes(g)
        budget = int(free * (1 - reserve))
        n = max(1, min(per_gpu_hint, budget // need))
        plan.append((g, n, free))
    return plan


# 方案2(2026-10-25): 下一个模型的 engine 在**当前模型还在打分**的时候预启动。
# 打分是纯 CPU 的(TEDS 编辑距离), 那 10 分钟 GPU 完全闲着; 而开机要 6~14 分钟。
# 预启动的 engine 用标记文件记录"端口 -> 模型路径 + pid", 下一个 eval_mix
# 发现自己要的端口上已经有**同一个模型**的 engine 在跑, 就直接复用。
PREBOOT_MARK = "/root/autodl-tmp/preboot_marks"


class AdoptedProc:
    """占位: 复用的 engine 不是本进程起的, 但仍要负责在最后把它杀掉。

    预启动时用了 start_new_session=True, 所以它自己是进程组组长,
    os.killpg(pid) 能整组收掉。
    """

    def __init__(self, pid):
        self.pid = pid
        self._alive = True

    def poll(self):
        return None if self._alive else 0

    def kill(self):
        self._alive = False


def _port_alive(port, timeout=3):
    try:
        urllib.request.urlopen(f"http://127.0.0.1:{port}/v1/models", timeout=timeout)
        return True
    except Exception:
        return False


def _read_mark(port):
    p = os.path.join(PREBOOT_MARK, f"{port}.json")
    try:
        with open(p) as f:
            return json.load(f)
    except Exception:
        return None


def start_servers(model, gpus, per_gpu, base_port, gmu, max_len, logdir, served,
                  adopt=True, wait=True):
    procs = []
    ready = []

    # --- 预热 trust_remote_code 的动态模块 -----------------------------------
    # PaddleOCR-VL 的 config/processor 是 trust_remote_code 的自定义类, transformers
    # 会把它**复制**到 ~/.cache/huggingface/modules/transformers_modules/<name>/<hash>/
    # 再 import。N 个 vLLM 进程同时做这件事时会互相踩: 有一次 12 个 engine 里
    # 最后一个报 "module ... has no attribute 'PaddleOCRVLImageProcessor'"
    # (复制到一半就被另一个进程读走)。所以先在父进程里 import 一次,
    # 让缓存目录被完整写好, 后面所有 engine 直接命中缓存。
    try:
        from transformers import AutoConfig, AutoProcessor  # noqa: F401
        AutoConfig.from_pretrained(model, trust_remote_code=True)
        try:
            AutoProcessor.from_pretrained(model, trust_remote_code=True)
        except Exception as e:
            log(f"  预热 processor 失败(忽略): {type(e).__name__} {str(e)[:120]}")
    except Exception as e:
        log(f"  预热动态模块失败(忽略): {type(e).__name__} {str(e)[:120]}")

    def wait_ready(p, port, budget=1800):
        deadline = time.time() + budget
        while True:
            if p.poll() is not None:
                return False
            try:
                urllib.request.urlopen(
                    f"http://127.0.0.1:{port}/v1/models", timeout=5)
                return True
            except Exception:
                if time.time() > deadline:
                    return False
                time.sleep(3)

    def tail(fh, n=25):
        try:
            fh.flush()
            with open(fh.name) as f:
                return "".join(f.readlines()[-n:])
        except Exception:
            return ""

    # 同卡上第 N 个 engine 要给剩下的显存, 不是给"整卡空闲显存"。
    # 之前所有 worker 都用同一个 gmu, 第 4 个起来时卡上已被前 3 个占了 ~67GB,
    # 只剩 11.9GB < 它要的 21GB -> "Free memory ... less than desired"。
    TOTAL_BYTES = gpu_free_bytes(gpus[0])
    TOTAL_GIB = TOTAL_BYTES / (1024 ** 3) or 94.0
    # (2026-10-24) **并行起 engine**。
    # vllm 0.32 起一个 engine 要 2~4 分钟(import + 权重 + inductor 编译 +
    # CUDA graph 捕获), 串行起 8 个要 ~30 分钟, 5 个模型就是 2.5 小时纯开机。
    # 并行起不会互相踩: 每个 engine 的显存预算 this_gmu 是**固定**的
    # (TOTAL_BYTES*0.36/per_gpu, 不随"当前空闲"变), 同卡 2 个 engine 共占
    # ~37G(KV 15G x2 + 权重 2.5G x2 + context) < 85G。
    # 设 POVL_PARALLEL_ENGINE_BOOT=0 可退回原来的串行行为。
    PARALLEL_BOOT = os.environ.get("POVL_PARALLEL_ENGINE_BOOT", "1") != "0"
    specs = []
    for gi, g in enumerate(gpus):
        for w in range(per_gpu):
            specs.append((g, w, base_port + gi * per_gpu + w))
    for (g, w, port) in specs:
        # --- 方案2: 端口上已经有**同一个模型**的 engine(预启动的) -> 直接复用 ---
        if adopt:
            m = _read_mark(port)
            if m and m.get("model") == model and m.get("pid") and _port_alive(port):
                log(f"  复用预启动的 engine :{port} ({model})")
                procs.append((AdoptedProc(m["pid"]), None, port))
                ready.append(port)
                continue
        # 现在这张卡真正还剩多少(前面几个 engine 已经占掉了), 按比例分配。
        # gmu 是 0~1 的比例, 不是字节。
        # 固定预算, 不做动态探测。vllm 在启动瞬间检查显存, 而同卡上一个
        # engine 那时还在分配中, 按"当前空闲"算必然偏大 -> 第二个就报
        # "Free memory ... less than desired"。模型只有 1.9G, 每 engine
        # 分 total/per_gpu 就够, 剩下的全给 KV cache。
        this_gmu = int(TOTAL_BYTES * 0.36 / per_gpu)   # KV cache 字节
        # 实测一个 engine 实际吃 ~17.5G(KV + 1.9G 权重 + CUDA context)
        env = dict(os.environ, CUDA_VISIBLE_DEVICES=str(g),
                   # 不要设 VLLM_ATTENTION_BACKEND: 一旦显式指定, vllm 会
                   # 绕开 paddlex 的 PaddleOCR-VL 插件、退回
                   # TransformersForCausalLM 回退路径, 而那条路径不认识
                   # 顶层模块 mlp_AR -> "no module or parameter named
                   # 'mlp_AR'". 让插件自己选 backend(它内部会选
                   # FLASH_ATTN, 用的是我们本地源码编译的 flash_attn)。
                   VLLM_USE_FLASHINFER_SAMPLER="0",
                   OMP_NUM_THREADS="2", MKL_NUM_THREADS="2")
        # vLLM 子进程必须用 **vllm_env 自己的 transformers(5.x)**:
        # transformers 4.57 把 PreTrainedConfig 改名成 PretrainedConfig(少个 T),
        # vllm 0.32 里 `from transformers import PreTrainedConfig` 会 ImportError。
        # 训练用的 venv_train 若排在 PYTHONPATH 前面就会踩到 -> 把那截摘掉。
        _pp = [p for p in (env.get("PYTHONPATH") or "").split(os.pathsep)
               if p and "venv_train" not in p]
        env["PYTHONPATH"] = os.pathsep.join(_pp)
        cmd = [VLLM, "serve", model, "--port", str(port),
               "--served-model-name", served,
               "--max-model-len", str(max_len),
               # 两个都得给: 只给 kv-cache-memory 的话, vllm 仍用默认
               # gpu_memory_utilization=0.9 做启动校验 -> 同卡第二三个 engine
               # 必然 "Free memory ... less than desired"。
               "--kv-cache-memory", str(this_gmu),
               "--gpu-memory-utilization", str(round(0.86 / per_gpu, 3)),
               # 必须 >= max_model_len, 否则新版 vllm 直接拒绝启动
               "--max-num-batched-tokens", str(max(16384, max_len * 2)),
               "--max-num-seqs", "128",
               "--no-enable-prefix-caching", "--mm-processor-cache-gb", "0"]
        if os.environ.get("POVL_TRC", "1") == "1":
            cmd.append("--trust-remote-code")
        if os.environ.get('POVL_ALLOW_TRUSTED_MM_KWARGS')=='1':
            # Official PaddleOCR clients send per-request pixel budgets. This
            # opt-in route only serves trusted local benchmark workers.
            cmd+=['--trust-request-mm-kwargs','--host','127.0.0.1']
        fh = open(f"{logdir}/vllm_g{g}_w{w}.log", "w")
        p = subprocess.Popen(cmd, env=env, stdout=fh, stderr=subprocess.STDOUT,
                             start_new_session=True)
        procs.append((p, fh, port))
        if not PARALLEL_BOOT:
            # 串行模式: 每个起来就单独等它就绪, 这样挂了能立刻定位到是哪个,
            # 也不会连坐杀掉已就绪的实例。
            if not wait_ready(p, port):
                log(f"  vLLM :{port} 启动失败\n{tail(fh)}")
                stop_servers(procs)
                raise RuntimeError(f"vLLM :{port} failed to start; see {logdir}")
    for (g, w, port), (p, fh, _pp) in zip(specs, procs):
        if not wait_ready(p, port):
            log(f"  vLLM :{port} 启动失败\n{tail(fh)}")
            stop_servers(procs)
            raise RuntimeError(f"vLLM :{port} failed to start; see {logdir}")
        ready.append(port)
        log(f"  vLLM :{port} ready ({len(ready)}/{len(gpus)*per_gpu}, "
            f"卡{g} 剩 {gpu_free_bytes(g)/(1024**3):.0f}G)")
        time.sleep(1)
    log(f"{len(procs)} vLLM servers ready on {sorted(gpus)}")
    return procs


def stop_servers(procs):
    for p, _, _ in procs:
        if p.poll() is None:
            try:
                os.killpg(p.pid, signal.SIGTERM)
            except ProcessLookupError:
                pass
    t = time.time() + 30
    while time.time() < t and any(p.poll() is None for p, _, _ in procs):
        time.sleep(0.5)
    for p, fh, _ in procs:
        if p.poll() is None:
            try:
                os.killpg(p.pid, signal.SIGKILL)
            except ProcessLookupError:
                pass
        if fh is not None:          # 复用的 engine 没有日志句柄
            fh.close()


def preboot_servers(model, gpus, per_gpu, base_port, gmu, max_len, logdir, served):
    """**后台**起一批 engine, 不等它们就绪, 直接返回。

    用途(方案2): 当前模型推理结束、engine 已停掉、GPU 空着, 但打分还要跑
    10 分钟(CPU 密集)。这段时间把**下一个模型**的 engine 起好, 下一个
    eval_mix 直接复用, 就省掉了 6~14 分钟的串行开机。

    标记文件 PREBOOT_MARK/<port>.json 记着 "端口 -> 模型 + pid",
    start_servers 的复用逻辑靠它判断"这个端口上的 engine 是不是我要的模型"。
    """
    os.makedirs(PREBOOT_MARK, exist_ok=True)
    specs = []
    for gi, g in enumerate(gpus):
        for w in range(per_gpu):
            specs.append((g, w, base_port + gi * per_gpu + w))
    total_bytes = gpu_free_bytes(gpus[0])
    this_gmu = int(total_bytes * 0.36 / per_gpu)
    env = dict(os.environ, VLLM_USE_FLASHINFER_SAMPLER="0",
               OMP_NUM_THREADS="2", MKL_NUM_THREADS="2")
    _pp = [p for p in (env.get("PYTHONPATH") or "").split(os.pathsep)
           if p and "venv_train" not in p]
    env["PYTHONPATH"] = os.pathsep.join(_pp)
    for (g, w, port) in specs:
        # 旧的标记先清掉, 免得被误当成"已经就绪"
        for f in (os.path.join(PREBOOT_MARK, f"{port}.json"),):
            try:
                os.remove(f)
            except OSError:
                pass
        # 等端口空出来(上一个模型的 engine 刚被 kill, socket 可能还在 TIME_WAIT;
        # 不等的话新 engine 会 "Address already in use" 直接死 —— 2026-10-26 踩过)
        import socket as _socket
        for _ in range(60):
            _s = _socket.socket()
            _s.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, 1)
            try:
                _s.bind(("127.0.0.1", port))
                _s.close()
                break
            except OSError:
                _s.close()
                time.sleep(1)
        cmd = [VLLM, "serve", model, "--port", str(port),
               "--served-model-name", served,
               "--max-model-len", str(max_len),
               "--kv-cache-memory", str(this_gmu),
               "--gpu-memory-utilization", str(round(0.86 / per_gpu, 3)),
               "--max-num-batched-tokens", str(max(16384, max_len * 2)),
               "--max-num-seqs", "128",
               "--no-enable-prefix-caching", "--mm-processor-cache-gb", "0"]
        if os.environ.get("POVL_TRC", "1") == "1":
            cmd.append("--trust-remote-code")
        os.makedirs(logdir, exist_ok=True)
        fh = open(os.path.join(logdir, f"preboot_g{g}_w{w}.log"), "w")
        e = dict(env, CUDA_VISIBLE_DEVICES=str(g))
        p = subprocess.Popen(cmd, env=e, stdout=fh, stderr=subprocess.STDOUT,
                             start_new_session=True)
        with open(os.path.join(PREBOOT_MARK, f"{port}.json"), "w") as mf:
            json.dump({"model": model, "pid": p.pid, "port": port}, mf)
        log(f"  预启动 engine :{port} (pid {p.pid}) <- {model}")


# ----------------------------------------------------------------------------
# load balancing
# ----------------------------------------------------------------------------
def _apply_text_metric_eligibility(job, result):
    # Keep TEDS=N/A for empty-text GT even on early prediction failures.
    try:
        tbl=ct.parse_table(job[2],job[3])
        so=ct.is_structure_only_gt(tbl)
        result['gt_structure_only']=so
        result['gt_fill_ratio']=ct.gt_fill_ratio(tbl)
        result['primary_metric']='teds_s'
        if so:result['teds']=None
        result['primary']=result.get('teds_s')
    except Exception:
        result.update(teds=None,teds_s=None,status='gt_error')
    return result

def score_one(job):
    return _apply_text_metric_eligibility(job,_score_one_impl(job))

def score_one_raw(job):
    return _apply_text_metric_eligibility(job,_score_one_raw_impl(job))

def apply_gt_override(rows, path):
    """用外部 GT 覆盖表替换 rows 里的 gt/gt_format。返回覆盖条数。

    匹配键: 先试 pack 的上游 id(rows[i]["_orig_id"]), 再试 (cohort, sample_id)。
    两种键都支持, 因为有些包带上游 id, 有些不带。
    """
    ov = {}
    for line in open(path, encoding="utf-8"):
        line = line.strip()
        if not line:
            continue
        d = json.loads(line)
        gt = d.get("gt")
        if not gt:
            continue
        ov[d["sample_id"]] = (gt, d.get("gt_format") or "otsl")
    n = 0
    for r in rows:
        for key in (r.get("_orig_id"), r.get("sample_id")):
            if key and key in ov:
                gt, fmt = ov[key]
                r["gt"], r["gt_format"] = gt, fmt
                n += 1
                break
    return n


def load_from_packs(pack_root, cohorts=None):
    """从 parquet shards 读评测行。

    与 cohort jsonl 路径产出同构的 row dict, 区别只有:
      image  = (shard, row_group, idx) 定位符, 由 _infer 惰性解析
      gt/gt_format 取自 gt_format_native 指向的那一份
        (OTSL->HTML 是有损方向, 见 eval_pack.otsl_roundtrip_ok)
    """
    import eval_pack_reader as epr
    epr.PACK_ROOT = pack_root
    rows = []
    for shard in epr.shard_files(pack_root):
        for rg, idx, meta, sid in epr.index_rows(shard, pack_root):
            if not meta.get("has_image"):
                continue  # 缺图行无法推理
            if cohorts and meta.get("cohort") not in cohorts:
                continue
            r = dict(meta)
            r["_cohort"] = meta.get("cohort")
            r["_shard"] = shard
            # 永远用 (shard, rg, idx) 合成 id, 不要用上游的 sample_id:
            # 84% 的行上游 id 是空的, 且少数 id 有重复(同一页面被切成多块),
            # 跨 pack join / bad-case 回溯都要靠这个唯一定位。
            # 保留上游 id 到 _orig_id 以便对照。
            r["_orig_id"] = sid
            r["sample_id"] = meta.get("canonical_sample_id") or f"{os.path.basename(shard)}#{rg}#{idx}"
            r["image"] = (shard, rg, idx)
            native = meta.get("gt_format_native") or "otsl"
            r["gt"] = meta["gt_otsl"] if native == "otsl" else meta["gt_html"]
            r["gt_format"] = native
            r["_px"] = meta["img_w"] * meta["img_h"]   # 宽高已是列, 无需解码
            rows.append(r)
    return filter_pack_rows(filter_evaluation(rows))


def image_pixels(path, row=None):
    """像素量, 供 lpt_assign 做负载均衡。

    parquet 行直接用 img_w/img_h 列, 不解码。
    注意: 这里**不能**像以前那样 except: return 0 —— 静默的 0 会让 LPT 权重
    全零、负载均衡无声失效, 而且不会报任何错。解不开就抛。
    """
    if isinstance(path, tuple):
        if row is not None and row.get("img_w"):
            return row["img_w"] * row["img_h"]
        return 1  # 缺图行(缺图的行本就该被过滤掉)
    from PIL import Image
    with Image.open(path) as im:
        w, h = im.size
    return w * h


def lpt_assign(rows, n_workers):
    """Greedy LPT on pixel count; return per-worker lists (each mixed-shuffled)."""
    order = sorted(range(len(rows)), key=lambda i: -rows[i]["_px"])
    heap = [(0, w) for w in range(n_workers)]
    buckets = [[] for _ in range(n_workers)]
    for i in order:
        load, w = heapq.heappop(heap)
        buckets[w].append(rows[i])
        heapq.heappush(heap, (load + rows[i]["_px"], w))
    rng = random.Random(0)
    for b in buckets:
        rng.shuffle(b)  # mix datasets and sizes within each worker
    return buckets


# ----------------------------------------------------------------------------
# inference
# ----------------------------------------------------------------------------
def shard_work_units(rows, n_workers):
    """把 rows 按 shard 聚成"工作单元", 按像素量降序。

    动态调度(而不是静态切桶)的前提: 每个单元必须能独立完成。
    单元按成本降序进队列, worker 领完一个跑完再去领下一个 ——
    领用本身是独占的(Queue.get), 所以不会出现两个 worker 抢同一片。
    """
    by = {}
    for r in rows:
        by.setdefault(r["_shard"], []).append(r)
    units = [(sum(x["_px"] for x in rs), sh, rs) for sh, rs in by.items()]
    units.sort(key=lambda t: -t[0])          # 贵的先领, 避免长尾
    log(f"  工作单元: {len(units)} 个 shard (按像素量降序), workers={n_workers}")
    return units


def infer(port, row, max_tokens, served, timeout, penalties=None):
    try:
        return _infer(port, row, max_tokens, served, timeout, penalties)
    except Exception as e:
        return {"prediction": "", "finish_reason": "error", "error": f"{type(e).__name__}: {e}"[:300]}


def _infer(port, row, max_tokens, served, timeout, penalties=None):
    # row["image"] 可能是散图路径, 也可能是 parquet 定位符 (shard, rg, idx)。
    # 定位符必须在这里才解析成字节 —— 见 eval_pack_reader 的模块说明。
    loc = row["image"]
    if isinstance(loc, tuple):
        import eval_pack_reader as epr
        raw = epr.image_bytes(*loc)
        # 从字节流探测, 不靠 img_format 列 —— reshard 的 pack 里没有这一列,
        # 靠它判会把所有 PNG 误标成 jpeg, vllm 解码失败 -> 每条都 error
        mime = ("image/png" if raw[:8] == b"\x89PNG\r\n\x1a\n"
                else "image/jpeg")
    else:
        mime = "image/png" if loc.lower().endswith(".png") else "image/jpeg"
        raw = open(loc, "rb").read()
    b64 = base64.b64encode(raw).decode()
    body = {"model": served, "temperature": 0, "max_tokens": max_tokens,
            "skip_special_tokens": False,
            # 复读惩罚(2026-10-21): 贪心解码下模型有时会陷进复读循环,
            # 一路生成到 max_tokens(16384) —— 推理时间全耗在这上面, 而且
            # 这些样本的分数基本是 0。vLLM 的 repetition_penalty>1 可以在
            # 出现重复时压低对应 token 的 logits, 让它换一条路。
            **(penalties or {}),
            "messages": [{"role": "user", "content": [
                {"type": "image_url", "image_url": {"url": f"data:{mime};base64,{b64}"}},
                {"type": "text", "text": PROMPT}]}]}
    req = urllib.request.Request(f"http://127.0.0.1:{port}/v1/chat/completions",
                                 data=json.dumps(body).encode(),
                                 headers={"Content-Type": "application/json"})
    t0 = time.time()
    for attempt in range(3):
        try:
            r = json.loads(urllib.request.urlopen(req, timeout=timeout).read())
            ch = r["choices"][0]
            return {"prediction": ch["message"]["content"] or "",
                    "finish_reason": ch.get("finish_reason"),
                    "completion_tokens": r.get("usage", {}).get("completion_tokens"),
                    "latency": round(time.time() - t0, 2)}
        except Exception as e:
            err = f"{type(e).__name__}: {e}"
            time.sleep(2 * (attempt + 1))
    return {"prediction": "", "finish_reason": "error", "error": err[:300]}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--model", required=True)
    ap.add_argument("--tag", required=True)
    ap.add_argument("--cohorts", nargs="*", default=[],
                    help="只跑这些 cohort; 留空 = 全跑(packs 模式下 benchmark 即 cohort)")
    ap.add_argument("--gpus", nargs="+", type=int, default=list(range(8)))
    ap.add_argument("--per-gpu", type=int, default=4)
    ap.add_argument("--gmu", type=float, default=0.0, help="0 = auto (0.92/per_gpu)")
    ap.add_argument("--conc-per-worker", type=int, default=24)
    ap.add_argument("--score-workers", type=int, default=96)
    ap.add_argument("--score-batch", type=int, default=256)
    ap.add_argument("--max-tokens", type=int, default=16384)
    ap.add_argument("--repetition-penalty", type=float, default=0.0,
                    help=">0 时启用 vLLM repetition_penalty(打断复读循环)")
    ap.add_argument("--frequency-penalty", type=float, default=0.0)
    ap.add_argument("--presence-penalty", type=float, default=0.0)
    ap.add_argument("--max-model-len", type=int, default=20000)
    ap.add_argument("--base-port", type=int, default=18000)
    ap.add_argument("--limit", type=int, default=0)
    ap.add_argument("--timeout", type=int, default=1800)
    ap.add_argument("--apply-blocklist", action="store_true",
                    help="在脚本内再过滤一次表过长/GT不可用的样本"
                         "(默认不过滤, 请直接用 eval_packs_filtered)")
    ap.add_argument("--span-subset", default=SPAN_SUBSET_DEFAULT,
                    help="15k 跨行跨列子集目录; 只做身份标记, 不额外推理")
    ap.add_argument("--exclude-cohorts", default="",
                    help="逗号分隔的 cohort 名, 这些来源**不参与**评测。"
                         "2026-10-25: tabrecset_en 的 GT 质量不行(374 条全空、"
                         "161 条本身是单列填空题表), 暂时移出评测。")
    ap.add_argument("--preboot-model", default="",
                    help="在**本模型打分期间**后台预启动这个模型的 engine "
                         "(方案2)。下一个 eval_mix 会自动复用。")
    ap.add_argument("--gt-override", default="",
                    help="GT 覆盖表(jsonl: sample_id/gt/gt_format)。"
                         "评测包里 TabRecSet 的 1566 条 GT 是坏的(OTSL 解析成 1 列), "
                         "用修好的 GT 覆盖。key 用 pack 的 sample_id(上游 id)或 "
                         "(cohort, sample_id)。")
    ap.add_argument("--packs", default="",
                    help="parquet shards 根目录; 非空则从 shard 读, 忽略 cohort jsonl")
    a = ap.parse_args()
    if route_existing_curriculum(a):
        return
    apply_run_parallel_config(a)

    outdir = f"{V5}/eval/runs/{a.tag}"
    logdir = f"{outdir}/logs"
    os.makedirs(logdir, exist_ok=True)
    global SPAN, PENALTIES
    SPAN = load_span_subset(a.span_subset) if a.span_subset else {}
    PENALTIES = {}
    if a.repetition_penalty and a.repetition_penalty > 0:
        PENALTIES["repetition_penalty"] = a.repetition_penalty
    if a.frequency_penalty:
        PENALTIES["frequency_penalty"] = a.frequency_penalty
    if a.presence_penalty:
        PENALTIES["presence_penalty"] = a.presence_penalty
    if PENALTIES:
        log(f"复读惩罚: {PENALTIES}")
    if SPAN:
        log(f"跨度子集: {len(SPAN)} 个 sample_id 会在汇总时分档")

    pred_path = f"/dev/shm/povl_v5/preds/{a.tag}.jsonl"
    os.makedirs(os.path.dirname(pred_path), exist_ok=True)
    score_path = f"{outdir}/scores.jsonl"

    rows, cohort_of = [], {}
    if a.packs:
        rows = load_from_packs(a.packs, a.cohorts)
    else:
        for c in a.cohorts:
            for line in open(f"{V5}/eval/cohorts/{c}.jsonl"):
                r = json.loads(line)
                r["_cohort"] = c
                # cohort 模式(不带 --packs)原来没给 _shard, 而 shard_work_units
                # 按 _shard 分工作单元 -> 直接 KeyError。packs 模式(184k 全量评测
                # 用的那条路)不受影响, 这里只补上散图模式缺的字段。
                r["_shard"] = c
                rows.append(r)

    # GT 覆盖(见 --gt-override): 评测包里 TabRecSet 的坏 GT 会把分数压到 1/8
    if a.gt_override:
        n_ov = apply_gt_override(rows, a.gt_override)
        log(f"GT 覆盖 {n_ov} 条 <- {a.gt_override}")

    # 默认不做名单过滤 —— 用 data/eval_packs_filtered 那份已经把表过长 / GT 不可用
    # 的样本剔掉的 parquet 即可, 过滤发生在数据侧而不是代码侧, 可审计。
    # 只有在直接喂未过滤的包/cohort 时才需要在这里兜一层。
    # 排除指定来源(GT 质量不行 / 暂时不参与评测的)
    if a.exclude_cohorts:
        drop = {c.strip() for c in a.exclude_cohorts.split(",") if c.strip()}
        before = len(rows)
        rows = [r for r in rows if (r.get("_cohort") or r.get("cohort")) not in drop]
        log(f"排除来源 {sorted(drop)}: {before} -> {len(rows)} 条")
    before_policy=len(rows)
    rows=filter_evaluation(rows)
    log(f'Evaluation policy: {evaluation_policy()}; additionally removed {before_policy-len(rows)} rows')

    if a.apply_blocklist:
        import eval_blocklist
        bl = eval_blocklist.Blocklist.load()
        rows, dropped = bl.filter_rows(rows)
        log(f"排除名单 {bl.summary()}, 本次剔除 {dict(dropped)} -> 剩 {len(rows)}")

    if a.limit:
        random.Random(1).shuffle(rows)
        rows = rows[:a.limit]
    # resume: skip already scored samples
    done = set()
    if os.path.exists(score_path):
        for line in open(score_path):
            try:
                d = json.loads(line)
                done.add((d["cohort"], d["sample_id"]))
            except Exception:
                pass
    rows = [r for r in rows if (r["_cohort"], r["sample_id"]) not in done]
    log(f"{len(rows)} samples to run ({len(done)} already scored), cohorts={a.cohorts}")
    if not rows:
        if os.path.exists(score_path):
            summarize(score_path, outdir, a)
        else:
            log("没有待评测样本, 且无历史 scores.jsonl")
        return
    if a.packs:
        # 宽高已经是 parquet 列, 不用再全量 stat 一遍
        for r in rows:
            r["_px"] = r["img_w"] * r["img_h"]
    else:
        with ThreadPoolExecutor(64) as ex:
            for r, px in zip(rows, ex.map(lambda r: image_pixels(r["image"]), rows)):
                r["_px"] = px
    served = "m"
    # OOM / startup failure -> fall back to fewer vLLM workers per GPU
    while True:
        plan = plan_workers(a.gpus, a.per_gpu, a.gmu or 0.9)
        log("  GPU 规划: " + ", ".join(
            f"gpu{g}->{n}worker(空闲{free/1e9:.0f}G)" for g, n, free in plan))
        per_gpu = max(n for _, n, _ in plan)
        n_workers = sum(n for _, n, _ in plan)
        # KV 预算: 按每卡空闲显存给每个 engine, 避免并发探测互相干扰
        gmu = a.gmu if a.gmu > 1 else int(
            min(free for _, _, free in plan) * 0.55 / per_gpu)
        log(f"  每卡 {per_gpu} worker, 共 {n_workers} 个, "
            f"每 engine KV 预算 {gmu/1e9:.1f} GB")
        try:
            procs = start_servers(a.model, a.gpus, per_gpu, a.base_port, gmu,
                                  a.max_model_len, logdir, served)
            break
        except RuntimeError as e:
            if per_gpu <= 1:
                raise
            log(f"server start failed: {e}")
            raise
    n_workers = len(a.gpus) * a.per_gpu
    # 动态调度: 成本降序的 shard 队列, worker 独占领取(见 worker_loop)
    shard_q = queue.Queue()
    for cost, shard, srows in shard_work_units(rows, n_workers):
        shard_q.put((cost, shard, srows))
    done_shards = []
    all_px = sorted(r["_px"] for r in rows)
    log(f"LPT: {n_workers} workers ({len(a.gpus)} GPU x {a.per_gpu}), "
        f"{shard_q.qsize()} 个 shard 待领, "
        f"总像素 {sum(all_px)/1e6:.1f}M (p50={all_px[len(all_px)//2]/1e6:.2f}M)")
    ports = [port for _, _, port in procs]

    done_q = queue.Queue()
    total = len(rows)
    t_start = time.time()

    def worker_loop(widx):
        """一个 worker 一个 vLLM 服务, 循环从共享队列领取未处理的 shard。

        队列是独占领取的: 一个 shard 被某个 worker 取走后, 其它 worker
        再取就拿不到同一片。worker 跑完手上的 shard 会立刻去看有没有
        别人没领的, 有就接着跑 —— 长尾 worker 不会早退, 空转的 worker
        也不会闲着。
        """
        port = ports[widx]
        while True:
            try:
                _, shard, srows = shard_q.get_nowait()
            except queue.Empty:
                break
            t0 = time.time()
            with ThreadPoolExecutor(a.conc_per_worker) as ex:
                futs = {ex.submit(infer, port, r, a.max_tokens, served,
                                  a.timeout, PENALTIES): r for r in srows}
                for f in futs:
                    res = f.result()
                    done_q.put((futs[f], res))
            done_shards.append((shard, len(srows), time.time() - t0))
            log(f"  [w{widx}] shard {shard} 完成 "
                f"({len(srows)} 行, {time.time()-t0:.0f}s), "
                f"剩余 {shard_q.qsize()}")

    threads = [threading.Thread(target=worker_loop, args=(i,), daemon=True)
               for i in range(n_workers)]
    for t in threads:
        t.start()

    def _score_unthrottle():
        """推理结束后把打分进程提权并放开全部核。

        打分在推理阶段压优先级是对的(TEDS 是纯 CPU 编辑距离, 抢推理的核会
        拖慢 GPU 喂数)。但推理一结束 GPU 就闲着、CPU 全空, 这时还压着
        就是纯浪费 —— 实测推理收尾时还剩 4,810 个批次, 尾部光排空就花了
        42 分钟(占整个 ckpt 的 41%)。
        """
        # 注意: 不能靠子进程自己往全局 set 里 add —— fork 出来的副本不会
        # 回传父进程。直接从 pool 的进程表里取 pid。
        pids = []
        try:
            pids = [p.pid for p in list(pool._processes.values()) if p.pid]
        except Exception:
            pids = list(SCORE_PIDS)
        n = 0
        for pid in pids:
            try:
                os.setpriority(os.PRIO_PROCESS, pid, 0)
                os.sched_setaffinity(pid, set(range(len(os.sched_getaffinity(0)))))
                n += 1
            except Exception:
                pass
        if n:
            log(f"  推理结束 -> {n} 个打分进程提权, 放开全部 CPU")

    def _score_init():
        """打分进程降优先级。

        TEDS 是纯 CPU 密集的编辑距离, 推理侧是 GPU 喂数, 两边抢同一批核。
        打分让位: 推理跑满的时候打分慢一点无所谓, 反过来会拖慢喂数、
        把 GPU 饿着。
        """
        try:
            os.nice(19)
        except Exception:
            pass
        # 打分池最多占一半的核, 剩下的留给推理
        try:
            c = len(os.sched_getaffinity(0))
            os.sched_setaffinity(0, set(range(0, max(1, c // 2))))
        except Exception:
            pass

    pool = ProcessPoolExecutor(a.score_workers,
                               initializer=lambda: (_score_init(), _register_pid()))
    pending = []
    n_pred = n_scored = 0
    pf = open(pred_path, "a")
    sf = open(score_path, "a")
    batch = []

    def flush_scores(block=False):
        nonlocal n_scored, pending
        keep = []
        for fut, meta in pending:
            if block or fut.done():
                for res, r in zip(fut.result(), meta):
                    res.update(cohort=r["_cohort"], dataset=r.get("dataset"),
                               origin=r.get("origin"),
                               has_numeric=r.get("has_numeric"),
                               res_bucket=r.get("res_bucket"),
                               metrics=r.get("metrics"),
                               n_merge=r.get("n_merge"),
                               difficulty=SPAN.get(r.get("sample_id") or ""),
                               n_spans=r.get("n_spans"),
                               finish_reason=r["_fr"], ctoks=r["_ct"],
                               **({"error": r["_err"]} if r.get("_err") else {}))
                    sf.write(json.dumps(res, ensure_ascii=False) + "\n")
                    n_scored += 1
                sf.flush()
            else:
                keep.append((fut, meta))
        pending = keep

    def submit(b):
        jobs = [(r["sample_id"], r["_pred"], r["gt"], r["gt_format"]) for r in b]
        # chunksize=1 so one huge table cannot pin a whole chunk
        fut = pool.submit(_score_batch, jobs)
        pending.append((fut, b))

    alive = lambda: any(t.is_alive() for t in threads)
    last = 0
    while alive() or not done_q.empty():
        try:
            r, res = done_q.get(timeout=1)
        except queue.Empty:
            flush_scores()
            continue
        dead = [port for p, _, port in procs if p.poll() is not None]
        if dead:
            raise RuntimeError(f"vLLM died: {dead}")
        rec = {"sample_id": r["sample_id"], "cohort": r["_cohort"], **res}
        pf.write(json.dumps(rec, ensure_ascii=False) + "\n")
        n_pred += 1
        r["_pred"], r["_fr"], r["_ct"] = res["prediction"], res.get("finish_reason"), res.get("completion_tokens")
        r["_err"] = res.get("error")
        batch.append(r)
        if len(batch) >= max(1, a.score_batch // 16):
            submit(batch)
            batch = []
        flush_scores()
        if time.time() - last > 30:
            el = time.time() - t_start
            log(f"pred {n_pred}/{total} ({n_pred/el:.1f}/s)  scored {n_scored}  pending_batches {len(pending)}")
            last = time.time()
    pf.close()
    if batch:
        submit(batch)
    stop_servers(procs)
    # 方案2: GPU 现在空着, 而打分还要跑一会儿(纯 CPU)。这段时间把下一个
    # 模型的 engine 起好, 下一个 eval_mix 直接复用, 省掉串行的开机时间。
    if a.preboot_model:
        try:
            preboot_servers(a.preboot_model, a.gpus, per_gpu, a.base_port, gmu,
                             a.max_model_len, logdir, served)
        except Exception as e:
            log(f"  预启动失败(忽略): {type(e).__name__}: {e}")
    _score_unthrottle()
    log(f"inference done in {time.time()-t_start:.0f}s; draining scoring")
    flush_scores(block=True)
    pool.shutdown()
    sf.close()
    log(f"all done in {time.time()-t_start:.0f}s")
    summarize(score_path, outdir, a)


def _score_batch(jobs):
    return [score_one(j) for j in jobs]


def _register_pid():
    """子进程把自己登记到 SCORE_PIDS, 供主进程推理结束后提权。"""
    try:
        import multiprocessing as _mp
        SCORE_PIDS.add(os.getpid())
    except Exception:
        pass


# ----------------------------------------------------------------------------
# 跨行跨列子集 (15k): 不重复推理, 只在跑全量时把命中的行标出来再分层汇报
# ----------------------------------------------------------------------------
SPAN_SUBSET_DEFAULT = "/autodl-tmp/span15k"
SPAN = {}          # sample_id -> difficulty, 由 --span-subset 填充
PENALTIES = {}     # 复读惩罚参数, 由 CLI 填充
SCORE_PIDS = set()  # 打分子进程 pid


def load_span_subset(path):
    """-> {sample_id: difficulty}。子集是 shard_* 的子集, 推理照常跑一遍,
    这里只做身份标记, 汇报时按 difficulty 聚合。"""
    import glob as _glob
    out = {}
    for f in sorted(_glob.glob(os.path.join(path, "*.parquet"))):
        t = pq.read_table(f, columns=["sample_id", "difficulty"])
        for sid, d in zip(t.column("sample_id").to_pylist(),
                          t.column("difficulty").to_pylist()):
            out.setdefault(sid, d)
    return out



def summarize(score_path, outdir, a):
    agg = defaultdict(lambda: defaultdict(list))

    def add(k, d):
        # teds 和 teds_s 可能只有一个有值: 纯结构集(GT 全是空 td)时
        # TEDS 不适用(None), 只有 TEDS-S 有意义。**两个指标要各自计分母** ——
        # 之前统一用 "teds 非 None 的条数" 当分母, 于是 synthtabnet 29,990 条
        # 里只有 40 条 teds 非 None, 汇总出来是 n=40 / TEDS-S=0.0000,
        # 而真实是 29,990 条 / 0.8510(2026-10-25 在 184k 全量汇总里发现的)。
        if d.get("teds") is None:
            agg[k]["na"].append(1)
        else:
            agg[k]["teds"].append(d["teds"])
        if d.get("teds_s") is None:
            agg[k]["na_s"].append(1)
        else:
            agg[k]["teds_s"].append(d["teds_s"])
        if d.get("finish_reason") == "length":
            agg[k]["trunc"].append(1)

    for line in open(score_path):
        d = json.loads(line)
        if row_is_excluded(d):continue
        c = d["cohort"]
        add(c, d)
        if c.startswith("cx_") and d.get("dataset"):
            add(f"{c}/{d['dataset']}", d)
        # parquet 带的新维度: 自建/公开, 有无数值, 分辨率档
        # 跨行跨列三档: 15k 子集的行会被额外聚合一次
        if d.get("difficulty"):
            agg[f"_span/{d['difficulty']}"]["teds"].append(
                d["teds"] if d["teds"] is not None else 0)
            agg[f"_span/{d['difficulty']}"]["teds_s"].append(
                d["teds_s"] if d["teds_s"] is not None else 0)
            if d["teds"] is None:
                agg[f"_span/{d['difficulty']}"]["na"].append(1)
            if d.get("benchmark"):
                agg[f"_span/{d['difficulty']}/{d['benchmark']}"]["teds"].append(
                    d["teds"] if d["teds"] is not None else 0)
                agg[f"_span/{d['difficulty']}/{d['benchmark']}"]["teds_s"].append(
                    d["teds_s"] if d["teds_s"] is not None else 0)
                if d["teds"] is None:
                    agg[f"_span/{d['difficulty']}/{d['benchmark']}"]["na"].append(1)
        for dim in ("origin", "has_numeric", "res_bucket"):
            v = d.get(dim)
            if v is not None:
                agg[f"_by/{dim}/{v}"]["teds"].append(d["teds"] if d["teds"] is not None else 0)
                agg[f"_by/{dim}/{v}"]["teds_s"].append(d["teds_s"] if d["teds_s"] is not None else 0)
                if d["teds"] is None:
                    agg[f"_by/{dim}/{v}"]["na"].append(1)
    out = {}
    for c, v in sorted(agg.items()):
        n_t = len(v["teds"])
        n_s = len(v["teds_s"])
        if not n_t and not n_s:
            continue
        out[c] = {
            "n": max(n_t, n_s),
            "n_teds": n_t, "n_teds_s": n_s,
            # 每个指标用它自己的分母
            "teds": round(sum(v["teds"]) / n_t, 5) if n_t else None,
            "teds_s": round(sum(v["teds_s"]) / n_s, 5) if n_s else None,
            "truncated": len(v["trunc"]),
            "na": len(v["na"]), "na_s": len(v.get("na_s", [])),
        }
    json.dump(out, open(f"{outdir}/summary.json", "w"), indent=1)
    for c, v in out.items():
        t = "  n/a " if v["teds"] is None else f"{v['teds']:.4f}"
        s_ = "  n/a " if v["teds_s"] is None else f"{v['teds_s']:.4f}"
        print(f"{c:40s} n={v['n']:6d} (t {v['n_teds']:6d} / ts {v['n_teds_s']:6d})"
              f" TEDS={t} TEDS-S={s_} trunc={v['truncated']}")
    # mustard / synthtabnet 等的 GT 是纯结构(全空 td), 只有 TEDS-S 有意义;
    # 它们的 TEDS 列天然是 0, 不要当成模型问题读。
    for c, v in out.items():
        # 只有"绝大多数行没有 TEDS"才是纯结构集(少数几行缺 TEDS 只是
        # 个别 GT 解析失败, 不是纯结构)
        if (not c.startswith("_by/") and v["n_teds_s"] > 0
                and v["n_teds"] < 0.5 * v["n_teds_s"]):
            print(f"  注: {c} 为纯结构集, TEDS 不适用({v['n_teds']} 条有值), "
                  f"请只看 TEDS-S")


if __name__ == "__main__":
    main()