"""Distill next-token distributions along LiSA's current greedy trajectories.""" import argparse import json from pathlib import Path 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 STOP_TEXT, evaluate, fingerprint, prompt from crossqkv.lisa_full_answer_train import FitCapture, checkpoint, load_locked, verified_fit_captures 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(): # Both models use the same frozen output weights. Read each block once # for the two projections, then revisit it only for the student gradient. student_logits = [] teacher_logits = [] for w in chunks(): student_logits.append(student @ w.T) teacher_logits.append(teacher @ w.T) logp = torch.cat(student_logits, dim=-1).log_softmax(-1) del student_logits logq = torch.cat(teacher_logits, dim=-1).log_softmax(-1) del teacher_logits 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() @torch.no_grad() def full_teacher_inputs(model, teacher, ids, lengths): hidden = torch.from_numpy(model.embedding(ids.numpy())) target, maps = teacher(hidden, None, lengths, 'native', ()) return target, teacher.residual, maps[SITES[0]-4][0] @torch.no_grad() def replay_teacher_inputs(tail, path, ids, start, lengths): with np.load(path, allow_pickle=False) as saved: if int(saved['start'].item()) != start or not np.array_equal(saved['ids'], ids.numpy()): raise ValueError('Cached sequence does not match this gold answer and prompt') residual = torch.from_numpy(saved['residual']) donor = torch.from_numpy(saved['donor']) target, _ = tail(residual, donor, lengths, 'native', ()) return target, residual, donor 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) captures = {} final = args.prior/'final' if args.prefix == 'reference' and (final/'verified-fit-capture.json').is_file(): try: captures = verified_fit_captures(final, tasks) except (OSError, ValueError, KeyError) as exc: print('Using full native forward for reference prefixes:', exc, flush=True) for offset, item in enumerate(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]]) if captures: try: cached = replay_teacher_inputs(tail, captures[item['id']], ids, len(base), lengths) except (OSError, ValueError, KeyError) as exc: print('Using full native forward for reference prefixes:', exc, flush=True) captures = {} if not captures or offset == 0: inputs = full_teacher_inputs(model, teacher, ids, lengths) if captures: if all(torch.equal(a, b) for a, b in zip(inputs, cached)): print('Reference cache matches full native target, residual and donor', flush=True) else: print('Reference cache differs. Using full native forward', flush=True) captures = {} else: inputs = cached target, residual, donor = inputs opt.zero_grad(set_to_none=True) student, _ = tail(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()