Evaluate linear and forward-only optimization for attention sharing

This commit is contained in:
2026-11-23 15:01:47 +08:00
parent 5dd3ab32c8
commit f769de90c6
9 changed files with 10014 additions and 0 deletions
+133
View File
@@ -0,0 +1,133 @@
"""Array-level controls for last-query replay and proposal acceptance."""
import json
from pathlib import Path
import struct
from tempfile import TemporaryDirectory
import unittest
from unittest.mock import patch
import numpy as np
from tokenizers import Tokenizer
from tokenizers.models import WordLevel
from tokenizers.pre_tokenizers import Whitespace
from crossqkv.forward_search import collect, problems
from crossqkv.forward_search_fit import LastLayer, random_search, run, SEARCH_STEPS
from functional.model import PREFIX, StreamingLM, attention, norm, sigmoid, silu
class ForwardSearchTests(unittest.TestCase):
def test_last_query_matches_full_causal_attention_and_mlp(self):
rng = np.random.default_rng(4)
def rand(*shape):
return rng.standard_normal(shape, dtype=np.float32) * .4
batch, seq, heads, width, hidden = 2, 6, 4, 2, 5
q = rand(batch, seq, heads, width)
k, v = [rand(batch, seq, heads // 2, width) for _ in range(2)]
gate, raw = rand(batch, seq, heads, width), rand(batch, seq, hidden)
model = LastLayer.__new__(LastLayer)
model.repeats, model.eps = 2, 1e-6
w = model.weights = {'o': rand(hidden, heads*width), 'post': rand(hidden),
'gate': rand(7, hidden), 'up': rand(7, hidden),
'down': rand(hidden, 7), 'final': rand(hidden)}
context, _ = attention(q, k, v)
h = raw + (context * sigmoid(gate)).reshape(batch, seq, -1) @ w['o'].T
n = norm(h, w['post'])
reference = norm(h + (silu(n @ w['gate'].T) * (n @ w['up'].T)) @ w['down'].T,
w['final'])
lengths = np.array([3, 6])
examples = np.arange(batch)
last = lengths - 1
scores = np.einsum('bhd,bshd->bhs', q[examples, last], np.repeat(k, 2, axis=2))
actual = model.forward({'lengths': lengths, 'gate': gate[examples, last],
'residual': raw[examples, last], 'values': v},
scores / np.float32(np.sqrt(width)))
np.testing.assert_allclose(actual, reference[examples, last], atol=1e-6, rtol=1e-6)
def test_search_respects_validation_and_improves_incumbent(self):
def loss(x):
return float(np.sum((x - .4) ** 2))
for method, cost in (('hill', 1), ('two_sided', 3)):
selected, rec = random_search(loss, loss, np.zeros((3, 3), np.float32),
1701, method)
incumbent = [loss(np.zeros((3, 3), np.float32))]
incumbent.extend(x['incumbent_loss'] for x in rec['trace'])
self.assertTrue(all(a >= b for a, b in zip(incumbent, incumbent[1:])))
self.assertLess(loss(selected), incumbent[0])
self.assertEqual(rec['fit_forward_evaluations'], 1 + SEARCH_STEPS * cost)
self.assertAlmostEqual(loss(selected), min(x['loss'] for x in rec['checkpoints']))
def test_task_labels_are_latest_values_and_splits_are_disjoint(self):
all_prompts = set()
for split in ('fit', 'validation', 'test'):
for row in problems(split):
prompt = row['prompt']
self.assertNotIn(prompt, all_prompts)
all_prompts.add(prompt)
records, suffix = prompt.split('. What is the latest value of ')
key = suffix.split('?')[0]
pairs = [x.split('=') for x in records.rsplit(': ', 1)[1].split(', ')]
matches = [int(value) for name, value in pairs if name == key]
self.assertEqual(len(matches), 2 if row['duplicate'] else 1)
self.assertEqual(matches[-1], row['gold'])
if row['duplicate']:
self.assertNotEqual(matches[0], matches[-1])
def test_capture_to_frozen_evaluation_on_tiny_checkpoint(self):
rng = np.random.default_rng(7)
with TemporaryDirectory() as temp:
root = Path(temp)
weights = root / 'weights'
weights.mkdir()
cfg = {'rms_norm_eps': 1e-6, 'num_attention_heads': 2,
'num_key_value_heads': 1, 'head_dim': 32,
'rope_parameters': {'rope_theta': 10000, 'partial_rotary_factor': .25},
'layer_types': ['full_attention'] * 24}
(root / 'model_config.json').write_text(json.dumps({'text_config': cfg}))
(root / 'manifest.json').write_text('{}\n')
tok = Tokenizer(WordLevel({'[UNK]': 0, **{str(i): i for i in range(1, 10)}},
unk_token='[UNK]'))
tok.pre_tokenizer = Whitespace()
tok.save(str(root / 'tokenizer.json'))
shapes = {'embed_tokens.weight': (10, 8), 'norm.weight': (8,)}
for layer in range(24):
for name, shape in {
'input_layernorm': (8,), 'post_attention_layernorm': (8,),
'self_attn.q_proj': (128, 8), 'self_attn.k_proj': (32, 8),
'self_attn.v_proj': (32, 8), 'self_attn.o_proj': (8, 64),
'self_attn.q_norm': (32,), 'self_attn.k_norm': (32,),
'mlp.gate_proj': (12, 8), 'mlp.up_proj': (12, 8),
'mlp.down_proj': (8, 12),
}.items():
shapes[f'layers.{layer}.{name}.weight'] = shape
header, chunks, offset = {}, [], 0
for name, shape in shapes.items():
raw = (rng.standard_normal(shape, dtype=np.float32) * .1).astype('<f4').tobytes()
header[PREFIX + name] = {'shape': shape, 'dtype': 'F32',
'data_offsets': [offset, offset + len(raw)]}
chunks.append(raw)
offset += len(raw)
metadata = json.dumps(header).encode()
(weights / 'tiny.safetensors').write_bytes(
struct.pack('<Q', len(metadata)) + metadata + b''.join(chunks))
cache, out = root / 'capture', root / 'evaluation'
cache.mkdir()
out.mkdir()
# Skip only Linux procfs monitoring for this local synthetic fixture.
with patch.object(StreamingLM, 'guard'), patch('builtins.print'):
collect(root, cache)
with patch.object(StreamingLM, 'forward', side_effect=AssertionError('cached')):
collect(root, cache, resume=True)
run(root, cache, out)
frozen = json.loads((out / 'frozen.json').read_text())
metrics = json.loads((out / 'metrics.json').read_text())
self.assertEqual(len(frozen['optimization']['searches']), 6)
self.assertEqual(set(metrics['test']), {'native'} | frozen['weights'].keys())
self.assertEqual(metrics['test']['native']['n'], 16)
self.assertIn(frozen['validation_winner'], metrics['test'])