91 lines
4.2 KiB
Python
91 lines
4.2 KiB
Python
"""Freeze paired lookup questions and restore individual native attention layers."""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import random
|
|
from pathlib import Path
|
|
|
|
import torch
|
|
from tokenizers import Tokenizer
|
|
|
|
from crossqkv.lisa_effect_screen import WORDS
|
|
from crossqkv.lisa_full_answer import evaluate
|
|
from crossqkv.lisa_train import LearnableSharingAttention
|
|
from functional.model import StreamingLM
|
|
from functional.run import write_json
|
|
|
|
|
|
SITES = (15, 19, 23)
|
|
ADAPTER_SHA = 'c82db5af7fa42cf58a349f3e53961da2360b211a7ed606f53a728860c64f6f29'
|
|
|
|
|
|
def paired_questions(split, pairs, seed):
|
|
rng = random.Random(seed)
|
|
rows = []
|
|
for i in range(pairs):
|
|
keys = rng.sample(WORDS, 12)
|
|
values = rng.sample(range(20, 100), 12)
|
|
target, foil = rng.sample(range(12), 2)
|
|
for variant in range(2):
|
|
records = ', '.join(f'{k}={v}' for k, v in zip(keys, values))
|
|
rows.append({'id': f'{split}-{i:03}-{variant}', 'task': 'lookup',
|
|
'question': f'Records in time order: {records}.\nWhat is the recorded number for {keys[target]}?',
|
|
'answer': values[target]})
|
|
values[target], values[foil] = values[foil], values[target]
|
|
return rows
|
|
|
|
|
|
def main():
|
|
p = argparse.ArgumentParser(description=__doc__)
|
|
for name in ('source', 'prior', 'out'):
|
|
p.add_argument('--'+name, type=Path, required=True)
|
|
args = p.parse_args()
|
|
args.out.mkdir(exist_ok=True, parents=True)
|
|
previous = json.loads((args.prior/'frozen.json').read_text())
|
|
splits = {s: paired_questions(s, n, seed) for s, n, seed in (
|
|
('diagnostic', 8, 72501), ('validation', 8, 72502), ('test', 32, 72503))}
|
|
seen = {r['question'] for rows in previous['problems'].values() for r in rows}
|
|
for rows in splits.values():
|
|
for row in rows:
|
|
if row['question'] in seen:
|
|
raise ValueError('Repeated question')
|
|
seen.add(row['question'])
|
|
spec = {'splits': splits, 'base_adapter': ADAPTER_SHA, 'sites': SITES,
|
|
'rank_budget': [32, 40, 48], 'uniform_rank': 40, 'cap': 24,
|
|
'rank_selection': 'Order layers by increase in complete-answer correct count upon single restoration; ties by ascending layer index, earlier gets higher rank.',
|
|
'primary_metric': 'complete answer accuracy; paired uncertainty resamples counterfactual pairs',
|
|
'secondary_metric': 'both members of pair correct'}
|
|
spec_path = args.out/'protocol.json'
|
|
if spec_path.exists() and json.loads(spec_path.read_text()) != json.loads(json.dumps(spec)):
|
|
raise ValueError('Protocol changed')
|
|
write_json(spec_path, spec)
|
|
weight_path = args.prior/'final/lisa.pt'
|
|
if hashlib.sha256(weight_path.read_bytes()).hexdigest() != ADAPTER_SHA:
|
|
raise ValueError('Prior adapter mismatch')
|
|
torch.set_num_threads(1)
|
|
c = json.loads((args.source/'model_config.json').read_text())
|
|
model = StreamingLM(args.source/'weights', c, seconds=172800, process_swap_limit_kib=None)
|
|
c = model.config
|
|
tok = Tokenizer.from_file(str(args.source/'tokenizer.json'))
|
|
adapters = torch.nn.ModuleDict({str(i): LearnableSharingAttention(c['hidden_size'],
|
|
c['num_attention_heads'], c['num_key_value_heads'], 40, c['rope_parameters']['rope_theta'],
|
|
c['rope_parameters']['partial_rotary_factor'], bias=c.get('attention_bias', False)) for i in SITES})
|
|
adapters.load_state_dict(torch.load(weight_path, weights_only=True, map_location='cpu'))
|
|
for restored in (None, *SITES):
|
|
active = tuple(i for i in SITES if i != restored)
|
|
label = 'baseline' if restored is None else f'restore-{restored}'
|
|
path = args.out/(label+'.json')
|
|
rows = json.loads(path.read_text()) if path.exists() else []
|
|
questions = splits['diagnostic']
|
|
if [r['id'] for r in rows] != [q['id'] for q in questions[:len(rows)]]:
|
|
raise ValueError('Diagnostic prefix mismatch')
|
|
for start in range(len(rows), len(questions), 2):
|
|
rows.extend(evaluate(model, tok, questions[start:start+2], {label: active},
|
|
{i: adapters[str(i)] for i in active}))
|
|
write_json(path, rows)
|
|
print(label, len(rows), flush=True)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|