"""Forward-only attention sharing experiments on one frozen Qwen checkpoint.""" import argparse import hashlib import json from pathlib import Path import random import numpy as np from tokenizers import Tokenizer from crossqkv.lisa_pilot import DONOR, TARGET, Study from functional.run import write_json SEEDS = {'fit': 22301, 'validation': 22302, 'test': 22303} def problems(split): rng = random.Random(SEEDS[split]) n = {'fit': 12, 'validation': 8, 'test': 16}[split] words = 'ash elm oak fir yew pine birch cedar maple reed moss fern'.split() examples = [] for i in range(n): count = 10 if split == 'test' and i % 4 >= 2 else 6 keys = rng.sample(words, count) first = rng.randrange(count - 1) if i % 2 else rng.randrange(count) key = keys[first] values = [rng.randrange(1, 10) for _ in keys] if i % 2: overwritten = rng.randrange(first + 1, count) keys[overwritten] = key values[overwritten] = (values[first] - 1 + rng.randrange(1, 9)) % 9 + 1 last = max(j for j, k in enumerate(keys) if k == key) entries = ', '.join(f'{k}={v}' for k, v in zip(keys, values)) prompt = f'Records (oldest first): {entries}. What is the latest value of {key}? Answer with one digit:' examples.append({'prompt': prompt, 'gold': values[last], 'entries': count, 'duplicate': bool(i % 2), 'id': f'{split}-{i:02}'}) return examples def encode(tok, examples): prompts, labels = [], None for ex in examples: rows = [tok.encode(f"{ex['prompt']} {i}", add_special_tokens=False).ids for i in range(1, 10)] prefix = rows[0][:-1] digits = [row[-1] for row in rows] if any(row[:-1] != prefix for row in rows) or len(set(digits)) != 9: raise ValueError('Digit answers must share a prefix and differ by one token') if labels is not None and digits != labels: raise ValueError('Digit tokens differ between prompts') prompts.append(prefix) labels = digits lengths = np.array([len(row) for row in prompts]) padded = [row + [0] * (max(lengths) - len(row)) for row in prompts] return np.array(padded, dtype=np.int64), lengths, labels def collect(source, out, resume=False): cfg = json.loads((source / 'model_config.json').read_text()) lm = Study(source / 'weights', cfg, seconds=3600) assert TARGET == len(lm.config['layer_types']) - 1 lm.capture_scores = True tok = Tokenizer.from_file(str(source / 'tokenizer.json')) rows = {s: problems(s) for s in SEEDS} assert len({q['prompt'] for qs in rows.values() for q in qs}) == 36 protocol = { 'donor': DONOR, 'recipient': TARGET, 'seeds': SEEDS, 'capture_code_sha256': hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), 'source_files_sha256': {name: hashlib.sha256((source / name).read_bytes()).hexdigest() for name in ('manifest.json', 'model_config.json', 'tokenizer.json')}, } for name, content in [('protocol.json', protocol), ('problems.json', rows)]: path = out / name if resume and path.exists(): if json.loads(path.read_text()) != content: raise ValueError(f'Existing capture uses different inputs: {path}') else: write_json(path, content) for split, examples in rows.items(): for start in range(0, len(examples), 4): group = examples[start:start+4] ids, lengths, labels = encode(tok, group) path = out / f'{split}-{start:02}.npz' if resume and path.is_file(): with np.load(path, allow_pickle=False) as previous: if (previous['ids'].tolist() != [ex['id'] for ex in group] or not np.array_equal(previous['lengths'], lengths) or not np.array_equal(previous['labels'], labels)): raise ValueError(f'Existing cache batch differs: {path}') print(f'{split}: reused {start + len(group)}/{len(examples)} prompts', flush=True) continue hidden, _ = lm.forward(ids) row = np.arange(len(group)) at = lengths - 1 recipient = lm.recipient pending = path.with_suffix('.tmp.npz') np.savez(pending, ids=[ex['id'] for ex in group], donor=lm.donor[row, :, at], teacher=lm.teacher[row, :, at], local=lm.local[row, :, at], values=recipient['v'], gate=recipient['gate'][row, at], residual=lm.recipient_input[row, at], hidden=hidden[row, at], lengths=lengths, labels=labels, gold=[ex['gold']-1 for ex in group]) pending.replace(path) print(f'{split}: captured {start + len(group)}/{len(examples)} prompts', flush=True) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('phase', choices=('capture',)) parser.add_argument('--source', required=True, type=Path) parser.add_argument('--out', required=True, type=Path) parser.add_argument('--resume', action='store_true') args = parser.parse_args() args.out.mkdir(exist_ok=args.resume) collect(args.source, args.out, resume=args.resume) if __name__ == '__main__': main()