154 lines
7.6 KiB
Python
154 lines
7.6 KiB
Python
"""Compare diagnostic rank allocation and uniform ranks under matched training."""
|
|
import argparse
|
|
import json
|
|
from pathlib import Path
|
|
|
|
import torch
|
|
from tokenizers import Tokenizer
|
|
|
|
from crossqkv.lisa_combination_screen import ADAPTER_SHA, SITES
|
|
from crossqkv.lisa_effect_answer_audit import vocabulary_scores
|
|
from crossqkv.lisa_full_answer import STOP_TEXT, fingerprint, prompt
|
|
from crossqkv.lisa_full_answer_train import FitCapture, load_locked, train, verified_fit_captures
|
|
from crossqkv.lisa_tail import TorchTail
|
|
from crossqkv.lisa_train import LearnableSharingAttention
|
|
from functional.model import PREFIX, StreamingLM
|
|
from functional.run import write_json
|
|
|
|
|
|
def assignments(protocol, directory):
|
|
expected = [(q['id'], q['answer']) for q in protocol['splits']['diagnostic']]
|
|
scores = {}
|
|
for label in ('baseline', *(f'restore-{i}' for i in SITES)):
|
|
rows = json.loads((directory/(label+'.json')).read_text())
|
|
if [(r['id'], r['gold']) for r in rows] != expected:
|
|
raise ValueError(f'Incomplete diagnostic arm {label}')
|
|
scores[label] = sum(r['arms'][label]['correct'] for r in rows)
|
|
ordered = sorted(SITES, key=lambda i: (-scores[f'restore-{i}'], i))
|
|
selected = dict(zip(ordered, reversed(protocol['rank_budget'])))
|
|
reverse = dict(zip(ordered, protocol['rank_budget']))
|
|
return scores, {'allocated':selected, 'reversed':reverse, 'uniform':dict.fromkeys(SITES, 40)}
|
|
|
|
|
|
def local_scores_only(module, args):
|
|
local, donor = args[0].chunk(2, dim=-1)
|
|
return (torch.cat((local, torch.zeros_like(donor)), dim=-1),)
|
|
|
|
|
|
def make_adapters(config, ranks, shared):
|
|
rope = config['rope_parameters']
|
|
adapters = {i: LearnableSharingAttention(config['hidden_size'], config['num_attention_heads'],
|
|
config['num_key_value_heads'], ranks[i], rope['rope_theta'], rope['partial_rotary_factor'],
|
|
bias=config.get('attention_bias', False)) for i in SITES}
|
|
if not shared:
|
|
for adapter in adapters.values():
|
|
adapter.fuse.register_forward_pre_hook(local_scores_only)
|
|
return adapters
|
|
|
|
|
|
def score_gold_answers(outputs, sequences, starts, embedding):
|
|
gold = [ids[first:] for ids, first in zip(sequences, starts)]
|
|
targets = torch.tensor([token for answer in gold for token in answer])
|
|
sizes = [len(answer) for answer in gold]
|
|
vectors = torch.cat([out[i, first-1:len(ids)-1] for out in outputs.values()
|
|
for i, (ids, first) in enumerate(zip(sequences, starts))])
|
|
_, nll = vocabulary_scores(vectors, targets.repeat(len(outputs)), embedding)
|
|
if not torch.isfinite(nll).all():
|
|
raise FloatingPointError('Invalid full-vocabulary diagnostic score')
|
|
scores = [{} for _ in gold]
|
|
for label, values in zip(outputs, nll.split(len(targets))):
|
|
for row, part in zip(scores, values.split(sizes)):
|
|
row[label] = (-part).tolist()
|
|
return gold, scores
|
|
|
|
|
|
@torch.no_grad()
|
|
def diagnostic_log_probs(model, tok, weights, questions, path):
|
|
"""Teacher-force gold answers; all restorations share the same frozen stem."""
|
|
if fingerprint(weights) != ADAPTER_SHA:
|
|
raise ValueError('Unexpected diagnostic checkpoint')
|
|
adapters = make_adapters(model.config, dict.fromkeys(SITES, 40), True)
|
|
tail = TorchTail(model, SITES[0], adapters)
|
|
tail.adapters.load_state_dict(torch.load(weights, weights_only=True, map_location='cpu'))
|
|
native = FitCapture(model, 0)
|
|
native.sites = SITES
|
|
rows = json.loads(path.read_text()) if path.exists() else []
|
|
if [r['id'] for r in rows] != [q['id'] for q in questions[:len(rows)]]:
|
|
raise ValueError('Unexpected gold-score prefix')
|
|
for start in range(len(rows), len(questions), 2):
|
|
batch = questions[start:start+2]
|
|
sequences, starts = [], []
|
|
for item in batch:
|
|
text = prompt(item['question'])
|
|
base = tok.encode(text, add_special_tokens=False).ids
|
|
ids = tok.encode(text + str(item['answer']) + STOP_TEXT[0], add_special_tokens=False).ids
|
|
if ids[:len(base)] != base or len(ids) <= len(base):
|
|
raise ValueError('Gold answer is not an extension of its prompt')
|
|
sequences.append(ids)
|
|
starts.append(len(base))
|
|
lengths = torch.tensor([len(ids)-1 for ids in sequences])
|
|
width = int(lengths.max())
|
|
padded = torch.tensor([ids[:-1] + [0]*(width-len(ids)+1) for ids in sequences])
|
|
h = torch.from_numpy(model.embedding(padded.numpy()))
|
|
original, maps = native(h, None, lengths, 'native', ())
|
|
outputs = {'native':original}
|
|
for restored in (None, *SITES):
|
|
sites = tuple(i for i in SITES if i != restored)
|
|
label = 'baseline' if restored is None else f'restore-{restored}'
|
|
outputs[label], _ = tail(native.residual, maps[SITES[0]-4][0], lengths, 'lisa', sites)
|
|
gold_tokens, log_probs = score_gold_answers(outputs, sequences, starts,
|
|
model.tensors[PREFIX+'embed_tokens.weight'])
|
|
results = [{'id': item['id'], 'gold': item['answer'], 'tokens': gold, 'log_probs': scores}
|
|
for item, gold, scores in zip(batch, gold_tokens, log_probs)]
|
|
rows.extend(results)
|
|
write_json(path, rows)
|
|
print('diagnostic gold sequence', len(rows), '/', len(questions), flush=True)
|
|
|
|
|
|
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()
|
|
torch.set_num_threads(1)
|
|
protocol_file = args.out/'protocol.json'
|
|
if fingerprint(protocol_file) != '6858dbc64db0b989e8112e9dbea70662a2a05f66f11b180e8f2c668c74c43aef':
|
|
raise ValueError('Protocol mismatch')
|
|
protocol = json.loads(protocol_file.read_text())
|
|
scores, ranks = assignments(protocol,args.out)
|
|
_, prior = load_locked(args.source,args.prior)
|
|
source = args.prior/'final'
|
|
captures = source/'fit-capture'
|
|
fit = [r for r in prior['problems']['fit'] if r['task']=='lookup']
|
|
verified_fit_captures(source, fit)
|
|
config = json.loads((args.source/'model_config.json').read_text())
|
|
tok = Tokenizer.from_file(str(args.source/'tokenizer.json'))
|
|
diagnostic_model = StreamingLM(args.source/'weights', config, seconds=172800, process_swap_limit_kib=None)
|
|
diagnostic_log_probs(diagnostic_model, tok, source/'lisa.pt', protocol['splits']['diagnostic'],
|
|
args.out/'diagnostic-gold-log-probs.json')
|
|
del diagnostic_model
|
|
arms = [('allocated',True),('uniform',True),('reversed',True),
|
|
('uniform',False),('allocated',False)]
|
|
for allocation, shared in arms:
|
|
label = ('shared-' if shared else 'local-')+allocation
|
|
out = args.out/label
|
|
out.mkdir(exist_ok=True)
|
|
torch.manual_seed(621011)
|
|
model = StreamingLM(args.source/'weights',config,seconds=172800,process_swap_limit_kib=None)
|
|
model.sites = SITES
|
|
adapters = make_adapters(model.config, ranks[allocation], shared)
|
|
count = sum(p.numel() for adapter in adapters.values() for p in adapter.parameters())
|
|
spec = {'diagnostic_correct':scores,'ranks':{str(k):v for k,v in ranks[allocation].items()},
|
|
'shared':shared,'parameters':count,'seed':621011,'epochs':2}
|
|
path = out/'config.json'
|
|
if count != 2476032 or (path.exists() and json.loads(path.read_text()) != spec):
|
|
raise ValueError('Unmatched rank budget or run configuration')
|
|
write_json(path,spec)
|
|
if not (out/'lisa.pt').exists():
|
|
train(model,tok,out,protocol['splits'],2,40,adapters=adapters,captures=captures)
|
|
print(label,'finished',flush=True)
|
|
|
|
|
|
if __name__=='__main__':
|
|
main()
|