pns-bind-25m / rr2 /campaign /runtime.py
nur-dev's picture
Add registered reviewer-requested held-out-name and acquisition tests
b945458 verified
Raw History Blame Contribute Delete
5.41 kB
"""Isolated RR2 execution against the immutable paper-v2.0 source release."""
from __future__ import annotations
import hashlib
import json
import os
import sys
from pathlib import Path
HERE = Path(__file__).resolve().parent
ART = Path(os.environ.get('PNS_RR2_ART', '/raid/nurgaly/datasets/pns/reviewer_rr2_20261004'))
PUBLIC = Path('/raid/nurgaly/datasets/pns/release/pns-hf-e8-20260911/model/e8_full')
ORIGINAL_ART = Path('/raid/nurgaly/datasets/pns/release/pns-e8-full-paper-20260910/PNS_experiment/campaigns/e8_full/artifacts')
sys.dont_write_bytecode = True
os.environ['TOKENIZERS_PARALLELISM'] = 'false'
os.environ['PNS_TOKENIZER'] = str(PUBLIC / 'source/tokenizer/tokenizer.json')
os.environ['PNS_GOLD'] = 'v2'
sys.path.insert(0, str(PUBLIC / 'source/campaigns/e8_full'))
import common
import data
import evaluate
import train as published_train
from model import FullModel
from pns.data.tokenize import load_tokenizer
from pns.world import schema
LEFT = ('Zavi', 'Pemo', 'Nori', 'Feta', 'Rulo', 'Gumi', 'Helo', 'Kora', 'Suni', 'Vepi', 'Wado', 'Yaku')
RIGHT = LEFT + ('Jomi', 'Celu', 'Ami', 'Oru', 'Umo', 'Qela')
KINDS = ('PERSON_NAMES', 'PROJECT_NAMES', 'SHIPMENT_NAMES', 'VAULT_NAMES', 'DEVICE_NAMES')
SIZES = (26, 14, 10, 8, 8)
ORIGINAL_NAMES = tuple(n for kind in KINDS for n in getattr(schema, kind))
def sha(path):
h = hashlib.sha256()
with Path(path).open('rb') as stream:
for chunk in iter(lambda: stream.read(1 << 20), b''):
h.update(chunk)
return h.hexdigest()
def write(path, obj):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
with path.open('x') as stream:
json.dump(obj, stream, indent=2, sort_keys=True, allow_nan=False)
stream.write('\n')
def read(path):
return json.loads(Path(path).read_text())
def inventories():
import random
result = []
for split in range(3):
names = [a + '-' + b for i, a in enumerate(LEFT) for j, b in enumerate(RIGHT)
if (i + j) % 3 == split]
random.Random(20261004 + split).shuffle(names)
result.append(tuple(names[:66]))
return tuple(result)
INVENTORIES = inventories()
def configure_names(partition=None):
names = ORIGINAL_NAMES if partition is None else INVENTORIES[partition]
offset = 0
# Mutate lists, not module files. Imported simulator references remain valid.
for kind, size in zip(KINDS, SIZES):
getattr(schema, kind)[:] = names[offset:offset + size]
offset += size
data.NAMES = list(names[:64])
evaluate.NAMES = list(names[:64])
return names
def source_hashes():
manifest = read(PUBLIC / 'MANIFEST.json')['files']
public_hashes = {}
for path in sorted((PUBLIC / 'source').rglob('*')):
if not path.is_file() or (path.suffix != '.py' and path.name != 'tokenizer.json'):
continue
key = str(path.relative_to(PUBLIC))
actual = sha(path)
if actual != manifest[key]:
raise RuntimeError(f'Immutable public source mismatch: {key}')
public_hashes[key] = actual
return {'campaign': {p.name: sha(p) for p in sorted(HERE.glob('*.py'))},
'preregistration': sha(HERE / 'PREREGISTRATION.md'), 'public': public_hashes}
def freeze():
frozen = read(ART / 'FREEZE.json')
if frozen['sources'] != source_hashes():
raise RuntimeError('Campaign source changed after freeze')
return frozen
def configure_data(suite):
data.ART = ORIGINAL_ART if suite == 'original_train' else ART / suite
def checkpoint(path, obj):
# Reuse the deposited append-only atomic checkpoint writer.
common.checkpoint(path, obj)
def name_checks():
import collections
tok = load_tokenizer()
encoded = [[tok.encode(name).ids for name in names] for names in INVENTORIES]
challenge_encoded = [[tok.encode(name).ids for name in names[:64]] for names in INVENTORIES]
support = [set(x for row in rows for x in row) for rows in encoded]
challenge_support = [set(x for row in rows for x in row) for rows in challenge_encoded]
checks = {
'three_disjoint_name_inventories': all(not set(INVENTORIES[i]) & set(INVENTORIES[j])
for i in range(3) for j in range(i)),
'exactly_66_names_each': all(len(set(n)) == 66 for n in INVENTORIES),
'all_names_exactly_seven_pieces': all(len(row) == 7 for rows in encoded for row in rows),
'shared_name_token_support': all(s == support[0] for s in support),
'challenge_shared_name_token_support': all(s == challenge_support[0] for s in challenge_support),
'each_component_occurs_each_split': all(all(any(name.startswith(a + '-') for name in names) for a in LEFT)
and all(any(name.endswith('-' + b) for name in names) for b in RIGHT)
for names in INVENTORIES),
'inventories_disjoint_from_original_names': all(not set(n) & set(ORIGINAL_NAMES) for n in INVENTORIES),
}
return checks, {'inventories': INVENTORIES, 'original_inventory': ORIGINAL_NAMES,
'length_counts': [dict(collections.Counter(map(len, rows))) for rows in encoded],
'token_support': [sorted(s) for s in support],
'challenge_token_support': [sorted(s) for s in challenge_support]}