VEHwang's picture
Upload CoCogni4D-Bench (questions, media, scripts, render records, code) (part 7)
7ff74f6 verified
Raw History Blame Contribute Delete
15.6 kB
"""Release answer forms, derived from current scoring rules and frozen proofs."""
import copy
import hashlib
import itertools
import functools
import json
from pathlib import Path
import math
import random
import re
from tools.release.numeric_choice import Format, formatter
from tools.evaluation import np_answers
NUMERIC = {'np:number', 'np:point', 'np:vector', 'np:clock_time'}
DURATION_VERSIONS = ('path_length.value.over_interval',) # distractors are answer/period ratios of the version, rescaled by this question's stated period (answer ~ walking speed x period would otherwise single out the truth)
PERIOD = re.compile(r'第\s*(\d+(?:\.\d+)?)\s*至\s*(\d+(?:\.\d+)?)\s*秒')
POOLS = {} # base version id -> sorted scalar true answers of the release (empirical distractor distribution)
KEEP_COUNTERFACTUAL = 1
def period_seconds(item):
"""Length of the period the question states (first '第a至b秒'), or None."""
m = PERIOD.search(item.get('question', {}).get('zh', ''))
return float(m.group(2))-float(m.group(1)) if m and float(m.group(2)) > float(m.group(1)) else None
def set_pools(items, truth):
"""Collect each scalar numeric version's true answers; the choice builder draws distractors from them."""
POOLS.clear()
for item in items:
value = truth.get(item['item_id'], {}).get('truth')
base = item['version_id'].split('@')[0]
if item['answer']['type'] == 'np:number' and base.startswith(DURATION_VERSIONS) and period_seconds(item) and type(value) in (int, float):
POOLS.setdefault(base, []).append(value/period_seconds(item)) # answer per second of the stated period
elif (item['answer']['type'] in ('np:point', 'np:vector') and isinstance(value, list) and len(value) in (2, 3)
and all(type(c) in (int, float) and math.isfinite(c) for c in value)):
POOLS.setdefault(item['version_id'].split('@')[0], []).append([float(f'{c:.1f}') for c in value[:2]] + [0.]) # whole vectors, as displayed
elif item['answer']['type'] in ('np:number', 'np:clock_time') and type(value) in (int, float) and math.isfinite(value):
POOLS.setdefault(item['version_id'].split('@')[0], []).append(float(f'{value:.1f}')) # as displayed
for values in POOLS.values():
values.sort()
def paired_index(items, choices):
"""Address both answer forms without changing an existing primary row."""
primary = {q['item_id']: (i, q) for i, q in enumerate(items, 1)}
supplemental = {q['item_id']: (i, q) for i, q in enumerate(choices, 1)}
result = []
for line, item in enumerate(items, 1):
iid, kind = item['item_id'], item['answer']['type']
if kind in NUMERIC and iid in supplemental:
original, choice_file, (choice_line, choice) = iid, 'choices.jsonl', supplemental[iid]
elif kind == 'np:angle' and iid.endswith('-angle') and iid[:-6] in primary:
original, choice_file, (choice_line, choice) = iid[:-6], 'items.jsonl', primary[iid[:-6]]
else:
continue
if len(choice['answer'].get('options', [])) != 4:
continue
result.append(dict(schema='release-form-pair/1', version_id=item['version_id'],
original_item_id=original, fill_item_id=iid, choice_item_id=choice['item_id'],
fill_file='items.jsonl', fill_line=line, choice_file=choice_file, choice_line=choice_line))
return result
def pair_problems(items, choices, pairs):
"""Verify physical row addresses and complete coverage of available pairs."""
streams = {'items.jsonl': items, 'choices.jsonl': choices}
primary = {q['item_id']: q for q in items}
choice_ids = {q['item_id'] for q in choices}
expected = {(q['item_id'], q['item_id']) for q in items
if q['answer']['type'] in NUMERIC and q['item_id'] in choice_ids}
expected |= {(q['item_id'], q['item_id'][:-6]) for q in items
if q['answer']['type'] == 'np:angle' and q['item_id'].endswith('-angle')
and q['item_id'][:-6] in primary
and len(primary[q['item_id'][:-6]]['answer'].get('options', [])) == 4}
seen, bad = set(), []
for pair in pairs:
try:
assert pair['schema'] == 'release-form-pair/1' and pair['fill_file'] == 'items.jsonl'
rows = []
for side in ('fill', 'choice'):
line = pair[side+'_line']; stream = streams[pair[side+'_file']]
assert type(line) is int and 1 <= line <= len(stream)
row = stream[line-1]
assert row['item_id'] == pair[side+'_item_id'] and row['version_id'] == pair['version_id']
rows.append(row)
fill, choice = rows
assert fill['answer']['type'] in NUMERIC | {'np:angle'} and len(choice['answer'].get('options', [])) == 4
assert pair['original_item_id'] == choice['item_id']
key = fill['item_id'], choice['item_id']
assert key in expected and key not in seen
seen.add(key)
except (AssertionError, KeyError, TypeError, IndexError):
bad.append('question forms: invalid paired row address')
if seen != expected:
bad.append('question forms: paired index coverage differs')
return bad
@functools.lru_cache(None)
def published_rules():
path = Path(__file__).resolve().parents[2] / 'packages/scoring-rules.json'
return json.loads(path.read_text())['rules'] if path.is_file() else None
def scoring_for(item):
if published_rules() is not None:
return published_rules()[item['version_id']][item['answer']['type'][3:]]
kind = item['answer']['type'][3:]
rule, source = np_answers.scorer(item['version_id'], kind)
return dict(rule, answer_type=kind, source=source)
def _numeric_words(text):
from collections import Counter
# Reference indices are names, not public measurements. All other numeric
# strings, including precision and repeated occurrences, must be retained.
names = re.findall(r'^([A-Za-z_\u4e00-\u9fff ]+[0-9]+)[::]', text, re.M)
for name in sorted(names, key=len, reverse=True):
text = text.replace(name, '对象')
return Counter(re.findall(r'(?<![A-Za-z0-9_])-?\d+(?:\.\d+)?(?![A-Za-z0-9_])', text))
def refresh_text(item, proof):
"""Refresh public prose before choices; retain frozen proof and numeric data.
Frozen scaffolds each occupy one leading piece. Auxiliary question scaffolds
require their own stored trees and are rejected rather than guessed.
"""
from embodied_pipeline.prover import surface
public = proof.get('public', {})
slots = public.get('slots') or {}
if not slots or not public.get('text'):
return proof
scaffolds = public.get('scaffold', [])
if 'given_answers' in scaffolds:
raise surface.SurfaceError('auxiliary questions require their frozen public trees')
roles = proof.get('presentation', {}).get('roles', [])
actor = proof.get('scope', {}).get('truth_actor')
ids = surface.public_ids(slots, roles)
texts = {}
# These leading strings identify fixture landmarks. Room qualifiers ending
# in 里/相通 remain room names; object names at the ends remain fixture names.
labels = surface._spec()[1]['fixture']
rooms = surface.room_labels()
for lang in item['question']:
old = public['text'].get(lang)
if old is None:
raise surface.SurfaceError(f'missing frozen {lang} text')
prefix = copy.deepcopy(old[:len(scaffolds)])
for piece in prefix:
text = piece['text']
if lang == 'zh':
for key, label in labels.items():
text = re.sub(r'(?<![A-Za-z0-9_])'+re.escape(key)+r'(?![A-Za-z0-9_])', label['zh'], text)
for key in labels.keys() & rooms.keys():
before, after = rooms[key]['zh'], labels[key]['zh']
if before != after:
text = re.sub(re.escape(before)+r'(?!里|内|相通|之间|通往)', after, text)
if '题中主体' in text:
text = text.replace('题中主体', surface.subject_name(slots, roles, actor, lang))
piece['text'] = text
texts[lang] = prefix + surface.render_parts(item['version_id'], slots, lang, ids=ids)
refreshed = ''.join(p['text'] for p in texts[lang])
if _numeric_words(refreshed) != _numeric_words(item['question'][lang]):
raise surface.SurfaceError(f'{item["item_id"]}: public numeric text changed')
item['question'][lang] = refreshed
options = surface.reply_options(slots)
if options:
by_id = {o['value']: o for o in options}
for option in item['answer'].get('options', []):
for lang in ('zh', 'en'):
if lang in option:
option[lang] = by_id[option['id']][lang]
return dict(proof, public=dict(public, text=texts))
def apply(item, truth, proof):
"""Refresh scoring; return a public choice, private answer, or skip record.
Numeric primary forms, including ratios, retain their numeric truth. The frozen proof is never changed.
"""
from embodied_pipeline.prover import numeric_choice
item['scoring'] = scoring_for(item)
if item['answer']['type'] not in NUMERIC:
return None, None, None
seed = int.from_bytes(hashlib.sha256(item['item_id'].encode()).digest()[:8], 'big')
minimum = formatter(proof['replay']['value'], item['scoring']).digits
formats = [Format(d) for d in range(minimum, max(minimum, 17)+1)]
result = numeric_choice.build(proof, random.Random(seed), quantizers=[f.value for f in formats],
pool=(None if item['version_id'].split('@')[0].startswith(DURATION_VERSIONS) and not period_seconds(item)
else POOLS.get(item['version_id'].split('@')[0])), keep_counterfactual=KEEP_COUNTERFACTUAL,
pool_scale=(period_seconds(item) or 1.) if item['version_id'].split('@')[0].startswith(DURATION_VERSIONS) else 1.)
if 'skip' in result:
if '.ratio.' in item['version_id']:
raise ValueError(f"{item['item_id']}: ratio choice unavailable: {result['skip']}")
return None, None, dict(item_id=item['item_id'], version_id=item['version_id'], reason=result['skip'])
fmt = formats[result['quantizer_index']]
choice = copy.deepcopy(item)
choice['answer'] = dict(type='np:options', options=[
dict(id=letter, value=value, zh=fmt.text(value), en=fmt.text(value))
for letter, value in zip('ABCD', result['options'])])
for key in ('unit', 'clock'):
if key in item['answer']:
choice['answer'][key] = item['answer'][key]
choice['scoring'] = scoring_for(choice)
choice['tags']['answer_kind'] = 'options'
reply = next((key for key, slot in proof.get('public', {}).get('slots', {}).items()
if slot.get('method') in numeric_choice.NUMERIC), None)
text_parts = proof.get('public', {}).get('text', {})
question = {lang: text.replace(''.join(part['text'] for part in text_parts.get(lang, [])
if reply is not None and part.get('slot') == reply), '')
for lang, text in item['question'].items()}
question = {lang: text.replace('?。', '?').replace('?.', '?').rstrip() for lang, text in question.items()}
choice['question'] = {lang: text + '\n' + ('请选择一项:' if lang == 'zh' else 'Choose one: ') +
';'.join(f"{o['id']}. {o[lang]}" for o in choice['answer']['options'])
for lang, text in question.items()}
private = dict(item_id=item['item_id'], truth=result['correct'],
numeric_truth=copy.deepcopy(truth['truth']), numeric_scoring=copy.deepcopy(item['scoring']),
distractor_source=result['distractor_source'])
return choice, private, None
def problems(items, truth, choices, choice_truth, skips):
"""Check published forms independently of option construction; aggregate errors."""
from collections import Counter
errors = Counter()
by = {q['item_id']: q for q in choices}
ct = {q['item_id']: q for q in choice_truth}
skipped = {q['item_id']: q for q in skips}
primary = {q['item_id']: q for q in items}
for name, rows, ids in [('choices', choices, by), ('choice truth', choice_truth, ct), ('skips', skips, skipped)]:
if len(rows) != len(ids):
errors[f'duplicate {name} identity'] += 1
if set(by) != set(ct) or set(by) & set(skipped) or (set(by) | set(skipped)) - set(primary):
errors['choice identities differ'] += 1
for q in items:
iid = q['item_id']
if q['scoring'] != scoring_for(q):
errors['stale scoring'] += 1
ratio = '.ratio.' in q['version_id']
if ratio and q['answer']['type'] != 'np:number':
errors['ratio missing numeric fill'] += 1
if (q['answer']['type'] in NUMERIC or ratio) and iid not in by and iid not in skipped:
errors['missing numeric choice'] += 1
if ratio and iid in skipped:
errors['ratio choice skipped'] += 1
for iid, q in by.items():
t = ct.get(iid)
if not t or iid not in primary:
continue
opts = q['answer'].get('options', [])
if (q['answer']['type'] != 'np:options' or [o['id'] for o in opts] != list('ABCD')
or q['scoring'] != scoring_for(q) or t['truth'] not in 'ABCD'):
errors['invalid choice form'] += 1; continue
values = [o['value'] for o in opts]
value = values['ABCD'.index(t['truth'])]
numeric_truth = t['numeric_truth']
vector = isinstance(numeric_truth, list)
passed = [np_answers.score(t['numeric_scoring'], numeric_truth,
{'status': 'PARSED', 'value': v})['passed'] for v in values]
if passed != [letter == t['truth'] for letter in 'ABCD']:
errors['choice truth differs'] += 1
labels = [o.get('zh', '') for o in opts]
fmt = Format(1)
uniform = all(o.get(lang) == fmt.text(o['value'])
for o in opts for lang in ('zh', 'en')) and all(
f"{o['id']}. {o[lang]}" in text
for o in opts for lang, text in q['question'].items())
if not uniform:
errors['choice display differs'] += 1
p = primary[iid]
expected_truth = numeric_truth
if truth.get(iid, {}).get('truth') != expected_truth:
errors['primary truth differs'] += 1
numeric = dict(p, answer={'type': 'np:' + t['numeric_scoring']['answer_type']})
if t['numeric_scoring'] != scoring_for(numeric):
errors['stale choice tolerance'] += 1
tau = np_answers.radius(numeric_truth, t['numeric_scoring'])[0]
distance = lambda a, b: math.dist(a[:2], b[:2]) if vector else abs(a-b)
if (not tau or not math.isfinite(tau) or any(not math.isfinite(x) for v in values
for x in (v if vector else [v])) or any((min(a,b) <= 0 or max(a/b,b/a) < t['numeric_scoring']['factor']**2)
if t['numeric_scoring']['kind'] == 'log_ratio' else distance(a,b) < 2*tau
for a,b in itertools.combinations(values,2))):
errors['choice spacing'] += 1
return [f'question forms: {key}: {n}' for key,n in sorted(errors.items())]