Files
exp-model-parameter-similarity/crossqkv/lisa_rank_residuals.py
T

104 lines
4.7 KiB
Python

"""Measure how much native attention score error extra rank can remove on frozen fit captures."""
import argparse
import hashlib
import io
import json
from itertools import permutations
from pathlib import Path
import numpy as np
RECEIPT_SHA = '682bc035a5bed9f9245f589cacf3e9616300e8bf5e85d3743b1264a56360fa55'
RANKS = (32, 40, 48)
def matrices(directory, record):
data = (directory / record['file']).read_bytes()
if hashlib.sha256(data).hexdigest() != record['sha256']:
raise ValueError(f"Capture changed for {record['id']}")
with np.load(io.BytesIO(data), allow_pickle=False) as capture:
donor = capture['donor'][0].astype(np.float64)
teachers = capture['teacher'][:, 0].astype(np.float64)
length = capture['ids'].shape[1]
start = int(capture['start'][0])
if start != record['input_tokens'] or length - start != record['answer_and_eos_tokens']:
raise ValueError(f"Unexpected token counts for {record['id']}")
if teachers.shape != (3, 8, length, length) or donor.shape != teachers.shape[1:]:
raise ValueError(f"Unexpected score shapes for {record['id']}")
features = donor.reshape(8, -1).T
features = np.column_stack((features, np.ones(length * length)))
targets = teachers.reshape(24, -1).T
return features, targets, length
def layer_designs(donor, teachers, adjacent_native):
for layer, target in enumerate(np.hsplit(teachers, 3)):
if adjacent_native and layer:
start = (layer - 1) * 8
features = np.column_stack((teachers[:, start:start + 8], donor[:, -1]))
else:
features = donor
yield features, target
def measure(prior, adjacent_native=False):
raw = (prior / 'verified-fit-capture.json').read_bytes()
if hashlib.sha256(raw).hexdigest() != RECEIPT_SHA:
raise ValueError('Expected the verified 24-example native score capture')
receipt = json.loads(raw)
records = receipt['records']
sites = receipt['recipients']
directory = prior / 'fit-capture'
# Fit one affine donor-head map on each half of the training examples.
gram = np.zeros((2, 3, 9, 9))
cross = np.zeros((2, 3, 9, 8))
for i, record in enumerate(records):
donor, teachers, _ = matrices(directory, record)
for layer, (x, y) in enumerate(layer_designs(donor, teachers, adjacent_native)):
gram[i % 2, layer] += x.T @ x
cross[i % 2, layer] += x.T @ y
coefficients = np.linalg.solve(gram, cross)
rows = []
for i, record in enumerate(records):
donor, teachers, length = matrices(directory, record)
errors = [(y - x @ coef).T.reshape(8, length, length)
for (x, y), coef in zip(layer_designs(donor, teachers, adjacent_native),
coefficients[1 - i % 2])]
residual = np.stack(errors)
singular_values = np.linalg.svd(residual, compute_uv=False)
energy = singular_values**2
np.testing.assert_allclose(energy.sum(-1), (residual**2).sum(axis=(-1, -2)), rtol=1e-10)
rows.append({
'id': record['id'], 'length': length,
'mse': {str(site): {str(rank): float(energy[j, :, rank:].sum() / (8 * length**2))
for rank in (0, *RANKS)} for j, site in enumerate(sites)}
})
means = {str(site): {str(rank): float(np.mean([r['mse'][str(site)][str(rank)] for r in rows]))
for rank in (0, *RANKS)} for site in sites}
uniform = np.array([np.mean([row['mse'][str(site)]['40'] for site in sites]) for row in rows])
configs = []
for ranks in ((40, 40, 40), *permutations(RANKS)):
errors = [np.mean([row['mse'][str(site)][str(rank)] for site, rank in zip(sites, ranks)])
for row in rows]
configs.append({'ranks': list(ranks), 'mean_mse': float(np.mean(errors)),
'examples_below_uniform_mse': int(np.sum(errors < uniform))})
return {
'source_receipt_sha256': RECEIPT_SHA, 'split': 'fit', 'sites': sites,
**({'native_donor_layers': [11, 15, 19]} if adjacent_native else {'donor_layer': 11}),
'donor_fit': 'affine, opposite index parity',
'metric': 'mean per-example, per-layer, per-head, all token-pair squared raw score residual',
'mean_mse': means, 'configurations': configs, 'examples': rows
}
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('prior_final', type=Path)
parser.add_argument('--adjacent-native', action='store_true',
help='Use each previous native full-attention layer as the donor')
args = parser.parse_args()
print(json.dumps(measure(args.prior_final, args.adjacent_native), indent=2, allow_nan=False))