diff --git a/crossqkv/lisa_combination_eval.py b/crossqkv/lisa_combination_eval.py new file mode 100644 index 0000000..630fe8f --- /dev/null +++ b/crossqkv/lisa_combination_eval.py @@ -0,0 +1,102 @@ +"""Evaluate all predeclared models on fresh counterfactual pairs.""" +import argparse +import json +from pathlib import Path +from time import monotonic + +import numpy as np +import torch +from tokenizers import Tokenizer + +from crossqkv.lisa_combination_screen import ADAPTER_SHA, SITES +from crossqkv.lisa_full_answer import evaluate, fingerprint +from crossqkv.lisa_full_answer_verify import verify +from crossqkv.lisa_rank_compare import make_adapters +from functional.model import StreamingLM +from functional.run import write_json + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for name in ('source','prior','out'): + parser.add_argument('--'+name, type=Path, required=True) + args = parser.parse_args() + torch.set_num_threads(1) + path = args.out/'protocol.json' + if fingerprint(path) != '6858dbc64db0b989e8112e9dbea70662a2a05f66f11b180e8f2c668c74c43aef': + raise ValueError('Frozen protocol mismatch') + questions = json.loads(path.read_text())['splits']['test'] + prior_protocol = json.loads((args.prior/'frozen.json').read_text())['protocol'] + config = json.loads((args.source/'model_config.json').read_text()) + tok = Tokenizer.from_file(str(args.source/'tokenizer.json')) + out = args.out/'holdout' + out.mkdir(exist_ok=True) + scores = {} + generation = {} + for arm in ('native','direct','prior-lisa','trajectory-student','trajectory-reference', + 'shared-uniform','shared-allocated','shared-reversed','local-uniform','local-allocated'): + model = StreamingLM(args.source/'weights', config, seconds=172800,process_swap_limit_kib=None) + sites = () if arm=='native' else SITES + adapters = None + if arm not in ('native','direct'): + ranks = dict.fromkeys(SITES,40) + shared = True + if arm=='prior-lisa': + weights = args.prior/'final/lisa.pt' + if fingerprint(weights) != ADAPTER_SHA: + raise ValueError('Incorrect starting checkpoint') + elif arm.startswith('trajectory-'): + weights = args.out/arm/'adapter.pt' + else: + spec = json.loads((args.out/arm/'config.json').read_text()) + ranks = {int(k):v for k,v in spec['ranks'].items()} + shared = spec['shared'] + weights = args.out/arm/'lisa.pt' + adapters = make_adapters(model.config,ranks,shared) + torch.nn.ModuleDict({str(i):v for i,v in adapters.items()}).load_state_dict( + torch.load(weights,weights_only=True,map_location='cpu')) + digest = fingerprint(weights) + else: + digest = prior_protocol['weights']['manifest.json'] + lock = out/(arm+'-source.json') + if lock.exists() and json.loads(lock.read_text()) != digest: + raise ValueError('Cannot resume with changed weights') + write_json(lock,digest) + path = out/(arm+'.json') + rows = json.loads(path.read_text()) if path.exists() else [] + if rows: + verify(tok,prior_protocol,questions,rows,(arm,),allow_prefix=True) + for start in range(len(rows),len(questions),2): + batch = questions[start:start+2] + before = monotonic() + generated = evaluate(model,tok,batch,{arm:sites},adapters) + seconds = monotonic() - before + verify(tok,prior_protocol,batch,generated,(arm,)) + generated[0]['batch_seconds'] = seconds + rows.extend(generated) + write_json(path,rows) + print(arm,len(rows),'/',len(questions),flush=True) + scores[arm] = np.array([x['arms'][arm]['correct'] for x in rows],dtype=int).reshape(-1,2) + generation[arm] = {'generated_tokens':sum(len(row['arms'][arm]['tokens']) for row in rows), + 'seconds':sum(row['batch_seconds'] for row in rows[::2])} + comparisons = {'rank-vs-uniform':scores['shared-allocated']-scores['shared-uniform'], + 'rank-vs-reversed':scores['shared-allocated']-scores['shared-reversed'], + 'rank-vs-local':scores['shared-allocated']-scores['local-allocated'], + 'rank-interaction':scores['shared-allocated']-scores['shared-uniform'] + -scores['local-allocated']+scores['local-uniform'], + 'student-vs-prior':scores['trajectory-student']-scores['prior-lisa'], + 'student-vs-reference':scores['trajectory-student']-scores['trajectory-reference']} + rng = np.random.default_rng(72505) + sample = rng.integers(0,len(questions)//2,size=(10000,len(questions)//2)) + audit = {'questions':len(questions), + 'generation':generation, + 'correct':{k:int(v.sum()) for k,v in scores.items()}, + 'pairs_both_correct':{k:int(v.all(1).sum()) for k,v in scores.items()}, + 'paired_differences':{k:{'delta':float(v.mean()), + 'interval_95':np.quantile(v.mean(1)[sample].mean(1),[.025,.975]).tolist()} + for k,v in comparisons.items()}} + write_json(out/'audit.json',audit) + + +if __name__=='__main__': + main() diff --git a/crossqkv/lisa_combination_screen.py b/crossqkv/lisa_combination_screen.py new file mode 100644 index 0000000..601e454 --- /dev/null +++ b/crossqkv/lisa_combination_screen.py @@ -0,0 +1,90 @@ +"""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() diff --git a/crossqkv/lisa_full_answer_train.py b/crossqkv/lisa_full_answer_train.py index f360121..dbb768e 100644 --- a/crossqkv/lisa_full_answer_train.py +++ b/crossqkv/lisa_full_answer_train.py @@ -77,12 +77,13 @@ def checkpoint(path, obj): pending.replace(path) -def train(model, tokenizer, out, split, epochs, rank): - c = model.config - rope = c['rope_parameters'] - adapters = {i: LearnableSharingAttention(c['hidden_size'], c['num_attention_heads'], - c['num_key_value_heads'], rank, rope['rope_theta'], rope['partial_rotary_factor'], - bias=c.get('attention_bias', False)) for i in model.sites} +def train(model, tokenizer, out, split, epochs, rank, *, adapters=None, captures=None): + if adapters is None: + c = model.config + rope = c['rope_parameters'] + adapters = {i: LearnableSharingAttention(c['hidden_size'], c['num_attention_heads'], + c['num_key_value_heads'], rank, rope['rope_theta'], rope['partial_rotary_factor'], + bias=c.get('attention_bias', False)) for i in model.sites} tail = TorchTail(model, model.sites[0], adapters) optim = torch.optim.AdamW(tail.parameters(), lr=.0003, weight_decay=.1) last = out/'resume.pt' @@ -101,7 +102,7 @@ def train(model, tokenizer, out, split, epochs, rank): yield start, w start += len(w) - paths = sorted((out/'fit-capture').glob('*.npz')) + paths = sorted((captures or out/'fit-capture').glob('*.npz')) for epoch in range(state['epoch'], epochs): for path in paths[len(state['steps']):]: with np.load(path, allow_pickle=False) as entry: diff --git a/crossqkv/lisa_rank_compare.py b/crossqkv/lisa_rank_compare.py new file mode 100644 index 0000000..4d31da4 --- /dev/null +++ b/crossqkv/lisa_rank_compare.py @@ -0,0 +1,97 @@ +"""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 SITES +from crossqkv.lisa_full_answer import fingerprint +from crossqkv.lisa_full_answer_train import load_locked, train +from crossqkv.lisa_train import LearnableSharingAttention +from functional.model import 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 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' + receipt = source/'verified-fit-capture.json' + if fingerprint(receipt) != '682bc035a5bed9f9245f589cacf3e9616300e8bf5e85d3743b1264a56360fa55': + raise ValueError('Capture receipt mismatch') + records = json.loads(receipt.read_text())['records'] + fit = [r for r in prior['problems']['fit'] if r['task']=='lookup'] + if ([r['id'] for r in records] != [r['id'] for r in fit] or + sorted(x.name for x in captures.glob('*.npz')) != [r['file'] for r in records]): + raise ValueError('Unexpected capture set') + for row in records: + if fingerprint(captures/row['file']) != row['sha256']: + raise ValueError('Fit capture mismatch') + config = json.loads((args.source/'model_config.json').read_text()) + tok = Tokenizer.from_file(str(args.source/'tokenizer.json')) + 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() diff --git a/crossqkv/lisa_trajectory_train.py b/crossqkv/lisa_trajectory_train.py new file mode 100644 index 0000000..afa8341 --- /dev/null +++ b/crossqkv/lisa_trajectory_train.py @@ -0,0 +1,134 @@ +"""Distill next-token distributions along LiSA's current greedy trajectories.""" +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_full_answer import STOP_TEXT, evaluate, fingerprint, prompt +from crossqkv.lisa_full_answer_train import FitCapture, checkpoint, load_locked +from crossqkv.lisa_full_answer_verify import verify +from crossqkv.lisa_tail import TorchTail, weight_chunks +from crossqkv.lisa_train import LearnableSharingAttention +from functional.model import PREFIX, StreamingLM +from functional.run import write_json + + +def reverse_kl(student, teacher, chunks): + """Exact reverse KL and its first derivative for a streamed, frozen head.""" + with torch.no_grad(): + logp = torch.cat([student @ w.T for w in chunks()], dim=-1).log_softmax(-1) + logq = torch.cat([teacher @ w.T for w in chunks()], dim=-1).log_softmax(-1) + diff = logp - logq + prob = logp.exp() + kl = (prob * diff).sum(-1, keepdim=True) + dlogits = prob * (diff - kl) / len(student) + grad = torch.zeros_like(student) + start = 0 + for w in chunks(): + grad.addmm_(dlogits[:, start:start+len(w)], w) + start += len(w) + return kl.mean() + ((student - student.detach()) * grad).sum() + + +def validate_checkpoint(model, tokenizer, adapters, questions, decode_spec, path): + label = path.stem + rows = json.loads(path.read_text()) if path.exists() else [] + if rows: + verify(tokenizer, decode_spec, questions, rows, (label,), allow_prefix=True) + for start in range(len(rows), len(questions), 2): + batch = questions[start:start+2] + outputs = evaluate(model, tokenizer, batch, {label: SITES}, adapters) + verify(tokenizer, decode_spec, batch, outputs, (label,)) + rows.extend(outputs) + write_json(path, rows) + correct = sum(row['arms'][label]['correct'] for row in rows) + print(label, 'validation correct', correct, '/', len(rows), flush=True) + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + for name in ('source', 'prior', 'out'): + p.add_argument('--'+name, required=True, type=Path) + p.add_argument('--prefix', choices=('student', 'reference'), required=True) + args = p.parse_args() + torch.set_num_threads(1) + torch.manual_seed(72504) + _, prior = load_locked(args.source, args.prior) + tasks = [x for x in prior['problems']['fit'] if x['task']=='lookup'] + protocol = args.out/'protocol.json' + if fingerprint(protocol) != '6858dbc64db0b989e8112e9dbea70662a2a05f66f11b180e8f2c668c74c43aef': + raise ValueError('Unknown combination study protocol') + validation = json.loads(protocol.read_text())['splits']['validation'] + old = args.prior/'final/lisa.pt' + if fingerprint(old) != ADAPTER_SHA: + raise ValueError('Unknown baseline checkpoint') + directory = args.out/('trajectory-'+args.prefix) + directory.mkdir(exist_ok=True) + config = json.loads((args.source/'model_config.json').read_text()) + model = StreamingLM(args.source/'weights', config, seconds=172800, process_swap_limit_kib=None) + c = model.config + rope = c['rope_parameters'] + adapters = {i: LearnableSharingAttention(c['hidden_size'], c['num_attention_heads'], + c['num_key_value_heads'], 40, rope['rope_theta'], rope['partial_rotary_factor'], + bias=c.get('attention_bias', False)) for i in SITES} + tail = TorchTail(model, SITES[0], adapters) + tail.adapters.load_state_dict(torch.load(old, weights_only=True)) + teacher = FitCapture(model, 0) + teacher.sites = SITES + opt = torch.optim.AdamW(tail.parameters(), lr=0.0001, weight_decay=0.1) + tok = Tokenizer.from_file(str(args.source/'tokenizer.json')) + if args.prefix == 'student': + validate_checkpoint(model, tok, adapters, validation, prior['protocol'], + args.out/'validation-prior-lisa.json') + statefile = directory/'resume.pt' + rows = [] + if statefile.exists(): + state = torch.load(statefile, weights_only=True) + rows = state['rows'] + tail.adapters.load_state_dict(state['weights']) + opt.load_state_dict(state['optimizer']) + if [r['id'] for r in rows] != [x['id'] for x in tasks[:len(rows)]]: + raise ValueError('Training prefix mismatch') + embedding = model.tensors[PREFIX+'embed_tokens.weight'] + + def chunks(): + yield from weight_chunks(embedding, 0, embedding.shape[0], rows=1024) + + for item in tasks[len(rows):]: + text = prompt(item['question']) + base = tok.encode(text, add_special_tokens=False).ids + if args.prefix == 'student': + rollout = evaluate(model, tok, [item], {'student': SITES}, adapters)[0]['arms']['student'] + sampled = rollout['tokens'] + else: + complete = tok.encode(text+str(item['answer'])+STOP_TEXT[0], add_special_tokens=False).ids + assert complete[:len(base)] == base + sampled = complete[len(base):] + ids = torch.tensor([base+sampled]) + lengths = torch.tensor([ids.shape[1]]) + with torch.no_grad(): + h = torch.from_numpy(model.embedding(ids.numpy())) + target, maps = teacher(h, None, lengths, 'native', ()) + donor = maps[SITES[0]-4][0] + opt.zero_grad(set_to_none=True) + student, _ = tail(teacher.residual, donor, lengths, 'lisa', SITES) + span = slice(len(base)-1, -1) + loss = reverse_kl(student[0, span], target[0, span], chunks) + loss.backward() + if not torch.isfinite(loss) or any(p.grad is None or not torch.isfinite(p.grad).all() for p in tail.parameters()): + raise FloatingPointError('Invalid reverse KL update') + opt.step() + rows.append({'id': item['id'], 'tokens': sampled, 'reverse_kl':float(loss.detach())}) + checkpoint(statefile, {'rows':rows,'weights':tail.adapters.state_dict(),'optimizer':opt.state_dict()}) + print(args.prefix, len(rows), '/', len(tasks), flush=True) + checkpoint(directory/'adapter.pt', tail.adapters.state_dict()) + write_json(directory/'trace.json', rows) + validate_checkpoint(model, tok, adapters, validation, prior['protocol'], + directory/('validation-'+args.prefix+'.json')) + + +if __name__ == '__main__': + main() diff --git a/docs/LISA_COMBINATIONS_PROTOCOL.md b/docs/LISA_COMBINATIONS_PROTOCOL.md new file mode 100644 index 0000000..5e84601 --- /dev/null +++ b/docs/LISA_COMBINATIONS_PROTOCOL.md @@ -0,0 +1,34 @@ +# 三层跨层注意力共享的两种改进实验 + +复用 Qwen3.5-2B 中层号为 15、19、23 的三个全注意力接收层(按整个模型从零编号),在新的查表任务上评估完整整数答案。上一轮第二个训练轮次的 LiSA 检查点作为轨迹蒸馏的起点,适配器 SHA-256 为 `c82db5af7fa42cf58a349f3e53961da2360b211a7ed606f53a728860c64f6f29`。 + +## 题集与验证 + +8 对诊断题用于为三个层分配秩,8 对验证题用于在两个分秩训练轮次之间选检查点,32 对新留出题用于最后的配对比较。每对保持键、查询和表格顺序一致,交换目标键和一个干扰键的值。训练使用上一轮的 24 道拟合题。生成上限为 24 个 token,判分要求正常结束并能提取完整整数。主指标是完整答案准确率,次指标是同一对的两个答案都正确的比例。准确率差的 bootstrap 以题对为重采样单位。 + +## 层敏感度与秩分配 + +依次用原生 Q/K 恢复单个接收层,其余层使用上一轮训练的 LiSA。在诊断集上恢复正确答案净增最多的层取秩 48,其次取 40,最后取 32。同分时层号小者优先。恢复分数并列时会弱化对敏感度排序的解释。对照包括均匀秩和反向分配,以及关闭跨层分数输入后的均匀秩和敏感度分配。关闭共享输入时在融合网络前将供给层的分数通道置零。每组名义参数量一致,置零通道对应的权重不会获得有效训练信号。 + +分秩实验沿用上一轮教师分数与训练题的缓存。五组从固定种子初始化,各做两轮、每轮 24 步。按验证正确数选择检查点,同分取较早轮次。四组交互项为共享时分秩相对均匀秩的增益,减去关闭共享输入时的同一增益。反向分配用于检验高秩是否确实给对了层。 + +## 学生轨迹蒸馏 + +在同一批 8 对验证题上,分别生成起始检查点、学生前缀组和标准答案前缀组三种完整答卷,并用冻结的分词器从 token 重算判分。三个检查点预先指定。验证答卷可用于在留出评估之前判断轨迹训练是否值得进一步研究。 + +两组均从上一轮 LiSA 权重开始,依次在相同 24 道训练题上各更新一次。学生轨迹组每步先用更新前的学生生成完整的贪心回答,在这些前缀上最小化学生对原模型的全词表逆 KL。参考轨迹组使用标准答案前缀,学习率、优化器和题序相同。两组均使用最后一步权重。生成路径固定时反向传播下一 token 分布的梯度。这是借鉴 MiniLLM 的简化方法。两组的训练步数相等,生成与训练 token 数和实际训练开销可不同。 + +## 复跑顺序 + +使用上一轮远程 CPU Python 环境和完整仓库依赖。所有命令共用 `--source`(冻结模型目录)、`--prior`(上一轮包含 frozen.json 和 final 子目录的作业目录)、`--out`(本轮独立目录)。按顺序运行以下 Python 模块。 + +1. `crossqkv.lisa_combination_screen` 冻结清单并生成四种诊断条件。 +2. `crossqkv.lisa_trajectory_train --prefix student` 和 `crossqkv.lisa_trajectory_train --prefix reference` 训练两个轨迹条件。 +3. `crossqkv.lisa_rank_compare` 根据诊断分数分配秩,训练五个条件。 +4. `crossqkv.lisa_combination_eval` 生成十组留出答卷,逐题校验并写入 holdout/audit.json。 + +冻结清单 SHA-256 为 `6858dbc64db0b989e8112e9dbea70662a2a05f66f11b180e8f2c668c74c43aef`。秩分配与轨迹方法分别和各自匹配的对照比较。跨路线的总训练预算不同。 + +留出评估按每批两题记录生成耗时,从提示词编码前计时到回答解析结束,同时汇总生成 token 数。远程 CPU 在多个作业间共享,这些运行记录用于解释实际开销。要验证部署加速,还需要在受控负载下重复测量。 + +已记录远程部署的 12 个实现与测试文件摘要。部署目录中的 `crossqkv/lisa_full_answer.py` 来自提交 `c53d78b`。它与本轮主线版本的差异限于该模块自身的筛选命令行入口,本轮调用的 `evaluate`、`prompt`、`grade` 等函数一致。 [远程代码摘要](../results/lisa-combinations/execution.sha256) diff --git a/results/lisa-combinations/execution.sha256 b/results/lisa-combinations/execution.sha256 new file mode 100644 index 0000000..91be5ef --- /dev/null +++ b/results/lisa-combinations/execution.sha256 @@ -0,0 +1,12 @@ +024720e9eae7556e4d5ca2ca1d71dd544815c79ed2c51b113564d5a6fb4ad004 crossqkv/lisa_combination_screen.py +f18432dad8bd567e4c11d74a14c0d2d8b774037ab41e0276749223b9033fcaef crossqkv/lisa_rank_compare.py +f55e6cebec2e462959279122d134e81770c035d4e46bbf7620ba5a738dcba4fb crossqkv/lisa_trajectory_train.py +efbbc2ee4fe821a5aa002dc90b144a49251a141bec38ca733bc429f4d0bdce49 crossqkv/lisa_combination_eval.py +519e0a031efcfb69c9b86fca1cb649fe8bb93d799401c8023ff7b6549cded448 crossqkv/lisa_full_answer.py +6369a674600812d06fc6d667e4a67ae97b63b4be3ba02ad28520eb9a748d272b crossqkv/lisa_full_answer_train.py +57e73f1e30c8db8daec7b13d6455af2822b2db3e600531f8a60e2381d093ad91 crossqkv/lisa_full_answer_verify.py +98927a1ccd935b2f7a438bad31bbd973e210a54deceac911c61551092e52c96c crossqkv/lisa_generate.py +d47b4c9cc34082e9b356e745821298a43981e4cd18ed55a3f59b4b6fe7cc46e3 crossqkv/lisa_tail.py +9f0b6a53f107950661e91c16f03b49440708b3936120e2f84ef1d66f185257b6 crossqkv/lisa_train.py +94437e0138c54ec34b1beaaa0e08a334ce0822f60af598a5a896459b778a3a1c functional/model.py +69b93db23aa1b551454b69de7d01426ea05d4f74f93350d282363dfe7b2c7e88 tests/test_lisa_combinations.py diff --git a/results/lisa-combinations/protocol.json b/results/lisa-combinations/protocol.json new file mode 100644 index 0000000..d05083a --- /dev/null +++ b/results/lisa-combinations/protocol.json @@ -0,0 +1,602 @@ +{ + "splits": { + "diagnostic": [ + { + "id": "diagnostic-000-0", + "task": "lookup", + "question": "Records in time order: vine=39, nettle=36, umber=91, quartz=28, larch=76, fern=47, heath=48, iris=82, reed=75, kelp=89, thyme=34, maple=94.\nWhat is the recorded number for larch?", + "answer": 76 + }, + { + "id": "diagnostic-000-1", + "task": "lookup", + "question": "Records in time order: vine=39, nettle=36, umber=91, quartz=28, larch=75, fern=47, heath=48, iris=82, reed=76, kelp=89, thyme=34, maple=94.\nWhat is the recorded number for larch?", + "answer": 75 + }, + { + "id": "diagnostic-001-0", + "task": "lookup", + "question": "Records in time order: maple=44, iris=23, fern=88, kelp=77, thyme=73, elm=29, birch=84, umber=76, amber=63, reed=72, quartz=27, yew=39.\nWhat is the recorded number for yew?", + "answer": 39 + }, + { + "id": "diagnostic-001-1", + "task": "lookup", + "question": "Records in time order: maple=44, iris=23, fern=88, kelp=77, thyme=73, elm=29, birch=84, umber=39, amber=63, reed=72, quartz=27, yew=76.\nWhat is the recorded number for yew?", + "answer": 76 + }, + { + "id": "diagnostic-002-0", + "task": "lookup", + "question": "Records in time order: iris=25, cedar=56, fern=69, jade=66, nettle=53, yew=78, kelp=67, quartz=31, elm=22, dune=52, amber=84, umber=49.\nWhat is the recorded number for umber?", + "answer": 49 + }, + { + "id": "diagnostic-002-1", + "task": "lookup", + "question": "Records in time order: iris=25, cedar=56, fern=69, jade=66, nettle=53, yew=78, kelp=67, quartz=31, elm=49, dune=52, amber=84, umber=22.\nWhat is the recorded number for umber?", + "answer": 22 + }, + { + "id": "diagnostic-003-0", + "task": "lookup", + "question": "Records in time order: fern=73, elm=86, thyme=44, vine=87, dune=75, slate=80, maple=84, larch=90, olive=70, yew=99, reed=63, quartz=21.\nWhat is the recorded number for reed?", + "answer": 63 + }, + { + "id": "diagnostic-003-1", + "task": "lookup", + "question": "Records in time order: fern=73, elm=86, thyme=44, vine=87, dune=75, slate=80, maple=84, larch=90, olive=70, yew=99, reed=21, quartz=63.\nWhat is the recorded number for reed?", + "answer": 21 + }, + { + "id": "diagnostic-004-0", + "task": "lookup", + "question": "Records in time order: yew=78, jade=99, maple=84, cedar=88, iris=74, quartz=42, willow=75, dune=89, fern=73, amber=23, reed=29, nettle=47.\nWhat is the recorded number for iris?", + "answer": 74 + }, + { + "id": "diagnostic-004-1", + "task": "lookup", + "question": "Records in time order: yew=78, jade=99, maple=84, cedar=88, iris=29, quartz=42, willow=75, dune=89, fern=73, amber=23, reed=74, nettle=47.\nWhat is the recorded number for iris?", + "answer": 29 + }, + { + "id": "diagnostic-005-0", + "task": "lookup", + "question": "Records in time order: dune=25, cedar=24, birch=92, nettle=64, slate=56, olive=69, grove=67, elm=98, willow=39, iris=81, reed=77, fern=48.\nWhat is the recorded number for willow?", + "answer": 39 + }, + { + "id": "diagnostic-005-1", + "task": "lookup", + "question": "Records in time order: dune=25, cedar=24, birch=92, nettle=64, slate=56, olive=69, grove=67, elm=98, willow=77, iris=81, reed=39, fern=48.\nWhat is the recorded number for willow?", + "answer": 77 + }, + { + "id": "diagnostic-006-0", + "task": "lookup", + "question": "Records in time order: quartz=35, kelp=51, reed=36, iris=55, vine=67, yew=70, thyme=83, heath=49, nettle=96, cedar=40, amber=31, dune=27.\nWhat is the recorded number for cedar?", + "answer": 40 + }, + { + "id": "diagnostic-006-1", + "task": "lookup", + "question": "Records in time order: quartz=35, kelp=51, reed=36, iris=55, vine=40, yew=70, thyme=83, heath=49, nettle=96, cedar=67, amber=31, dune=27.\nWhat is the recorded number for cedar?", + "answer": 67 + }, + { + "id": "diagnostic-007-0", + "task": "lookup", + "question": "Records in time order: umber=48, iris=43, grove=44, maple=73, thyme=89, birch=61, larch=81, amber=93, olive=46, cedar=76, kelp=33, yew=51.\nWhat is the recorded number for thyme?", + "answer": 89 + }, + { + "id": "diagnostic-007-1", + "task": "lookup", + "question": "Records in time order: umber=48, iris=43, grove=44, maple=73, thyme=61, birch=89, larch=81, amber=93, olive=46, cedar=76, kelp=33, yew=51.\nWhat is the recorded number for thyme?", + "answer": 61 + } + ], + "validation": [ + { + "id": "validation-000-0", + "task": "lookup", + "question": "Records in time order: kelp=68, dune=98, nettle=92, maple=60, reed=72, birch=74, thyme=91, umber=83, cedar=25, willow=44, grove=79, olive=78.\nWhat is the recorded number for willow?", + "answer": 44 + }, + { + "id": "validation-000-1", + "task": "lookup", + "question": "Records in time order: kelp=68, dune=98, nettle=92, maple=60, reed=72, birch=74, thyme=44, umber=83, cedar=25, willow=91, grove=79, olive=78.\nWhat is the recorded number for willow?", + "answer": 91 + }, + { + "id": "validation-001-0", + "task": "lookup", + "question": "Records in time order: vine=46, kelp=91, cedar=72, reed=97, heath=28, pine=48, willow=20, quartz=69, maple=45, elm=22, thyme=33, fern=47.\nWhat is the recorded number for thyme?", + "answer": 33 + }, + { + "id": "validation-001-1", + "task": "lookup", + "question": "Records in time order: vine=46, kelp=91, cedar=72, reed=97, heath=33, pine=48, willow=20, quartz=69, maple=45, elm=22, thyme=28, fern=47.\nWhat is the recorded number for thyme?", + "answer": 28 + }, + { + "id": "validation-002-0", + "task": "lookup", + "question": "Records in time order: iris=57, fern=72, elm=56, vine=69, dune=42, yew=51, cedar=71, nettle=93, umber=75, maple=43, slate=22, olive=66.\nWhat is the recorded number for dune?", + "answer": 42 + }, + { + "id": "validation-002-1", + "task": "lookup", + "question": "Records in time order: iris=57, fern=72, elm=42, vine=69, dune=56, yew=51, cedar=71, nettle=93, umber=75, maple=43, slate=22, olive=66.\nWhat is the recorded number for dune?", + "answer": 56 + }, + { + "id": "validation-003-0", + "task": "lookup", + "question": "Records in time order: jade=33, quartz=72, slate=34, dune=81, elm=43, willow=95, thyme=83, vine=23, reed=56, fern=48, iris=93, maple=82.\nWhat is the recorded number for iris?", + "answer": 93 + }, + { + "id": "validation-003-1", + "task": "lookup", + "question": "Records in time order: jade=33, quartz=72, slate=34, dune=81, elm=43, willow=95, thyme=93, vine=23, reed=56, fern=48, iris=83, maple=82.\nWhat is the recorded number for iris?", + "answer": 83 + }, + { + "id": "validation-004-0", + "task": "lookup", + "question": "Records in time order: fern=70, vine=25, cedar=72, dune=69, olive=23, iris=81, kelp=89, maple=85, quartz=88, jade=32, slate=91, thyme=29.\nWhat is the recorded number for olive?", + "answer": 23 + }, + { + "id": "validation-004-1", + "task": "lookup", + "question": "Records in time order: fern=70, vine=25, cedar=72, dune=69, olive=89, iris=81, kelp=23, maple=85, quartz=88, jade=32, slate=91, thyme=29.\nWhat is the recorded number for olive?", + "answer": 89 + }, + { + "id": "validation-005-0", + "task": "lookup", + "question": "Records in time order: willow=60, iris=36, grove=22, thyme=82, pine=74, maple=63, vine=44, yew=62, heath=32, amber=49, slate=96, umber=47.\nWhat is the recorded number for maple?", + "answer": 63 + }, + { + "id": "validation-005-1", + "task": "lookup", + "question": "Records in time order: willow=60, iris=36, grove=22, thyme=82, pine=74, maple=49, vine=44, yew=62, heath=32, amber=63, slate=96, umber=47.\nWhat is the recorded number for maple?", + "answer": 49 + }, + { + "id": "validation-006-0", + "task": "lookup", + "question": "Records in time order: pine=32, iris=35, amber=88, heath=48, thyme=77, kelp=78, willow=37, jade=31, grove=97, maple=74, slate=69, umber=29.\nWhat is the recorded number for kelp?", + "answer": 78 + }, + { + "id": "validation-006-1", + "task": "lookup", + "question": "Records in time order: pine=32, iris=35, amber=88, heath=48, thyme=77, kelp=29, willow=37, jade=31, grove=97, maple=74, slate=69, umber=78.\nWhat is the recorded number for kelp?", + "answer": 29 + }, + { + "id": "validation-007-0", + "task": "lookup", + "question": "Records in time order: heath=86, grove=50, iris=83, maple=64, reed=95, olive=46, jade=97, umber=24, amber=53, thyme=33, birch=93, pine=96.\nWhat is the recorded number for maple?", + "answer": 64 + }, + { + "id": "validation-007-1", + "task": "lookup", + "question": "Records in time order: heath=86, grove=64, iris=83, maple=50, reed=95, olive=46, jade=97, umber=24, amber=53, thyme=33, birch=93, pine=96.\nWhat is the recorded number for maple?", + "answer": 50 + } + ], + "test": [ + { + "id": "test-000-0", + "task": "lookup", + "question": "Records in time order: larch=28, willow=64, thyme=87, dune=51, birch=63, umber=24, olive=72, kelp=97, slate=82, cedar=49, heath=46, nettle=37.\nWhat is the recorded number for nettle?", + "answer": 37 + }, + { + "id": "test-000-1", + "task": "lookup", + "question": "Records in time order: larch=28, willow=64, thyme=87, dune=51, birch=63, umber=24, olive=72, kelp=97, slate=82, cedar=49, heath=37, nettle=46.\nWhat is the recorded number for nettle?", + "answer": 46 + }, + { + "id": "test-001-0", + "task": "lookup", + "question": "Records in time order: heath=60, nettle=61, birch=31, cedar=67, umber=88, elm=44, grove=72, amber=78, thyme=48, quartz=33, yew=29, slate=25.\nWhat is the recorded number for cedar?", + "answer": 67 + }, + { + "id": "test-001-1", + "task": "lookup", + "question": "Records in time order: heath=60, nettle=61, birch=31, cedar=33, umber=88, elm=44, grove=72, amber=78, thyme=48, quartz=67, yew=29, slate=25.\nWhat is the recorded number for cedar?", + "answer": 33 + }, + { + "id": "test-002-0", + "task": "lookup", + "question": "Records in time order: fern=41, iris=93, heath=36, vine=91, thyme=73, elm=25, reed=83, maple=55, birch=99, grove=35, larch=49, slate=29.\nWhat is the recorded number for grove?", + "answer": 35 + }, + { + "id": "test-002-1", + "task": "lookup", + "question": "Records in time order: fern=35, iris=93, heath=36, vine=91, thyme=73, elm=25, reed=83, maple=55, birch=99, grove=41, larch=49, slate=29.\nWhat is the recorded number for grove?", + "answer": 41 + }, + { + "id": "test-003-0", + "task": "lookup", + "question": "Records in time order: slate=59, dune=25, olive=64, nettle=70, grove=89, cedar=76, kelp=54, larch=97, umber=36, amber=71, elm=53, pine=80.\nWhat is the recorded number for umber?", + "answer": 36 + }, + { + "id": "test-003-1", + "task": "lookup", + "question": "Records in time order: slate=59, dune=25, olive=64, nettle=70, grove=89, cedar=36, kelp=54, larch=97, umber=76, amber=71, elm=53, pine=80.\nWhat is the recorded number for umber?", + "answer": 76 + }, + { + "id": "test-004-0", + "task": "lookup", + "question": "Records in time order: olive=26, reed=73, yew=37, jade=54, thyme=76, umber=95, cedar=59, slate=52, birch=49, kelp=43, willow=69, pine=63.\nWhat is the recorded number for jade?", + "answer": 54 + }, + { + "id": "test-004-1", + "task": "lookup", + "question": "Records in time order: olive=26, reed=73, yew=37, jade=52, thyme=76, umber=95, cedar=59, slate=54, birch=49, kelp=43, willow=69, pine=63.\nWhat is the recorded number for jade?", + "answer": 52 + }, + { + "id": "test-005-0", + "task": "lookup", + "question": "Records in time order: thyme=92, amber=21, larch=31, jade=80, birch=52, willow=99, pine=88, cedar=57, kelp=61, slate=33, nettle=67, quartz=69.\nWhat is the recorded number for amber?", + "answer": 21 + }, + { + "id": "test-005-1", + "task": "lookup", + "question": "Records in time order: thyme=92, amber=52, larch=31, jade=80, birch=21, willow=99, pine=88, cedar=57, kelp=61, slate=33, nettle=67, quartz=69.\nWhat is the recorded number for amber?", + "answer": 52 + }, + { + "id": "test-006-0", + "task": "lookup", + "question": "Records in time order: elm=38, yew=66, iris=28, pine=25, quartz=79, willow=49, maple=75, jade=32, umber=96, cedar=86, grove=61, slate=55.\nWhat is the recorded number for jade?", + "answer": 32 + }, + { + "id": "test-006-1", + "task": "lookup", + "question": "Records in time order: elm=38, yew=66, iris=28, pine=25, quartz=32, willow=49, maple=75, jade=79, umber=96, cedar=86, grove=61, slate=55.\nWhat is the recorded number for jade?", + "answer": 79 + }, + { + "id": "test-007-0", + "task": "lookup", + "question": "Records in time order: yew=29, maple=50, kelp=83, jade=76, thyme=53, elm=26, reed=90, iris=23, willow=33, quartz=31, cedar=57, grove=49.\nWhat is the recorded number for thyme?", + "answer": 53 + }, + { + "id": "test-007-1", + "task": "lookup", + "question": "Records in time order: yew=29, maple=50, kelp=83, jade=76, thyme=33, elm=26, reed=90, iris=23, willow=53, quartz=31, cedar=57, grove=49.\nWhat is the recorded number for thyme?", + "answer": 33 + }, + { + "id": "test-008-0", + "task": "lookup", + "question": "Records in time order: reed=20, willow=26, maple=62, cedar=52, larch=47, kelp=29, slate=84, grove=49, thyme=37, elm=30, olive=66, nettle=58.\nWhat is the recorded number for cedar?", + "answer": 52 + }, + { + "id": "test-008-1", + "task": "lookup", + "question": "Records in time order: reed=52, willow=26, maple=62, cedar=20, larch=47, kelp=29, slate=84, grove=49, thyme=37, elm=30, olive=66, nettle=58.\nWhat is the recorded number for cedar?", + "answer": 20 + }, + { + "id": "test-009-0", + "task": "lookup", + "question": "Records in time order: slate=91, iris=23, jade=93, elm=92, maple=99, amber=66, thyme=74, nettle=59, grove=81, olive=67, yew=68, reed=60.\nWhat is the recorded number for maple?", + "answer": 99 + }, + { + "id": "test-009-1", + "task": "lookup", + "question": "Records in time order: slate=91, iris=23, jade=93, elm=92, maple=74, amber=66, thyme=99, nettle=59, grove=81, olive=67, yew=68, reed=60.\nWhat is the recorded number for maple?", + "answer": 74 + }, + { + "id": "test-010-0", + "task": "lookup", + "question": "Records in time order: olive=97, heath=37, amber=20, birch=59, larch=58, reed=35, vine=87, kelp=65, thyme=83, cedar=99, dune=96, willow=27.\nWhat is the recorded number for heath?", + "answer": 37 + }, + { + "id": "test-010-1", + "task": "lookup", + "question": "Records in time order: olive=97, heath=20, amber=37, birch=59, larch=58, reed=35, vine=87, kelp=65, thyme=83, cedar=99, dune=96, willow=27.\nWhat is the recorded number for heath?", + "answer": 20 + }, + { + "id": "test-011-0", + "task": "lookup", + "question": "Records in time order: reed=37, iris=78, amber=28, grove=38, olive=61, heath=94, birch=55, kelp=99, pine=91, maple=59, willow=36, vine=22.\nWhat is the recorded number for willow?", + "answer": 36 + }, + { + "id": "test-011-1", + "task": "lookup", + "question": "Records in time order: reed=37, iris=78, amber=28, grove=38, olive=61, heath=94, birch=55, kelp=99, pine=91, maple=36, willow=59, vine=22.\nWhat is the recorded number for willow?", + "answer": 59 + }, + { + "id": "test-012-0", + "task": "lookup", + "question": "Records in time order: iris=41, reed=70, jade=98, willow=28, slate=34, birch=69, elm=80, nettle=46, pine=33, amber=86, vine=72, kelp=73.\nWhat is the recorded number for jade?", + "answer": 98 + }, + { + "id": "test-012-1", + "task": "lookup", + "question": "Records in time order: iris=41, reed=70, jade=46, willow=28, slate=34, birch=69, elm=80, nettle=98, pine=33, amber=86, vine=72, kelp=73.\nWhat is the recorded number for jade?", + "answer": 46 + }, + { + "id": "test-013-0", + "task": "lookup", + "question": "Records in time order: vine=81, olive=56, willow=24, slate=93, elm=82, heath=59, grove=97, fern=57, thyme=78, yew=52, dune=37, umber=23.\nWhat is the recorded number for fern?", + "answer": 57 + }, + { + "id": "test-013-1", + "task": "lookup", + "question": "Records in time order: vine=81, olive=56, willow=24, slate=57, elm=82, heath=59, grove=97, fern=93, thyme=78, yew=52, dune=37, umber=23.\nWhat is the recorded number for fern?", + "answer": 93 + }, + { + "id": "test-014-0", + "task": "lookup", + "question": "Records in time order: iris=89, amber=56, cedar=47, slate=31, elm=34, kelp=38, nettle=50, grove=23, fern=90, willow=61, vine=94, heath=68.\nWhat is the recorded number for elm?", + "answer": 34 + }, + { + "id": "test-014-1", + "task": "lookup", + "question": "Records in time order: iris=89, amber=56, cedar=47, slate=31, elm=94, kelp=38, nettle=50, grove=23, fern=90, willow=61, vine=34, heath=68.\nWhat is the recorded number for elm?", + "answer": 94 + }, + { + "id": "test-015-0", + "task": "lookup", + "question": "Records in time order: willow=73, thyme=57, amber=49, quartz=58, olive=81, heath=64, fern=93, nettle=74, iris=61, reed=32, yew=35, vine=26.\nWhat is the recorded number for reed?", + "answer": 32 + }, + { + "id": "test-015-1", + "task": "lookup", + "question": "Records in time order: willow=73, thyme=32, amber=49, quartz=58, olive=81, heath=64, fern=93, nettle=74, iris=61, reed=57, yew=35, vine=26.\nWhat is the recorded number for reed?", + "answer": 57 + }, + { + "id": "test-016-0", + "task": "lookup", + "question": "Records in time order: nettle=58, willow=62, olive=93, thyme=38, elm=27, cedar=20, birch=86, heath=73, kelp=53, pine=34, dune=50, fern=88.\nWhat is the recorded number for willow?", + "answer": 62 + }, + { + "id": "test-016-1", + "task": "lookup", + "question": "Records in time order: nettle=58, willow=20, olive=93, thyme=38, elm=27, cedar=62, birch=86, heath=73, kelp=53, pine=34, dune=50, fern=88.\nWhat is the recorded number for willow?", + "answer": 20 + }, + { + "id": "test-017-0", + "task": "lookup", + "question": "Records in time order: slate=55, reed=97, heath=36, pine=35, grove=70, fern=37, elm=38, nettle=59, thyme=34, larch=47, vine=30, olive=87.\nWhat is the recorded number for grove?", + "answer": 70 + }, + { + "id": "test-017-1", + "task": "lookup", + "question": "Records in time order: slate=70, reed=97, heath=36, pine=35, grove=55, fern=37, elm=38, nettle=59, thyme=34, larch=47, vine=30, olive=87.\nWhat is the recorded number for grove?", + "answer": 55 + }, + { + "id": "test-018-0", + "task": "lookup", + "question": "Records in time order: dune=58, umber=27, willow=59, larch=43, nettle=64, jade=50, slate=42, heath=44, cedar=77, reed=85, iris=65, yew=72.\nWhat is the recorded number for yew?", + "answer": 72 + }, + { + "id": "test-018-1", + "task": "lookup", + "question": "Records in time order: dune=58, umber=27, willow=59, larch=72, nettle=64, jade=50, slate=42, heath=44, cedar=77, reed=85, iris=65, yew=43.\nWhat is the recorded number for yew?", + "answer": 43 + }, + { + "id": "test-019-0", + "task": "lookup", + "question": "Records in time order: pine=99, slate=58, yew=25, quartz=54, willow=88, vine=40, heath=68, grove=33, elm=32, cedar=80, fern=98, jade=85.\nWhat is the recorded number for fern?", + "answer": 98 + }, + { + "id": "test-019-1", + "task": "lookup", + "question": "Records in time order: pine=99, slate=58, yew=25, quartz=54, willow=88, vine=40, heath=68, grove=33, elm=32, cedar=80, fern=85, jade=98.\nWhat is the recorded number for fern?", + "answer": 85 + }, + { + "id": "test-020-0", + "task": "lookup", + "question": "Records in time order: amber=80, umber=98, dune=50, maple=90, slate=41, pine=57, birch=74, elm=27, quartz=66, larch=61, iris=35, kelp=49.\nWhat is the recorded number for iris?", + "answer": 35 + }, + { + "id": "test-020-1", + "task": "lookup", + "question": "Records in time order: amber=80, umber=98, dune=50, maple=90, slate=35, pine=57, birch=74, elm=27, quartz=66, larch=61, iris=41, kelp=49.\nWhat is the recorded number for iris?", + "answer": 41 + }, + { + "id": "test-021-0", + "task": "lookup", + "question": "Records in time order: fern=74, olive=20, elm=37, kelp=33, slate=86, iris=99, quartz=61, yew=39, jade=21, pine=50, amber=64, thyme=73.\nWhat is the recorded number for elm?", + "answer": 37 + }, + { + "id": "test-021-1", + "task": "lookup", + "question": "Records in time order: fern=74, olive=20, elm=64, kelp=33, slate=86, iris=99, quartz=61, yew=39, jade=21, pine=50, amber=37, thyme=73.\nWhat is the recorded number for elm?", + "answer": 64 + }, + { + "id": "test-022-0", + "task": "lookup", + "question": "Records in time order: dune=48, reed=49, birch=31, jade=83, thyme=72, willow=50, heath=54, pine=39, slate=56, nettle=26, vine=22, grove=57.\nWhat is the recorded number for heath?", + "answer": 54 + }, + { + "id": "test-022-1", + "task": "lookup", + "question": "Records in time order: dune=48, reed=49, birch=31, jade=83, thyme=72, willow=50, heath=56, pine=39, slate=54, nettle=26, vine=22, grove=57.\nWhat is the recorded number for heath?", + "answer": 56 + }, + { + "id": "test-023-0", + "task": "lookup", + "question": "Records in time order: thyme=82, vine=61, jade=68, quartz=93, cedar=76, grove=59, willow=67, fern=65, amber=38, dune=29, maple=37, slate=21.\nWhat is the recorded number for fern?", + "answer": 65 + }, + { + "id": "test-023-1", + "task": "lookup", + "question": "Records in time order: thyme=82, vine=61, jade=68, quartz=93, cedar=76, grove=59, willow=67, fern=29, amber=38, dune=65, maple=37, slate=21.\nWhat is the recorded number for fern?", + "answer": 29 + }, + { + "id": "test-024-0", + "task": "lookup", + "question": "Records in time order: fern=27, elm=39, willow=90, heath=36, slate=61, grove=85, vine=67, birch=56, cedar=47, iris=93, kelp=54, thyme=84.\nWhat is the recorded number for thyme?", + "answer": 84 + }, + { + "id": "test-024-1", + "task": "lookup", + "question": "Records in time order: fern=27, elm=39, willow=90, heath=84, slate=61, grove=85, vine=67, birch=56, cedar=47, iris=93, kelp=54, thyme=36.\nWhat is the recorded number for thyme?", + "answer": 36 + }, + { + "id": "test-025-0", + "task": "lookup", + "question": "Records in time order: heath=41, quartz=66, reed=48, willow=47, fern=44, slate=40, pine=52, grove=90, nettle=33, maple=23, larch=92, olive=55.\nWhat is the recorded number for maple?", + "answer": 23 + }, + { + "id": "test-025-1", + "task": "lookup", + "question": "Records in time order: heath=41, quartz=66, reed=48, willow=47, fern=23, slate=40, pine=52, grove=90, nettle=33, maple=44, larch=92, olive=55.\nWhat is the recorded number for maple?", + "answer": 44 + }, + { + "id": "test-026-0", + "task": "lookup", + "question": "Records in time order: thyme=30, olive=71, quartz=40, cedar=37, larch=55, amber=90, maple=74, grove=21, pine=23, birch=70, jade=89, slate=43.\nWhat is the recorded number for maple?", + "answer": 74 + }, + { + "id": "test-026-1", + "task": "lookup", + "question": "Records in time order: thyme=30, olive=71, quartz=40, cedar=37, larch=55, amber=90, maple=70, grove=21, pine=23, birch=74, jade=89, slate=43.\nWhat is the recorded number for maple?", + "answer": 70 + }, + { + "id": "test-027-0", + "task": "lookup", + "question": "Records in time order: heath=84, yew=47, amber=48, reed=91, elm=79, grove=99, fern=95, kelp=90, olive=29, dune=39, maple=92, vine=98.\nWhat is the recorded number for heath?", + "answer": 84 + }, + { + "id": "test-027-1", + "task": "lookup", + "question": "Records in time order: heath=39, yew=47, amber=48, reed=91, elm=79, grove=99, fern=95, kelp=90, olive=29, dune=84, maple=92, vine=98.\nWhat is the recorded number for heath?", + "answer": 39 + }, + { + "id": "test-028-0", + "task": "lookup", + "question": "Records in time order: slate=79, umber=50, heath=41, larch=87, elm=48, yew=51, willow=45, olive=53, fern=60, cedar=27, kelp=68, reed=30.\nWhat is the recorded number for slate?", + "answer": 79 + }, + { + "id": "test-028-1", + "task": "lookup", + "question": "Records in time order: slate=68, umber=50, heath=41, larch=87, elm=48, yew=51, willow=45, olive=53, fern=60, cedar=27, kelp=79, reed=30.\nWhat is the recorded number for slate?", + "answer": 68 + }, + { + "id": "test-029-0", + "task": "lookup", + "question": "Records in time order: maple=24, elm=41, amber=60, willow=78, quartz=20, thyme=28, olive=92, vine=23, fern=72, iris=33, umber=47, pine=66.\nWhat is the recorded number for quartz?", + "answer": 20 + }, + { + "id": "test-029-1", + "task": "lookup", + "question": "Records in time order: maple=24, elm=41, amber=60, willow=20, quartz=78, thyme=28, olive=92, vine=23, fern=72, iris=33, umber=47, pine=66.\nWhat is the recorded number for quartz?", + "answer": 78 + }, + { + "id": "test-030-0", + "task": "lookup", + "question": "Records in time order: grove=47, fern=45, elm=26, amber=22, quartz=86, reed=78, birch=29, cedar=74, willow=99, slate=52, larch=58, maple=55.\nWhat is the recorded number for fern?", + "answer": 45 + }, + { + "id": "test-030-1", + "task": "lookup", + "question": "Records in time order: grove=47, fern=74, elm=26, amber=22, quartz=86, reed=78, birch=29, cedar=45, willow=99, slate=52, larch=58, maple=55.\nWhat is the recorded number for fern?", + "answer": 74 + }, + { + "id": "test-031-0", + "task": "lookup", + "question": "Records in time order: heath=50, jade=46, birch=70, larch=99, dune=78, nettle=49, umber=38, vine=60, amber=28, grove=69, olive=58, kelp=92.\nWhat is the recorded number for kelp?", + "answer": 92 + }, + { + "id": "test-031-1", + "task": "lookup", + "question": "Records in time order: heath=50, jade=46, birch=92, larch=99, dune=78, nettle=49, umber=38, vine=60, amber=28, grove=69, olive=58, kelp=70.\nWhat is the recorded number for kelp?", + "answer": 70 + } + ] + }, + "base_adapter": "c82db5af7fa42cf58a349f3e53961da2360b211a7ed606f53a728860c64f6f29", + "sites": [ + 15, + 19, + 23 + ], + "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" +} diff --git a/tests/test_lisa_combinations.py b/tests/test_lisa_combinations.py new file mode 100644 index 0000000..6558af9 --- /dev/null +++ b/tests/test_lisa_combinations.py @@ -0,0 +1,57 @@ +"""Regression checks for rank allocation, donor controls and reverse KL.""" +import json +import tempfile +import unittest +from pathlib import Path + +import torch + +from crossqkv.lisa_combination_screen import SITES, paired_questions +from crossqkv.lisa_rank_compare import assignments, make_adapters +from crossqkv.lisa_trajectory_train import reverse_kl + + +class CombinationTests(unittest.TestCase): + def test_reverse_kl_gradient_matches_dense_unequal_vocab_chunks(self): + rng = torch.Generator().manual_seed(72504) + def normal(*shape): + return torch.randn(*shape, dtype=torch.float64, generator=rng) + student = normal(3, 4).requires_grad_() + teacher = normal(3, 4) + weight = normal(13, 4) + loss = reverse_kl(student, teacher, lambda: iter(weight.split(5))) + logp = (student @ weight.T).log_softmax(-1) + logq = (teacher @ weight.T).log_softmax(-1) + dense = (logp.exp() * (logp - logq)).sum(-1).mean() + torch.testing.assert_close(loss, dense) + torch.testing.assert_close(torch.autograd.grad(loss, student)[0], + torch.autograd.grad(dense, student)[0]) + + def test_diagnostic_tie_rule_and_wrong_assignment_control(self): + rows = paired_questions('diagnostic', 2, 72501) + protocol = {'splits': {'diagnostic': rows}, 'rank_budget': [32, 40, 48]} + with tempfile.TemporaryDirectory() as folder: + directory = Path(folder) + for label, correct in [('baseline', 0), ('restore-15', 1), + ('restore-19', 3), ('restore-23', 1)]: + data = [{'id': x['id'], 'gold': x['answer'], + 'arms': {label: {'correct': i < correct}}} for i, x in enumerate(rows)] + (directory/(label+'.json')).write_text(json.dumps(data)) + _, ranks = assignments(protocol, directory) + self.assertEqual(ranks['allocated'], {19: 48, 15: 40, 23: 32}) + self.assertEqual(ranks['reversed'], {19: 32, 15: 40, 23: 48}) + + def test_local_control_is_insensitive_to_donor_with_equal_parameter_count(self): + config = {'hidden_size': 8, 'num_attention_heads': 4, 'num_key_value_heads': 2, + 'rope_parameters': {'rope_theta': 10000, 'partial_rotary_factor': 0.25}} + allocated = dict(zip(SITES, (32, 40, 48))) + local = make_adapters(config, allocated, False) + uniform = make_adapters(config, dict.fromkeys(SITES, 40), True) + def count(adapters): + return sum(p.numel() for a in adapters.values() for p in a.parameters()) + self.assertEqual(count(local), count(uniform)) + h = torch.randn(1, 3, 8) + donor = torch.randn(1, 4, 3, 3) + pos = torch.arange(3)[None, :] + a = local[15] + torch.testing.assert_close(a(h, donor, pos), a(h, donor * 5 + 2, pos))