Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 59072884ff | |||
| 1c8943a2e8 |
@@ -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
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -0,0 +1,173 @@
|
||||
"""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):
|
||||
d = int(x.shape[-1] * fraction)
|
||||
inv = theta ** (-torch.arange(0, d, 2, dtype=x.dtype, device=x.device) / d)
|
||||
phase = torch.arange(x.shape[1], dtype=x.dtype, device=x.device)[:, None] * inv
|
||||
angle = torch.cat((phase, phase), dim=-1)[None, :, None, :]
|
||||
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(q, k, v, g, beta):
|
||||
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()
|
||||
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)
|
||||
|
||||
|
||||
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):
|
||||
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')
|
||||
convolved = F.conv1d(projected, kernel, padding=kernel.shape[-1]-1,
|
||||
groups=projected.shape[1])[..., :x.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 = gated_delta(q, k, v, g, beta)
|
||||
return self.linear((self.norm(out, p+'norm', centered=False)*F.silu(gate)).flatten(-2),
|
||||
p+'out_proj')
|
||||
|
||||
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
|
||||
@@ -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,26 @@ 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):
|
||||
"""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)
|
||||
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)
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
# 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. 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)
|
||||
|
||||
## 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.
|
||||
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.
|
||||
@@ -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
@@ -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,49 @@
|
||||
{
|
||||
"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",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
@@ -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'))
|
||||
@@ -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())
|
||||
@@ -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)
|
||||
@@ -0,0 +1,138 @@
|
||||
"""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_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)
|
||||
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)
|
||||
@@ -27,6 +27,22 @@ 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_causality_and_gradients_for_both_adapter_components(self):
|
||||
torch.manual_seed(9)
|
||||
a = LearnableSharingAttention(8, 2, 1, 8, 10000, .25, width=10)
|
||||
|
||||
Reference in New Issue
Block a user