"""Fit lightweight attention adapters and compare them on held-out prompts.""" import argparse import hashlib import json from pathlib import Path import numpy as np from crossqkv.lisa_pilot import TARGET, solve from functional.model import PREFIX, norm, sigmoid, silu from functional.run import write_json from pilot.tensors import decode, load_tensors SPLITS = {'fit': 12, 'validation': 8, 'test': 16} SEARCH_SEEDS = (1701, 1702, 1703) SEARCH_STEPS = 24 def load_split(root, name): paths = sorted(root.glob(f'{name}-*.npz')) if len(paths) * 4 != SPLITS[name]: raise ValueError(f'Incomplete capture for {name}') records = [] for path in paths: with np.load(path, allow_pickle=False) as data: records.append(dict(data)) if any(not np.array_equal(x['labels'], records[0]['labels']) for x in records): raise ValueError('Digit token mismatch') out = {'labels': records[0]['labels']} for k in records[0].keys() - {'labels'}: arrays = [r[k] for r in records] if k in ('donor', 'teacher', 'local', 'values'): axis = 1 if k == 'values' else 2 width = max(a.shape[axis] for a in arrays) padded = [] for a in arrays: pad = [(0, 0)] * a.ndim pad[axis] = (0, width - a.shape[axis]) padded.append(np.pad(a, pad)) arrays = padded out[k] = np.concatenate(arrays, axis=0) return out class LastLayer: def __init__(self, source): cfg = json.loads((source / 'model_config.json').read_text())['text_config'] self.eps = cfg['rms_norm_eps'] self.repeats = cfg['num_attention_heads'] // cfg['num_key_value_heads'] self.tensors = load_tensors(source / 'weights') layer = f'layers.{TARGET}.' names = { 'o': layer + 'self_attn.o_proj', 'gate': layer + 'mlp.gate_proj', 'up': layer + 'mlp.up_proj', 'down': layer + 'mlp.down_proj', 'post': layer + 'post_attention_layernorm', 'final': 'norm', } self.weights = {} for key, name in names.items(): t = self.tensors[PREFIX + name + '.weight'] self.weights[key] = t.read().reshape(t.shape) t.evict() self.embedding = self.tensors[PREFIX + 'embed_tokens.weight'] def digits(self, labels): t = self.embedding out = decode(t.raw.reshape(t.shape)[labels], t.dtype) t.evict() return out def forward(self, batch, scores): keys = np.arange(scores.shape[-1]) < batch['lengths'][:, None] x = np.where(keys[:, None, :], scores, -np.inf) p = np.exp(x - x.max(axis=-1, keepdims=True)) p /= p.sum(axis=-1, keepdims=True) v = np.repeat(batch['values'], self.repeats, axis=2) context = np.einsum('bhs,bshd->bhd', p, v) gated = (context * sigmoid(batch['gate'])).reshape(len(scores), -1) w = self.weights h = batch['residual'] + gated @ w['o'].T n = norm(h, w['post'], self.eps) return norm(h + (silu(n @ w['gate'].T) * (n @ w['up'].T)) @ w['down'].T, w['final'], self.eps) def greedy(self, states): t = self.embedding best = np.full(len(states), -np.inf) tokens = np.zeros(len(states), dtype=int) cols = np.arange(len(states)) for start in range(0, t.shape[0], 1024): end = min(start + 1024, t.shape[0]) w = t.read(slice(start*t.shape[1], end*t.shape[1])).reshape(end-start, -1) logits = states @ w.T local = logits.argmax(axis=1) values = logits[cols, local] better = values > best tokens[better] = start + local[better] best[better] = values[better] t.evict() return tokens def features(batch): return np.concatenate((batch['donor'], batch['local']), axis=1) def transform(batch, weights): return np.einsum('bhs,hi->bis', features(batch), weights) def centered(rows, lengths): return np.concatenate([(x[:, :n] - x[:, :n].mean(axis=1, keepdims=True)).T for x, n in zip(rows, lengths)]).astype(np.float64) def digit_losses(logits, gold): return np.logaddexp.reduce(logits.astype(np.float64), axis=1) - logits[np.arange(len(gold)), gold] def candidate_loss(model, batch, weights): h = model.forward(batch, transform(batch, weights)) return float(digit_losses(h @ model.digits(batch['labels']).T, batch['gold']).mean()) def random_search(loss, validation, start, seed, method): rng = np.random.default_rng(seed) current = start.copy() current_loss = loss(current) checkpoints = [(validation(current), 0, current.copy())] trace = [] for step in range(SEARCH_STEPS): noise = rng.standard_normal(current.shape, dtype=np.float32) radius = .10 * .5 ** (step // 8) if method == 'hill': proposal = current + radius * noise trial = loss(proposal) accepted = trial < current_loss else: plus = loss(current + .025 * noise) minus = loss(current - .025 * noise) # Bounded two-sided directional update. Clip the RMS step per coordinate. scale = float(np.clip(.03 * (plus - minus) / .05, -radius, radius)) proposal = current - scale * noise trial = loss(proposal) accepted = trial < current_loss if accepted: current, current_loss = proposal, trial rec = {'step': step + 1, 'proposal_loss': trial, 'accepted': bool(accepted), 'incumbent_loss': current_loss} if method != 'hill': rec.update(plus_loss=plus, minus_loss=minus) trace.append(rec) if (step + 1) % 6 == 0: checkpoints.append((validation(current), step + 1, current.copy())) val, step, chosen = min(checkpoints, key=lambda item: (item[0], item[1])) return chosen, {'seed': seed, 'selected_step': step, 'validation_loss': val, 'checkpoints': [{'step': s, 'loss': l} for l, s, _ in checkpoints], 'fit_forward_evaluations': 1 + SEARCH_STEPS * (1 if method == 'hill' else 3), 'trace': trace} def run(source, cache, out): protocol = json.loads((cache / 'protocol.json').read_text()) for name, sha in protocol['source_files_sha256'].items(): if hashlib.sha256((source / name).read_bytes()).hexdigest() != sha: raise ValueError(f'Source provenance mismatch: {name}') problems = json.loads((cache / 'problems.json').read_text()) model = LastLayer(source) fit, validation = (load_split(cache, split) for split in ('fit', 'validation')) for split, batch in [('fit', fit), ('validation', validation)]: if batch['ids'].tolist() != [ex['id'] for ex in problems[split]]: raise ValueError(f'Capture order differs for {split}') heads = fit['donor'].shape[1] eye = np.eye(heads, dtype=np.float32) direct = np.concatenate((eye, np.zeros_like(eye))) q = centered(features(fit), fit['lengths']) y = centered(fit['teacher'], fit['lengths']) linear = np.concatenate((solve(q[:, :heads], y), np.zeros_like(eye))) weights = {'direct': direct, 'linear_donor': linear, 'linear_joint': solve(q, y)} fit_loss = lambda w: candidate_loss(model, fit, w) val_loss = lambda w: candidate_loss(model, validation, w) grid = [(a, b, np.concatenate((a*eye, b*eye))) for a in (.5, 1., 1.5) for b in (0., .25, .5, 1.)] grid_scores = [(val_loss(w), a, b, w) for a, b, w in grid] _, gain, local, weights['diagonal_grid'] = min(grid_scores, key=lambda r: r[0]) optimization = {'grid': [{'donor_gain': a, 'local_gain': b, 'loss': l} for l, a, b, _ in grid_scores], 'selected_gains': [gain, local], 'searches': {}} for method in ('hill', 'two_sided'): for seed in SEARCH_SEEDS: key = f'{method}_{seed}' weights[key], optimization['searches'][key] = random_search( fit_loss, val_loss, direct, seed, method) print(key, 'selected step', optimization['searches'][key]['selected_step'], flush=True) validation_scores = {key: val_loss(w) for key, w in weights.items()} chosen = min(weights, key=validation_scores.get) write_json(out / 'frozen.json', {'validation_winner': chosen, 'validation_nll': validation_scores, 'optimization': optimization, 'weights': {k: w.tolist() for k, w in weights.items()}}) result = {} for split in SPLITS: data = load_split(cache, split) if data['ids'].tolist() != [ex['id'] for ex in problems[split]]: raise ValueError(f'Capture order differs for {split}') native = model.forward(data, data['teacher']) err = float(np.max(np.abs(native - data['hidden']))) if not np.allclose(native, data['hidden'], atol=3e-5, rtol=2e-5): raise AssertionError(f'{split} native full-prefix vs last-query parity failed: {err}') states = {'native': native, **{k: model.forward(data, transform(data, w)) for k, w in weights.items()}} modes = list(states) greedy = np.split(model.greedy(np.concatenate(list(states.values()))), len(states)) labels = data['labels'] gold = data['gold'] result[split] = {} groups = {} for i, ex in enumerate(problems[split]): groups.setdefault(f"{ex['entries']}-entries", []).append(i) groups.setdefault('duplicate' if ex['duplicate'] else 'unique', []).append(i) for key, pred in zip(modes, greedy): logits = states[key] @ model.digits(labels).T losses = digit_losses(logits, gold) correct = logits.argmax(axis=1) == gold exact = pred == labels[gold] result[split][key] = {'digit_accuracy': int(correct.sum()), 'greedy_exact_digit': int(exact.sum()), 'by_group': {g: {'n': len(ix), 'digit_accuracy': int(correct[ix].sum()), 'greedy_exact_digit': int(exact[ix].sum()), 'digit_nll': float(losses[ix].mean())} for g, ix in groups.items()}, 'n': len(gold), 'digit_nll': float(losses.mean()), 'loss_by_item': losses.tolist(), 'greedy_ids': pred.tolist(), 'digit_logits': logits.tolist()} print(split, 'native parity max abs', err, flush=True) write_json(out / 'metrics.json', result) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--source', required=True, type=Path) parser.add_argument('--cache', required=True, type=Path) parser.add_argument('--out', required=True, type=Path) args = parser.parse_args() args.out.mkdir() run(args.source, args.cache, args.out) if __name__ == '__main__': main()