Datasets:
Download code/evaluation-code/ent400-a06a1576/tools/evaluation/runner.py from VEHwang/cocogni4d: direct link, hf CLI and curl.
- Browser
- Download file 23.3 kB
-
https://huggingface.co/datasets/VEHwang/cocogni4d/resolve/main/code/evaluation-code/ent400-a06a1576/tools/evaluation/runner.py
- Command line
-
hf download hf://datasets/VEHwang/cocogni4d/code/evaluation-code/ent400-a06a1576/tools/evaluation/runner.py
-
curl -L -o runner.py https://huggingface.co/datasets/VEHwang/cocogni4d/resolve/main/code/evaluation-code/ent400-a06a1576/tools/evaluation/runner.py
23.3 kB
| """Run one model endpoint over an evaluation item set. | |
| Items (``items.jsonl``, public, one JSON object per line):: | |
| {"item_id": "...", "version_id": "position.coordinates.at_time/single_ego", | |
| "question": {"zh": "...", "en": "..."}, # instantiated public text | |
| "answer": {...}, # v0 answer spec (public) | |
| "scoring": {...}, # answer.scoring (prover.scoring.rule) | |
| "granularity": "sector4", # choice items only | |
| "videos": [{"view": "A", "path": "A.mp4"}, ...], # relative to items file | |
| "tags": {...}} # optional report factors | |
| Next-pipeline items come from ``np_export.py`` (answer type ``np:<kind>``, | |
| ``scoring`` is the scorer from ``embodied_pipeline.prover.scoring``); see ``np_answers.py``. | |
| Truth (``truth.jsonl``, private, kept separate and only read when scoring):: | |
| {"item_id": "...", "truth": [x, y] | number | option index, | |
| "magnitude": number (optional override)} | |
| Settings (track) select the input mode, mirroring the benchmarks surveyed: | |
| ``frames`` with ``frames=N`` (VSI-Bench/Video-MME ``nframes``), ``fps`` with | |
| ``rate``/``max_frames`` (Qwen/Gemini style), ``video`` (native video API), and | |
| ``text_only`` (question-only blind baseline). ``budget`` is ``per_view`` or | |
| ``total`` for multi-recording items (plan section 7). | |
| Outputs go to a fresh run directory: ``responses.jsonl`` (one line per item, | |
| append-only, so an interrupted run resumes), ``run.json`` (endpoint, settings, | |
| item set hash) and, after ``score``, ``scores.jsonl`` and ``summary.json``. | |
| """ | |
| import argparse | |
| import concurrent.futures | |
| import hashlib | |
| import json | |
| import re | |
| import sys | |
| import threading | |
| import time | |
| from pathlib import Path | |
| if __package__ in (None, ''): | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| import media, np_answers, prompts, providers, scoring # noqa: E401 | |
| else: | |
| from . import media, np_answers, prompts, providers, scoring | |
| TRUNCATED = {'length', 'max_tokens', 'MAX_TOKENS'} | |
| SETTINGS_KEYS = {'mode', 'frames', 'rate', 'max_frames', 'budget', 'max_side', 'lang', | |
| 'text_only', 'max_tokens', 'temperature', 'seed', 'video_fallback_frames', 'frame_labels', | |
| 'images_in_budget'} | |
| def read_jsonl(path): | |
| rows = [] | |
| with open(path, encoding='utf-8') as fh: | |
| for n, line in enumerate(fh, 1): | |
| if line.strip(): | |
| try: | |
| rows.append(json.loads(line)) | |
| except json.JSONDecodeError as exc: | |
| raise ValueError(f'{path}:{n}: {exc}') from None | |
| return rows | |
| def file_sha256(path): | |
| h = hashlib.sha256() | |
| with open(path, 'rb') as fh: | |
| for chunk in iter(lambda: fh.read(1 << 20), b''): | |
| h.update(chunk) | |
| return h.hexdigest() | |
| def load_items(path): | |
| path = Path(path) | |
| items = read_jsonl(path) | |
| seen = set() | |
| for item in items: | |
| for key in ('item_id', 'version_id', 'question', 'answer', 'videos'): | |
| if key not in item: | |
| raise ValueError(f"item {item.get('item_id')!r} lacks {key}") | |
| if item['item_id'] in seen: | |
| raise ValueError(f"duplicate item_id {item['item_id']!r}") | |
| seen.add(item['item_id']) | |
| if 'truth' in item or 'private_truth' in item: | |
| raise ValueError(f"item {item['item_id']!r} carries truth; keep it in truth.jsonl") | |
| prompts.answer_spec(item) | |
| for v in item['videos']: | |
| v['path'] = str((path.parent / v['path']).resolve()) | |
| if not item.get('images'): # 平面图题的图出题时就写进 presentation.images(label 可缺);map_choice 的由导出现画进 images | |
| item['images'] = [dict(image) for image in (item.get('presentation') or {}).get('images') or []] | |
| for image in item.get('images') or []: | |
| image['path'] = str((path.parent / image['path']).resolve()) | |
| return items | |
| def normalize_settings(raw): | |
| unknown = set(raw) - SETTINGS_KEYS | |
| if unknown: | |
| raise ValueError(f'unknown settings: {sorted(unknown)}') | |
| s = {'mode': 'frames', 'frames': 16, 'rate': None, 'max_frames': None, 'budget': 'per_view', | |
| 'max_side': 768, 'lang': 'zh', 'text_only': False, 'max_tokens': 16384, | |
| 'temperature': 0.0, 'seed': 0, 'video_fallback_frames': None, | |
| # True labels every frame with its index and time and states the duration (11-02). Off by default so | |
| # earlier runs keep their prompt wording when resumed; new runs opt in. | |
| 'frame_labels': False, **raw} | |
| # images_in_budget (11-09, opt-in, no default key so earlier run.json files still resume): a total frame | |
| # budget also counts the item's attached images (floor plans, option maps), so an endpoint capped at | |
| # N images per request (aigw: 50) gets N-1 frames plus the map. | |
| if s['mode'] not in media.MODES: | |
| raise ValueError(f"mode must be one of {media.MODES}") | |
| if s['budget'] not in media.BUDGETS: | |
| raise ValueError(f"budget must be one of {media.BUDGETS}") | |
| if s['lang'] not in ('zh', 'en'): | |
| raise ValueError('lang must be zh or en') | |
| if s.get('images_in_budget') and (s['mode'] == 'video' or s['budget'] != 'total' | |
| or (s['mode'] == 'fps' and s['max_frames'] is None)): | |
| raise ValueError('images_in_budget needs budget total and a frame cap (frames, or fps with max_frames)') | |
| return s | |
| def frame_budget(item, settings): | |
| """(frames, max_frames, attached images) for this item; the cap shrinks by the attached images | |
| when ``images_in_budget`` is set.""" | |
| frames, cap = settings['frames'], settings['max_frames'] | |
| n = len(item.get('images') or []) if settings.get('images_in_budget') else 0 | |
| if n: | |
| if settings['mode'] == 'fps': | |
| cap -= n | |
| else: | |
| frames -= n | |
| left = cap if settings['mode'] == 'fps' else frames | |
| if left < len(item['videos']): | |
| raise ValueError(f"item {item['item_id']!r}: {n} attached images leave {left} frames " | |
| f"for {len(item['videos'])} views") | |
| return frames, cap, n | |
| def build_request(item, settings, cache_dir): | |
| if settings['text_only']: | |
| views, access = [], {'mode': 'text_only', 'views': []} | |
| else: | |
| if prompts.is_np(item) and not item['videos']: | |
| raise ValueError(f"item {item['item_id']!r} has no recordings; only text_only settings can run it") | |
| frames, max_frames, attached = frame_budget(item, settings) | |
| views, access = media.build_inputs( | |
| item['videos'], settings['mode'], cache_dir, frames=frames, | |
| rate=settings['rate'], max_frames=max_frames, budget=settings['budget'], | |
| max_side=settings['max_side']) | |
| if settings.get('images_in_budget'): | |
| access['images_in_budget'] = attached | |
| if settings['mode'] == 'video' and settings['video_fallback_frames']: | |
| # Providers without native video (Anthropic) expand to these frames. | |
| framed, _ = media.build_inputs(item['videos'], 'frames', cache_dir, | |
| frames=settings['video_fallback_frames'], | |
| budget=settings['budget'], max_side=settings['max_side']) | |
| for v, f in zip(views, framed): | |
| v['fallback_frames'] = [{'type': 'image', 'path': x['path'], 'mime': 'image/jpeg'} | |
| for x in f['frames']] | |
| parts = prompts.build_parts(item, views, settings['lang'], settings['mode'], settings['text_only'], | |
| settings['frame_labels']) | |
| request = {'system': prompts.SYSTEM[settings['lang']], 'parts': parts, | |
| 'max_tokens': settings['max_tokens'], 'temperature': settings['temperature'], | |
| 'seed': settings['seed']} | |
| return request, access | |
| def prompt_text(request): | |
| """Text-only view of a request, stored for audit (media replaced by markers).""" | |
| out = [] | |
| for part in request['parts']: | |
| if part['type'] == 'text': | |
| out.append(part['text']) | |
| elif part['type'] == 'image': | |
| out.append('<image>') | |
| elif part['type'] == 'video': | |
| out.append(f"<video {len(part['frames'])} frames>" if part.get('frames') and not part.get('path') | |
| else '<video file>') | |
| return '\n'.join(out) | |
| DENIED = (401, 403) | |
| def run(items_path, endpoint, settings, out_dir, workers=1, limit=None, stop_after_denied=0, keep_errors=None): | |
| """Answer every item not yet OK in out_dir/responses.jsonl. | |
| ``stop_after_denied`` N > 0: after N answers fail with HTTP 401/403 (key revoked, account banned), stop sending; | |
| the items not yet sent are left unanswered (no record) for a later resume, and the result says ``stopped``. | |
| ``keep_errors`` (regex): items whose latest record is an ERROR matching it count as done on resume, e.g. gateway | |
| cuts that already used their tries (top-effort passes), so a resume does not try them again. | |
| """ | |
| out = Path(out_dir) | |
| out.mkdir(parents=True, exist_ok=True) | |
| settings = normalize_settings(settings) | |
| client = providers.Client(endpoint) | |
| items = load_items(items_path)[:limit] if limit else load_items(items_path) | |
| meta = {'schema': 'model-evaluation-run/1', 'items_path': str(Path(items_path).resolve()), | |
| 'items_sha256': file_sha256(items_path), 'endpoint': client.describe(), | |
| 'settings': settings} | |
| run_file = out / 'run.json' | |
| if run_file.exists(): | |
| old = json.loads(run_file.read_text()) | |
| if {k: old.get(k) for k in meta} != meta: | |
| raise ValueError(f'{out} holds a run with different items, endpoint or settings') | |
| else: | |
| run_file.write_text(json.dumps({**meta, 'started_utc': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())}, | |
| ensure_ascii=False, indent=2)) | |
| responses = out / 'responses.jsonl' | |
| done, kept = set(), set() | |
| if responses.exists(): | |
| latest = {} | |
| for r in read_jsonl(responses): | |
| if r['status'] == 'OK': | |
| done.add(r['item_id']) | |
| latest[r['item_id']] = r | |
| if keep_errors: | |
| pattern = re.compile(keep_errors) | |
| kept = {i for i, r in latest.items() if i not in done and r['status'] == 'ERROR' | |
| and pattern.search(r.get('error') or '')} | |
| todo = [i for i in items if i['item_id'] not in done and i['item_id'] not in kept] | |
| lock = threading.Lock() | |
| cache = out / 'frames' | |
| denied, stop = [0], threading.Event() | |
| def one(item): | |
| if stop.is_set(): | |
| return {'item_id': item['item_id'], 'status': 'SKIPPED'} | |
| record = {'item_id': item['item_id'], 'version_id': item['version_id']} | |
| try: | |
| request, access = build_request(item, settings, cache) | |
| record.update(access=access, prompt=prompt_text(request)) | |
| reply = client.generate(request) | |
| parsed = prompts.parse(reply['text'], item) | |
| if parsed['status'] == 'UNPARSED' and reply.get('finish_reason') in TRUNCATED: | |
| # The token budget ran out (often inside reasoning) before an answer. | |
| parsed = {**parsed, 'status': 'TRUNCATED'} | |
| if reply.get('video_input') == 'frames': | |
| # Native-video request expanded to fallback frames by this endpoint. | |
| videos = [p for p in request['parts'] if p['type'] == 'video' and p.get('path')] | |
| record['access'] = {**access, 'views': [ | |
| {**v, 'frames_sent': len(p.get('frames') or []), 'bytes_sent': sum( | |
| Path(f['path']).stat().st_size for f in p.get('frames') or [])} | |
| for v, p in zip(access['views'], videos)]} | |
| record.update(status='OK', text=reply['text'], parsed=parsed, video_input=reply.get('video_input'), | |
| finish_reason=reply.get('finish_reason'), usage=reply.get('usage'), | |
| latency_s=reply.get('latency_s'), attempts=reply.get('attempts')) | |
| if reply.get('reasoning'): | |
| record['reasoning'] = reply['reasoning'] | |
| for key in ('tool_calls', 'text_source'): | |
| if reply.get(key): | |
| record[key] = reply[key] | |
| if not (reply.get('text') or '').strip(): | |
| # Empty replies keep the provider payload, so the cause stays inspectable. | |
| record['raw'] = reply.get('raw') | |
| except (providers.ProviderError, RuntimeError, OSError, ValueError) as exc: | |
| record.update(status='ERROR', error=f'{type(exc).__name__}: {exc}'[:2000]) | |
| if stop_after_denied and getattr(exc, 'status', None) in DENIED: | |
| with lock: | |
| denied[0] += 1 | |
| if denied[0] >= stop_after_denied: | |
| stop.set() | |
| with lock, open(responses, 'a', encoding='utf-8') as fh: | |
| fh.write(json.dumps(record, ensure_ascii=False) + '\n') | |
| return record | |
| counts = {'OK': 0, 'ERROR': 0} | |
| with concurrent.futures.ThreadPoolExecutor(max_workers=max(1, workers)) as pool: | |
| for record in pool.map(one, todo): | |
| if record['status'] == 'SKIPPED': | |
| counts['not_sent'] = counts.get('not_sent', 0) + 1 | |
| continue | |
| counts[record['status']] += 1 | |
| print(f"[{counts['OK'] + counts['ERROR']}/{len(todo)}] {record['item_id']} {record['status']}" | |
| + (f" {record.get('parsed', {}).get('status')}" if record['status'] == 'OK' | |
| else f" {record['error'][:120]}"), flush=True) | |
| result = {'items': len(items), 'skipped_done': len(done), **counts} | |
| if kept: | |
| result['kept_errors'] = len(kept) | |
| if stop.is_set(): | |
| result['stopped'] = f'{denied[0]} answers refused with HTTP 401/403 (key or account denied); rest not sent' | |
| return result | |
| def latest_responses(path): | |
| """Last record per item: a later OK replaces an earlier ERROR.""" | |
| latest = {} | |
| for r in read_jsonl(path): | |
| if r['item_id'] not in latest or r['status'] == 'OK' or latest[r['item_id']]['status'] != 'OK': | |
| latest[r['item_id']] = r | |
| return latest | |
| def reparse(run_dir): | |
| """Re-parse every OK reply's stored ``text`` with the current parser (no model calls), e.g. after a parser fix. | |
| The original file is kept once as responses.before-reparse.jsonl; a record whose parse changes keeps the old | |
| one in ``parsed_before``. Run ``score`` afterwards. Returns counts. | |
| """ | |
| run_dir = Path(run_dir) | |
| meta = json.loads((run_dir / 'run.json').read_text()) | |
| items = {i['item_id']: i for i in load_items(meta['items_path'])} | |
| path = run_dir / 'responses.jsonl' | |
| backup = run_dir / 'responses.before-reparse.jsonl' | |
| if not backup.exists(): | |
| backup.write_bytes(path.read_bytes()) | |
| out, counts = [], {'records': 0, 'reparsed': 0, 'changed': 0} | |
| for r in read_jsonl(path): | |
| counts['records'] += 1 | |
| if r['status'] == 'OK' and r.get('text') is not None and r['item_id'] in items: | |
| new = prompts.parse(r['text'], items[r['item_id']]) | |
| if new['status'] == 'UNPARSED' and r.get('finish_reason') in TRUNCATED: | |
| new = {**new, 'status': 'TRUNCATED'} | |
| counts['reparsed'] += 1 | |
| if new != r.get('parsed'): | |
| counts['changed'] += 1 | |
| r = {**r, 'parsed_before': r.get('parsed'), 'parsed': new} | |
| out.append(json.dumps(r, ensure_ascii=False) + '\n') | |
| tmp = path.with_suffix('.jsonl.tmp') | |
| tmp.write_text(''.join(out), encoding='utf-8') | |
| tmp.replace(path) | |
| return counts | |
| def score(run_dir, truth_path, group_keys=('version_id',)): | |
| run_dir = Path(run_dir) | |
| meta = json.loads((run_dir / 'run.json').read_text()) | |
| items = {i['item_id']: i for i in load_items(meta['items_path'])} | |
| truth = {t['item_id']: t for t in read_jsonl(truth_path)} | |
| replies = latest_responses(run_dir / 'responses.jsonl') if (run_dir / 'responses.jsonl').exists() else {} | |
| missing_truth = sorted(set(items) - set(truth)) | |
| if missing_truth: | |
| raise ValueError(f'truth missing for {len(missing_truth)} items, e.g. {missing_truth[:3]}') | |
| rows = [] | |
| for item_id, item in items.items(): | |
| reply = replies.get(item_id) | |
| parsed = reply.get('parsed') if reply and reply['status'] == 'OK' else None | |
| t = truth[item_id] | |
| if prompts.is_np(item): | |
| row = np_answers.score(item['scoring'], t['truth'], parsed) | |
| else: | |
| row = scoring.score_one(item['answer'], scoring.rule_for(item), t['truth'], parsed, | |
| t.get('magnitude'), len(prompts.item_options(item)) or None) | |
| if reply is None: | |
| row['status'] = 'NOT_RUN' | |
| access = (reply or {}).get('access') or {} | |
| rows.append({'item_id': item_id, 'version_id': item['version_id'], **item.get('tags', {}), | |
| **row, 'answer': parsed.get('value') if parsed else None, 'truth': t['truth'], | |
| 'frames_sent': sum(v.get('frames_sent') or 0 for v in access.get('views', [])), | |
| 'bytes_sent': sum(v.get('bytes_sent') or 0 for v in access.get('views', []))}) | |
| with open(run_dir / 'scores.jsonl', 'w', encoding='utf-8') as fh: | |
| for row in rows: | |
| fh.write(json.dumps(row, ensure_ascii=False) + '\n') | |
| summary = {'schema': 'model-evaluation-summary/1', 'endpoint': meta['endpoint'], | |
| 'settings': meta['settings'], 'items_sha256': meta['items_sha256'], | |
| 'truth_sha256': file_sha256(truth_path), | |
| 'overall': scoring.summarize(rows, ())[0] if rows else None, | |
| 'groups': {','.join(k): scoring.summarize(rows, k) for k in | |
| [tuple(group_keys)] + [(k,) for k in group_keys if len(group_keys) > 1]}, | |
| 'scope': 'Model answers scored against private truth with prover.scoring tolerances; ' | |
| 'qualification of the items themselves is not established here.'} | |
| (run_dir / 'summary.json').write_text(json.dumps(summary, ensure_ascii=False, indent=2)) | |
| return summary | |
| def main(argv=None): | |
| ap = argparse.ArgumentParser(description=__doc__.split('\n')[0]) | |
| sub = ap.add_subparsers(dest='command', required=True) | |
| r = sub.add_parser('run', help='query one endpoint over an item set') | |
| r.add_argument('--items', required=True) | |
| r.add_argument('--endpoint', required=True, help='endpoint JSON file (see endpoints.example.json)') | |
| r.add_argument('--name', help='endpoint name inside a multi-endpoint file') | |
| r.add_argument('--settings', default='{}', help='JSON object, path to a JSON file, or preset:<name> from presets.json') | |
| r.add_argument('--out', required=True, help='fresh or resumable run directory') | |
| r.add_argument('--workers', type=int, default=1) | |
| r.add_argument('--limit', type=int) | |
| r.add_argument('--stop-after-denied', type=int, default=0, | |
| help='stop sending after N answers fail with HTTP 401/403 (banned key/account); exit code 3') | |
| r.add_argument('--keep-errors', help='regex: items whose latest ERROR matches count as done on resume') | |
| rp = sub.add_parser('reparse', help='re-parse stored replies with the current parser (no model calls)') | |
| rp.add_argument('--run', required=True) | |
| s = sub.add_parser('score', help='score a run against private truth') | |
| s.add_argument('--run', required=True) | |
| s.add_argument('--truth', required=True) | |
| s.add_argument('--by', default='version_id', help='comma-separated grouping keys') | |
| k = sub.add_parser('ping', help='send one short text request to each named endpoint') | |
| k.add_argument('--endpoint', required=True) | |
| k.add_argument('--name', action='append', help='endpoint name; repeat, default all') | |
| k.add_argument('--image', help='also attach this image, to check vision input') | |
| k.add_argument('--timeout', type=float, default=30.0) | |
| p = sub.add_parser('preview', help='print the request for one item without calling a model') | |
| p.add_argument('--items', required=True) | |
| p.add_argument('--settings', default='{}') | |
| p.add_argument('--item') | |
| p.add_argument('--cache', default='/tmp/eval-preview-frames') | |
| args = ap.parse_args(argv) | |
| def load_obj(text): | |
| if Path(text).is_file(): | |
| return json.loads(Path(text).read_text()) | |
| if text.startswith('preset:'): | |
| presets = json.loads((Path(__file__).with_name('presets.json')).read_text())['presets'] | |
| name = text.split(':', 1)[1] | |
| if name not in presets: | |
| raise SystemExit(f'unknown preset {name!r}; choose from {sorted(presets)}') | |
| return presets[name] | |
| return json.loads(text) | |
| if args.command == 'ping': | |
| data = load_obj(args.endpoint) | |
| table = data.get('endpoints', {'endpoint': data}) | |
| names = args.name or sorted(table) | |
| failed = 0 | |
| for name in names: | |
| parts = [{'type': 'text', 'text': 'Reply with the JSON {"answer": "ok"} and nothing else.'}] | |
| if args.image: | |
| parts.insert(0, {'type': 'image', 'path': args.image, 'mime': 'image/jpeg'}) | |
| try: | |
| client = providers.Client({**table[name], 'max_retries': 0, 'timeout_s': args.timeout}) | |
| reply = client.generate({'parts': parts, 'max_tokens': 256, 'temperature': 0.0}) | |
| print(f"{name}: OK {reply['latency_s']}s {reply.get('model_reported') or ''} " | |
| f"{reply['text'][:80]!r}") | |
| except (providers.ProviderError, ValueError, KeyError) as exc: | |
| failed += 1 | |
| print(f'{name}: FAIL {type(exc).__name__}: {str(exc)[:200]}') | |
| raise SystemExit(1 if failed else 0) | |
| if args.command == 'run': | |
| endpoint = load_obj(args.endpoint) | |
| if 'endpoints' in endpoint: | |
| if not args.name: | |
| raise SystemExit(f"--name required; choose from {sorted(endpoint['endpoints'])}") | |
| endpoint = endpoint['endpoints'][args.name] | |
| result = run(args.items, endpoint, load_obj(args.settings), args.out, args.workers, args.limit, | |
| args.stop_after_denied, args.keep_errors) | |
| print(json.dumps(result)) | |
| if result.get('stopped'): | |
| raise SystemExit(3) | |
| elif args.command == 'reparse': | |
| print(json.dumps(reparse(args.run))) | |
| elif args.command == 'score': | |
| summary = score(args.run, args.truth, tuple(k for k in args.by.split(',') if k)) | |
| print(json.dumps(summary['overall'], ensure_ascii=False, indent=2)) | |
| else: | |
| items = load_items(args.items) | |
| item = next((i for i in items if i['item_id'] == args.item), items[0]) if args.item else items[0] | |
| request, access = build_request(item, normalize_settings(load_obj(args.settings)), args.cache) | |
| print(prompt_text(request)) | |
| print(json.dumps(access, ensure_ascii=False, indent=2)) | |
| if __name__ == '__main__': | |
| main() | |