File size: 22,024 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 | """Independent PaddleOCR-VL native-page table benchmark; never loads 184k packs."""
import argparse
import fcntl
import hashlib
import json
import os
from pathlib import Path
import shutil
import signal
import statistics
import subprocess
import sys
import time
import urllib.request
REFERENCE = Path('/autodl-tmp/official_benchmark_eval_20261030').resolve()
ROOT = Path('/autodl-tmp/official_table_pages_20261031')
BASE = '/autodl-fs/data/PaddleOCR-VL-1.6'
PACK = ROOT / 'parquet_16'
PIPELINE_ENV = Path('/root/autodl-tmp/venv_paddleocrvl_eval')
NAMES = ['ccocr', 'omnidocbench15', 'omnidocbench16', 'real5_scanning',
'real5_warping', 'real5_screen_photography', 'real5_illumination', 'real5_skew']
def dump(path, data):
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(path.suffix + '.tmp')
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2))
tmp.replace(path)
def prepare(model, tag):
import yaml
model_path = Path(model).resolve()
config_path = model_path / 'config.json'
if not config_path.exists():
raise ValueError('A complete, merged PaddleOCR-VL checkpoint is required: ' + str(model_path))
config = json.loads(config_path.read_text())
if config.get('model_type') != 'paddleocr_vl':
raise ValueError('This pipeline is for PaddleOCR-VL checkpoints, got: ' + str(config.get('model_type')))
weights = sorted(model_path.glob('*.safetensors'))
if not weights or (model_path / 'adapter_config.json').exists():
raise ValueError('Merge the LoRA adapter with its base before evaluating')
if Path(tag).name != tag or tag in ('.', '..'):
raise ValueError('tag must be a single directory name')
target = ROOT / tag
target.mkdir(parents=True, exist_ok=True)
identity = {'model': str(Path(model).resolve()), 'selection': 'gt_tables > 0',
'scope': 'native whole-page table evaluation; separate from 184k'}
identity_path = target / 'identity.json'
if identity_path.exists() and json.loads(identity_path.read_text()) != identity:
raise RuntimeError('Refusing to reuse predictions from a different model or selection')
dump(identity_path, identity)
vlm = {'vllm_model_path': str(model_path), 'backend': 'vllm-server', 'api_model_name': 'm',
'pipeline_version': 'v1.6', 'pipeline_environment': str(PIPELINE_ENV),
'layout_model_path': '/autodl-fs/data/PP-DocLayoutV3',
'config_sha256': hashlib.sha256(config_path.read_bytes()).hexdigest(),
'weight_files': [{'name': p.name, 'bytes': p.stat().st_size,
'mtime_ns': p.stat().st_mtime_ns} for p in weights]}
binding = target / 'vlm_weights.json'
if binding.exists() and json.loads(binding.read_text()) != vlm:
raise RuntimeError('Weight binding changed; use a new tag instead of reusing cached predictions')
dump(binding, vlm)
dump(target / 'engineering_config.json', {
'gpus': 4, 'vllm_instances_per_gpu': 3, 'vllm_instances_total': 12,
'engine_startup': 'parallel, reuse existing eval_mix.start_servers implementation',
'page_workers': 4, 'balanced_shards_per_worker': 4,
'shard_balance_metric': 'original image width * height',
'mixed_sources_in_inference': True, 'score_report_grouping': 'benchmark',
'scoring': 'CPU process pools run concurrently with GPU inference',
'scoring_workers': {'v15': 6, 'v16_ccocr': 6},
'resume': 'atomic per-page completion markers and durable per-page score packets',
'vlm_weights': 'custom --model; verify all 12 server model paths before inference',
'historical_184k_rerun': False})
for name in ('manifests', 'annotations', 'configs', 'predictions', 'logs', 'stream_scores'):
(target / name).mkdir(exist_ok=True)
packed_gt = {}
if (PACK / 'pack_audit.json').exists():
import pyarrow.parquet as pq
pack_audit = json.loads((PACK / 'pack_audit.json').read_text())
if not pack_audit.get('explicit_table_gt'):
raise RuntimeError('Parquet table-GT extraction is not complete yet')
for shard in pack_audit['by_shard']:
for batch in pq.ParquetFile(PACK / shard['shard']).iter_batches(batch_size=64,
columns=['benchmark', 'sample_id', 'gt_tables', 'gt_page_json', 'gt_html', 'gt_tables_json']):
for row in batch.to_pylist():
assert len(json.loads(row['gt_tables_json'])) == row['gt_tables']
packed_gt[(row['benchmark'], row['sample_id'])] = row
audit = {}
for name in NAMES:
all_rows = [json.loads(line) for line in (REFERENCE / 'manifests' / (name + '.jsonl')).open()]
selected = [r for r in all_rows if r.get('gt_tables', 0) > 0]
assert len({r['sample_id'] for r in selected}) == len(selected)
if packed_gt and name == 'ccocr':
for row in selected:
packed = packed_gt[(name, row['sample_id'])]
assert row['gt_html'] == packed['gt_html']
row['gt_html'] = json.loads(packed['gt_tables_json'])[0]['html']
manifest = target / 'manifests' / (name + '.jsonl')
manifest.write_text(''.join(json.dumps(r, ensure_ascii=False) + '\n' for r in selected))
audit[name] = {'all_pages': len(all_rows), 'selected_pages': len(selected),
'gt_tables': sum(r['gt_tables'] for r in selected),
'manifest_sha256': hashlib.sha256(manifest.read_bytes()).hexdigest()}
if name != 'ccocr':
ids = {r['sample_id'] for r in selected}
pages = json.loads((REFERENCE / 'annotations' / (name + '.json')).read_text())
pages = [p for p in pages if Path(p['page_info']['image_path']).name in ids]
assert len(pages) == len(selected)
if packed_gt:
extracted = []
for row in selected:
packed = packed_gt[(name, row['sample_id'])]
page = json.loads(packed['gt_page_json'])
tables = json.loads(packed['gt_tables_json'])
assert tables == [t for t in page['layout_dets'] if t.get('category_type') == 'table']
# Official truncated-block relations can reference non-table
# annotations. Keep that context; the metric config still
# selects only the table track.
extracted.append(page)
pages = extracted
dump(target / 'annotations' / (name + '.json'), pages)
config = yaml.safe_load((REFERENCE / 'configs' / (name + '.yaml')).read_text())
dataset = config['end2end_eval']['dataset']
dataset['ground_truth']['data_path'] = str(target / 'annotations' / (name + '.json'))
dataset['prediction']['data_path'] = str(target / 'predictions' / name)
(target / 'configs' / (name + '.yaml')).write_text(yaml.safe_dump(config, allow_unicode=True))
dump(target / 'selection_audit.json', {'by_source': audit,
'selected_pages': sum(v['selected_pages'] for v in audit.values()),
'gt_only_used_for_selection_and_scoring': True, 'training_allowed': False,
'original_184k_predictions_modified': False, 'original_184k_rerun': False})
if packed_gt:
dump(target / 'table_gt_provenance.json', {'source': str(PACK),
'pages': len(packed_gt), 'gt_tables': sum(r['gt_tables'] for r in packed_gt.values()),
'annotation_categories_scored': ['table'],
'gt_extracted_from_parquet': True, 'gt_sent_to_model': False,
'matching': 'official OmniDocBench/CC-OCR library matching; no zip by table order'})
if (PACK / 'pack_audit.json').exists():
pack_audit = json.loads((PACK / 'pack_audit.json').read_text())
expected = {(name, json.loads(line)['sample_id']) for name in NAMES
for line in (target / 'manifests' / (name + '.jsonl')).open()}
indexed = [json.loads(line) for line in (PACK / 'index.jsonl').open()]
assert len(indexed) == len(expected) == pack_audit['n']
assert {(r['benchmark'], r['sample_id']) for r in indexed} == expected
dump(target / 'image_pack.json', {'path': str(PACK), 'shards': pack_audit['shards'],
'allocation': '4 workers each consume 4 pixel-balanced shards; mixed sources',
'gt_annotations_not_read_by_inference_worker': True})
shutil.copy2(Path(__file__).parent / 'packed_page_worker.py', target / 'packed_page_worker.py')
for name in ('repos', 'venv_pipeline', 'venv_eval_v15', 'venv_eval_v16'):
link = target / name
destination = PIPELINE_ENV if name == 'venv_pipeline' else REFERENCE / name
if link.is_symlink() and link.resolve() != destination.resolve():
link.unlink()
if not link.exists():
link.symlink_to(destination, target_is_directory=True)
for name in ('run.py', 'pipeline_worker.py', 'score_ccocr.py', 'table_export.py',
'summarize.py', 'servers.py', 'proxy.py', 'stream_score.py'):
code = ((Path(__file__).parent / name) if name == 'table_export.py' else (REFERENCE / name)).read_text()
if name == 'servers.py':
default_call = "start_servers('/autodl-fs/data/PaddleOCR-VL-1.6',"
if code.count(default_call) != 1:
raise RuntimeError('Server template changed; refusing to silently use default VLM weights')
code = code.replace(default_call,
'start_servers(' + repr(str(Path(model).resolve())) + ',')
code = code.replace("'model':'PaddleOCR-VL-1.6'", "'model':" + repr(str(model_path)))
elif name == 'pipeline_worker.py':
code = code.replace("'model':'/autodl-fs/data/PaddleOCR-VL-1.6'",
"'model':" + repr(str(Path(model).resolve())))
elif name == 'summarize.py':
code = code.replace("'model':'PaddleOCR-VL-1.6 base'", "'model':" + repr(str(Path(model).resolve())))
(target / name).write_text(code)
return target
def finalize_score_coverage(target):
"""Rebuild page packets from complete official results and audit every GT table."""
summary = json.loads((target / 'SUMMARY.json').read_text())
if not summary.get('complete'):
raise RuntimeError('Cannot finalize coverage before official evaluation completes')
marker = target / 'score_coverage.json'
if marker.exists() and json.loads(marker.read_text()).get('complete'):
return
# Earlier table-only GT views omitted context for truncated-block relations.
# Official CLI results now use the full original annotation. Rebuild the
# streaming cache from those completed results rather than retaining stale packets.
backup = target / 'stream_scores_before_full_gt_context'
backup.mkdir(exist_ok=True)
for name in NAMES:
path = target / 'stream_scores' / name
if path.exists():
destination = backup / name
if destination.exists():
shutil.rmtree(destination)
path.rename(destination)
env = dict(os.environ); env.pop('PYTHONPATH', None)
for version in ('v15', 'v16'):
with (target / 'logs' / ('coverage_' + version + '.log')).open('a') as output:
subprocess.run([str(target / ('venv_eval_' + version) / 'bin/python'),
str(target / 'stream_score.py'), '--version', version, '--once'],
env=env, stdout=output, stderr=subprocess.STDOUT, check=True)
audit = {'complete': True, 'by_source': {}, 'pages': 0, 'gt_tables': 0,
'provenance': 'completed official CLI results; full original GT context; table metric only'}
for name in NAMES:
rows = [json.loads(line) for line in (target / 'manifests' / (name + '.jsonl')).open()]
missing, gt_count = [], 0
for row in rows:
path = target / 'stream_scores' / name / (row['output_name'] + '.json')
if not path.exists():
missing.append({'sample_id': row['sample_id'], 'reason': 'score packet missing'}); continue
packet = json.loads(path.read_text())
if not isinstance(packet.get('page_teds_s'), (int, float)):
missing.append({'sample_id': row['sample_id'], 'reason': 'TEDS-S missing'})
indices = {int(index) for table in packet['tables'] for index in table['gt_idx']
if str(index).isdigit()}
if indices != set(range(row['gt_tables'])):
missing.append({'sample_id': row['sample_id'], 'reason': 'GT table index coverage mismatch',
'expected': row['gt_tables'], 'scored_indices': sorted(indices)})
gt_count += row['gt_tables']
audit['by_source'][name] = {'pages': len(rows), 'gt_tables': gt_count, 'missing': missing}
audit['pages'] += len(rows); audit['gt_tables'] += gt_count
audit['complete'] &= not missing
dump(marker, audit)
if not audit['complete']:
raise RuntimeError('Official score coverage incomplete; inspect ' + str(marker))
def verify_server_bindings(target, model):
expected = Path(model).resolve()
records = []
for port in range(19000, 19012):
with urllib.request.urlopen(f'http://127.0.0.1:{port}/v1/models', timeout=10) as response:
models = json.load(response)['data']
matching = [m for m in models if m['id'] == 'm']
if len(matching) != 1 or not matching[0].get('root'):
raise RuntimeError('VLM service did not report its loaded model path: ' + str(port))
actual = Path(matching[0]['root']).resolve()
if actual != expected:
raise RuntimeError(f'VLM weight mismatch on port {port}: {actual} != {expected}')
records.append({'port': port, 'model_alias': 'm', 'loaded_model_path': str(actual)})
dump(target / 'verified_server_weights.json', {'expected': str(expected), 'servers': records})
def reuse_base(target):
"""Reuse committed predictions AND existing official per-page scores, no inference."""
summary = []
for name in NAMES:
rows = [json.loads(line) for line in (target / 'manifests' / (name + '.jsonl')).open()]
packets = []
destination = target / 'predictions' / name
destination.mkdir(exist_ok=True)
for row in rows:
stem = row['output_name']
meta = json.loads((REFERENCE / 'predictions' / name / (stem + '.done.json')).read_text())
assert meta['status'] == 'ok' and meta['inference_mode'] == 'page'
packet = json.loads((REFERENCE / 'stream_scores' / name / (stem + '.json')).read_text())
assert packet['sample_id'] == row['sample_id'] and packet['status'] == 'ok'
assert isinstance(packet['page_teds_s'], (int, float))
markdown = REFERENCE / 'predictions' / name / (stem + '.md')
assert hashlib.sha256(markdown.read_bytes()).hexdigest() == packet['prediction_sha256']
packets.append(packet)
# Page stems may contain glob characters such as brackets.
for source in [REFERENCE / 'predictions' / name / (stem + suffix) for suffix in
('.json', '.done.json', '.md', '.tables.html', '.tables.json')]:
if not source.exists():
continue
link = destination / source.name
if not link.exists():
link.symlink_to(source)
summary.append({'benchmark': name, 'n_inputs': len(rows), 'complete': True,
'teds': statistics.fmean(p['page_teds'] for p in packets),
'teds_s': statistics.fmean(p['page_teds_s'] for p in packets)})
dump(target / 'SUMMARY.json', {'model': BASE, 'complete': True,
'selection': 'gt_tables > 0', 'sources': summary, 'inference_rerun': False,
'scoring_rerun': False, 'reused_from': str(REFERENCE),
'scope': 'native whole-page table evaluation; GT-positive page subset'})
def stop(process):
if process.poll() is None:
process.terminate()
try:
process.wait(timeout=45)
except subprocess.TimeoutExpired:
# Every launched controller has its own session, never kill the caller.
os.killpg(process.pid, signal.SIGKILL)
process.wait()
def evaluate(model, tag, prepare_only=False):
target = prepare(model, tag)
if Path(model).resolve() == Path(BASE).resolve():
reuse_base(target)
return target
if prepare_only:
return target
if not (PIPELINE_ENV / 'environment_verified.json').exists():
raise RuntimeError('Dedicated PaddleOCR-VL environment has not passed its import checks')
summary = target / 'SUMMARY.json'
if summary.exists() and json.loads(summary.read_text()).get('complete'):
finalize_score_coverage(target)
return target
ROOT.mkdir(parents=True, exist_ok=True)
with (ROOT / 'gpu_and_official_repo.lock').open('w') as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
if summary.exists() and json.loads(summary.read_text()).get('complete'):
finalize_score_coverage(target)
return target
free = subprocess.check_output(['nvidia-smi', '--query-gpu=memory.free', '--format=csv,noheader,nounits'], text=True)
if len(free.splitlines()) != 4 or min(map(int, free.splitlines())) < 40000:
raise RuntimeError('Full-page evaluation requires four free GPUs; current training is left running')
(target / 'STOP_SERVERS').unlink(missing_ok=True)
env = dict(os.environ, POVL_ALLOW_TRUSTED_MM_KWARGS='1',
POVL_VLLM='/root/autodl-tmp/vllm_local/bin/vllm', POVL_PARALLEL_ENGINE_BOOT='1')
env['PYTHONPATH'] = '/root/autodl-tmp/vllm_local/site-packages:/root/autodl-tmp/venv_train/lib/python3.12/site-packages:/autodl-fs/data/vllm_env/lib/python3.12/site-packages'
processes, logs = [], []
def launch(cmd, name, process_env):
log = (target / 'logs' / name).open('a'); logs.append(log)
p = subprocess.Popen(cmd, env=process_env, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
processes.append(p)
return p
clean_env = dict(env)
clean_env.pop('PYTHONPATH', None)
try:
server = launch([sys.executable, '-u', str(target / 'servers.py')], 'server_controller.log', env)
proxies = [launch([sys.executable, str(target / 'proxy.py'), '--listen', str(19080 + gpu),
'--backends', *[str(19000 + gpu * 3 + i) for i in range(3)]],
f'proxy_{gpu}.log', clean_env) for gpu in range(4)]
scorers = [launch([str(target / ('venv_eval_' + version) / 'bin/python'), '-u',
str(target / 'stream_score.py'), '--version', version, '--workers', '6'],
'stream_' + version + '.log', clean_env) for version in ('v15', 'v16')]
if (target / 'image_pack.json').exists():
deadline = time.monotonic() + 1800
while not (target / 'servers_ready.json').exists():
if server.poll() is not None or time.monotonic() > deadline:
raise RuntimeError('VLM startup failed before packed-page inference')
time.sleep(2)
verify_server_bindings(target, model)
workers = [launch([str(target / 'venv_pipeline/bin/python'), '-u',
str(target / 'packed_page_worker.py'), '--pack', str(PACK),
'--worker', str(gpu), '--workers', '4'], f'packed_worker_{gpu}.log',
dict(clean_env, CUDA_VISIBLE_DEVICES=str(gpu))) for gpu in range(4)]
for worker in workers:
if worker.wait():
raise RuntimeError('Packed whole-page inference failed; inspect worker logs')
command = [sys.executable, '-u', str(target / 'run.py')]
with (target / 'logs' / 'official_run.log').open('a') as log:
subprocess.run(command, env=clean_env, stdout=log, stderr=subprocess.STDOUT, check=True)
for p in scorers:
if p.wait(timeout=1800):
print('Streaming scorer failed; rebuilding from completed official CLI results', flush=True)
result = json.loads(summary.read_text())
assert result['complete']
finalize_score_coverage(target)
finally:
(target / 'STOP_SERVERS').touch()
# Graceful server cleanup owns all vLLM engine children.
for process in reversed(processes):
stop(process)
for log in logs:
log.close()
return target
def batch(run):
stages = json.loads((run / 'stage_results.json').read_text())['stages']
targets = []
for stage in stages:
path = evaluate(stage['model'], stage['stage'])
targets.append({'stage': stage['stage'], 'model': stage['model'], 'summary': str(path / 'SUMMARY.json')})
dump(run / 'whole_page_results.json', {'separate_from_184k': True, 'stages': targets})
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--model'); parser.add_argument('--tag')
parser.add_argument('--prepare-only', action='store_true')
parser.add_argument('--batch-run', type=Path)
args = parser.parse_args()
if args.batch_run:
batch(args.batch_run)
else:
if not args.model or not args.tag:
parser.error('--model and --tag are required without --batch-run')
print(evaluate(args.model, args.tag, args.prepare_only))
if __name__ == '__main__':
main()
|