Verify complete answers from archived generation tokens

This commit is contained in:
2026-11-24 16:34:33 +08:00
parent c53d78b4aa
commit 0f4c0a982c
4 changed files with 175 additions and 0 deletions
+73
View File
@@ -0,0 +1,73 @@
"""Reconstruct complete-answer scores from the saved token streams."""
import argparse
import json
from pathlib import Path
from tokenizers import Tokenizer
from crossqkv.lisa_full_answer import SCHEDULES, fingerprint, grade
from crossqkv.lisa_full_answer_train import audit
from functional.run import write_json
def verify(tokenizer, protocol, expected, rows, arms, allow_prefix=False):
"""Validate each recorded model answer against its frozen prompt and token IDs."""
if not rows or len(rows) > len(expected) or (not allow_prefix and len(rows) != len(expected)):
raise ValueError('Unexpected number of evaluated items')
stop_ids = {tokenizer.token_to_id(text) for text in protocol['stops']}
if None in stop_ids:
raise ValueError('Missing stop token in the frozen tokenizer')
for item, row in zip(expected, rows):
if (row['id'], row['task'], row['gold']) != (item['id'], item['task'], item['answer']):
raise ValueError(f"Unexpected row for {item['id']}")
if set(row['arms']) != set(arms):
raise ValueError(f"Unexpected arms for {item['id']}")
for arm in arms:
stored = row['arms'][arm]
tokens = stored['tokens']
if (not 0 < len(tokens) <= protocol['cap']
or any(type(token) is not int or tokenizer.id_to_token(token) is None
for token in tokens)
or any(token in stop_ids for token in tokens[:-1])):
raise ValueError(f"Invalid generated token stream for {item['id']} / {arm}")
ended = tokens[-1] in stop_ids
if not ended and len(tokens) != protocol['cap']:
raise ValueError(f"Generation ended before a stop or the cap for {item['id']} / {arm}")
score = grade(tokenizer, tokens, 'eos' if ended else 'max_new_tokens', item['answer'])
if stored != score:
raise ValueError(f"Archived score does not match the tokens for {item['id']} / {arm}")
def main():
parser = argparse.ArgumentParser(description=__doc__)
for name in ('tokenizer', 'frozen', 'rows', 'out'):
parser.add_argument('--'+name, required=True, type=Path)
parser.add_argument('--selection', type=Path, help='Verify the selected task on the test split')
parser.add_argument('--allow-screen-prefix', action='store_true')
args = parser.parse_args()
if args.selection and args.allow_screen_prefix:
parser.error('Test verification requires all frozen test rows')
frozen = json.loads(args.frozen.read_bytes())
protocol = frozen['protocol']
if fingerprint(args.tokenizer) != protocol['weights']['tokenizer.json']:
raise ValueError('Tokenizer differs from the frozen experiment')
rows = json.loads(args.rows.read_bytes())
tokenizer = Tokenizer.from_file(str(args.tokenizer))
report = {'frozen_sha256': fingerprint(args.frozen), 'rows_sha256': fingerprint(args.rows),
'rows_verified': len(rows)}
if args.selection:
chosen = json.loads(args.selection.read_bytes())
if chosen['frozen_sha256'] != report['frozen_sha256']:
raise ValueError('Selection points to a different frozen manifest')
expected = [item for item in frozen['problems']['test']
if item['task'] == chosen['chosen']['task']]
verify(tokenizer, protocol, expected, rows, ('native', 'direct', 'lisa'))
report['final_answer_audit'] = audit(rows)
else:
verify(tokenizer, protocol, frozen['problems']['screen'], rows, SCHEDULES,
allow_prefix=args.allow_screen_prefix)
write_json(args.out, report)
if __name__ == '__main__':
main()