CheneyWong's picture
Add unified crop/fullpage checkpoint evaluation entry point
7123a00 verified
Raw History Blame Contribute Delete
6.87 kB
"""Single entry point for independent crop and native-fullpage checkpoint evaluation."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
EXP = Path(__file__).resolve().parent
V5 = EXP.parent.parent
PAGE = Path('/autodl-tmp/official_table_pages_20261031')
PACK = PAGE / 'hf_sync/canonical_rebalanced'
CROP_PY = '/root/autodl-tmp/venv_train/bin/python'
PAGE_PY = '/root/autodl-tmp/venv_paddleocrvl_eval/bin/python'
def dump(path, obj):
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix('.tmp')
tmp.write_text(json.dumps(obj, ensure_ascii=False, indent=2) + '\n')
tmp.replace(path)
def digest(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def plan(model, tag, track):
crop_env = dict(os.environ,
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',
POVL_VLLM='/root/autodl-tmp/vllm_local/bin/vllm', POVL_PARALLEL_ENGINE_BOOT='1',
TOKENIZERS_PARALLELISM='false', OMP_NUM_THREADS='4', MKL_NUM_THREADS='4')
crop_env.pop('POVL_RUN_DIR', None)
page_env = dict(crop_env)
page_env.pop('PYTHONPATH', None)
jobs = []
if track in ('crop', 'both'):
jobs.append(('crop', [CROP_PY, str(V5 / 'src/eval_mix.py'), '--model', model,
'--tag', tag + '_crop', '--packs', str(PACK), '--gpus', '0', '1', '2', '3',
'--per-gpu', '3', '--conc-per-worker', '16', '--score-workers', '12',
'--score-batch', '64', '--max-tokens', '16384'], crop_env))
if track in ('fullpage', 'both'):
jobs.append(('fullpage', [PAGE_PY, str(EXP / 'whole_page_eval.py'), '--model', model,
'--tag', tag + '_fullpage'], page_env))
return jobs
def crop_complete(directory):
scores, summary = directory / 'scores.jsonl', directory / 'summary.json'
if not scores.exists() or not summary.exists():
return False
keys = set()
for line in scores.open():
r = json.loads(line)
key = r['cohort'], r['sample_id']
if key in keys:
raise RuntimeError('Duplicate crop score identity: ' + str(key))
keys.add(key)
return len(keys) == 176810
def check_free_gpus():
free = subprocess.check_output(['nvidia-smi', '--query-gpu=memory.free',
'--format=csv,noheader,nounits'], text=True).splitlines()
if len(free) != 4 or min(map(int, free)) < 40000:
raise RuntimeError('Crop evaluation needs four free GPUs with >=40000 MiB each; existing training is left running.')
def main():
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument('--model', required=True, help='Complete PaddleOCR-VL merged checkpoint directory')
ap.add_argument('--tag', required=True, help='Unique checkpoint/run name')
ap.add_argument('--track', choices=['both', 'crop', 'fullpage'], default='both')
ap.add_argument('--output-dir', type=Path, default=Path('/autodl-tmp/table_evaluation'))
ap.add_argument('--dry-run', action='store_true', help='Print commands only; no writes or GPU work')
args = ap.parse_args()
if not args.tag or Path(args.tag).name != args.tag or args.tag in ('.', '..'):
ap.error('--tag must be one directory name')
model_path = Path(args.model).resolve()
config = model_path / 'config.json'
if not config.exists() or json.loads(config.read_text()).get('model_type') != 'paddleocr_vl':
ap.error('--model must contain a PaddleOCR-VL config.json')
weights = sorted(model_path.glob('*.safetensors'))
if not weights or (model_path / 'adapter_config.json').exists():
ap.error('Merge the adapter with the base first; a complete model is required')
jobs = plan(str(model_path), args.tag, args.track)
if args.dry_run:
print(json.dumps({'model': str(model_path), 'track': args.track,
'gpus': 4, 'vllm_instances_per_gpu': 3,
'commands': {name: cmd for name, cmd, env in jobs},
'inherited_training_run_removed': all('POVL_RUN_DIR' not in env for _, _, env in jobs),
'fullpage_pythonpath_removed': all('PYTHONPATH' not in env for name, _, env in jobs if name == 'fullpage'),
'summary': str(args.output_dir / args.tag / 'results.json')}, indent=2))
return
root = args.output_dir / args.tag
identity = {'model': str(model_path), 'config_sha256': digest(config),
'weights': [{'name': p.name, 'bytes': p.stat().st_size, 'mtime_ns': p.stat().st_mtime_ns} for p in weights],
'crop_release_sha256': digest(PACK / 'release_audit.json')}
binding = root / 'identity.json'
if binding.exists() and json.loads(binding.read_text()) != identity:
raise RuntimeError('Model or evaluation pack changed; use a new --tag')
# An unbound old crop cache cannot safely be associated with this model.
crop_dir = V5 / 'eval/runs' / (args.tag + '_crop')
if not binding.exists() and args.track in ('crop', 'both') and crop_dir.exists():
raise RuntimeError('Existing crop tag has no unified model binding; use a new --tag')
dump(binding, identity)
report_path = root / 'results.json'
report = json.loads(report_path.read_text()) if report_path.exists() else {'model': str(model_path),
'tracks': {}, 'combined_metric': None, 'note': 'Crop/fullpage metrics remain independent.'}
for name, cmd, env in jobs:
dump(root / 'status.json', {'phase': name, 'command': cmd})
if name == 'crop' and crop_complete(crop_dir):
print('Reusing completed, identity-bound crop scores', flush=True)
else:
if name == 'crop':
check_free_gpus()
print('Evaluating ' + name, flush=True)
with (root / (name + '.log')).open('a') as log:
subprocess.run(cmd, cwd=V5, env=env, stdout=log, stderr=subprocess.STDOUT, check=True)
summary = crop_dir / 'summary.json' if name == 'crop' else PAGE / (args.tag + '_fullpage') / 'SUMMARY.json'
if name == 'crop' and not crop_complete(crop_dir):
raise RuntimeError('Crop evaluation incomplete; inspect ' + str(root / 'crop.log'))
result = json.loads(summary.read_text())
if name == 'fullpage' and not result.get('complete'):
raise RuntimeError('Fullpage evaluation incomplete; inspect ' + str(root / 'fullpage.log'))
report['tracks'][name] = {'summary_file': str(summary), 'summary': result}
dump(report_path, report)
dump(root / 'status.json', {'phase': 'complete', 'tracks': [name for name, _, _ in jobs],
'results': str(report_path)})
print(str(report_path), flush=True)
if __name__ == '__main__':
main()