Compare commits

...

8 Commits

40 changed files with 11443 additions and 9 deletions
+101
View File
@@ -0,0 +1,101 @@
"""Incremental full-attention sites for measuring LiSA's real K/V allocation.
The scheduler supplies the earlier full-attention site's raw score row for
the same query. This file measures an attention site, excluding GDN, MLP,
embedding, and scheduler overhead.
"""
import math
import torch
from crossqkv.lisa_tail import TorchTail, rotate
class AttentionSiteCache:
def __init__(self, tail: TorchTail, layer, batch_size, capacity, adapter=None,
dtype=torch.float32):
self.tail, self.adapter = tail, adapter
self.name = f'layers.{layer}.self_attn.'
self.heads = tail.c['num_attention_heads']
self.kv_heads = tail.c['num_key_value_heads']
self.head_dim = tail.c['head_dim']
self.key_dim = adapter.rank if adapter is not None else self.head_dim
self.capacity = capacity
self.next_position = 0
self.k = torch.empty(batch_size, capacity, self.kv_heads, self.key_dim, dtype=dtype)
self.v = torch.empty(batch_size, capacity, self.kv_heads, self.head_dim, dtype=dtype)
rp = tail.c['rope_parameters']
n = int(self.head_dim * rp['partial_rotary_factor'])
self.rotary_frequency = rp['rope_theta'] ** (-torch.arange(0, n, 2, dtype=dtype) / n)
def reset(self):
self.next_position = 0
@property
def allocated_bytes(self):
return {'k': self.k.numel()*self.k.element_size(),
'v': self.v.numel()*self.v.element_size()}
def native_rotate(self, x, position):
angle = self.rotary_frequency * position
a, b = x[..., :2*len(angle)].chunk(2, -1)
angle = torch.cat((angle, angle))
return torch.cat((torch.cat((a, b), -1)*angle.cos()
+ torch.cat((-b, a), -1)*angle.sin(),
x[..., 2*len(self.rotary_frequency):]), -1)
@torch.no_grad()
def prefill(self, h):
"""Populate K/V from a fresh prefix without scoring its queries."""
n = h.shape[1]
if h.shape[0] != self.k.shape[0] or n > self.capacity:
raise ValueError('Prefix does not fit the attention cache')
base, name = self.tail, self.name
if self.adapter is None:
rp = base.c['rope_parameters']
k = base.linear(h, name+'k_proj').unflatten(-1, (self.kv_heads, self.head_dim))
k = rotate(base.norm(k, name+'k_norm'), rp['rope_theta'], rp['partial_rotary_factor'])
else:
a = self.adapter
k = a.k_proj(h).unflatten(-1, (self.kv_heads, self.key_dim))
k = a.rotate(k, torch.arange(n, device=h.device)[None, :])
self.k[:, :n].copy_(k)
self.v[:, :n].copy_(base.linear(h, name+'v_proj').unflatten(-1, (self.kv_heads, self.head_dim)))
self.next_position = n
@torch.no_grad()
def step(self, h, donor=None):
"""h has shape (batch, 1, hidden). Return output and unmasked score row."""
pos = self.next_position
if h.shape[:2] != (self.k.shape[0], 1) or pos >= self.capacity:
raise ValueError('Wrong input shape or full attention cache')
if self.adapter is not None and (donor is None or
donor.shape != (len(h), self.heads, 1, pos+1)):
raise ValueError('LiSA requires the upstream score row for its full prefix')
base = self.tail
name = self.name
if self.adapter is None:
packed = base.linear(h, name+'q_proj').unflatten(-1, (self.heads, 2*self.head_dim))
q, gate = packed.chunk(2, -1)
k = base.linear(h, name+'k_proj').unflatten(-1, (self.kv_heads, self.head_dim))
q = self.native_rotate(base.norm(q, name+'q_norm'), pos)
k = self.native_rotate(base.norm(k, name+'k_norm'), pos)
else:
a = self.adapter
position = torch.tensor([[pos]], device=h.device)
q = a.rotate(a.q_proj(h).unflatten(-1, (self.heads, self.key_dim)), position)
k = a.rotate(a.k_proj(h).unflatten(-1, (self.kv_heads, self.key_dim)), position)
gate = base.gate_only(h, name)
v = base.linear(h, name+'v_proj').unflatten(-1, (self.kv_heads, self.head_dim))
self.k[:, pos:pos+1].copy_(k)
self.v[:, pos:pos+1].copy_(v)
self.next_position += 1
groups = self.heads // self.kv_heads
keys = self.k[:, :pos+1].repeat_interleave(groups, 2)
values = self.v[:, :pos+1].repeat_interleave(groups, 2)
scores = torch.einsum('bthd,bshd->bhts', q, keys) / math.sqrt(self.key_dim)
if self.adapter is not None:
both = torch.cat((scores, donor), dim=1).permute(0, 2, 3, 1)
scores = self.adapter.fuse(both).permute(0, 3, 1, 2)
context = torch.einsum('bhts,bshd->bthd', scores.softmax(-1), values)
return base.linear((context * gate.sigmoid()).flatten(-2), name+'o_proj'), scores
+130
View File
@@ -0,0 +1,130 @@
"""Measure real K/V allocation and isolated incremental attention on Qwen."""
import argparse
import json
import time
from statistics import median
from pathlib import Path
import numpy as np
import torch
from torch.nn import functional as F
from crossqkv.lisa_decode import AttentionSiteCache
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
class TracedTail(TorchTail):
def full(self, h, layer, donor, lengths, mode, recipients, keep_teacher):
self.inputs[layer] = (h, donor)
return super().full(h, layer, donor, lengths, mode, recipients, keep_teacher)
class ResidentSite:
"""Keep one site's frozen projections resident to isolate compute latency."""
def __init__(self, tail, layer):
self.tail, self.c = tail, tail.c
self.name = f'layers.{layer}.self_attn.'
self.weights = {}
for k in ('q_proj', 'k_proj', 'v_proj', 'o_proj'):
t = tail.source.tensors[PREFIX + self.name + k + '.weight']
self.weights[self.name+k] = torch.cat(list(weight_chunks(t, 0, t.shape[0])))
w = self.weights[self.name+'q_proj']
heads, dim = self.c['num_attention_heads'], self.c['head_dim']
self.gate_weight = w.reshape(heads, 2*dim, -1)[:, dim:].reshape(heads*dim, -1).contiguous()
def linear(self, h, name, start=0, end=None):
return F.linear(h, self.weights[name][start:end])
def gate_only(self, h, name):
if name != self.name:
raise ValueError('Resident gate called for the wrong site')
return F.linear(h, self.gate_weight).unflatten(-1,
(self.c['num_attention_heads'], self.c['head_dim']))
def norm(self, *args):
return self.tail.norm(*args)
def timed_site(groups, h, donor, n, samples=3, rounds=4):
timings = {k: [] for k in groups}
states = {}
for i in range(rounds):
order = tuple(groups) if i % 2 == 0 else tuple(reversed(groups))
for mode in order:
cache = groups[mode]
cache.reset()
cache.prefill(h[:, :n-samples])
for pos in range(n-samples, n):
row = donor[:, :, pos:pos+1, :pos+1].contiguous() if mode == 'lisa' else None
start = time.perf_counter()
result, attention = cache.step(h[:, pos:pos+1], row)
elapsed = time.perf_counter() - start
if i:
timings[mode].append(elapsed)
if not torch.isfinite(result).all():
raise FloatingPointError('Invalid cached decode')
states[mode] = result, attention
return timings, states
def run(source, capture, checkpoint, out):
torch.set_num_threads(1)
spec = json.loads((capture/'selection.json').read_text())
sites = spec['sites']
source = StreamingLM(source/'weights', json.loads((source/'model_config.json').read_text()))
cfg = source.config
rope = cfg['rope_parameters']
adap = {i: LearnableSharingAttention(cfg['hidden_size'], cfg['num_attention_heads'],
cfg['num_key_value_heads'], 40, rope['rope_theta'], rope['partial_rotary_factor'],
bias=cfg.get('attention_bias', False)) for i in sites}
tail = TracedTail(source, sites[0], adap)
tail.adapters.load_state_dict(torch.load(checkpoint, map_location='cpu', weights_only=True))
with np.load(sorted(capture.glob('validation-*.npz'))[0], allow_pickle=False) as f:
n = int(f['lengths'][0])
data = {k: torch.from_numpy(f[k][:1]) for k in ('residual', 'donor', 'lengths')}
data['residual'] = data['residual'][:, :n]
data['donor'] = data['donor'][:, :, :n, :n]
tail.inputs = {}
measurements = {}
with torch.no_grad():
tail(data['residual'], data['donor'], data['lengths'], 'native', ())
for layer in sites:
h, donor = tail.inputs[layer]
groups = {'native': AttentionSiteCache(tail, layer, 1, n),
'lisa': AttentionSiteCache(tail, layer, 1, n, adap[layer])}
timings, reference = timed_site(groups, h, donor, n)
resident = ResidentSite(tail, layer)
resident_groups = {mode: AttentionSiteCache(resident, layer, 1, n,
adap[layer] if mode == 'lisa' else None) for mode in groups}
warm, checked = timed_site(resident_groups, h, donor, n)
for mode in groups:
for actual, expected in zip(checked[mode], reference[mode]):
torch.testing.assert_close(actual, expected, rtol=5e-5, atol=5e-5)
measurements[layer] = {'seconds_per_token': timings,
'resident_seconds_per_token': warm,
'resident_median_s_per_token': {k: median(v) for k,v in warm.items()},
'resident_matches_streamed': True,
'allocated_bytes': {k: v.allocated_bytes for k, v in groups.items()},
'lisa_input_score_row_bytes': (
cfg['num_attention_heads'] * n * h.element_size()),
'sequence_length': n}
write_json(out, {'scope': 'isolated full-attention recipient, FP32, frozen true activations; '
'excludes donor generation and full-model decode', 'sites': measurements,
'streamed_timings_include_weight_reads': True,
'resident_timings_exclude_projection_load': True})
def main():
p = argparse.ArgumentParser(description=__doc__)
for name in ('source', 'capture', 'checkpoint', 'out'):
p.add_argument('--'+name, type=Path, required=True)
a = p.parse_args()
run(a.source, a.capture, a.checkpoint, a.out)
if __name__ == '__main__':
main()
+296
View File
@@ -0,0 +1,296 @@
"""Train matched multi-recipient sharing adapters and evaluate the frozen test set."""
import argparse
import hashlib
import json
import time
from pathlib import Path
import numpy as np
from crossqkv.core import QKVModel
from crossqkv.lisa_effect_screen import TASKS
from crossqkv.lisa_pilot import batch, scores
from functional.model import PREFIX
from functional.run import write_json
CANDIDATES = ('linear', 'lisa', 'lisa_answer_weighted')
def selection(screen):
eligible = []
for task, modes in screen.items():
base = modes['native']
if base['correct'] < 5:
continue
for name, sites in [('direct_23', [23]), ('direct_19_23', [19, 23])]:
row = modes[name]
if row['native_wins_lost']:
eligible.append((row['native_wins_lost'], len(sites),
base['correct']-row['correct'], task, sites))
if not eligible:
raise ValueError('No task/schedule met the prespecified development eligibility rule')
_, _, _, task, sites = max(eligible)
return {'task': task, 'sites': sites}
class Capture(QKVModel):
def normalization(self, x, name):
if name == f'layers.{self.first}.input_layernorm':
self.residual = x
return super().normalization(x, name)
def full_attention(self, h, layer, shared_p=None):
if layer != self.first - 4:
return super().full_attention(h, layer, shared_p)
part = self.parts(h, layer, heads=False)
self.donor = scores(part['q'], part['k'])
return part['output'], part['p']
def capture(source, screen_dir, out, schedule):
from tokenizers import Tokenizer
fixed_path = screen_dir/'fixed-problems.json'
fixed = json.loads(fixed_path.read_text())
chosen = selection(json.loads((screen_dir/'screen-summary.json').read_text()))
if schedule == 'chain':
modes = json.loads((screen_dir/'screen-summary.json').read_text())[chosen['task']]
if not modes['direct_19_23']['native_wins_lost']:
raise ValueError('The development-selected task has no recorded losses under the chain')
chosen['sites'] = [19, 23]
model = Capture(source/'weights', json.loads((source/'model_config.json').read_text()),
seconds=7200)
model.first = chosen['sites'][0]
tok = Tokenizer.from_file(str(source/'tokenizer.json'))
sha = lambda path: hashlib.sha256(path.read_bytes()).hexdigest()
write_json(out/'selection.json', {**chosen, 'fixed_problems_sha256': sha(fixed_path),
'source_sha256': {n: sha(source/n) for n in
('manifest.json', 'model_config.json', 'tokenizer.json')}})
for split in ('fit', 'validation', 'test'):
selected = [ex for ex in fixed[split] if ex['task'] == chosen['task']]
for start in range(0, len(selected), 4):
group = selected[start:start+4]
ids, lengths, labels = batch(tok, group)
gold = np.array([r['answer_index'] for r in group])
ids = np.pad(ids, ((0, 0), (0, 1)))
ids[np.arange(len(group)), lengths] = np.asarray(labels)[gold]
h, _ = model.forward(ids)
pending = out/f'{split}-{start:03}.tmp.npz'
np.savez(pending, ids=ids, lengths=np.asarray(lengths)+1, labels=labels, gold=gold,
residual=model.residual, donor=model.donor, expected=h,
names=[x['id'] for x in group])
pending.replace(out/f'{split}-{start:03}.npz')
print('capture', split, start+len(group), '/', len(selected), flush=True)
def train(source, cache, out, epochs, resume=False):
import torch
from torch import nn
from crossqkv.lisa_tail import TorchTail
from crossqkv.lisa_train import LearnableSharingAttention, huber_distillation, language_model_loss
from functional.model import StreamingLM
torch.set_num_threads(1)
torch.manual_seed(415005)
spec = json.loads((cache/'selection.json').read_text())
if any(hashlib.sha256((source/n).read_bytes()).hexdigest() != s
for n, s in spec['source_sha256'].items()):
raise ValueError('Checkpoint provenance mismatch')
expected_batches = {'fit':12, 'validation':12, 'test':32}
for split, count in expected_batches.items():
actual = 0
for p in cache.glob(f'{split}-*.npz'):
with np.load(p, allow_pickle=False) as b:
actual += len(b['names'])
if actual != count:
raise ValueError(f'Expected {count} {split} examples, found {actual}')
run_config = {'epochs': epochs, 'selection': spec, 'optimizer': 'AdamW',
'lr': .0003, 'weight_decay': .1, 'answer_weight': 16., 'seed': 415005}
config_path = out/'train-protocol.json'
if resume:
if json.loads(config_path.read_text()) != run_config:
raise ValueError('Training configuration differs from the original run')
else:
write_json(config_path, run_config)
model = StreamingLM(source/'weights', json.loads((source/'model_config.json').read_text()))
sites = tuple(spec['sites'])
cfg = model.config
heads = cfg['num_attention_heads']
rope = cfg['rope_parameters']
t = model.tensors[PREFIX+'embed_tokens.weight']
def vocab():
for start in range(0, t.shape[0], 1024):
end = min(start+1024, t.shape[0])
yield start, torch.from_numpy(t.read(slice(start*t.shape[1], end*t.shape[1]))
.reshape(end-start, t.shape[1]))
t.evict()
def batches(split, micro=False):
for path in sorted(cache.glob(f'{split}-*.npz')):
with np.load(path, allow_pickle=False) as f:
b = {k: torch.from_numpy(f[k]) for k in f.files if k != 'names'}
names = f['names'].tolist()
if not micro:
yield b, names
else:
for j, name in enumerate(names):
yield {k: v if k == 'labels' else v[j:j+1] for k, v in b.items()}, [name]
def make(candidate):
torch.manual_seed(415005)
if candidate == 'linear':
blocks = {i: nn.Linear(heads, heads, bias=False) for i in sites}
for value in blocks.values():
with torch.no_grad():
value.weight.copy_(torch.eye(heads))
else:
blocks = {i: LearnableSharingAttention(cfg['hidden_size'], heads,
cfg['num_key_value_heads'], 40, rope['rope_theta'],
rope['partial_rotary_factor'], bias=cfg.get('attention_bias', False))
for i in sites}
return TorchTail(model, sites[0], blocks)
def run(tail, b, mode, teacher=False):
return tail(b['residual'], b['donor'], b['lengths'], mode, sites, teacher)
def score(h, b):
index = b['lengths'] - 2
f = h[torch.arange(len(index)), index]
labels = b['labels'].tolist()
weights = np.stack([t.read(slice(i*t.shape[1], (i+1)*t.shape[1])) for i in labels])
t.evict()
logits = f @ torch.from_numpy(weights).T
nll = torch.logsumexp(logits, -1) - logits[torch.arange(len(index)), b['gold']]
return logits, nll
def evaluate(tail, split, mode):
rows = []
with torch.no_grad():
for b, names in batches(split):
h, _ = run(tail, b, mode)
if mode == 'native':
valid = torch.arange(h.shape[1])[None] < b['lengths'][:, None]
torch.testing.assert_close(h[valid], b['expected'][valid], rtol=7e-5, atol=8e-5)
logits, nll = score(h, b)
rows.extend({'id': name, 'gold': int(g), 'logits': x.tolist(),
'pred': int(x.argmax()), 'answer_nll': float(v)}
for name, g, x, v in zip(names, b['gold'], logits, nll))
if not rows:
raise ValueError(f'No cached rows for {split}')
return rows
def mean_nll(rows):
return sum(r['answer_nll'] for r in rows) / len(rows)
trace = {}
for candidate in CANDIDATES:
tail = make(candidate)
mode = 'linear' if candidate == 'linear' else 'lisa'
optim = torch.optim.AdamW(tail.parameters(), lr=.0003, weight_decay=.1)
ans_weight = 16.0 if candidate == 'lisa_answer_weighted' else 1.0
best = float('inf')
best_weights = None
trace[candidate] = []
last = out/f'{candidate}-resume.pt'
if resume and last.exists():
state = torch.load(last, weights_only=True, map_location='cpu')
tail.adapters.load_state_dict(state['parameters'])
optim.load_state_dict(state['optimizer'])
trace[candidate] = state['trace']
best = state['best']
best_weights = state['best_parameters']
for epoch in range(len(trace[candidate]), epochs):
loss_total = 0.
count = 0
for b, _ in batches('fit', micro=True):
optim.zero_grad(set_to_none=True)
h, layer = run(tail, b, mode, teacher=True)
kd = torch.stack([huber_distillation(*layer[i], b['lengths']) for i in sites]).mean()
ce = None if mode == 'linear' else language_model_loss(
h, b['ids'], b['lengths'], vocab, answer_weight=ans_weight)
loss = kd if ce is None else .25 * kd + .75 * ce
loss.backward()
if any(p.grad is None or not torch.isfinite(p.grad).all() for p in tail.parameters()):
raise FloatingPointError('Invalid adapter gradients')
optim.step()
loss_total += float(loss.detach())
count += 1
rows = evaluate(tail, 'validation', mode)
val = mean_nll(rows)
trace[candidate].append({'epoch': epoch+1, 'fit_loss': loss_total/count,
'validation_answer_nll': val})
if val < best:
best = val
best_weights = {k: v.detach().clone() for k, v in tail.adapters.state_dict().items()}
pending = last.with_suffix('.tmp')
torch.save({'parameters': tail.adapters.state_dict(), 'optimizer': optim.state_dict(),
'trace': trace[candidate], 'best': best, 'best_parameters': best_weights},
pending)
pending.replace(last)
write_json(out/'trace.json', trace)
print(candidate, epoch+1, 'validation answer NLL', val, flush=True)
selected = out/f'{candidate}.pt'
pending = selected.with_suffix('.tmp')
torch.save(best_weights, pending)
pending.replace(selected)
# All checkpoints are frozen before evaluating holdout. Native and direct
# go through the same path, including numerical parity with NumPy.
results = {}
empty = TorchTail(model, sites[0])
for mode in ('native', 'direct'):
results[mode] = evaluate(empty, 'test', mode)
for name in CANDIDATES:
tail = make(name)
tail.adapters.load_state_dict(torch.load(out/f'{name}.pt', map_location='cpu', weights_only=True))
results[name] = evaluate(tail, 'test', 'linear' if name == 'linear' else 'lisa')
write_json(out/'test-items.json', results)
b, _ = next(batches('validation'))
b = {k: v if k == 'labels' else v[:1] for k, v in b.items()}
trained = make('lisa')
trained.adapters.load_state_dict(torch.load(out/'lisa.pt', weights_only=True))
timing = {'native': [], 'direct': [], 'lisa': []}
with torch.no_grad():
for turn in range(4):
modes = list(timing)
for mode in modes[turn % 3:] + modes[:turn % 3]:
t0 = time.perf_counter()
_, _ = run(trained if mode == 'lisa' else empty, b, mode)
if turn:
timing[mode].append(time.perf_counter()-t0)
tokens = int(b['lengths'][0])
kv, d = cfg['num_key_value_heads'], cfg['head_dim']
cache_bytes = {'scope': 'formula for one sequence, BF16 keys and score buffers',
'native_recipient_key_bytes': len(sites)*tokens*kv*d*2,
'lisa_recipient_key_bytes': len(sites)*tokens*kv*40*2,
'one_shared_decode_score_row_bytes': heads*tokens*2,
'one_full_prefill_score_matrix_bytes': heads*tokens*tokens*2}
write_json(out/'performance.json', {'scope': 'cached-prefix last layers, prefill',
'seconds': timing, 'real_tokens': tokens, 'cache_estimate': cache_bytes})
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('phase', choices=('capture', 'train'))
p.add_argument('--source', required=True, type=Path)
p.add_argument('--input', required=True, type=Path)
p.add_argument('--out', required=True, type=Path)
p.add_argument('--schedule', choices=('best','chain'), default='best')
p.add_argument('--epochs', type=int, default=2)
p.add_argument('--resume', action='store_true')
a = p.parse_args()
if a.epochs < 1:
p.error('--epochs must be positive')
if a.resume and a.phase != 'train':
p.error('--resume is for training with saved epoch checkpoints')
a.out.mkdir(exist_ok=a.resume)
if a.phase == 'capture':
capture(a.source, a.input, a.out, a.schedule)
else:
train(a.source, a.input, a.out, a.epochs, a.resume)
if __name__ == '__main__':
main()
+115
View File
@@ -0,0 +1,115 @@
"""Compare one vs two recipients on the same task using full-vocabulary answers."""
import argparse
import json
from pathlib import Path
import numpy as np
import torch
from torch.nn import functional as F
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 vocabulary_scores(hidden, targets, embedding):
n = len(hidden)
peak = hidden.new_full((n,), -torch.inf)
total = peak.clone()
top = torch.zeros(n, dtype=torch.int64)
true = torch.zeros_like(peak)
start = 0
for w in weight_chunks(embedding, 0, embedding.shape[0], rows=1024):
logits = F.linear(hidden, w)
total = torch.logaddexp(total, logits.logsumexp(dim=-1))
values, indices = logits.max(dim=-1)
top = torch.where(values > peak, indices + start, top)
peak = torch.maximum(values, peak)
local = (targets >= start) & (targets < start + len(w))
true[local] = logits[local, targets[local]-start]
start += len(w)
return top, total-true
def run(source, cache, trained, out):
torch.set_num_threads(1)
spec = json.loads((cache/'selection.json').read_text())
sites = tuple(spec['sites'])
stream = StreamingLM(source/'weights', json.loads((source/'model_config.json').read_text()))
cfg = stream.config
rp = cfg['rope_parameters']
heads, kv = cfg['num_attention_heads'], cfg['num_key_value_heads']
def loaded(mode):
if mode == 'linear':
from torch import nn
modules = {site: nn.Linear(heads, heads, bias=False) for site in sites}
else:
modules = {site: LearnableSharingAttention(cfg['hidden_size'], heads, kv, 40,
rp['rope_theta'], rp['partial_rotary_factor'],
bias=cfg.get('attention_bias', False)) for site in sites}
tail = TorchTail(stream, sites[0], modules)
tail.adapters.load_state_dict(torch.load(trained/f'{mode}.pt', weights_only=True,
map_location='cpu'))
return tail
empty = TorchTail(stream, sites[0])
fitted = loaded('lisa')
arms = [('native', empty, 'native', ()),
('direct_23', empty, 'direct', (sites[-1],)),
('lisa_23_ablation', fitted, 'lisa', (sites[-1],))]
if len(sites) > 1:
arms.extend([('direct_chain', empty, 'direct', sites),
('lisa_chain', fitted, 'lisa', sites)])
arms.extend([('linear', loaded('linear'), 'linear', sites),
('lisa_answer_weighted', loaded('lisa_answer_weighted'), 'lisa', sites)])
answers = {name: [] for name, *_ in arms}
ids, labels, options = [], [], []
with torch.no_grad():
for path in sorted(cache.glob('test-*.npz')):
with np.load(path, allow_pickle=False) as f:
b = {k: torch.from_numpy(f[k]) for k in f.files if k != 'names'}
ids.extend(f['names'].tolist())
labels.append(b['labels'][b['gold']])
options.append(b['labels'].expand(len(b['gold']), -1))
for name, tail, mode, chosen in arms:
h, _ = tail(b['residual'], b['donor'], b['lengths'], mode, chosen)
answers[name].append(h[torch.arange(len(h)), b['lengths']-2])
print('matched full-vocabulary audit', len(ids), flush=True)
if not ids:
raise ValueError('No captured holdout batches')
y = torch.cat(labels)
t = stream.tensors[PREFIX+'embed_tokens.weight']
hidden = torch.cat([torch.cat(answers[k]) for k in answers])
pred, nll = vocabulary_scores(hidden, y.repeat(len(answers)), t)
result = {}
opts = torch.cat(options)
for (name, h), p, v in zip(answers.items(), pred.split(len(y)), nll.split(len(y))):
option_w = torch.stack([torch.from_numpy(t.read(slice(i*t.shape[1], (i+1)*t.shape[1])))
for i in opts[0].tolist()])
if not torch.equal(opts, opts[0].expand_as(opts)):
raise ValueError('Option token IDs unexpectedly vary across items')
t.evict()
choice = opts[torch.arange(len(y)), F.linear(torch.cat(h), option_w).argmax(-1)]
result[name] = {'n': len(y), 'full_vocab_correct': int((p==y).sum()),
'four_choice_correct': int((choice==y).sum()),
'full_vocab_nll': float(v.mean()),
'rows': [{'id': key, 'gold_id': int(g), 'greedy_id': int(j),
'choice_id': int(c), 'nll': float(s)}
for key, g, j, c, s in zip(ids, y, p, choice, v)]}
write_json(out, {'single_lisa_is_ablation_of_joint_checkpoint': len(sites) > 1,
'candidate_sites': list(sites), 'arms': result})
def main():
p = argparse.ArgumentParser(description=__doc__)
for name in ('source', 'cache', 'trained', 'out'):
p.add_argument('--'+name, type=Path, required=True)
a = p.parse_args()
run(a.source, a.cache, a.trained, a.out)
if __name__ == '__main__':
main()
+157
View File
@@ -0,0 +1,157 @@
"""Independently validate frozen test outputs and report paired capability recovery."""
import argparse
import hashlib
import json
import math
from pathlib import Path
from statistics import median
import numpy as np
from functional.run import write_json
MODES = ('native', 'direct', 'linear', 'lisa', 'lisa_answer_weighted')
def paired_interval(delta):
rng = np.random.default_rng(415006)
draw = rng.integers(0, len(delta), size=(10000, len(delta)))
return np.quantile(delta[draw].mean(1), [.025, .975]).tolist()
def paired(native, direct, candidate):
damaged = native & ~direct
rescued = damaged & candidate
newly_lost = native & direct & ~candidate
candidate_only = ~direct & candidate
direct_only = direct & ~candidate
delta = candidate.astype(int) - direct.astype(int)
a, b = int(candidate_only.sum()), int(direct_only.sum())
k = a + b
p = min(1., 2. * sum(math.comb(k, i) for i in range(min(a, b)+1)) / 2**k)
return {'native_correct_lost_by_direct': int(damaged.sum()), 'rescued': int(rescued.sum()),
'newly_lost_among_native_and_direct_correct': int(newly_lost.sum()),
'candidate_correct_direct_wrong': a, 'direct_correct_candidate_wrong': b,
'accuracy_delta_vs_direct': float(delta.mean()),
'paired_prompt_bootstrap_95': paired_interval(delta), 'mcnemar_exact_p': p}
def loss_delta(losses, baseline):
delta = losses - baseline
return {'mean_delta': float(delta.mean()), 'paired_prompt_bootstrap_95': paired_interval(delta)}
def full_vocab_metrics(path, expected, sites, choices):
report = json.loads(path.read_text())
chain = len(sites) > 1
if (report['candidate_sites'] != sites
or report['single_lisa_is_ablation_of_joint_checkpoint'] != chain):
raise ValueError('Full-vocabulary layers differ from the locked schedule')
arms = report['arms']
mapped = {'native': 'native', 'linear': 'linear', 'lisa_answer_weighted': 'lisa_answer_weighted',
'direct_chain' if chain else 'direct_23': 'direct',
'lisa_chain' if chain else 'lisa_23_ablation': 'lisa'}
if set(arms) != set(mapped) | {'direct_23', 'lisa_23_ablation'}:
raise ValueError('Unexpected full-vocabulary arms')
expected_ids = [name for name, _ in expected]
correct, nll = {}, {}
gold_ids = [row['gold_id'] for row in arms['native']['rows']]
for mode, summary in arms.items():
rows = summary['rows']
if (summary['n'] != len(expected_ids) or [row['id'] for row in rows] != expected_ids
or [row['gold_id'] for row in rows] != gold_ids):
raise ValueError(f'{mode} vocabulary result does not match the locked rows')
correct[mode] = np.array([row['greedy_id'] == row['gold_id'] for row in rows])
nll[mode] = np.array([row['nll'] for row in rows])
choice_correct = np.array([row['choice_id'] == row['gold_id'] for row in rows])
if (not np.isfinite(nll[mode]).all() or (nll[mode] < 0).any()
or int(correct[mode].sum()) != summary['full_vocab_correct']
or int(choice_correct.sum()) != summary['four_choice_correct']
or not np.isclose(nll[mode].mean(), summary['full_vocab_nll'])):
raise ValueError(f'Invalid vocabulary metrics for {mode}')
if mode in mapped and not np.array_equal(choice_correct, choices[mapped[mode]]):
raise ValueError(f'{mode} choices differ across the two evaluations')
matches = {'lisa_23_ablation': 'direct_23',
'native': 'direct_chain' if chain else 'direct_23',
'linear': 'direct_chain' if chain else 'direct_23',
'lisa_answer_weighted': 'direct_chain' if chain else 'direct_23'}
if chain:
matches['lisa_chain'] = 'direct_chain'
return {
'arms': {mode: {'correct': int(correct[mode].sum()), 'answer_nll': float(nll[mode].mean())}
for mode in arms},
'matched_direct_comparisons': {
mode: {'baseline': direct, 'answer_nll_delta': loss_delta(nll[mode], nll[direct]),
**paired(correct['native'], correct[direct], correct[mode])}
for mode, direct in matches.items()},
}
def audit(fixed, selection, items, perf=None, decode=None, full_vocab=None):
spec = json.loads(selection.read_text())
if hashlib.sha256(fixed.read_bytes()).hexdigest() != spec['fixed_problems_sha256']:
raise ValueError('Fixed problems provenance mismatch')
problem = json.loads(fixed.read_text())
task = spec['task']
expected = [(r['id'], r['answer_index']) for r in problem['test'] if r['task'] == task]
data = json.loads(items.read_text())
if set(data) != set(MODES) or not expected:
raise ValueError('Unexpected test arms or empty selected split')
correct = {}
losses = {}
for mode, rows in data.items():
if [(r['id'], r['gold']) for r in rows] != expected:
raise ValueError(f'{mode} result does not match the locked challenge')
logits = np.array([r['logits'] for r in rows])
gold = np.array([r['gold'] for r in rows])
pred = np.array([r['pred'] for r in rows])
nll = np.logaddexp.reduce(logits, 1) - logits[np.arange(len(rows)), gold]
if (logits.shape != (len(rows), 4) or not np.isfinite(logits).all()
or not np.array_equal(logits.argmax(1), pred)):
raise ValueError(f'Invalid choice scores for {mode}')
np.testing.assert_allclose(nll, [row['answer_nll'] for row in rows], atol=3e-6, rtol=2e-6)
correct[mode], losses[mode] = pred == gold, nll
metrics = {'selected_task': task, 'sites': spec['sites'], 'n': len(expected),
'arms': {mode: {'correct': int(correct[mode].sum()),
'answer_nll_4': float(losses[mode].mean()),
'answer_nll_4_vs_direct': loss_delta(losses[mode], losses['direct']),
**paired(correct['native'], correct['direct'], correct[mode])}
for mode in MODES}}
if perf:
measured = json.loads(perf.read_text())
med = {k: median(v) for k,v in measured['seconds'].items()}
metrics['prefill'] = {'scope': measured['scope'], 'median_s': med,
'lisa_median_ratio_to_native': med['lisa']/med['native']}
if decode:
measured = json.loads(decode.read_text())
metrics['decode'] = {'scope': measured['scope'], 'sites': {}}
for layer, raw in measured['sites'].items():
times = {k: median(v) for k,v in raw['seconds_per_token'].items()}
mem = raw['allocated_bytes']
native = mem['native']['k'] + mem['native']['v']
lisa = mem['lisa']['k'] + mem['lisa']['v']
nn = raw['lisa_input_score_row_bytes']
assert mem['lisa']['v'] == mem['native']['v'] and mem['lisa']['k'] < mem['native']['k']
metrics['decode']['sites'][layer] = {
'median_s_per_token': times, 'measured_kv_bytes': {'native': native, 'lisa': lisa},
'lisa_upstream_score_row_bytes': nn, 'recipient_bytes_delta': lisa+nn-native,
}
if full_vocab:
metrics['full_vocab'] = full_vocab_metrics(full_vocab, expected, spec['sites'], correct)
return metrics
def main():
parser = argparse.ArgumentParser(description=__doc__)
for name in ('fixed', 'selection', 'items', 'out'):
parser.add_argument('--'+name, type=Path, required=True)
parser.add_argument('--perf', type=Path)
parser.add_argument('--decode', type=Path)
parser.add_argument('--full-vocab', type=Path)
a = parser.parse_args()
report = audit(a.fixed, a.selection, a.items, a.perf, a.decode, a.full_vocab)
write_json(a.out, report)
if __name__ == '__main__':
main()
+183
View File
@@ -0,0 +1,183 @@
"""Screen task difficulty and joint sharing schedules without opening test results."""
import argparse
import json
import random
from pathlib import Path
import numpy as np
from tokenizers import Tokenizer
from crossqkv.core import QKVModel
from crossqkv.lisa_pilot import batch
from functional.model import PREFIX
from functional.run import write_json
from pilot.tensors import decode
MODES = ('native', 'direct_23', 'direct_19_23')
SITES = (15, 19, 23)
TASKS = ('lookup8', 'lookup16', 'latest8', 'arithmetic')
SPLIT_SEEDS = {'screen': 415001, 'fit': 415002, 'validation': 415003, 'test': 415004}
WORDS = ('amber birch cedar dune elm fern grove heath iris jade kelp larch '
'maple nettle olive pine quartz reed slate thyme umber vine willow yew').split()
def problems(split, per_task):
rng = random.Random(SPLIT_SEEDS[split])
rows = []
for task in TASKS:
answers = [i % 4 for i in range(per_task)]
rng.shuffle(answers)
for i, answer in enumerate(answers):
if task == 'arithmetic':
a, b = rng.sample(range(12, 99), 2)
target = a + b
distractors = [target - 10, target + 10, target + rng.choice((-1, 1))]
question = f'What is {a} + {b}?'
else:
size = 16 if task == 'lookup16' else 8
keys, vals = rng.sample(WORDS, size), rng.sample(range(10, 100), size)
if task == 'latest8':
first = rng.randrange(size - 1)
last = rng.randrange(first + 1, size)
keys[last] = keys[first]
target = vals[last]
remaining = [v for j, v in enumerate(vals) if j not in (first, last)]
distractors = [vals[first], *rng.sample(remaining, 2)]
key = keys[first]
else:
match = rng.randrange(size)
target, key = vals[match], keys[match]
distractors = rng.sample([v for v in vals if v != target], 3)
table = '\n'.join(f'{k}: {v}' for k, v in zip(keys, vals))
request = 'latest value' if task == 'latest8' else 'value'
order = ' (oldest first)' if task == 'latest8' else ''
question = f'Use the lookup table{order}.\n{table}\nWhich option is the {request} for {key}?'
rng.shuffle(distractors)
distractors.insert(answer, target)
options = '\n'.join(f'{j+1}. {v}' for j, v in enumerate(distractors))
prompt = f'{question}\n{options}\nAnswer with only the option number.\nAnswer:'
rows.append({'id': f'{split}-{task}-{i:03}', 'task': task,
'prompt': prompt, 'answer_index': answer})
return rows
class ScreeningModel(QKVModel):
def normalization(self, h, name):
if getattr(self, 'capture_prefix', False) and name == 'layers.19.input_layernorm':
self.residual_19 = h
return super().normalization(h, name)
def full_attention(self, h, layer, shared_p=None):
if layer not in SITES:
return super().full_attention(h, layer, shared_p)
own = self.parts(h, layer, heads=False)
p = own['p'].copy()
if getattr(self, 'capture_prefix', False):
if layer == 15:
self.donor_15 = p
return own['output'], p
if layer == 19:
p[self.chain] = self.prior[self.chain]
elif layer == 23:
p[self.shared] = self.prior[self.shared]
self.prior = p
repeats = self.config['num_attention_heads'] // self.config['num_key_value_heads']
v = np.repeat(own['v'], repeats, axis=2)
out = self.project(np.einsum('bhts,bshd->bthd', p, v), own['gate'], layer)
return out, p
def evaluate(model, tokenizer, examples):
ids, lengths, labels = batch(tokenizer, examples)
n = len(examples)
model.chain = slice(2*n, 3*n)
model.shared = slice(n, 3*n)
if not getattr(model, 'reuse_prefix', False):
h, _ = model.forward(np.tile(ids, (len(MODES), 1)))
else:
model.capture_prefix = True
native, _ = model.forward(ids)
model.capture_prefix = False
h = np.concatenate([model.residual_19] * len(MODES))
model.prior = np.concatenate([model.donor_15] * len(MODES))
for layer, kind in enumerate(model.config['layer_types'][19:], 19):
model.guard()
p = f'layers.{layer}.'
n_h = model.normalization(h, p+'input_layernorm')
out = (model.full_attention(n_h, layer)[0] if kind == 'full_attention'
else model.linear_attention(n_h, layer))
h = h + out
h = h + model.mlp(model.normalization(h, p+'post_attention_layernorm'), layer)
h = model.normalization(h, 'norm')
np.testing.assert_allclose(h[:n], native, atol=4e-5, rtol=3e-5)
t = model.tensors[PREFIX + 'embed_tokens.weight']
digit_weights = decode(t.raw.reshape(t.shape)[labels], t.dtype)
t.evict()
scores = [x[np.arange(n), np.asarray(lengths) - 1] @ digit_weights.T
for x in np.split(h, len(MODES))]
rows = []
for i, ex in enumerate(examples):
gold = ex['answer_index']
item = {'id': ex['id'], 'task': ex['task'], 'gold': gold, 'scores': {}}
for mode, logits in zip(MODES, scores):
values = logits[i].astype(float)
item['scores'][mode] = {'pred': int(values.argmax()), 'logits': values.tolist(),
'nll': float(np.logaddexp.reduce(values) - values[gold])}
rows.append(item)
return rows
def summarize(rows):
table = {}
for task in TASKS:
group = [r for r in rows if r['task'] == task]
if not group:
continue
table[task] = {}
for mode in MODES:
table[task][mode] = {
'n': len(group),
'correct': sum(r['scores'][mode]['pred'] == r['gold'] for r in group),
'native_wins_lost': sum(r['scores']['native']['pred'] == r['gold']
and r['scores'][mode]['pred'] != r['gold'] for r in group),
'nll': float(np.mean([r['scores'][mode]['nll'] for r in group])),
}
return table
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--source', required=True, type=Path)
parser.add_argument('--out', required=True, type=Path)
parser.add_argument('--resume', action='store_true', help='Keep completed batches')
parser.add_argument('--reuse-prefix', action='store_true', help='Run layers 0–18 once per input')
args = parser.parse_args()
args.out.mkdir(exist_ok=args.resume)
model = ScreeningModel(args.source/'weights',
json.loads((args.source/'model_config.json').read_text()), seconds=3600)
if any(model.config['layer_types'][ix] != 'full_attention' for ix in SITES):
raise ValueError('Scheduled layers must all have full attention')
model.reuse_prefix = args.reuse_prefix
tok = Tokenizer.from_file(str(args.source/'tokenizer.json'))
data = {split: problems(split, n) for split, n in
[('screen', 8), ('fit', 12), ('validation', 12), ('test', 32)]}
prompts = [r['prompt'] for xs in data.values() for r in xs]
if len(set(prompts)) != len(prompts):
raise ValueError('Prompt sets overlap')
manifest = args.out/'fixed-problems.json'
collected = args.out/'screen-rows.json'
if args.resume and manifest.exists() and json.loads(manifest.read_text()) != data:
raise ValueError('Fixed prompts changed')
write_json(manifest, data)
rows = json.loads(collected.read_text()) if args.resume and collected.exists() else []
if len(rows) % 4 or [r['id'] for r in rows] != [r['id'] for r in data['screen'][:len(rows)]]:
raise ValueError('Existing screen does not match the fixed prompt sequence')
for i in range(len(rows), len(data['screen']), 4):
rows.extend(evaluate(model, tok, data['screen'][i:i+4]))
write_json(args.out/'screen-rows.json', rows)
print('screen', len(rows), flush=True)
write_json(args.out/'screen-summary.json', summarize(rows))
if __name__ == '__main__':
main()
+208
View File
@@ -0,0 +1,208 @@
"""Freeze numeric tasks and screen the effect of sharing on complete answers."""
import argparse
from hashlib import sha256
import json
from pathlib import Path
import random
import re
import torch
from tokenizers import Tokenizer
from crossqkv.lisa_effect_screen import WORDS
from crossqkv.lisa_generate import GenerationDecoder, generate
from crossqkv.lisa_tail import TorchTail
from functional.model import StreamingLM
from functional.run import write_json
TASKS = ('lookup', 'latest', 'addition', 'count')
SEEDS = {'screen': 621001, 'fit': 621002, 'validation': 621003, 'test': 621004}
COUNTS = {'screen': 8, 'fit': 24, 'validation': 8, 'test': 32}
SCHEDULES = {'native': (), 'direct_3': (15, 19, 23),
'direct_4': (11, 15, 19, 23), 'direct_5': (7, 11, 15, 19, 23)}
STOP_TEXT = ('<|im_end|>', '<|endoftext|>')
MAX_NEW_TOKENS = 24
def fixed_problems():
output = {}
for split, seed in SEEDS.items():
rng = random.Random(seed)
rows = []
for task in TASKS:
for i in range(COUNTS[split]):
if task in ('lookup', 'latest'):
keys = rng.sample(WORDS, 12)
values = rng.sample(range(20, 100), 12)
pos = rng.randrange(len(keys))
key = keys[pos]
if task == 'latest':
later = rng.randrange(1, len(keys))
earlier = rng.randrange(later)
keys[earlier] = keys[later]
pos, key = later, keys[later]
schedule = ', '.join(f'{k}={v}' for k, v in zip(keys, values))
descriptor = 'last recorded' if task == 'latest' else 'recorded'
question = f'Records in time order: {schedule}.\nWhat is the {descriptor} number for {key}?'
answer = values[pos]
elif task == 'addition':
a, b = sorted((rng.randint(20, 89), rng.randint(20, 89)))
question = f'What is {a} plus {b}?'
answer = a + b
else:
first, second = rng.sample(WORDS, 2)
answer = rng.randint(10, 15)
values = [first] * answer + [second] * rng.randint(3, 9)
rng.shuffle(values)
question = f"Items: {', '.join(values)}.\nHow many items are exactly '{first}'?"
rows.append({'id': f'{split}-{task}-{i:03}', 'task': task,
'question': question, 'answer': answer})
output[split] = rows
# Arithmetic questions can repeat across independently seeded splits.
# Keep the first generated occurrence and fill duplicates with new disjoint sums.
used = set()
replacement = random.Random(621005)
for rows in output.values():
for row in rows:
while row['task'] == 'addition' and row['question'] in used:
a, b = sorted((replacement.randint(20, 89), replacement.randint(20, 89)))
row.update(question=f'What is {a} plus {b}?', answer=a+b)
if row['question'] in used:
raise ValueError('Prompt repeated across the frozen set')
used.add(row['question'])
return output
def prompt(question):
return ('<|im_start|>user\n' + question + '\nReply with the integer and no other text.'
'<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n')
def final_integer(text):
# Only completed reasoning prefixes precede an answer.
text = re.sub(r'\A\s*(?:<think>.*?</think>\s*)+', '', text, flags=re.S).strip()
if '<think>' in text or '</think>' in text:
return None
match = re.fullmatch(r'(?:[Ff]inal answer:\s*|[Aa]nswer:\s*)?([+-]?\d+)\.?', text)
if not match:
match = re.search(r'(?:^|\n)\s*(?:[Ff]inal answer|[Aa]nswer):\s*([+-]?\d+)\.?\s*\Z', text)
return int(match[1]) if match else None
def grade(tokenizer, tokens, stop, expected):
whole = tokenizer.decode(tokens, skip_special_tokens=False)
body = tokenizer.decode(tokens[:-1] if stop == 'eos' else tokens,
skip_special_tokens=False)
value = final_integer(body) if stop == 'eos' else None
return {'tokens': tokens, 'response': whole, 'stop': stop, 'answer': value,
'correct': value == expected}
def evaluate(model, tokenizer, examples, arms, adapters=None):
stop_ids = {tokenizer.token_to_id(text) for text in STOP_TEXT}
if None in stop_ids or len(stop_ids) != len(STOP_TEXT):
raise ValueError('Unexpected tokenizer stop tokens')
ids = [tokenizer.encode(prompt(x['question']), add_special_tokens=False).ids for x in examples]
expanded = [x for x in ids for _ in arms]
schedules = list(arms.values()) * len(examples)
predictions = iter(generate(model, expanded, schedules, stop_ids, MAX_NEW_TOKENS, adapters))
return [{'id': x['id'], 'task': x['task'], 'gold': x['answer'],
'arms': {mode: grade(tokenizer, *next(predictions), x['answer']) for mode in arms}}
for x in examples]
def summarize(rows):
results = {}
for task in TASKS:
group = [row for row in rows if row['task'] == task]
results[task] = {}
for name in SCHEDULES:
original_correct = lambda row: row['arms']['native']['correct']
produced_wrong = lambda row: row['arms'][name]['answer'] is not None and not row['arms'][name]['correct']
results[task][name] = {
'n': len(group),
'correct': sum(row['arms'][name]['correct'] for row in group),
'unscored': sum(row['arms'][name]['answer'] is None for row in group),
'native_correct_to_wrong_integer': [
row['id'] for row in group if original_correct(row) and produced_wrong(row)],
}
return results
def choose(summary):
options = []
for task, arms in summary.items():
if arms['native']['correct'] >= 6:
for arm in ('direct_3', 'direct_4', 'direct_5'):
losses = arms[arm]['native_correct_to_wrong_integer']
if len(losses) >= 2:
options.append((len(losses), arms['native']['correct'],
len(SCHEDULES[arm]), task, arm))
if not options:
return None
_, _, _, task, arm = max(options)
return {'task': task, 'arm': arm, 'recipients': list(SCHEDULES[arm])}
def fingerprint(path):
return sha256(path.read_bytes()).hexdigest()
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--source', required=True, type=Path)
parser.add_argument('--out', required=True, type=Path)
parser.add_argument('--seconds', default=21600, type=int)
parser.add_argument('--batch-prompts', default=2, type=int, choices=(1, 2))
parser.add_argument('--preflight', action='store_true')
args = parser.parse_args()
torch.set_num_threads(1)
args.out.mkdir(exist_ok=True)
files = {name: fingerprint(args.source/name) for name in
('manifest.json', 'model_config.json', 'tokenizer.json')}
protocol = {'weights': files, 'schedules': SCHEDULES, 'cap': MAX_NEW_TOKENS,
'stops': STOP_TEXT, 'batch_prompts': args.batch_prompts,
'decode': 'full vocabulary greedy, closed thinking prefix'}
manifest = args.out/'frozen.json'
frozen = {'protocol': protocol, 'problems': fixed_problems()}
frozen = json.loads(json.dumps(frozen))
if manifest.exists() and json.loads(manifest.read_text()) != frozen:
raise ValueError('Frozen protocol or prompts changed')
write_json(manifest, frozen)
model = StreamingLM(args.source/'weights', json.loads((args.source/'model_config.json').read_text()),
seconds=args.seconds, process_swap_limit_kib=None)
tokenizer = Tokenizer.from_file(str(args.source/'tokenizer.json'))
examples = frozen['problems']['screen']
if args.preflight:
ids = torch.tensor([tokenizer.encode(prompt(examples[0]['question']),
add_special_tokens=False).ids])
hidden = torch.from_numpy(model.embedding(ids.numpy()))
with torch.no_grad():
expected, _ = TorchTail(model, 0)(hidden, None, torch.tensor([ids.shape[1]]),
'native', ())
decoder = GenerationDecoder(model, [()], [0])
decoder.advance(ids[:, :-2])
actual = decoder.advance(ids[:, -2:])
ref = expected[:, -2:]
torch.testing.assert_close(actual, ref, atol=8e-5, rtol=7e-5)
write_json(args.out/'preflight.json', {'prompt_id': examples[0]['id'],
'prompt_tokens': ids.shape[1], 'tail_hidden_max_abs': float((actual-ref).abs().max())})
return
path = args.out/'screen-rows.json'
rows = json.loads(path.read_text()) if path.exists() else []
if [r['id'] for r in rows] != [x['id'] for x in examples[:len(rows)]]:
raise ValueError('Existing screen results do not match frozen prompts')
for start in range(len(rows), len(examples), args.batch_prompts):
rows.extend(evaluate(model, tokenizer, examples[start:start+args.batch_prompts], SCHEDULES))
write_json(path, rows)
print('screen complete', len(rows), '/', len(examples), flush=True)
summary = summarize(rows)
write_json(args.out/'screen-summary.json', summary)
write_json(args.out/'selection.json', {'frozen_sha256': fingerprint(manifest),
'screen_sha256': fingerprint(path),
'chosen': choose(summary)})
if __name__ == '__main__':
main()
+206
View File
@@ -0,0 +1,206 @@
"""Fit LiSA on a development-selected schedule, then evaluate fresh continuations."""
import argparse
import json
from pathlib import Path
import numpy as np
import torch
from tokenizers import Tokenizer
from crossqkv.lisa_effect_audit import paired
from crossqkv.lisa_full_answer import (SCHEDULES, STOP_TEXT, choose, evaluate, fingerprint,
prompt, summarize)
from crossqkv.lisa_tail import TorchTail, weight_chunks
from crossqkv.lisa_train import LearnableSharingAttention, huber_distillation, language_model_loss
from functional.model import PREFIX, StreamingLM
from functional.run import write_json
class FitCapture(TorchTail):
def norm(self, x, name, centered=True):
if name == f'layers.{self.sites[0]}.input_layernorm':
self.residual = x
return super().norm(x, name, centered)
def load_locked(source, screen):
fixed = screen/'frozen.json'
rows = screen/'screen-rows.json'
chosen = json.loads((screen/'selection.json').read_text())
if (chosen['frozen_sha256'] != fingerprint(fixed)
or chosen['screen_sha256'] != fingerprint(rows)):
raise ValueError('Locked screening hashes do not match')
manifest = json.loads(fixed.read_text())
screen_rows = json.loads(rows.read_text())
expected = [(x['id'], x['task'], x['answer']) for x in manifest['problems']['screen']]
if [(x['id'], x['task'], x['gold']) for x in screen_rows] != expected:
raise ValueError('Screening did not evaluate the frozen development set')
expected_selection = choose(summarize(screen_rows))
if expected_selection is None or chosen['chosen'] != expected_selection:
raise ValueError('Development screen did not produce a qualifying schedule')
for name, digest in manifest['protocol']['weights'].items():
if fingerprint(source/name) != digest:
raise ValueError(f'Model input {name} changed')
return chosen, manifest
@torch.no_grad()
def capture(model, tokenizer, fit_examples, directory):
directory.mkdir(exist_ok=True)
teacher = FitCapture(model, 0)
teacher.sites = model.sites
for i, row in enumerate(fit_examples):
path = directory/f'{i:03}.npz'
if path.exists():
continue
text = prompt(row['question'])
base = tokenizer.encode(text, add_special_tokens=False).ids
complete = tokenizer.encode(text + str(row['answer']) + STOP_TEXT[0],
add_special_tokens=False).ids
if complete[:len(base)] != base or len(complete) <= len(base):
raise ValueError('Answer did not tokenize as an extension of the frozen prompt')
ids = np.array([complete])
model.guard()
hidden = torch.from_numpy(model.embedding(ids))
_, side = teacher(hidden, None, torch.tensor([len(complete)]), 'native', ())
pending = path.with_suffix('.tmp.npz')
np.savez(pending, ids=ids, start=[len(base)], residual=teacher.residual.numpy(),
donor=side[model.sites[0]-4][0].numpy(),
teacher=np.stack([side[i][0].numpy() for i in model.sites]))
pending.replace(path)
print('fit capture', i+1, '/', len(fit_examples), flush=True)
def checkpoint(path, obj):
pending = path.with_suffix('.tmp')
torch.save(obj, pending)
pending.replace(path)
def train(model, tokenizer, out, split, epochs, rank):
c = model.config
rope = c['rope_parameters']
adapters = {i: LearnableSharingAttention(c['hidden_size'], c['num_attention_heads'],
c['num_key_value_heads'], rank, rope['rope_theta'], rope['partial_rotary_factor'],
bias=c.get('attention_bias', False)) for i in model.sites}
tail = TorchTail(model, model.sites[0], adapters)
optim = torch.optim.AdamW(tail.parameters(), lr=.0003, weight_decay=.1)
last = out/'resume.pt'
selected = out/'lisa.pt'
state = {'epoch': 0, 'steps': [], 'trace': [], 'best_correct': -1}
if last.exists():
state = torch.load(last, weights_only=True, map_location='cpu')
tail.adapters.load_state_dict(state['parameters'])
optim.load_state_dict(state['optimizer'])
embedding = model.tensors[PREFIX+'embed_tokens.weight']
def vocab():
start = 0
for w in weight_chunks(embedding, 0, embedding.shape[0], rows=1024):
yield start, w
start += len(w)
paths = sorted((out/'fit-capture').glob('*.npz'))
for epoch in range(state['epoch'], epochs):
for path in paths[len(state['steps']):]:
with np.load(path, allow_pickle=False) as entry:
b = {key: torch.from_numpy(entry[key]) for key in entry.files}
lengths = torch.tensor([b['ids'].shape[1]])
optim.zero_grad(set_to_none=True)
h, side = tail(b['residual'], b['donor'], lengths, 'lisa', model.sites)
kd = torch.stack([huber_distillation(side[i][0], t, lengths)
for i, t in zip(model.sites, b['teacher'])]).mean()
ce = language_model_loss(h, b['ids'], lengths, vocab, completion_starts=b['start'])
loss = .25*kd + .75*ce
loss.backward()
if any(p.grad is None or not torch.isfinite(p.grad).all() for p in tail.parameters()):
raise FloatingPointError('Nonfinite LiSA gradient')
optim.step()
state['steps'].append({'capture': path.name, 'huber': float(kd.detach()),
'completion_ce': float(ce.detach())})
checkpoint(last, {**state, 'parameters': tail.adapters.state_dict(),
'optimizer': optim.state_dict()})
print('fit epoch', epoch+1, 'step', len(state['steps']), '/', len(paths), flush=True)
val = []
for start in range(0, len(split['validation']), 2):
val.extend(evaluate(model, tokenizer, split['validation'][start:start+2],
{'lisa': model.sites}, adapters))
correct = sum(x['arms']['lisa']['correct'] for x in val)
if correct > state['best_correct']:
state['best_correct'] = correct
state['best_epoch'] = epoch+1
state['best_parameters'] = {
name: param.detach().clone() for name, param in tail.adapters.state_dict().items()
}
state['trace'].append({'epoch': epoch+1, 'steps': state['steps'], 'validation': val})
state['steps'] = []
state['epoch'] = epoch+1
checkpoint(last, {**state, 'parameters': tail.adapters.state_dict(),
'optimizer': optim.state_dict()})
write_json(out/'trace.json', {'selected_epoch': state['best_epoch'], 'epochs': state['trace']})
checkpoint(selected, state['best_parameters'])
tail.adapters.load_state_dict(state['best_parameters'])
return adapters
def audit(rows):
correct = {name: np.array([r['arms'][name]['correct'] for r in rows])
for name in ('native', 'direct', 'lisa')}
bad_value = [r for r in rows if r['arms']['native']['correct']
and r['arms']['direct']['answer'] is not None and not r['arms']['direct']['correct']]
return {'n': len(rows), 'correct': {name: int(x.sum()) for name, x in correct.items()},
'substantive_loss_ids': [r['id'] for r in bad_value],
'substantive_rescued_ids': [r['id'] for r in bad_value if r['arms']['lisa']['correct']],
'unscored': {name: sum(r['arms'][name]['answer'] is None for r in rows) for name in correct},
**paired(correct['native'], correct['direct'], correct['lisa'])}
def main():
p = argparse.ArgumentParser(description=__doc__)
for path in ('source', 'screen', 'out'):
p.add_argument('--'+path, type=Path, required=True)
p.add_argument('--epochs', type=int, default=2)
args = p.parse_args()
if args.epochs < 1:
p.error('--epochs must be positive')
torch.set_num_threads(1)
torch.manual_seed(621011)
locked, manifest = load_locked(args.source, args.screen)
selection = locked['chosen']
sites = tuple(selection['recipients'])
if sites != SCHEDULES[selection['arm']]:
raise ValueError('Unexpected selected schedule')
spec = {'screen': locked, 'epochs': args.epochs, 'rank': 40, 'seed': 621011,
'objective': '0.25 teacher attention Huber + 0.75 full-vocabulary completion CE'}
args.out.mkdir(exist_ok=True)
run = args.out/'train-spec.json'
if run.exists() and json.loads(run.read_text()) != spec:
raise ValueError('Cannot resume with a different experiment definition')
write_json(run, spec)
tasks = {name: [r for r in rows if r['task'] == selection['task']]
for name, rows in manifest['problems'].items()}
model = StreamingLM(args.source/'weights', json.loads((args.source/'model_config.json').read_text()),
seconds=86400, process_swap_limit_kib=None)
model.sites = sites
tokenizer = Tokenizer.from_file(str(args.source/'tokenizer.json'))
capture(model, tokenizer, tasks['fit'], args.out/'fit-capture')
adapters = train(model, tokenizer, args.out, tasks, args.epochs, spec['rank'])
output = args.out/'test-items.json'
rows = json.loads(output.read_text()) if output.exists() else []
if [r['id'] for r in rows] != [x['id'] for x in tasks['test'][:len(rows)]]:
raise ValueError('Test continuation does not match the frozen rows')
for start in range(len(rows), len(tasks['test']), 2):
batch = tasks['test'][start:start+2]
base = evaluate(model, tokenizer, batch, {'native': (), 'direct': sites})
lisa = evaluate(model, tokenizer, batch, {'lisa': sites}, adapters)
for x, y in zip(base, lisa):
x['arms'].update(y['arms'])
rows.extend(base)
write_json(output, rows)
print('test complete', len(rows), '/', len(tasks['test']), flush=True)
write_json(args.out/'test-audit.json', audit(rows))
if __name__ == '__main__':
main()
+131
View File
@@ -0,0 +1,131 @@
"""Cached autoregressive Qwen text generation for the LiSA comparisons."""
import math
import torch
from torch.nn import functional as F
from crossqkv.lisa_tail import TorchTail, rotate, weight_chunks
from functional.model import PREFIX
class GenerationDecoder(TorchTail):
"""Share the previous full-attention layer's actual scores per batch lane."""
def __init__(self, source, schedules, padding, adapters=None):
super().__init__(source, 0, adapters)
full = [i for i, kind in enumerate(self.c['layer_types']) if kind == 'full_attention']
if (len(schedules) != len(padding) or not schedules
or any(set(sites) - set(full[1:]) for sites in schedules)):
raise ValueError('Recipients need an earlier full-attention layer')
if self.adapters and any(tuple(sites) != tuple(map(int, self.adapters)) for sites in schedules):
raise ValueError('LiSA decoding requires one shared schedule for the batch')
self.padding = torch.tensor(padding)
self.share = {i: torch.tensor([i in sites for sites in schedules])[:, None, None, None]
for i in set().union(*schedules)}
self.position = 0
self.states = {}
def attention_chunk(self, h, layer, positions, allowed, donor):
heads, kv, dim = (self.c[k] for k in
('num_attention_heads', 'num_key_value_heads', 'head_dim'))
p = f'layers.{layer}.self_attn.'
adapter = self.adapters[str(layer)] if str(layer) in self.adapters else None
if adapter is None:
q, gate = self.linear(h, p+'q_proj').unflatten(-1, (heads, 2*dim)).chunk(2, -1)
k = self.linear(h, p+'k_proj').unflatten(-1, (kv, dim))
rope = self.c['rope_parameters']
q = rotate(self.norm(q, p+'q_norm'), rope['rope_theta'],
rope['partial_rotary_factor'], positions)
k = rotate(self.norm(k, p+'k_norm'), rope['rope_theta'],
rope['partial_rotary_factor'], positions)
else:
gate = self.gate_only(h, p)
q = adapter.rotate(adapter.q_proj(h).unflatten(-1, (heads, adapter.rank)), positions)
k = adapter.rotate(adapter.k_proj(h).unflatten(-1, (kv, adapter.rank)), positions)
v = self.linear(h, p+'v_proj').unflatten(-1, (kv, dim))
if layer in self.states:
prior_k, prior_v = self.states[layer]
k = torch.cat((prior_k, k), dim=1)
v = torch.cat((prior_v, v), dim=1)
self.states[layer] = k, v
repeats = heads // kv
scores = torch.einsum('bthd,bshd->bhts', q, k.repeat_interleave(repeats, 2))
scores = scores / math.sqrt(q.shape[-1])
if adapter is not None:
both = torch.cat((scores, donor), dim=1).permute(0, 2, 3, 1)
scores = adapter.fuse(both).permute(0, 3, 1, 2)
elif layer in self.share:
scores = torch.where(self.share[layer], donor, scores)
weights = scores.masked_fill(~allowed, -torch.inf).softmax(dim=-1)
context = torch.einsum('bhts,bshd->bthd', weights, v.repeat_interleave(repeats, 2))
return self.linear((context * gate.sigmoid()).flatten(-2), p+'o_proj'), scores
@torch.no_grad()
def advance(self, ids):
"""Consume a prompt or continuation and return the final-normalized states."""
stop = self.position + ids.shape[1]
queries = torch.arange(self.position, stop)
keys = torch.arange(stop)
positions = (queries[None, :] - self.padding[:, None]).clamp_min(0)
q_valid = queries[None, :] >= self.padding[:, None]
k_valid = keys[None, :] >= self.padding[:, None]
allowed = (queries[:, None] >= keys)[None, None] & (
k_valid[:, None, None, :] | ~q_valid[:, None, :, None])
h = torch.from_numpy(self.source.embedding(ids.numpy())) * q_valid[..., None]
donor = None
trim = getattr(self.source, 'malloc_trim', None)
for layer, kind in enumerate(self.c['layer_types']):
if hasattr(self.source, 'guard'):
self.source.guard()
p = f'layers.{layer}.'
n = self.norm(h, p+'input_layernorm')
if kind == 'full_attention':
out, donor = self.attention_chunk(n, layer, positions, allowed, donor)
else:
out, self.states[layer] = self.linear_attention_chunk(n, layer, self.states.get(layer))
h = h + out
n = self.norm(h, p+'post_attention_layernorm')
activation = F.silu(self.linear(n, p+'mlp.gate_proj')) * self.linear(n, p+'mlp.up_proj')
h = h + self.linear(activation, p+'mlp.down_proj')
del n, out, activation
if trim is not None:
trim(0)
self.position = stop
return self.norm(h, 'norm')
def greedy_tokens(hidden, embedding):
"""Take the argmax over the complete tied vocabulary in bounded blocks."""
peak = hidden.new_full((len(hidden),), -torch.inf)
ids = torch.zeros(len(hidden), dtype=torch.long)
start = 0
for weight in weight_chunks(embedding, 0, embedding.shape[0], rows=1024):
score, arg = F.linear(hidden, weight).max(dim=-1)
ids = torch.where(score > peak, arg + start, ids)
peak = torch.maximum(peak, score)
start += len(weight)
if not torch.isfinite(peak).all():
raise FloatingPointError('Non-finite next-token score')
return ids
@torch.no_grad()
def generate(source, prompts, schedules, stop_tokens, max_new_tokens, adapters=None):
width = max(map(len, prompts))
padding = [width - len(prompt) for prompt in prompts]
seed = torch.tensor([[0] * n + prompt for prompt, n in zip(prompts, padding)])
decoder = GenerationDecoder(source, schedules, padding, adapters)
head = source.tensors[PREFIX+'embed_tokens.weight']
state = decoder.advance(seed)[:, -1]
output = [[] for _ in prompts]
finished = [False] * len(prompts)
for step in range(max_new_tokens):
ids = greedy_tokens(state, head)
for row, token in enumerate(ids.tolist()):
if not finished[row]:
output[row].append(token)
finished[row] = token in stop_tokens
if all(finished) or step + 1 == max_new_tokens:
break
state = decoder.advance(ids[:, None])[:, -1]
return [(tokens, 'eos' if done else 'max_new_tokens') for tokens, done in zip(output, finished)]
+190
View File
@@ -0,0 +1,190 @@
"""Differentiable Qwen text tail with streamed frozen weights and LiSA sites."""
import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.utils.checkpoint import checkpoint
from crossqkv.lisa_train import causal_attention
from functional.model import PREFIX
def weight_chunks(tensor, start, end, rows=512):
width = tensor.shape[1]
for lo in range(start, end, rows):
hi = min(lo + rows, end)
yield torch.from_numpy(tensor.read(slice(lo * width, hi * width)).reshape(hi-lo, width))
tensor.evict()
class FrozenLinear(torch.autograd.Function):
"""Read only the requested output rows and stream them again for dX."""
@staticmethod
def forward(ctx, hidden, weight, start, end):
ctx.weight, ctx.start, ctx.end = weight, start, end
return torch.cat([F.linear(hidden, w) for w in weight_chunks(weight, start, end)], dim=-1)
@staticmethod
def backward(ctx, grad):
out = grad.new_zeros((*grad.shape[:-1], ctx.weight.shape[1]))
lo = 0
for w in weight_chunks(ctx.weight, ctx.start, ctx.end):
hi = lo + len(w)
out = out + grad[..., lo:hi] @ w
lo = hi
return out, None, None, None
def rotate(x, theta, fraction, positions=None):
d = int(x.shape[-1] * fraction)
inv = theta ** (-torch.arange(0, d, 2, dtype=x.dtype, device=x.device) / d)
if positions is None:
positions = torch.arange(x.shape[1], dtype=x.dtype, device=x.device)[None, :]
phase = positions[..., None] * inv
angle = torch.cat((phase, phase), dim=-1).unsqueeze(-2)
a, b = x[..., :d].chunk(2, dim=-1)
return torch.cat((x[..., :d] * angle.cos() + torch.cat((-b, a), -1) * angle.sin(),
x[..., d:]), dim=-1)
def gated_delta_chunk(q, k, v, g, beta, state=None):
q = q * (q.square().sum(-1, keepdim=True) + 1e-6).rsqrt() / math.sqrt(q.shape[-1])
k = k * (k.square().sum(-1, keepdim=True) + 1e-6).rsqrt()
if state is None:
state = v.new_zeros(v.shape[0], v.shape[2], k.shape[-1], v.shape[-1])
rows = []
for i in range(v.shape[1]):
qt, kt, vt = q[:, i], k[:, i], v[:, i]
state = state * g[:, i, :, None, None].exp()
delta = (vt - (state * kt.unsqueeze(-1)).sum(-2)) * beta[:, i, :, None]
state = state + kt.unsqueeze(-1) * delta.unsqueeze(-2)
rows.append((state * qt.unsqueeze(-1)).sum(-2))
return torch.stack(rows, dim=1), state
def gated_delta(q, k, v, g, beta):
return gated_delta_chunk(q, k, v, g, beta)[0]
class TorchTail(nn.Module):
"""Inputs start immediately before the first trainable recipient."""
def __init__(self, source_model, start, adapters=None):
super().__init__()
self.source = source_model
self.c = source_model.config
self.eps = source_model.eps
self.start = start
self.adapters = nn.ModuleDict({str(k): v for k, v in (adapters or {}).items()})
self._small = {}
def small(self, name):
if name not in self._small:
self._small[name] = torch.from_numpy(self.source.small(name))
return self._small[name]
def linear(self, h, name, start=0, end=None):
t = self.source.tensors[PREFIX + name + '.weight']
return FrozenLinear.apply(h, t, start, t.shape[0] if end is None else end)
def norm(self, x, name, centered=True):
w = self.small(name + '.weight')
return x * (x.square().mean(-1, keepdim=True) + self.eps).rsqrt() * (1+w if centered else w)
def gate_only(self, h, name):
heads, dim = self.c['num_attention_heads'], self.c['head_dim']
return torch.stack([self.linear(h, name+'q_proj', (2*j+1)*dim, (2*j+2)*dim)
for j in range(heads)], dim=2)
def native_scores(self, q, h, name):
c = self.c
k = self.linear(h, name+'k_proj').unflatten(-1, (c['num_key_value_heads'], c['head_dim']))
params = c['rope_parameters']
q = rotate(self.norm(q, name+'q_norm'), params['rope_theta'], params['partial_rotary_factor'])
k = rotate(self.norm(k, name+'k_norm'), params['rope_theta'], params['partial_rotary_factor'])
k = k.repeat_interleave(q.shape[2] // k.shape[2], dim=2)
return torch.einsum('bthd,bshd->bhts', q, k) / math.sqrt(q.shape[-1])
def full(self, h, layer, donor, lengths, mode, recipients, keep_teacher):
c = self.c
heads, kv_heads, dim = c['num_attention_heads'], c['num_key_value_heads'], c['head_dim']
name = f'layers.{layer}.self_attn.'
shared = layer in recipients and mode != 'native'
if not shared or keep_teacher:
packed = self.linear(h, name+'q_proj').unflatten(-1, (heads, 2*dim))
q, gate = packed.chunk(2, dim=-1)
if shared:
with torch.no_grad():
native = self.native_scores(q, h, name)
else:
native = self.native_scores(q, h, name)
else:
gate = self.gate_only(h, name)
native = None
if not shared:
scores = native
elif mode == 'direct':
scores = donor
elif mode == 'lisa':
pos = torch.arange(h.shape[1], device=h.device)[None, :]
scores = self.adapters[str(layer)](h, donor, pos)
elif mode == 'linear':
matrix = self.adapters[str(layer)]
scores = matrix(donor.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)
else:
raise ValueError(f'Unknown mode {mode}')
v = self.linear(h, name+'v_proj').unflatten(-1, (kv_heads, dim))
out = causal_attention(scores, v, lengths) * gate.sigmoid()
return self.linear(out.flatten(-2), name+'o_proj'), scores, native
def linear_attention(self, x, layer):
return self.linear_attention_chunk(x, layer)[0]
def linear_attention_chunk(self, x, layer, previous=None):
p = f'layers.{layer}.linear_attn.'
c = self.c
kh, vh = c['linear_num_key_heads'], c['linear_num_value_heads']
kd, vd = c['linear_key_head_dim'], c['linear_value_head_dim']
projected = self.linear(x, p+'in_proj_qkv').transpose(1, 2)
kernel = self.small(p+'conv1d.weight')
history = kernel.shape[-1] - 1
if previous is None:
projected = F.pad(projected, (history, 0))
state = None
else:
prefix, state = previous
projected = torch.cat((prefix, projected), dim=-1)
convolved = F.conv1d(projected, kernel, groups=projected.shape[1])
q, k, v = F.silu(convolved.transpose(1, 2)).split((kh*kd, kh*kd, vh*vd), dim=-1)
q = q.unflatten(-1, (kh, kd)).repeat_interleave(vh//kh, dim=2)
k = k.unflatten(-1, (kh, kd)).repeat_interleave(vh//kh, dim=2)
v = v.unflatten(-1, (vh, vd))
gate = self.linear(x, p+'in_proj_z').unflatten(-1, (vh, vd))
beta = self.linear(x, p+'in_proj_b').sigmoid()
a = self.linear(x, p+'in_proj_a')
g = -self.small(p+'A_log').exp() * F.softplus(a + self.small(p+'dt_bias'))
out, state = gated_delta_chunk(q, k, v, g, beta, state)
output = self.linear((self.norm(out, p+'norm', centered=False)*F.silu(gate)).flatten(-2),
p+'out_proj')
return output, (projected[..., projected.shape[-1]-history:].clone(), state)
def forward(self, h, donor, lengths, mode, recipients, keep_teacher=False):
side = {}
for layer, kind in enumerate(self.c['layer_types'][self.start:], self.start):
p = f'layers.{layer}.'
n = self.norm(h, p+'input_layernorm')
if kind == 'full_attention':
out, donor, native = self.full(n, layer, donor, lengths, mode, recipients,
keep_teacher)
side[layer] = (donor, native)
elif torch.is_grad_enabled() and n.requires_grad:
out = checkpoint(self.linear_attention, n, layer, use_reentrant=True)
else:
out = self.linear_attention(n, layer)
h = h + out
n = self.norm(h, p+'post_attention_layernorm')
x = F.silu(self.linear(n, p+'mlp.gate_proj')) * self.linear(n, p+'mlp.up_proj')
h = h + self.linear(x, p+'mlp.down_proj')
return self.norm(h, 'norm'), side
+12 -7
View File
@@ -90,7 +90,7 @@ class _FrozenVocabularyCE(torch.autograd.Function):
"""Exact full-vocabulary CE with a streamed frozen head in both passes."""
@staticmethod
def forward(ctx, hidden, targets, vocabulary):
def forward(ctx, hidden, targets, weights, vocabulary):
log_total = hidden.new_full((hidden.shape[0],), -torch.inf)
selected = hidden.new_zeros(hidden.shape[0])
for start, w in vocabulary():
@@ -98,24 +98,29 @@ class _FrozenVocabularyCE(torch.autograd.Function):
log_total = torch.logaddexp(log_total, logits.logsumexp(dim=-1))
belongs = (targets >= start) & (targets < start + w.shape[0])
selected[belongs] = logits[belongs, targets[belongs] - start]
ctx.save_for_backward(hidden, targets, log_total)
ctx.save_for_backward(hidden, targets, log_total, weights)
ctx.vocabulary = vocabulary
return (log_total - selected).mean()
return ((log_total - selected) * weights).sum() / weights.sum()
@staticmethod
def backward(ctx, gradient):
hidden, targets, log_total = ctx.saved_tensors
hidden, targets, log_total, weights = ctx.saved_tensors
grad_hidden = torch.zeros_like(hidden)
for start, w in ctx.vocabulary():
probs = (F.linear(hidden, w) - log_total[:, None]).exp()
belongs = (targets >= start) & (targets < start + w.shape[0])
probs[belongs, targets[belongs] - start] -= 1
grad_hidden.addmm_(probs, w)
return grad_hidden * (gradient / hidden.shape[0]), None, None
return grad_hidden * (gradient * weights[:, None] / weights.sum()), None, None, None
def language_model_loss(hidden, ids, lengths, vocabulary):
def language_model_loss(hidden, ids, lengths, vocabulary, answer_weight=1.0,
completion_starts=None):
"""Train on all valid next-token targets, avoiding padding and final positions."""
positions = torch.arange(ids.shape[1] - 1, device=ids.device)
valid = positions[None, :] + 1 < lengths[:, None]
return _FrozenVocabularyCE.apply(hidden[:, :-1][valid], ids[:, 1:][valid], vocabulary)
if completion_starts is not None:
valid = valid & (positions[None, :] + 1 >= completion_starts[:, None])
weights = torch.where(positions[None, :] + 2 == lengths[:, None], answer_weight, 1.0)
return _FrozenVocabularyCE.apply(hidden[:, :-1][valid], ids[:, 1:][valid],
weights[valid].to(dtype=hidden.dtype), vocabulary)
+165
View File
@@ -0,0 +1,165 @@
# LiSA effect reproduction on Qwen3.5-2B
The earlier single-layer training verified the method but used an evaluation
where the frozen 2B model answered only one of sixteen items. This protocol
measures retention of an existing capability and the cost of exercising it.
## Comparison with the published experiment
The 96.44% in Table 2 is the average performance retained by LLaMA2-13B
with 22 recipient layers across the reported benchmarks excluding LAMBADA.
At the same 22 layers, direct score sharing retained 46.76% and the direct
sharing plus LoRA baseline retained 65.95%. The published main uptraining
used 4.2 billion sampled RedPajama tokens on eight A800 GPUs. This experiment
uses a frozen Qwen3.5-2B backbone, two recipient layers, 12 synthetic fit
prompts and a single CPU runner. Each epoch of the trainable variants sees
1,874 next-token targets drawn from those same 12 prompts. The comparable
effect is an improvement over direct sharing under a fixed layer schedule.
The magnitude on a 32-item lookup test and the timing of CPU attention should
be interpreted within those settings. [Mu et al., Table 2 and Appendix C.1](https://aclanthology.org/2026.tacl-1.30.pdf)
Qwen's text decoder has six full-attention layers and 18 linear-attention
layers. The chained configuration modifies two of the six full-attention
layers and two of the 24 decoder layers overall. Layer numbers are zero-based.
The source record in `results/lisa-effect-reproduction/runtime.json` pins
the original model revision, the checkpoint shard and its download-manifest hash.
## Task and layer screening
All four tasks, answer-position balances, and generators are fixed in
`crossqkv/lisa_effect_screen.py`. The screening split is used only for
selecting a primary task family and the schedule. Fit, validation, and test
prompts have disjoint fixed seeds. The screen must finish before opening
test metrics.
Test original attention, 19→23 direct reuse, and a chained 15→19→23
configuration, with each donor providing its actual scores in the current
run. Primary eligibility on the development screen requires original accuracy
at least 5/8 and at least one original-correct item lost under shared
attention. Compare candidate schedules by the count of native-correct items
lost, preferring the two-receiver schedule among ties and recording net
accuracy and four-option NLL. If none qualify, retain the screen and expand
development coverage before choosing a new task; never pick based on test
errors. The fixed test also reports all outcomes on the chosen task, including
native-incorrect items.
## Performance comparison
Compare native, direct, fit-only linear calibration and trainable LiSA on
identical prompts. Preserve Qwen recipient gates, V, and output projection.
Compare the published 0.25 Huber and 0.75 next-token CE objective with an
explicit answer-weighted variant. All adaptation and model selection use
only fit/validation. Record the whole-sequence training loss. On held-out prompts, report
answer-only loss, correctly recovered and newly lost questions, net
accuracy, and performance at one and two recipients. A measured failure to recover is a valid outcome.
For speed, use a path that actually skips dense Q/K at shared sites, keeping
gate rows. Verify against a reference first. With identical prompts,
checkpoint and runner, report measured latency for the implemented prefill
or decode path and its true scope. Account for both the reduced K storage
and additional score tensors. Do not call analytical estimates measured
speed or apply paper throughput figures to this CPU implementation.
The incremental recipient benchmark uses actual K/V buffers and compares the
shared implementation with native attention at the same prefix length and FP32
storage format. Numerical tests compare incremental scores and outputs with
batched causal attention at every query position. Report observed allocation
for K/V and the donor score row separately from end-to-end prefill or decode.
It does not include upstream score generation or the rest of the decoder.
```sh
python -B -m crossqkv.lisa_decode_bench --source runs/cpu-qwen35-2b \
--capture runs/LISA_EFFECT_CAPTURE --checkpoint runs/LISA_EFFECT_RESULTS/lisa.pt \
--out runs/LISA_EFFECT_RESULTS/decode.json
```
An interrupted development screen can resume with the same fixed prompt set
using `--resume`. Use `--reuse-prefix` to compute the frozen prefix once per
prompt. The replay checks original-mode parity before accepting results.
## Recorded development selection
The fixed screen completed with 32 prompts. The prespecified eligibility rule
selected the 16-entry lookup task with recipients at layers 19 and 23. Native
and one-recipient direct sharing each scored 8/8. Two-recipient direct sharing
scored 7/8 and lost one native-correct answer. The selected configuration,
all screened logits, and the disjoint prompt manifest are archived under
`results/lisa-effect-reproduction/`. This was selection evidence only.
The held-out analysis records rescue of native-correct errors, newly introduced
errors, paired uncertainty and answer NLL. A second pass streams the complete
vocabulary at the same answer positions and compares one- and two-recipient
forward paths. In the one-recipient LiSA ablation the final adapter comes from
the joint checkpoint. It is evaluated unchanged, with the earlier recipient
restored to native attention.
Training also saves each finished epoch's adapter, AdamW state, validation
history and selected weights atomically per variant. For interrupted training,
re-run the same command with `--resume` and the same output directory and epoch
budget. Resume verifies the frozen training configuration, preserves finished
epochs and re-scores the locked test set from the validation-selected weights.
The separate selected checkpoints retain the original weights-only schema.
The development error was `screen-lookup16-005`. Its correct choice was
option 4. Across native, single-recipient direct reuse and chained direct reuse,
the four-choice probability of option 4 was 0.706, 0.815 and 0.403,
respectively. Its correct-versus-best-distractor logit margins were
+1.265, +1.861 and −0.258. The chained result chose option 2. These are
development observations that describe the selected condition, not test
results or a basis for changing the frozen prompts.
## Reproduction commands
Run from the project code root on the confirmed remote CPU environment.
Choose new output directories. Keep the same source checkpoint across all
commands. The fixed manifest contains all four split definitions, and capture
writes an independent selection record and source fingerprints.
```sh
export OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1
PYTHON=venv/bin/python
SOURCE=runs/cpu-qwen35-2b
SCREEN=runs/NEW_EFFECT_SCREEN
CAPTURE=runs/NEW_EFFECT_CAPTURE
RESULT=runs/NEW_EFFECT_RESULT
"$PYTHON" -B -m crossqkv.lisa_effect_screen --source "$SOURCE" --out "$SCREEN" --reuse-prefix
"$PYTHON" -B -m crossqkv.lisa_effect capture --source "$SOURCE" --input "$SCREEN" --out "$CAPTURE"
"$PYTHON" -B -m crossqkv.lisa_effect train --source "$SOURCE" --input "$CAPTURE" --out "$RESULT" --epochs 2
"$PYTHON" -B -m crossqkv.lisa_decode_bench --source "$SOURCE" --capture "$CAPTURE" \
--checkpoint "$RESULT/lisa.pt" --out "$RESULT/decode.json"
"$PYTHON" -B -m crossqkv.lisa_effect_answer_audit --source "$SOURCE" --cache "$CAPTURE" \
--trained "$RESULT" --out "$RESULT/full-vocab-answers.json"
"$PYTHON" -B -m crossqkv.lisa_effect_audit --fixed "$SCREEN/fixed-problems.json" \
--selection "$CAPTURE/selection.json" --items "$RESULT/test-items.json" \
--perf "$RESULT/performance.json" --decode "$RESULT/decode.json" \
--full-vocab "$RESULT/full-vocab-answers.json" --out "$RESULT/paired-audit.json"
```
The paired audit defines a rescue as a native-correct item made wrong by
direct sharing and made correct again by the tested adapter. It reports
newly lost native-and-direct-correct items separately. An improvement in
mean four-option answer NLL, including among items already answered
correctly, does not by itself establish a rescue. The audit computes paired
intervals for NLL differences and checks that common arms have identical
four-choice correctness in the primary test and the full-vocabulary pass.
Training scores *all* valid shifted tokens with exact full-vocabulary CE
and uses the validation four-option answer loss to freeze checkpoints. The
answer audit scores only the answer position over the whole vocabulary.
The answer is one token per prompt. In the fit set, it accounts for about
0.64% of the unweighted CE target mass and about 9.35% with the 16-fold answer
weight. The objective applies the same 0.75 coefficient to the resulting
mean CE in both trainable variants.
It does not report whole-prompt CE for the held-out items or free-form
multi-token answer accuracy. That distinction is important for interpreting
the previous experiment, in which those two losses moved in opposite
directions.
For the isolated incremental attention timing, report both streamed
checkpoint projections and an otherwise identical timing with only that
site's frozen projections resident in memory. Verify output and raw score
parity before interpreting the pair of timings. The resident measurements
exclude weight-load time, and both timings exclude upstream computation and
other decoder blocks. K/V and upstream score-row allocation are itemized
separately; neither timing is an end-to-end server throughput claim.
+49
View File
@@ -0,0 +1,49 @@
# Qwen3.5-2B 双层 LiSA 复现实验
在冻结的 32 道查找题上,原模型、直接共享、线性修正和两版 LiSA 的四选一准确率均为 32/32。全词表首 token 命中率从双层直接共享的 27/32 升到两版 LiSA 的 32/32。五道变化题都涉及首 token 从 `<think>` 变成正确选项。两个接收层各自的 K/V 缓存减少 42.2%。耗时随权重是否驻留及测量阶段而异。
## 四选一任务表现
开发筛选中,原模型和单层直接共享各答对 8/8,双层直接共享答对 7/8。以此冻结 16 条目查找任务,测试使用独立题目。共享链为 15→19→23,层号从 0 起算。第 19、23 层占 6 个全注意力层的三分之一,占 24 个解码层的十二分之一。
| 方法 | 留出正确数 | 四选一答案 NLL ↓ |
| --- | ---: | ---: |
| 原模型 | 32/32 | 0.1341 |
| 双层直接共享 | 32/32 | 0.0728 |
| 双层线性修正 | 32/32 | 0.0720 |
| 双层 LiSA | 32/32 | 0.1846 |
| 双层 LiSA,答案损失加权 | 32/32 | 0.1260 |
直接共享在留出集上丢失 0 道原模型答对的题,因此无法估计 LiSA 对这类错题的恢复率。答案加权把 LiSA 的四选一 NLL 降低了 0.0586,仍高于直接共享。相比直接共享,原版 LiSA 的 NLL 增加 0.1118,按题配对 bootstrap 95% 区间为 [0.0968, 0.1282]。答案加权 LiSA 的差为 0.0532,区间为 [0.0327, 0.0749]。三种训练方法各用 12 道拟合题跑两轮,并由另外 12 道验证题选择检查点。所选检查点都是第 2 轮。
## 全词表首 token
| 方法 | 正确选项为首 token | 全词表答案 NLL ↓ |
| --- | ---: | ---: |
| 原模型 | 27/32 | 0.5633 |
| 单层直接共享,第 23 层 | 32/32 | 0.3124 |
| 单层 LiSA,第 23 层,使用双层训练的适配器 | 32/32 | 0.2554 |
| 双层直接共享 | 27/32 | 0.5579 |
| 双层线性修正 | 27/32 | 0.5574 |
| 双层 LiSA | 32/32 | 0.4706 |
| 双层 LiSA,答案损失加权 | 32/32 | 0.1545 |
两版 LiSA 对双层直接共享的首 token 净改善均为 5/32,另有 0 道从正确变成错误,McNemar 精确双侧 p = 0.0625。双层直接共享比单层直接共享少答对的五道,恰好也是原模型和线性修正先输出 `<think>` 的五道。它们的正确选项都是 `4`,四选一口径在全部方法上均答对。输出符合格式是这里观察到的改善,后续生成内容没有记录。
原版 LiSA 相对双层直接共享的全词表 NLL 差为 −0.0872,按题配对 bootstrap 95% 区间为 [−0.1498, −0.0305]。答案加权版的差为 −0.4033,区间为 [−0.4796, −0.3344]。原版和加权版的首 token 命中数一致,加权版的平均答案 NLL 更低。由于五道变化集中于同一选项和同一个替代 token,推广到其它任务或输出格式还需要独立证据。
## CPU 计时和缓存
| 测量范围 | 原模型 | LiSA |
| --- | ---: | ---: |
| 缓存前缀后的尾部预填充,157 tokens | 12.37 s | 16.31 s |
| 第 19 层单步,流式读取权重 | 136.15 ms | 96.32 ms |
| 第 23 层单步,流式读取权重 | 136.39 ms | 138.80 ms |
| 第 19 层单步,投影权重常驻 | 42.57 ms | 32.09 ms |
| 第 23 层单步,投影权重常驻 | 44.80 ms | 22.79 ms |
每个接收层的 FP32 K/V 实际分配从 643,072 降到 371,776 字节,下降 42.2%。计入该层所用的 5,024 字节上游分数行后,单层合计下降 41.4%。V 缓存为 321,536 字节。解码计时的单位是单个接收层的一步,计时范围从接收现成分数行开始,至该层注意力输出结束。预填充用 3 次计时的中位数,单层解码每个配置用 9 步计时的中位数。
论文表 2 的 96.44% 衡量 LLaMA2-13B 在共享 22 层时多个基准上的平均性能保留率。这里每轮只有 1,874 个训练目标 token,测到的是单一查找任务的表现和 CPU 组件耗时。 [论文表 2、表 3 和附录 C.1](https://aclanthology.org/2026.tacl-1.30.pdf)
训练轨迹、两种答案口径的逐题记录、配对统计、缓存和时延原始结果均在 [实验结果目录](../results/lisa-effect-reproduction/)。[复跑协议](LISA_EFFECT_PROTOCOL.md)
+37
View File
@@ -0,0 +1,37 @@
# 完整答案评估下的 LiSA 共享实验
本轮在同一 Qwen3.5-2B 检查点上比较 3、4、5 个全注意力层接收共享分数的效果。上一轮发现首 token 命中的变化集中在 `<think>` 和同一个选项。本轮要求模型从全词表生成完整的多 token 数值答案,逐题复核答案的数值。
## 开发筛选与冻结
从 0 开始编号。接收层分别为 `[15, 19, 23]`、`[11, 15, 19, 23]` 和 `[7, 11, 15, 19, 23]`。每个接收层使用本次前向中前一全注意力层实际输出的分数。接收端保留自身的 V、门控和输出投影。原模型与三个直接共享配置配对生成。
候选任务为表中数值查找、重复键最后值查找、两位数加法、重复项计数。固定生成器在运行筛选之前写出每类任务 8 道开发题、24 道训练题、8 道验证题和 32 道留出测试题。同一数值题跨数据划分去重,加法按交换律规范操作数。每个候选都要满足原模型至少答对 6/8 且至少 2 道原模型答对的题在直接共享下生成了错误整数。选择时依次比较数字错误数、原模型正确数和接收层数。完成了生成却没有可提取答案的情况单独记数。
使用检查点发布的单轮聊天模板和关闭 thinking 的生成前缀。所有配置从全词表逐 token 贪心生成,遇到回合结束或文本结束 token 停止,最多生成 24 tokens。主要指标要求已生成停止 token,并从整条答复提取完整整数。接受纯整数或明确的最终答案行,可去掉开头完整的 thinking 区块。原始 token、文本、停止原因和提取值都随结果存档。 [检查点聊天模板](https://huggingface.co/Qwen/Qwen3.5-2B/blob/15852e8c16360a2fea060d615a32b45270f8a8fc/chat_template.jinja)
## LiSA 训练与测试
开发筛选完成后用固定哈希验证题集、共享配置、原模型和筛选数据。仅在存在达标配置时启动训练。冻结原模型,只训练两个线性层组成的注意力头融合和 rank 40 的低秩 Q/K。用原模型在同一训练序列上的因果注意力分数作为教师。损失为 0.25 倍 Huber 距离加 0.75 倍全词表交叉熵,交叉熵覆盖参考答案的所有 token 和结束 token。每个训练样本更新后保存优化器和模型状态。验证集上生成完整答案,按正确数选择两轮中的最佳检查点,同分选较早者。
最终对同一批留出题的原模型、直接共享、训练后的 LiSA 分别生成并保存完整回答。报告准确率、直接共享造成的数值错误、其中被 LiSA 恢复的题、新增错误和缺少可提取答案的情况。准确率差按题配对估计,另报告 McNemar 精确双侧检验。
## 运行命令
在已确认的远程 CPU 环境中,从源代码目录运行,使用独立输出目录。模型源目录需要包含上一轮实验使用的权重、配置、下载清单和 tokenizer。
```sh
export OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1
PYTHON=venv/bin/python
SOURCE=runs/cpu-qwen35-2b
SCREEN=runs/NEW_FULL_ANSWER_SCREEN
RESULT=runs/NEW_FULL_ANSWER_RESULT
"$PYTHON" -B -m crossqkv.lisa_full_answer --source "$SOURCE" --out "$SCREEN" --batch-prompts 1 --preflight
"$PYTHON" -B -m crossqkv.lisa_full_answer --source "$SOURCE" --out "$SCREEN" --batch-prompts 1
"$PYTHON" -B -m crossqkv.lisa_full_answer_train --source "$SOURCE" --screen "$SCREEN" --out "$RESULT"
```
使用原目录运行相同命令即可续跑。筛选和测试将按已保存的题号继续。训练使用已保存的优化器和训练步。
服务器约有 1.7 GiB 内存。本轮每次筛选输入一道题,四个配置共享权重读取。前两次预检和一次生成在服务器仍有约 1 GiB 可用内存时触发进程独立换页上限。当前作业沿用原冻结题集,并在每层结束时释放空闲内存。可用内存、进程 RSS、低可用内存下的持续换页压力和运行时间均由原检查器监控。
+6 -2
View File
@@ -77,11 +77,13 @@ def attention(q, k, v):
class StreamingLM:
def __init__(self, weights, config, seconds=7200, enforce_memory=True):
def __init__(self, weights, config, seconds=7200, enforce_memory=True,
process_swap_limit_kib=128*1024):
self.tensors = load_tensors(Path(weights))
self.config = config.get('text_config', config)
self.deadline = time.monotonic() + seconds
self.enforce_memory = enforce_memory
self.process_swap_limit_kib = process_swap_limit_kib
self.eps = self.config['rms_norm_eps']
self.norm_replacement = None
self.capture_qk = False
@@ -107,7 +109,9 @@ class StreamingLM:
rate = (count-self.swap_observation[1])*4096/elapsed
self.swap_pressure_windows = self.swap_pressure_windows+1 if rate > 4*1024**2 else 0
own_swap_kib = int(status.get('VmSwap', '0 kB').split()[0])
if self.swap_pressure_windows >= 3 and (available < 384*1024 or own_swap_kib > 128*1024):
over_process_limit = (self.process_swap_limit_kib is not None
and own_swap_kib > self.process_swap_limit_kib)
if self.swap_pressure_windows >= 3 and (available < 384*1024 or over_process_limit):
raise MemoryError(f'Sustained host swap pressure plus constrained memory: available={available} KiB, process_swap={own_swap_kib} KiB')
self.swap_observation = (now,count)
if rss_kib > 512*1024 or available < 256*1024:
@@ -0,0 +1,104 @@
{
"tokenizer_sha256": "5f9e4d4901a92b997e463c1f46055088b6cca5ca61a6522d1b9f64c4bb81cb42",
"source_sha256": "b3a113d5ea1e4d11e9fdd2ff5e066a50ad3e75b3c20b109e2add05179c7e3eb4",
"decoded_tokens": {
"16": "1",
"17": "2",
"18": "3",
"19": "4",
"248068": "<think>"
},
"target_counts": {
"1": 8,
"4": 8,
"2": 8,
"3": 8
},
"wrong_first_tokens": {
"native": [
{
"item": "test-lookup16-012",
"expected": "4",
"produced": "<think>"
},
{
"item": "test-lookup16-017",
"expected": "4",
"produced": "<think>"
},
{
"item": "test-lookup16-022",
"expected": "4",
"produced": "<think>"
},
{
"item": "test-lookup16-024",
"expected": "4",
"produced": "<think>"
},
{
"item": "test-lookup16-029",
"expected": "4",
"produced": "<think>"
}
],
"direct_23": [],
"lisa_23_ablation": [],
"direct_chain": [
{
"item": "test-lookup16-012",
"expected": "4",
"produced": "<think>"
},
{
"item": "test-lookup16-017",
"expected": "4",
"produced": "<think>"
},
{
"item": "test-lookup16-022",
"expected": "4",
"produced": "<think>"
},
{
"item": "test-lookup16-024",
"expected": "4",
"produced": "<think>"
},
{
"item": "test-lookup16-029",
"expected": "4",
"produced": "<think>"
}
],
"lisa_chain": [],
"linear": [
{
"item": "test-lookup16-012",
"expected": "4",
"produced": "<think>"
},
{
"item": "test-lookup16-017",
"expected": "4",
"produced": "<think>"
},
{
"item": "test-lookup16-022",
"expected": "4",
"produced": "<think>"
},
{
"item": "test-lookup16-024",
"expected": "4",
"produced": "<think>"
},
{
"item": "test-lookup16-029",
"expected": "4",
"produced": "<think>"
}
],
"lisa_answer_weighted": []
}
}
@@ -0,0 +1,141 @@
{
"scope": "isolated full-attention recipient, FP32, frozen true activations; excludes donor generation and full-model decode",
"sites": {
"19": {
"seconds_per_token": {
"native": [
0.13286287058144808,
0.1361464262008667,
0.12924433965235949,
0.1288278056308627,
0.13502545654773712,
0.14447933342307806,
0.21267611254006624,
0.19696053490042686,
0.17250606417655945
],
"lisa": [
0.0882081063464284,
0.0963163236156106,
0.0912644388154149,
0.09147092420607805,
0.09272865019738674,
0.11763023491948843,
0.09996491950005293,
0.11747161205857992,
0.11429349146783352
]
},
"resident_seconds_per_token": {
"native": [
0.03415969293564558,
0.030925235711038113,
0.03575391788035631,
0.04256666451692581,
0.04327994678169489,
0.0476421257480979,
0.04229569900780916,
0.04316695313900709,
0.04567800182849169
],
"lisa": [
0.041921489872038364,
0.04422656074166298,
0.03127973526716232,
0.03182042483240366,
0.03665950056165457,
0.03138743154704571,
0.028396621346473694,
0.037525477819144726,
0.03209121432155371
]
},
"resident_median_s_per_token": {
"native": 0.04256666451692581,
"lisa": 0.03209121432155371
},
"resident_matches_streamed": true,
"allocated_bytes": {
"native": {
"k": 321536,
"v": 321536
},
"lisa": {
"k": 50240,
"v": 321536
}
},
"lisa_input_score_row_bytes": 5024,
"sequence_length": 157
},
"23": {
"seconds_per_token": {
"native": [
0.1291032126173377,
0.12674292363226414,
0.1282597053796053,
0.13638535235077143,
0.1298640752211213,
0.1457589939236641,
0.20920543558895588,
0.20562185905873775,
0.19381640758365393
],
"lisa": [
0.14143545273691416,
0.08705597650259733,
0.08696427289396524,
0.1120216203853488,
0.1387955490499735,
0.13695972133427858,
0.14612034149467945,
0.1524249343201518,
0.1556852562353015
]
},
"resident_seconds_per_token": {
"native": [
0.04479535948485136,
0.04507693089544773,
0.04067131970077753,
0.04552943166345358,
0.05950945522636175,
0.05104204546660185,
0.03087245672941208,
0.03152573574334383,
0.03583979792892933
],
"lisa": [
0.022208196111023426,
0.021793252788484097,
0.03165019955486059,
0.025800297036767006,
0.022528269328176975,
0.022276684641838074,
0.02320440299808979,
0.0227946899831295,
0.024175109341740608
]
},
"resident_median_s_per_token": {
"native": 0.04479535948485136,
"lisa": 0.0227946899831295
},
"resident_matches_streamed": true,
"allocated_bytes": {
"native": {
"k": 321536,
"v": 321536
},
"lisa": {
"k": 50240,
"v": 321536
}
},
"lisa_input_score_row_bytes": 5024,
"sequence_length": 157
}
},
"streamed_timings_include_weight_reads": true,
"resident_timings_exclude_projection_load": true
}
@@ -0,0 +1,10 @@
{
"task": "lookup16",
"source": "frozen Qwen3.5-2B hidden states at the answer position from native forward",
"metric": "4-option accuracy and mean NLL over four option logits",
"frozen_native_reference": {
"fit": {"samples": 12, "native_correct": 12, "choice_nll": 0.13035377124382475},
"validation": {"samples": 12, "native_correct": 12, "choice_nll": 0.13171539331834095}
},
"test_predictions_opened": false
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,123 @@
{
"selected_task": "lookup16",
"sites": [
19,
23
],
"n": 32,
"arms": {
"native": {
"correct": 32,
"answer_nll_4": 0.1341308259358034,
"native_correct_lost_by_direct": 0,
"rescued": 0,
"newly_lost_among_native_and_direct_correct": 0,
"candidate_correct_direct_wrong": 0,
"direct_correct_candidate_wrong": 0,
"accuracy_delta_vs_direct": 0.0,
"paired_prompt_bootstrap_95": [
0.0,
0.0
],
"mcnemar_exact_p": 1.0
},
"direct": {
"correct": 32,
"answer_nll_4": 0.07281379044277814,
"native_correct_lost_by_direct": 0,
"rescued": 0,
"newly_lost_among_native_and_direct_correct": 0,
"candidate_correct_direct_wrong": 0,
"direct_correct_candidate_wrong": 0,
"accuracy_delta_vs_direct": 0.0,
"paired_prompt_bootstrap_95": [
0.0,
0.0
],
"mcnemar_exact_p": 1.0
},
"linear": {
"correct": 32,
"answer_nll_4": 0.07204867493801925,
"native_correct_lost_by_direct": 0,
"rescued": 0,
"newly_lost_among_native_and_direct_correct": 0,
"candidate_correct_direct_wrong": 0,
"direct_correct_candidate_wrong": 0,
"accuracy_delta_vs_direct": 0.0,
"paired_prompt_bootstrap_95": [
0.0,
0.0
],
"mcnemar_exact_p": 1.0
},
"lisa": {
"correct": 32,
"answer_nll_4": 0.1846203565157959,
"native_correct_lost_by_direct": 0,
"rescued": 0,
"newly_lost_among_native_and_direct_correct": 0,
"candidate_correct_direct_wrong": 0,
"direct_correct_candidate_wrong": 0,
"accuracy_delta_vs_direct": 0.0,
"paired_prompt_bootstrap_95": [
0.0,
0.0
],
"mcnemar_exact_p": 1.0
},
"lisa_answer_weighted": {
"correct": 32,
"answer_nll_4": 0.12601824456448818,
"native_correct_lost_by_direct": 0,
"rescued": 0,
"newly_lost_among_native_and_direct_correct": 0,
"candidate_correct_direct_wrong": 0,
"direct_correct_candidate_wrong": 0,
"accuracy_delta_vs_direct": 0.0,
"paired_prompt_bootstrap_95": [
0.0,
0.0
],
"mcnemar_exact_p": 1.0
}
},
"prefill": {
"scope": "cached-prefix last layers, prefill",
"median_s": {
"native": 12.369724708609283,
"direct": 11.017615622840822,
"lisa": 16.311319678090513
},
"lisa_median_ratio_to_native": 1.3186485602818545
},
"decode": {
"scope": "isolated full-attention recipient, FP32, frozen true activations; excludes donor generation and full-model decode",
"sites": {
"19": {
"median_s_per_token": {
"native": 0.1361464262008667,
"lisa": 0.0963163236156106
},
"measured_kv_bytes": {
"native": 643072,
"lisa": 371776
},
"lisa_upstream_score_row_bytes": 5024,
"recipient_bytes_delta": -266272
},
"23": {
"median_s_per_token": {
"native": 0.13638535235077143,
"lisa": 0.1387955490499735
},
"measured_kv_bytes": {
"native": 643072,
"lisa": 371776
},
"lisa_upstream_score_row_bytes": 5024,
"recipient_bytes_delta": -266272
}
}
}
}
@@ -0,0 +1,28 @@
{
"scope": "cached-prefix last layers, prefill",
"seconds": {
"native": [
11.3411781527102,
12.700857263058424,
12.369724708609283
],
"direct": [
11.017615622840822,
10.737364768981934,
11.625513913109899
],
"lisa": [
15.469715679064393,
16.857490073889494,
16.311319678090513
]
},
"real_tokens": 157,
"cache_estimate": {
"scope": "formula for one sequence, BF16 keys and score buffers",
"native_recipient_key_bytes": 321536,
"lisa_recipient_key_bytes": 50240,
"one_shared_decode_score_row_bytes": 2512,
"one_full_prefill_score_matrix_bytes": 394384
}
}
@@ -0,0 +1,12 @@
{
"date": "2026-11-23",
"task": "lookup16",
"item": "fit-lookup16-000",
"recipient_layers": [19, 23],
"sample_tokens_including_answer": 158,
"native_hidden_max_abs_error_against_streaming_reference": 0.000020503997802734375,
"skipped_dense_qk_max_abs_difference": 0.0,
"finite_nonzero_huber_gradients_for_all_adapter_parameters": true,
"peak_rss_kib": 555036,
"scope": "One real Qwen3.5-2B fit sample, synthetic task; the backward path used attention distillation only."
}
@@ -0,0 +1,98 @@
{
"runtime": "3.14.4",
"platform": "Linux",
"machine": "x86_64",
"logical_cpus": 2,
"cpu": "Intel(R) Xeon(R) Platinum",
"numpy": "2.5.4",
"torch": "2.15.0+cpu",
"tokenizers": "0.23.3",
"model_source": {
"repository": "Qwen/Qwen3.5-2B",
"revision": "15852e8c16360a2fea060d615a32b45270f8a8fc",
"manifest_sha256": "28efbaf94a5034333339a35f08ead151459a7d20c6c2d2f07a451e7f3bf154de",
"weight_shard": {
"name": "model.safetensors-00001-of-00001.safetensors",
"bytes": 4548221488,
"sha256_in_download_manifest": "aa33250c4fc64891ddfaba3a314fd9542ea371843c387178b425fbcc5ed680b1"
},
"decoder_layers": 24,
"linear_attention_layers": 18,
"full_attention_layers_zero_based": [3, 7, 11, 15, 19, 23],
"query_heads": 8,
"key_value_heads": 2,
"native_head_dimension": 256,
"hidden_size": 2048,
"vocabulary_size": 248320
},
"capture_sizes": {
"fit": {"prompts": 12, "input_tokens": 1886, "shifted_target_tokens": 1874, "min_input_tokens": 155, "median_input_tokens": 157.5, "max_input_tokens": 158},
"validation": {"prompts": 12, "input_tokens": 1882, "shifted_target_tokens": 1870, "min_input_tokens": 154, "median_input_tokens": 157.0, "max_input_tokens": 160},
"test": {"prompts": 32, "input_tokens": 5017, "shifted_target_tokens": 4985, "min_input_tokens": 153, "median_input_tokens": 157.0, "max_input_tokens": 159}
},
"validation_selected_checkpoints": {
"trace_sha256": "b432fba669d45c09634e96498a15f9d93f971d1ee2b67a826d6f8bc979525866",
"linear.pt": {"epoch": 2, "sha256": "cf204dc784a925de69faa8bed0789ef42877204edb9537d914486d39518fe8ce"},
"lisa.pt": {"epoch": 2, "sha256": "358272c5eb90cea9e3ed006b2c75a4bcd7f5db4f857982e078dd7f71c6c46c5b"},
"lisa_answer_weighted.pt": {"epoch": 2, "sha256": "2b384d5618c190b29bdbb1bc0151c1eb64e1699e209a50ed8171a2d"}
},
"final_remote_verification": {
"pipeline_exit_code": 0,
"unittest_modules": [
"tests.test_lisa_train",
"tests.test_lisa_tail",
"tests.test_lisa_effect_screen",
"tests.test_lisa_effect_resume",
"tests.test_lisa_effect_audit"
],
"passed": 13,
"sha256": {
"test-items.json": "e978b482479deec2d78f8b19d75a5f708bd383111a4c360aad41384e572d48af",
"full-vocab-answers.json": "b3a113d5ea1e4d11e9fdd2ff5e066a50ad3e75b3c20b109e2add05179c7e3eb4",
"paired-audit.json": "f66e60b229cdeaaf6c295382b3bf617332e28f95d6610c11be571edd937e4570",
"verified-audit.json": "a5d496bb5f6d5518a5da2fd6ca3007934558860397a7678c8af8ee23a8d9b92d",
"decode.json": "36b84fbba56bd609f24f550124cd1417e67781eaa6a2401f152fb9f86641370b",
"performance.json": "5f806f713f00b794592899feb3b8188b352fb73052daf304d9026a1294801e17",
"train-protocol.json": "98c71cde7f8ab1bcdb9e05a814fd2c303a046cca51a0d8dfdc936c699da62cce"
}
},
"main_code_sha256": {
"lisa_effect.py": "8a3ecad71f23e3e8b8faf4a7c21c0c93f00fd0bffe14bdee6117921b548dce8a",
"lisa_tail.py": "4bd2c3c8690a8ae30cc1a9573ec17b7bbe25edf43a33507482719dc03cfeb9af",
"lisa_train.py": "d9b96258111e13a3c72483c954714b9ee56e1f308ec4371bafe47026246051a5",
"lisa_decode.py": "9c723fa245ee4dd8f4d0f9a0d7a3d15e3db3ae40db3fa82ea413ecd24fe20f06",
"lisa_decode_bench.py": "979e566a3391b9418b49beb10c200a48aac706ee95c145510850c929bcc2885a",
"lisa_effect_screen.py": "8aaf515d888f921e60082b69d898cb5037a160c5d09a584db2599f197c4aa74b"
},
"audit_code_sha256": {
"lisa_effect_audit.py": "75c3445d96521daa2832ee96eb128383fc81f6914d491c2804a9337d1d6af35b",
"lisa_effect_answer_audit.py": "e1d70b10863dab1e13dfa9573c0d87fc6ca017039c3cf9b90f7628f3e7fe5664"
},
"local_code_match": {
"lisa_effect.py": true,
"lisa_tail.py": true,
"lisa_train.py": true,
"lisa_decode.py": true,
"lisa_decode_bench.py": true,
"lisa_effect_screen.py": true,
"lisa_effect_audit.py": true,
"lisa_effect_answer_audit.py": true
},
"phase_updates": {
"lisa_decode_bench.py": {
"initial_unexecuted_benchmark_sha256": "0b9867b3f17dbe6373627fa3901c2ea113fc7e0d690b4a358350cfaae62ef223",
"validated_remote_benchmark_sha256": "979e566a3391b9418b49beb10c200a48aac706ee95c145510850c929bcc2885a",
"reason": "Measure compute with resident projections separately from streamed execution",
"remote_numeric_tests": "4 passed; resident projection outputs compared with streamed output"
},
"lisa_effect_audit.py": {
"verified_audit_sha256": "2d7feb79c23bed05d4d961ead7cbdfcff61b5425f1c3ef88192c2c3cd5afecb4",
"reason": "Cross-check the four-choice arms against the full-vocabulary pass and quantify paired answer-loss changes",
"remote_numeric_tests": "4 passed in an isolated source directory",
"outputs": {
"paired-audit.json": "original audit hash in audit_code_sha256",
"verified-audit.json": "verified_audit_sha256"
}
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,82 @@
{
"lookup8": {
"native": {
"n": 8,
"correct": 8,
"native_wins_lost": 0,
"nll": 0.22260868260464628
},
"direct_23": {
"n": 8,
"correct": 8,
"native_wins_lost": 0,
"nll": 0.15405775362854435
},
"direct_19_23": {
"n": 8,
"correct": 8,
"native_wins_lost": 0,
"nll": 0.1474619847851022
}
},
"lookup16": {
"native": {
"n": 8,
"correct": 8,
"native_wins_lost": 0,
"nll": 0.137068848385562
},
"direct_23": {
"n": 8,
"correct": 8,
"native_wins_lost": 0,
"nll": 0.08428237400849126
},
"direct_19_23": {
"n": 8,
"correct": 7,
"native_wins_lost": 1,
"nll": 0.17225019742912862
}
},
"latest8": {
"native": {
"n": 8,
"correct": 6,
"native_wins_lost": 0,
"nll": 0.5951684205201615
},
"direct_23": {
"n": 8,
"correct": 6,
"native_wins_lost": 0,
"nll": 0.5312782958402527
},
"direct_19_23": {
"n": 8,
"correct": 7,
"native_wins_lost": 0,
"nll": 0.5573033796086375
}
},
"arithmetic": {
"native": {
"n": 8,
"correct": 3,
"native_wins_lost": 0,
"nll": 1.2998106862759977
},
"direct_23": {
"n": 8,
"correct": 3,
"native_wins_lost": 0,
"nll": 1.2773446956117458
},
"direct_19_23": {
"n": 8,
"correct": 4,
"native_wins_lost": 0,
"nll": 1.2912787564044454
}
}
}
@@ -0,0 +1,13 @@
{
"task": "lookup16",
"sites": [
19,
23
],
"fixed_problems_sha256": "34252a9e02e79c0e0d786ee8b90bb0c5a4fe22e97852929fedf73db7b6dc7826",
"source_sha256": {
"manifest.json": "28efbaf94a5034333339a35f08ead151459a7d20c6c2d2f07a451e7f3bf154de",
"model_config.json": "ed1c1723241f23f7f4e23430759cbd7dcfb4103cbdfe052bfe7626b57c2615b4",
"tokenizer.json": "5f9e4d4901a92b997e463c1f46055088b6cca5ca61a6522d1b9f64c4bb81cb42"
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,38 @@
{
"linear": [
{
"epoch": 1,
"fit_loss": 1.528187096118927,
"validation_answer_nll": 0.08188676834106445
},
{
"epoch": 2,
"fit_loss": 1.4630066951115925,
"validation_answer_nll": 0.08137226104736328
}
],
"lisa": [
{
"epoch": 1,
"fit_loss": 2.8282371163368225,
"validation_answer_nll": 0.21536986033121744
},
{
"epoch": 2,
"fit_loss": 2.06735689441363,
"validation_answer_nll": 0.18566656112670898
}
],
"lisa_answer_weighted": [
{
"epoch": 1,
"fit_loss": 2.752801299095154,
"validation_answer_nll": 0.23118178049723306
},
{
"epoch": 2,
"fit_loss": 1.9780630469322205,
"validation_answer_nll": 0.1396172841389974
}
]
}
@@ -0,0 +1,21 @@
{
"epochs": 2,
"selection": {
"task": "lookup16",
"sites": [
19,
23
],
"fixed_problems_sha256": "34252a9e02e79c0e0d786ee8b90bb0c5a4fe22e97852929fedf73db7b6dc7826",
"source_sha256": {
"manifest.json": "28efbaf94a5034333339a35f08ead151459a7d20c6c2d2f07a451e7f3bf154de",
"model_config.json": "ed1c1723241f23f7f4e23430759cbd7dcfb4103cbdfe052bfe7626b57c2615b4",
"tokenizer.json": "5f9e4d4901a92b997e463c1f46055088b6cca5ca61a6522d1b9f64c4bb81cb42"
}
},
"optimizer": "AdamW",
"lr": 0.0003,
"weight_decay": 0.1,
"answer_weight": 16.0,
"seed": 415005
}
@@ -0,0 +1,297 @@
{
"selected_task": "lookup16",
"sites": [
19,
23
],
"n": 32,
"arms": {
"native": {
"correct": 32,
"answer_nll_4": 0.1341308259358034,
"answer_nll_4_vs_direct": {
"mean_delta": 0.06131703549302525,
"paired_prompt_bootstrap_95": [
0.04199299138593708,
0.07944046845013401
]
},
"native_correct_lost_by_direct": 0,
"rescued": 0,
"newly_lost_among_native_and_direct_correct": 0,
"candidate_correct_direct_wrong": 0,
"direct_correct_candidate_wrong": 0,
"accuracy_delta_vs_direct": 0.0,
"paired_prompt_bootstrap_95": [
0.0,
0.0
],
"mcnemar_exact_p": 1.0
},
"direct": {
"correct": 32,
"answer_nll_4": 0.07281379044277814,
"answer_nll_4_vs_direct": {
"mean_delta": 0.0,
"paired_prompt_bootstrap_95": [
0.0,
0.0
]
},
"native_correct_lost_by_direct": 0,
"rescued": 0,
"newly_lost_among_native_and_direct_correct": 0,
"candidate_correct_direct_wrong": 0,
"direct_correct_candidate_wrong": 0,
"accuracy_delta_vs_direct": 0.0,
"paired_prompt_bootstrap_95": [
0.0,
0.0
],
"mcnemar_exact_p": 1.0
},
"linear": {
"correct": 32,
"answer_nll_4": 0.07204867493801925,
"answer_nll_4_vs_direct": {
"mean_delta": -0.0007651155047588842,
"paired_prompt_bootstrap_95": [
-0.0011749581537977532,
-0.00035981557985461103
]
},
"native_correct_lost_by_direct": 0,
"rescued": 0,
"newly_lost_among_native_and_direct_correct": 0,
"candidate_correct_direct_wrong": 0,
"direct_correct_candidate_wrong": 0,
"accuracy_delta_vs_direct": 0.0,
"paired_prompt_bootstrap_95": [
0.0,
0.0
],
"mcnemar_exact_p": 1.0
},
"lisa": {
"correct": 32,
"answer_nll_4": 0.1846203565157959,
"answer_nll_4_vs_direct": {
"mean_delta": 0.11180656607301775,
"paired_prompt_bootstrap_95": [
0.09675488440532508,
0.12821407122333472
]
},
"native_correct_lost_by_direct": 0,
"rescued": 0,
"newly_lost_among_native_and_direct_correct": 0,
"candidate_correct_direct_wrong": 0,
"direct_correct_candidate_wrong": 0,
"accuracy_delta_vs_direct": 0.0,
"paired_prompt_bootstrap_95": [
0.0,
0.0
],
"mcnemar_exact_p": 1.0
},
"lisa_answer_weighted": {
"correct": 32,
"answer_nll_4": 0.12601824456448818,
"answer_nll_4_vs_direct": {
"mean_delta": 0.05320445412171004,
"paired_prompt_bootstrap_95": [
0.03266015039585242,
0.07493446492664697
]
},
"native_correct_lost_by_direct": 0,
"rescued": 0,
"newly_lost_among_native_and_direct_correct": 0,
"candidate_correct_direct_wrong": 0,
"direct_correct_candidate_wrong": 0,
"accuracy_delta_vs_direct": 0.0,
"paired_prompt_bootstrap_95": [
0.0,
0.0
],
"mcnemar_exact_p": 1.0
}
},
"prefill": {
"scope": "cached-prefix last layers, prefill",
"median_s": {
"native": 12.369724708609283,
"direct": 11.017615622840822,
"lisa": 16.311319678090513
},
"lisa_median_ratio_to_native": 1.3186485602818545
},
"decode": {
"scope": "isolated full-attention recipient, FP32, frozen true activations; excludes donor generation and full-model decode",
"sites": {
"19": {
"median_s_per_token": {
"native": 0.1361464262008667,
"lisa": 0.0963163236156106
},
"measured_kv_bytes": {
"native": 643072,
"lisa": 371776
},
"lisa_upstream_score_row_bytes": 5024,
"recipient_bytes_delta": -266272
},
"23": {
"median_s_per_token": {
"native": 0.13638535235077143,
"lisa": 0.1387955490499735
},
"measured_kv_bytes": {
"native": 643072,
"lisa": 371776
},
"lisa_upstream_score_row_bytes": 5024,
"recipient_bytes_delta": -266272
}
}
},
"full_vocab": {
"arms": {
"native": {
"correct": 27,
"answer_nll": 0.5633379220962524
},
"direct_23": {
"correct": 32,
"answer_nll": 0.31241124868392944
},
"lisa_23_ablation": {
"correct": 32,
"answer_nll": 0.2554302215576172
},
"direct_chain": {
"correct": 27,
"answer_nll": 0.5578678846359253
},
"lisa_chain": {
"correct": 32,
"answer_nll": 0.4706266522407532
},
"linear": {
"correct": 27,
"answer_nll": 0.5574188828468323
},
"lisa_answer_weighted": {
"correct": 32,
"answer_nll": 0.15454155206680298
}
},
"matched_direct_comparisons": {
"lisa_23_ablation": {
"baseline": "direct_23",
"answer_nll_delta": {
"mean_delta": -0.056981027126312256,
"paired_prompt_bootstrap_95": [
-0.0759883001446724,
-0.03968979567289353
]
},
"native_correct_lost_by_direct": 0,
"rescued": 0,
"newly_lost_among_native_and_direct_correct": 0,
"candidate_correct_direct_wrong": 0,
"direct_correct_candidate_wrong": 0,
"accuracy_delta_vs_direct": 0.0,
"paired_prompt_bootstrap_95": [
0.0,
0.0
],
"mcnemar_exact_p": 1.0
},
"native": {
"baseline": "direct_chain",
"answer_nll_delta": {
"mean_delta": 0.0054700374603271484,
"paired_prompt_bootstrap_95": [
-0.04259051829576492,
0.05237825959920882
]
},
"native_correct_lost_by_direct": 0,
"rescued": 0,
"newly_lost_among_native_and_direct_correct": 0,
"candidate_correct_direct_wrong": 0,
"direct_correct_candidate_wrong": 0,
"accuracy_delta_vs_direct": 0.0,
"paired_prompt_bootstrap_95": [
0.0,
0.0
],
"mcnemar_exact_p": 1.0
},
"linear": {
"baseline": "direct_chain",
"answer_nll_delta": {
"mean_delta": -0.0004490017890930176,
"paired_prompt_bootstrap_95": [
-0.002629266679286957,
0.0016906306147575377
]
},
"native_correct_lost_by_direct": 0,
"rescued": 0,
"newly_lost_among_native_and_direct_correct": 0,
"candidate_correct_direct_wrong": 0,
"direct_correct_candidate_wrong": 0,
"accuracy_delta_vs_direct": 0.0,
"paired_prompt_bootstrap_95": [
0.0,
0.0
],
"mcnemar_exact_p": 1.0
},
"lisa_answer_weighted": {
"baseline": "direct_chain",
"answer_nll_delta": {
"mean_delta": -0.4033263325691223,
"paired_prompt_bootstrap_95": [
-0.47958737164735793,
-0.33443659693002703
]
},
"native_correct_lost_by_direct": 0,
"rescued": 0,
"newly_lost_among_native_and_direct_correct": 0,
"candidate_correct_direct_wrong": 5,
"direct_correct_candidate_wrong": 0,
"accuracy_delta_vs_direct": 0.15625,
"paired_prompt_bootstrap_95": [
0.03125,
0.28125
],
"mcnemar_exact_p": 0.0625
},
"lisa_chain": {
"baseline": "direct_chain",
"answer_nll_delta": {
"mean_delta": -0.08724123239517212,
"paired_prompt_bootstrap_95": [
-0.14977428913116456,
-0.030542241036891984
]
},
"native_correct_lost_by_direct": 0,
"rescued": 0,
"newly_lost_among_native_and_direct_correct": 0,
"candidate_correct_direct_wrong": 5,
"direct_correct_candidate_wrong": 0,
"accuracy_delta_vs_direct": 0.15625,
"paired_prompt_bootstrap_95": [
0.03125,
0.28125
],
"mcnemar_exact_p": 0.0625
}
}
}
}
@@ -0,0 +1,9 @@
94437e0138c54ec34b1beaaa0e08a334ce0822f60af598a5a896459b778a3a1c functional/model.py
98927a1ccd935b2f7a438bad31bbd973e210a54deceac911c61551092e52c96c crossqkv/lisa_generate.py
519e0a031efcfb69c9b86fca1cb649fe8bb93d799401c8023ff7b6549cded448 crossqkv/lisa_full_answer.py
74d6cbe3be94a8118f670c8810037b6d8abe085bd42b638a58af856eb45a17f3 crossqkv/lisa_full_answer_train.py
d47b4c9cc34082e9b356e745821298a43981e4cd18ed55a3f59b4b6fe7cc46e3 crossqkv/lisa_tail.py
9f0b6a53f107950661e91c16f03b49440708b3936120e2f84ef1d66f185257b6 crossqkv/lisa_train.py
96d12fdfa266ca02ac50330971ff403e04b977358f479d63c8d6276a514fe025 tests/test_lisa_full_answer.py
d1f3b3b2b92005c47f7fbc4f558407749b7059592c3b54d8b784da58ea12b3ef tests/test_lisa_tail.py
d249035103ed7f43978c0d6452bf70ec9a345777289cb92c0b6a2a181e6d4380 tests/test_lisa_train.py
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,5 @@
{
"prompt_id": "screen-lookup-000",
"prompt_tokens": 103,
"tail_hidden_max_abs": 0.0001049041748046875
}
+66
View File
@@ -0,0 +1,66 @@
"""Check answer-only metrics and isolate recovery from newly lost items."""
import json
from pathlib import Path
from tempfile import TemporaryDirectory
import unittest
import numpy as np
import torch
from torch.nn import functional as F
from crossqkv.lisa_effect_answer_audit import vocabulary_scores
from crossqkv.lisa_effect_audit import MODES, full_vocab_metrics, loss_delta, paired
from tests.test_lisa_tail import Tensor
class EffectAuditTests(unittest.TestCase):
def test_loss_interval_uses_paired_differences(self):
direct = np.array([0.5, 1.0, 4.0, 9.0])
result = loss_delta(direct - 0.25, direct)
self.assertEqual(result, {'mean_delta': -0.25,
'paired_prompt_bootstrap_95': [-0.25, -0.25]})
def test_full_vocab_compares_each_recipient_schedule_to_matched_direct(self):
mapped = ('native', 'linear', 'direct_chain', 'lisa_chain', 'lisa_answer_weighted',
'direct_23', 'lisa_23_ablation')
payload = {'candidate_sites': [19, 23], 'single_lisa_is_ablation_of_joint_checkpoint': True,
'arms': {}}
for name in mapped:
correct = name not in ('direct_chain', 'direct_23')
payload['arms'][name] = {
'n': 1, 'full_vocab_correct': int(correct), 'four_choice_correct': 1,
'full_vocab_nll': 0.25 if correct else 2.0,
'rows': [{'id': 'test-a', 'gold_id': 3, 'greedy_id': 3 if correct else 4,
'choice_id': 3, 'nll': 0.25 if correct else 2.0}],
}
choices = {name: np.array([True]) for name in MODES}
with TemporaryDirectory() as scratch:
path = Path(scratch) / 'answers.json'
path.write_text(json.dumps(payload))
measured = full_vocab_metrics(path, [('test-a', 0)], [19, 23], choices)
comparisons = measured['matched_direct_comparisons']
self.assertEqual(comparisons['lisa_chain']['baseline'], 'direct_chain')
self.assertEqual(comparisons['lisa_23_ablation']['baseline'], 'direct_23')
self.assertEqual(comparisons['lisa_chain']['rescued'], 1)
self.assertEqual(comparisons['lisa_chain']['answer_nll_delta']['mean_delta'], -1.75)
choices['lisa'] = np.array([False])
with self.assertRaisesRegex(ValueError, 'lisa_chain choices differ'):
full_vocab_metrics(path, [('test-a', 0)], [19, 23], choices)
def test_paired_rescue_excludes_natively_wrong_items(self):
native, direct, candidate = (np.array(x, dtype=bool) for x in
[(1, 1, 1, 0), (0, 0, 1, 1), (1, 0, 0, 1)])
result = paired(native, direct, candidate)
self.assertEqual(result['native_correct_lost_by_direct'], 2)
self.assertEqual(result['rescued'], 1)
self.assertEqual(result['newly_lost_among_native_and_direct_correct'], 1)
self.assertEqual(result['accuracy_delta_vs_direct'], 0)
def test_streamed_answer_scores_match_full_reference(self):
g = torch.Generator().manual_seed(9)
h, w = torch.randn(4, 6, generator=g), torch.randn(1033, 6, generator=g)
target = torch.tensor([2, 1032, 22, 1024])
actual, loss = vocabulary_scores(h, target, Tensor(w.numpy()))
logits = F.linear(h, w)
torch.testing.assert_close(actual, logits.argmax(-1))
torch.testing.assert_close(loss, F.cross_entropy(logits, target, reduction='none'))
+62
View File
@@ -0,0 +1,62 @@
"""Check exact epoch resume through the actual LiSA training entry point."""
import json
from pathlib import Path
from tempfile import TemporaryDirectory
import unittest
from unittest.mock import patch
import numpy as np
import torch
from crossqkv.lisa_effect import train
from functional.model import PREFIX
from functional.reference_check import ArrayLM
from tests.test_lisa_tail import Tensor
class TrainingResumeTests(unittest.TestCase):
def test_checkpoint_resume_preserves_all_selected_outputs(self):
rng = np.random.default_rng(22)
def rand(shape):
return (.13*rng.standard_normal(shape)).astype('f4')
torch.set_num_threads(1)
c = {'rms_norm_eps': 1e-6, 'layer_types': ['full_attention'], 'hidden_size': 8,
'num_attention_heads': 2, 'num_key_value_heads': 1, 'head_dim': 8,
'rope_parameters': {'rope_theta': 10000., 'partial_rotary_factor': .5}}
shapes = {'input_layernorm': (8,), 'post_attention_layernorm': (8,),
'self_attn.q_proj': (32, 8), 'self_attn.k_proj': (8, 8),
'self_attn.v_proj': (8, 8), 'self_attn.o_proj': (8, 16),
'self_attn.q_norm': (8,), 'self_attn.k_norm': (8,),
'mlp.gate_proj': (13, 8), 'mlp.up_proj': (13, 8), 'mlp.down_proj': (8, 13)}
weights = {f'layers.0.{k}.weight': rand(v) for k, v in shapes.items()}
weights.update({'embed_tokens.weight': rand((12,8)), 'norm.weight': rand((8,))})
model = ArrayLM(weights, c)
model.tensors = {PREFIX+k: Tensor(v) for k,v in weights.items()}
with TemporaryDirectory() as directory:
p = Path(directory)
cache, out = p/'cache', p/'out'
cache.mkdir()
out.mkdir()
(p/'model_config.json').write_text(json.dumps(c))
(cache/'selection.json').write_text(json.dumps({'sites':[0], 'task':'fixture',
'source_sha256':{}}))
labels = np.arange(1, 5, dtype=np.int64)
for split, count in [('fit',12), ('validation',12), ('test',32)]:
for i in range(0, count, 4):
ids = rng.integers(1, 12, size=(4, 4))
gold = rng.integers(0, 4, size=4)
ids[:, -1] = labels[gold]
expected, _ = model.forward(ids)
np.savez(cache/f'{split}-{i:03}.npz', ids=ids, lengths=np.full(4,4),
labels=labels, gold=gold, residual=model.embedding(ids),
donor=rand((4,2,4,4)), expected=expected,
names=[f'{split}-{k}' for k in range(i,i+4)])
with patch('functional.model.StreamingLM', return_value=model), patch('builtins.print'):
train(p, cache, out, 1)
before = (out/'test-items.json').read_bytes()
lines = (out/'trace.json').read_bytes()
train(p, cache, out, 1, resume=True)
self.assertEqual(before, (out/'test-items.json').read_bytes())
self.assertEqual(lines, (out/'trace.json').read_bytes())
+53
View File
@@ -0,0 +1,53 @@
"""Prove shared-prefix replay matches the original replicated-batch screen."""
import unittest
import numpy as np
from tokenizers import Tokenizer
from tokenizers.models import WordLevel
from tokenizers.pre_tokenizers import Whitespace
from crossqkv.lisa_effect_screen import MODES, ScreeningModel, evaluate, problems
from functional.model import PREFIX
from functional.reference_check import ArrayLM
class ArrayTensor:
def __init__(self, values):
self.raw = values
self.shape = values.shape
self.dtype = 'F32'
def evict(self):
pass
class TinyScreen(ScreeningModel, ArrayLM):
pass
class ScreenTests(unittest.TestCase):
def test_replay_preserves_all_three_arms(self):
rng = np.random.default_rng(11)
cfg = {'rms_norm_eps': 1e-6, 'layer_types': ['full_attention']*24,
'num_attention_heads': 2, 'num_key_value_heads': 1, 'head_dim': 8,
'rope_parameters': {'rope_theta': 10000., 'partial_rotary_factor': .5}}
rand = lambda shape: (.12*rng.standard_normal(shape)).astype('f4')
weights = {'norm.weight': rand((8,)), 'embed_tokens.weight': rand((15, 8))}
shapes = {'input_layernorm': (8,), 'post_attention_layernorm': (8,),
'self_attn.q_proj': (32, 8), 'self_attn.k_proj': (8, 8),
'self_attn.v_proj': (8, 8), 'self_attn.o_proj': (8, 16),
'self_attn.q_norm': (8,), 'self_attn.k_norm': (8,),
'mlp.gate_proj': (13, 8), 'mlp.up_proj': (13, 8), 'mlp.down_proj': (8, 13)}
weights.update({f'layers.{i}.{k}.weight': rand(v) for i in range(24) for k,v in shapes.items()})
model = TinyScreen(weights, cfg)
model.tensors = {PREFIX+k: ArrayTensor(v) for k,v in weights.items()}
tok = Tokenizer(WordLevel({'[UNK]': 0, **{str(i): i for i in range(1, 10)}}, unk_token='[UNK]'))
tok.pre_tokenizer = Whitespace()
examples = problems('screen', 2)
originals = evaluate(model, tok, examples)
model.reuse_prefix = True
replay = evaluate(model, tok, examples)
for orig, new in zip(originals, replay):
for key in MODES:
np.testing.assert_allclose(orig['scores'][key]['logits'],
new['scores'][key]['logits'], atol=1e-6)
+43
View File
@@ -0,0 +1,43 @@
"""Protect final-answer scoring, split isolation and the screening threshold."""
import unittest
from crossqkv.lisa_full_answer import SCHEDULES, choose, final_integer, fixed_problems, grade
from crossqkv.lisa_full_answer_train import audit
class FullAnswerTests(unittest.TestCase):
def test_reads_the_terminal_answer_and_requires_eos(self):
self.assertEqual(final_integer('<think>First try 17.</think>\n42'), 42)
self.assertEqual(final_integer('Working: 17 and 25.\nFinal answer: 42.'), 42)
self.assertIsNone(final_integer('17 or 42'))
self.assertIsNone(final_integer('<think>17'))
self.assertIsNone(final_integer('<think>\nFinal answer: 42'))
class TextTokenizer:
def decode(self, tokens, skip_special_tokens):
return ''.join(tokens)
tok = TextTokenizer()
self.assertTrue(grade(tok, ['4', '2', '<EOS>'], 'eos', 42)['correct'])
self.assertFalse(grade(tok, ['4', '2'], 'max_new_tokens', 42)['correct'])
def test_frozen_splits_are_disjoint_and_schedule_must_lose_answers(self):
data = fixed_problems()
questions = [row['question'] for rows in data.values() for row in rows]
self.assertEqual(len(questions), len(set(questions)))
self.assertTrue(all(row['answer'] >= 10 for rows in data.values() for row in rows))
a = {name: {'correct': 6, 'native_correct_to_wrong_integer': []} for name in SCHEDULES}
self.assertIsNone(choose({'lookup': a}))
a['direct_4']['native_correct_to_wrong_integer'] = ['a', 'b']
self.assertEqual(choose({'lookup': a})['recipients'], [11, 15, 19, 23])
def test_audit_distinguishes_wrong_numbers_and_missing_answers(self):
def row(name, direct):
return {'id': name, 'arms': {'native': {'answer': 12, 'correct': True},
'direct': {'answer': direct, 'correct': False},
'lisa': {'answer': 12, 'correct': True}}}
report = audit([row('wrong', 13), row('missing', None)])
self.assertEqual(report['rescued'], 2)
self.assertEqual(report['substantive_loss_ids'], ['wrong'])
self.assertEqual(report['substantive_rescued_ids'], ['wrong'])
+150
View File
@@ -0,0 +1,150 @@
"""Check streamed frozen gradients and the Torch tail against the CPU reference."""
import unittest
import numpy as np
import torch
from torch.nn import functional as F
from crossqkv.lisa_decode import AttentionSiteCache
from crossqkv.lisa_decode_bench import ResidentSite, timed_site
from crossqkv.lisa_generate import GenerationDecoder
from crossqkv.lisa_tail import FrozenLinear, TorchTail, gated_delta, rotate
from crossqkv.lisa_train import LearnableSharingAttention
from functional.model import PREFIX, delta_rule, rope
from functional.reference_check import ArrayLM
class Tensor:
def __init__(self, value):
self.value = value
self.shape = value.shape
def read(self, selection):
return self.value.ravel()[selection]
def evict(self):
pass
class TailTests(unittest.TestCase):
def test_frozen_rows_and_input_gradient(self):
torch.manual_seed(4)
x = torch.randn(2, 3, 5, requires_grad=True)
w = torch.randn(14, 5)
actual = FrozenLinear.apply(x, Tensor(w.numpy()), 2, 11)
dense = F.linear(x, w[2:11])
torch.testing.assert_close(actual, dense)
torch.testing.assert_close(torch.autograd.grad(actual.square().sum(), x)[0],
torch.autograd.grad(dense.square().sum(), x)[0])
def test_rotary_and_gated_delta(self):
rng = np.random.default_rng(8)
q, k, v = [rng.normal(size=(2, 5, 2, 8)).astype('f4') for _ in range(3)]
g = -np.abs(rng.normal(size=(2, 5, 2)).astype('f4'))
b = rng.uniform(size=(2, 5, 2)).astype('f4')
tx = torch.tensor(q)
torch.testing.assert_close(rotate(tx, 10000000., .5),
torch.tensor(rope(q, 10000000., .5)))
actual = gated_delta(*map(torch.tensor, (q, k, v, g, b)))
torch.testing.assert_close(actual, torch.tensor(delta_rule(q, k, v, g, b)[0]))
def test_two_recipient_forward_parity_and_both_get_gradients(self):
rng = np.random.default_rng(5)
cfg = {'rms_norm_eps': 1e-6, 'layer_types': ['full_attention', 'linear_attention',
'full_attention'], 'num_attention_heads': 2, 'num_key_value_heads': 1,
'head_dim': 8, 'linear_num_key_heads': 1, 'linear_num_value_heads': 2,
'linear_key_head_dim': 4, 'linear_value_head_dim': 4,
'rope_parameters': {'rope_theta': 10000., 'partial_rotary_factor': .5}}
def rand(*shape):
return (rng.normal(size=shape) * .2).astype('f4')
a = {'norm.weight': rand(8), 'embed_tokens.weight': rand(10, 8)}
for i, kind in enumerate(cfg['layer_types']):
names = {'input_layernorm': (8,), 'post_attention_layernorm': (8,),
'mlp.gate_proj': (12, 8), 'mlp.up_proj': (12, 8), 'mlp.down_proj': (8, 12)}
if kind == 'full_attention':
names.update({'self_attn.q_proj': (32, 8), 'self_attn.k_proj': (8, 8),
'self_attn.v_proj': (8, 8), 'self_attn.o_proj': (8, 16),
'self_attn.q_norm': (8,), 'self_attn.k_norm': (8,)})
else:
names.update({'linear_attn.in_proj_qkv': (16, 8), 'linear_attn.in_proj_z': (8, 8),
'linear_attn.in_proj_b': (2, 8), 'linear_attn.in_proj_a': (2, 8),
'linear_attn.out_proj': (8, 8), 'linear_attn.norm': (4,),
'linear_attn.conv1d': (16, 1, 3)})
a[f'layers.{i}.linear_attn.A_log'] = rand(2)
a[f'layers.{i}.linear_attn.dt_bias'] = rand(2)
a.update({f'layers.{i}.{name}.weight': rand(*shape) for name, shape in names.items()})
original = ArrayLM(a, cfg)
original.tensors = {PREFIX+k: Tensor(v) for k,v in a.items()}
ids = rng.integers(0, 10, (2, 5))
h = torch.tensor(original.embedding(ids))
expected, _ = original.forward(ids)
adapters = {i: LearnableSharingAttention(8, 2, 1, 4, 10000., .5, 16)
for i in (0, 2)}
tail = TorchTail(original, 0, adapters)
lengths = torch.tensor([5, 5])
native, _ = tail(h, None, lengths, 'native', ())
torch.testing.assert_close(native, torch.tensor(expected), atol=2e-5, rtol=2e-5)
padded = np.stack([ids[0], np.concatenate(([0, 0], ids[1, 2:]))])
for mode, schedules, modules in (
('direct', [(), (2,)], None), ('lisa', [(2,), (2,)], {2: adapters[2]})
):
decoder = GenerationDecoder(original, schedules, [0, 2], modules)
actual = torch.cat((decoder.advance(torch.tensor(padded[:, :4])),
decoder.advance(torch.tensor(padded[:, 4:]))), dim=1)
for bi, pad in enumerate((0, 2)):
x = h[bi:bi+1, pad:]
ref, _ = tail(x, None, torch.tensor([5-pad]), mode, schedules[bi])
torch.testing.assert_close(actual[bi:bi+1, pad:], ref, atol=2e-6, rtol=2e-5)
donor = torch.tensor(rand(2, 2, 5, 5))
run, _ = tail(h, donor, lengths, 'lisa', (0,2), keep_teacher=False)
ref, _ = tail(h, donor, lengths, 'lisa', (0,2), keep_teacher=True)
torch.testing.assert_close(run, ref)
run.square().sum().backward()
self.assertTrue(all(p.grad is not None and p.grad.abs().sum() > 0 for p in tail.parameters()))
def test_decode_uses_rotary_offsets_and_compact_key_cache(self):
rng = np.random.default_rng(252)
cfg = {'rms_norm_eps': 1e-6, 'layer_types': ['full_attention'],
'num_attention_heads': 2, 'num_key_value_heads': 1, 'head_dim': 16,
'rope_parameters': {'rope_theta': 10000., 'partial_rotary_factor': .5}}
names = {'q_proj': (64, 8), 'k_proj': (16, 8), 'v_proj': (16, 8),
'o_proj': (8, 32), 'q_norm': (16,), 'k_norm': (16,)}
weights = {'layers.0.self_attn.' + k + '.weight':
rng.normal(0, .2, shape).astype('f4') for k, shape in names.items()}
source = ArrayLM(weights, cfg)
source.tensors = {PREFIX+k: Tensor(v) for k,v in weights.items()}
adapter = LearnableSharingAttention(8, 2, 1, 4, 10000., .5, width=12)
tail = TorchTail(source, 0, {0: adapter})
hidden = torch.tensor(rng.normal(0, .8, (2, 5, 8)).astype('f4'))
donor = torch.tensor(rng.normal(0, 1, (2, 2, 5, 5)).astype('f4'))
lengths = torch.tensor([5, 5])
native = AttentionSiteCache(tail, 0, 2, 5)
shared = AttentionSiteCache(tail, 0, 2, 5, adapter)
for mode, cache in [('native', native), ('lisa', shared)]:
out, raw, _ = tail.full(hidden, 0, donor, lengths, mode, (0,), False)
for pos in range(hidden.shape[1]):
row = donor[:, :, pos:pos+1, :pos+1] if mode == 'lisa' else None
actual, scores = cache.step(hidden[:, pos:pos+1], row)
torch.testing.assert_close(actual, out[:, pos:pos+1], atol=2e-6, rtol=2e-5)
torch.testing.assert_close(scores, raw[:, :, pos:pos+1, :pos+1],
atol=2e-6, rtol=2e-5)
cache.reset()
cache.prefill(hidden[:, :4])
row = donor[:, :, 4:5, :] if mode == 'lisa' else None
actual, scores = cache.step(hidden[:, 4:5], row)
torch.testing.assert_close(actual, out[:, 4:5], atol=2e-6, rtol=2e-5)
torch.testing.assert_close(scores, raw[:, :, 4:5, :], atol=2e-6, rtol=2e-5)
self.assertEqual(shared.allocated_bytes['v'], native.allocated_bytes['v'])
self.assertEqual(shared.allocated_bytes['k']*4, native.allocated_bytes['k'])
resident = ResidentSite(tail, 0)
_, original_states = timed_site({'native': native, 'lisa': shared}, hidden, donor, 5,
samples=2, rounds=2)
_, warm_states = timed_site({'native': AttentionSiteCache(resident, 0, 2, 5),
'lisa': AttentionSiteCache(resident, 0, 2, 5, adapter)},
hidden, donor, 5, samples=2, rounds=2)
for mode in ('native', 'lisa'):
for old, new in zip(original_states[mode], warm_states[mode]):
torch.testing.assert_close(old, new, atol=2e-6, rtol=2e-5)
+30
View File
@@ -27,6 +27,36 @@ class LiSATrainingTests(unittest.TestCase):
torch.testing.assert_close(torch.autograd.grad(streamed, hidden)[0],
torch.autograd.grad(dense, hidden)[0])
def test_answer_weighted_ce_matches_dense(self):
torch.manual_seed(12)
h = torch.randn((2, 4, 3), dtype=torch.float64, requires_grad=True)
w = torch.randn((5, 3), dtype=h.dtype)
ids = torch.randint(0, 5, (2, 4))
lengths = torch.tensor([4, 3])
valid = torch.arange(1, 4) < lengths[:, None]
answer = torch.arange(2, 5) == lengths[:, None]
weights = torch.where(answer, 16., 1.)[valid]
ce = F.cross_entropy(F.linear(h[:, :-1][valid], w), ids[:, 1:][valid], reduction='none')
dense = (ce * weights).sum() / weights.sum()
streamed = language_model_loss(h, ids, lengths, lambda: iter([(0, w)]), answer_weight=16.)
torch.testing.assert_close(streamed, dense)
torch.testing.assert_close(torch.autograd.grad(streamed, h)[0],
torch.autograd.grad(dense, h)[0])
def test_completion_loss_covers_all_reply_tokens(self):
h = torch.randn((2, 6, 3), generator=torch.Generator().manual_seed(4),
requires_grad=True)
w = torch.randn((8, 3), generator=torch.Generator().manual_seed(5))
ids = torch.tensor([[1, 2, 1, 4, 2, 7], [1, 3, 5, 7, 0, 0]])
lengths, starts = torch.tensor([6, 4]), torch.tensor([3, 2])
valid = (torch.arange(1, 6) < lengths[:, None]) & (torch.arange(1, 6) >= starts[:, None])
reference = F.cross_entropy(F.linear(h[:, :-1][valid], w), ids[:, 1:][valid])
streamed = language_model_loss(h, ids, lengths, lambda: iter([(0, w)]),
completion_starts=starts)
torch.testing.assert_close(streamed, reference)
torch.testing.assert_close(torch.autograd.grad(streamed, h)[0],
torch.autograd.grad(reference, h)[0])
def test_causality_and_gradients_for_both_adapter_components(self):
torch.manual_seed(9)
a = LearnableSharingAttention(8, 2, 1, 8, 10000, .25, width=10)