Compare commits

...

13 Commits

Author SHA1 Message Date
codex-bot 0f4c0a982c Verify complete answers from archived generation tokens 2026-11-24 16:34:33 +08:00
codex-bot c53d78b4aa Keep deep sharing generation within host memory guards 2026-11-24 16:12:37 +08:00
codex-bot 453b2ff787 Screen deeper LiSA sharing with complete autoregressive answers 2026-11-24 15:58:43 +08:00
Zayden-Jung 38545d4217 Merge pull request '复现 Qwen3.5-2B 双层 LiSA 的任务与缓存效果' (#13) from codex/lisa-effect-reproduction into main
Reviewed-on: #13
2026-11-23 18:48:15 +00:00
codex-bot 78f3869060 Verify LiSA full-vocabulary results and report scope 2026-11-24 01:39:44 +08:00
codex-bot c2aa23f32f Record LiSA task and CPU performance results 2026-11-24 01:16:08 +08:00
codex-bot 59072884ff Cross-check LiSA held-out metrics across scoring paths 2026-11-24 00:06:58 +08:00
codex-bot 1c8943a2e8 Add controlled two-layer LiSA reproduction on Qwen 2026-11-24 00:00:42 +08:00
Zayden-Jung 115e440455 Merge pull request '复现 Qwen3.5-2B 的可训练 LiSA 注意力共享' (#12) from codex/lisa-full-reproduction into main
Reviewed-on: #12
2026-11-23 09:01:22 +00:00
codex-bot 67327d62d8 Reproduce trainable LiSA attention on Qwen3.5-2B 2026-11-23 16:47:19 +08:00
Zayden-Jung 0df3b0bfe6 Merge pull request '评估 Qwen3.5-2B 注意力共享的线性拟合和无梯度搜索' (#11) from codex/lisa-forward-search into main
Reviewed-on: #11
2026-11-23 07:05:47 +00:00
codex-bot f769de90c6 Evaluate linear and forward-only optimization for attention sharing 2026-11-23 15:01:47 +08:00
Zayden-Jung 5dd3ab32c8 Merge pull request '验证 Qwen3.5-2B 的免训练注意力共享和 LiSA 式轻量校准' (#10) from codex/lisa-attention-pilot into main
Reviewed-on: #10
2026-11-22 14:12:34 +00:00
58 changed files with 22656 additions and 2 deletions
+78
View File
@@ -66,3 +66,81 @@ OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 venv/bin/python -B -m crossqkv.lisa_pil
The diagnostic forward still computes native full Q/K and does not measure
latency or parameter savings. Refer to LiSA (arXiv:2408.01890, §5.1) for its
learned nonlinear head aligner and learned low-rank Q/K projections.
## Forward-only calibration and search
This follow-up keeps the final-layer intervention at 19→23 and changes the
task to generating the latest value of a key. Some prompts contain two
conflicting records for that key. The fit, validation and test splits contain
12, 8 and 16 prompts, respectively. The test set adds longer lists. All
checkpoints and grid settings are selected using validation loss before test
replay. Each prompt's final-query scores, values, gate and residual are captured
from a single native forward. Substitutions replay only the final query of the
last layer and check the native replay against full-prefix activations.
The conditions cover direct sharing, a closed-form linear layer over the donor
heads, a linear layer with a small current-layer Q/K branch, a two-coefficient
diagonal grid, and two forward-only optimizers. The latter each start at
direct sharing and run three fixed seeds. One proposes additive Gaussian
perturbations and keeps improvements. The other proposes a bounded update
from a two-sided directional estimate and applies the same acceptance rule.
These methods fit only the small adapter. The backbone is frozen, and there
is no autograd. Search traces expose forward-call budgets and selected steps.
From the confirmed remote workspace containing the code and retained weights:
```sh
OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 venv/bin/python -B -m crossqkv.forward_search capture \
--source runs/cpu-qwen35-2b --out runs/NEW_SEARCH_CACHE
OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 venv/bin/python -B -m crossqkv.forward_search_fit \
--source runs/cpu-qwen35-2b --cache runs/NEW_SEARCH_CACHE --out runs/NEW_SEARCH_EVAL
```
The main optimization metric is nine-digit NLL. Evaluation also reports
full-vocabulary greedy exact digit at the first answer token, and strata by
list length and duplicate key. Each perturbation reuses fixed lower-layer
activations, so its forward objective computes the exact affected final query
without repeatedly forwarding the whole backbone. For interrupted captures,
`--resume` checks source and code fingerprints and keeps finished batches.
This is a single-site
comparison, not an evaluation of full-model fine-tuning or measured speedup.
## LiSA with the published trainable modules and loss
`lisa_train.py` implements the two-layer 256-unit ReLU head fusion and
learned low-rank grouped Q/K branch. The objective is the published
0.25 Huber (delta 1) attention-score distillation plus 0.75 next-token
full-vocabulary cross-entropy. The loss and gradient stream the frozen
vocabulary head in chunks. This avoids allocating the whole embedding
matrix or retaining dense vocabulary logits across backward.
The Qwen-specific run shares scores from layer 19 at layer 23, using
zero-based numbering. The recipient's V, output gate, projection, MLP
and final norm are preserved and frozen. The low-rank branch uses
40 coordinates per head and Qwen text-mode partial RoPE. Earlier layers
are frozen, and only the final layer is replaced, so training on cached
recipient inputs evaluates the same next-token objective as rerunning
the frozen prefix. The teacher path computes native scores and checks
final hidden states against the original model. The comparison includes
native, direct sharing, and the previous joint linear mapping.
The dataset is the fixed 36-prompt retrieval study with each gold digit
appended as a next-token target. Training uses every valid shifted token
of the fit sequences, and early model selection uses the validation
objective before the test set. The evaluation also measures exact greedy
digit at the answer position. This is a single-recipient port of the method.
The paper's LLaMA configurations, RedPajama training budget, and 13-task
results are separate experimental conditions.
```sh
OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 venv/bin/python -B -m crossqkv.lisa_reproduction capture \
--source runs/cpu-qwen35-2b --out runs/NEW_LISA_FULL_CACHE
OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 venv/bin/python -B -m crossqkv.lisa_reproduction train \
--source runs/cpu-qwen35-2b --cache runs/NEW_LISA_FULL_CACHE --out runs/NEW_LISA_FULL_RESULT \
--linear-control results/lisa-forward-search/frozen.json
```
References: [paper §5 and Appendix C](https://arxiv.org/html/2408.01890v2) and
[authors' implementation](https://github.com/takagi97/lisa). The official
code names its distillation weight `mse_loss_weight` but computes Huber,
consistent with the paper.
+119
View File
@@ -0,0 +1,119 @@
"""Forward-only attention sharing experiments on one frozen Qwen checkpoint."""
import argparse
import hashlib
import json
from pathlib import Path
import random
import numpy as np
from tokenizers import Tokenizer
from crossqkv.lisa_pilot import DONOR, TARGET, Study
from functional.run import write_json
SEEDS = {'fit': 22301, 'validation': 22302, 'test': 22303}
def problems(split):
rng = random.Random(SEEDS[split])
n = {'fit': 12, 'validation': 8, 'test': 16}[split]
words = 'ash elm oak fir yew pine birch cedar maple reed moss fern'.split()
examples = []
for i in range(n):
count = 10 if split == 'test' and i % 4 >= 2 else 6
keys = rng.sample(words, count)
first = rng.randrange(count - 1) if i % 2 else rng.randrange(count)
key = keys[first]
values = [rng.randrange(1, 10) for _ in keys]
if i % 2:
overwritten = rng.randrange(first + 1, count)
keys[overwritten] = key
values[overwritten] = (values[first] - 1 + rng.randrange(1, 9)) % 9 + 1
last = max(j for j, k in enumerate(keys) if k == key)
entries = ', '.join(f'{k}={v}' for k, v in zip(keys, values))
prompt = f'Records (oldest first): {entries}. What is the latest value of {key}? Answer with one digit:'
examples.append({'prompt': prompt, 'gold': values[last], 'entries': count,
'duplicate': bool(i % 2), 'id': f'{split}-{i:02}'})
return examples
def encode(tok, examples):
prompts, labels = [], None
for ex in examples:
rows = [tok.encode(f"{ex['prompt']} {i}", add_special_tokens=False).ids
for i in range(1, 10)]
prefix = rows[0][:-1]
digits = [row[-1] for row in rows]
if any(row[:-1] != prefix for row in rows) or len(set(digits)) != 9:
raise ValueError('Digit answers must share a prefix and differ by one token')
if labels is not None and digits != labels:
raise ValueError('Digit tokens differ between prompts')
prompts.append(prefix)
labels = digits
lengths = np.array([len(row) for row in prompts])
padded = [row + [0] * (max(lengths) - len(row)) for row in prompts]
return np.array(padded, dtype=np.int64), lengths, labels
def collect(source, out, resume=False):
cfg = json.loads((source / 'model_config.json').read_text())
lm = Study(source / 'weights', cfg, seconds=3600)
assert TARGET == len(lm.config['layer_types']) - 1
lm.capture_scores = True
tok = Tokenizer.from_file(str(source / 'tokenizer.json'))
rows = {s: problems(s) for s in SEEDS}
assert len({q['prompt'] for qs in rows.values() for q in qs}) == 36
protocol = {
'donor': DONOR, 'recipient': TARGET, 'seeds': SEEDS,
'capture_code_sha256': hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
'source_files_sha256': {name: hashlib.sha256((source / name).read_bytes()).hexdigest()
for name in ('manifest.json', 'model_config.json', 'tokenizer.json')},
}
for name, content in [('protocol.json', protocol), ('problems.json', rows)]:
path = out / name
if resume and path.exists():
if json.loads(path.read_text()) != content:
raise ValueError(f'Existing capture uses different inputs: {path}')
else:
write_json(path, content)
for split, examples in rows.items():
for start in range(0, len(examples), 4):
group = examples[start:start+4]
ids, lengths, labels = encode(tok, group)
path = out / f'{split}-{start:02}.npz'
if resume and path.is_file():
with np.load(path, allow_pickle=False) as previous:
if (previous['ids'].tolist() != [ex['id'] for ex in group] or
not np.array_equal(previous['lengths'], lengths) or
not np.array_equal(previous['labels'], labels)):
raise ValueError(f'Existing cache batch differs: {path}')
print(f'{split}: reused {start + len(group)}/{len(examples)} prompts', flush=True)
continue
hidden, _ = lm.forward(ids)
row = np.arange(len(group))
at = lengths - 1
recipient = lm.recipient
pending = path.with_suffix('.tmp.npz')
np.savez(pending, ids=[ex['id'] for ex in group],
donor=lm.donor[row, :, at], teacher=lm.teacher[row, :, at],
local=lm.local[row, :, at], values=recipient['v'],
gate=recipient['gate'][row, at], residual=lm.recipient_input[row, at],
hidden=hidden[row, at], lengths=lengths, labels=labels,
gold=[ex['gold']-1 for ex in group])
pending.replace(path)
print(f'{split}: captured {start + len(group)}/{len(examples)} prompts', flush=True)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('phase', choices=('capture',))
parser.add_argument('--source', required=True, type=Path)
parser.add_argument('--out', required=True, type=Path)
parser.add_argument('--resume', action='store_true')
args = parser.parse_args()
args.out.mkdir(exist_ok=args.resume)
collect(args.source, args.out, resume=args.resume)
if __name__ == '__main__':
main()
+249
View File
@@ -0,0 +1,249 @@
"""Fit lightweight attention adapters and compare them on held-out prompts."""
import argparse
import hashlib
import json
from pathlib import Path
import numpy as np
from crossqkv.lisa_pilot import TARGET, solve
from functional.model import PREFIX, norm, sigmoid, silu
from functional.run import write_json
from pilot.tensors import decode, load_tensors
SPLITS = {'fit': 12, 'validation': 8, 'test': 16}
SEARCH_SEEDS = (1701, 1702, 1703)
SEARCH_STEPS = 24
def load_split(root, name):
paths = sorted(root.glob(f'{name}-*.npz'))
if len(paths) * 4 != SPLITS[name]:
raise ValueError(f'Incomplete capture for {name}')
records = []
for path in paths:
with np.load(path, allow_pickle=False) as data:
records.append(dict(data))
if any(not np.array_equal(x['labels'], records[0]['labels']) for x in records):
raise ValueError('Digit token mismatch')
out = {'labels': records[0]['labels']}
for k in records[0].keys() - {'labels'}:
arrays = [r[k] for r in records]
if k in ('donor', 'teacher', 'local', 'values'):
axis = 1 if k == 'values' else 2
width = max(a.shape[axis] for a in arrays)
padded = []
for a in arrays:
pad = [(0, 0)] * a.ndim
pad[axis] = (0, width - a.shape[axis])
padded.append(np.pad(a, pad))
arrays = padded
out[k] = np.concatenate(arrays, axis=0)
return out
class LastLayer:
def __init__(self, source):
cfg = json.loads((source / 'model_config.json').read_text())['text_config']
self.eps = cfg['rms_norm_eps']
self.repeats = cfg['num_attention_heads'] // cfg['num_key_value_heads']
self.tensors = load_tensors(source / 'weights')
layer = f'layers.{TARGET}.'
names = {
'o': layer + 'self_attn.o_proj', 'gate': layer + 'mlp.gate_proj',
'up': layer + 'mlp.up_proj', 'down': layer + 'mlp.down_proj',
'post': layer + 'post_attention_layernorm', 'final': 'norm',
}
self.weights = {}
for key, name in names.items():
t = self.tensors[PREFIX + name + '.weight']
self.weights[key] = t.read().reshape(t.shape)
t.evict()
self.embedding = self.tensors[PREFIX + 'embed_tokens.weight']
def digits(self, labels):
t = self.embedding
out = decode(t.raw.reshape(t.shape)[labels], t.dtype)
t.evict()
return out
def forward(self, batch, scores):
keys = np.arange(scores.shape[-1]) < batch['lengths'][:, None]
x = np.where(keys[:, None, :], scores, -np.inf)
p = np.exp(x - x.max(axis=-1, keepdims=True))
p /= p.sum(axis=-1, keepdims=True)
v = np.repeat(batch['values'], self.repeats, axis=2)
context = np.einsum('bhs,bshd->bhd', p, v)
gated = (context * sigmoid(batch['gate'])).reshape(len(scores), -1)
w = self.weights
h = batch['residual'] + gated @ w['o'].T
n = norm(h, w['post'], self.eps)
return norm(h + (silu(n @ w['gate'].T) * (n @ w['up'].T)) @ w['down'].T,
w['final'], self.eps)
def greedy(self, states):
t = self.embedding
best = np.full(len(states), -np.inf)
tokens = np.zeros(len(states), dtype=int)
cols = np.arange(len(states))
for start in range(0, t.shape[0], 1024):
end = min(start + 1024, t.shape[0])
w = t.read(slice(start*t.shape[1], end*t.shape[1])).reshape(end-start, -1)
logits = states @ w.T
local = logits.argmax(axis=1)
values = logits[cols, local]
better = values > best
tokens[better] = start + local[better]
best[better] = values[better]
t.evict()
return tokens
def features(batch):
return np.concatenate((batch['donor'], batch['local']), axis=1)
def transform(batch, weights):
return np.einsum('bhs,hi->bis', features(batch), weights)
def centered(rows, lengths):
return np.concatenate([(x[:, :n] - x[:, :n].mean(axis=1, keepdims=True)).T
for x, n in zip(rows, lengths)]).astype(np.float64)
def digit_losses(logits, gold):
return np.logaddexp.reduce(logits.astype(np.float64), axis=1) - logits[np.arange(len(gold)), gold]
def candidate_loss(model, batch, weights):
h = model.forward(batch, transform(batch, weights))
return float(digit_losses(h @ model.digits(batch['labels']).T, batch['gold']).mean())
def random_search(loss, validation, start, seed, method):
rng = np.random.default_rng(seed)
current = start.copy()
current_loss = loss(current)
checkpoints = [(validation(current), 0, current.copy())]
trace = []
for step in range(SEARCH_STEPS):
noise = rng.standard_normal(current.shape, dtype=np.float32)
radius = .10 * .5 ** (step // 8)
if method == 'hill':
proposal = current + radius * noise
trial = loss(proposal)
accepted = trial < current_loss
else:
plus = loss(current + .025 * noise)
minus = loss(current - .025 * noise)
# Bounded two-sided directional update. Clip the RMS step per coordinate.
scale = float(np.clip(.03 * (plus - minus) / .05, -radius, radius))
proposal = current - scale * noise
trial = loss(proposal)
accepted = trial < current_loss
if accepted:
current, current_loss = proposal, trial
rec = {'step': step + 1, 'proposal_loss': trial,
'accepted': bool(accepted), 'incumbent_loss': current_loss}
if method != 'hill':
rec.update(plus_loss=plus, minus_loss=minus)
trace.append(rec)
if (step + 1) % 6 == 0:
checkpoints.append((validation(current), step + 1, current.copy()))
val, step, chosen = min(checkpoints, key=lambda item: (item[0], item[1]))
return chosen, {'seed': seed, 'selected_step': step, 'validation_loss': val,
'checkpoints': [{'step': s, 'loss': l} for l, s, _ in checkpoints],
'fit_forward_evaluations': 1 + SEARCH_STEPS * (1 if method == 'hill' else 3),
'trace': trace}
def run(source, cache, out):
protocol = json.loads((cache / 'protocol.json').read_text())
for name, sha in protocol['source_files_sha256'].items():
if hashlib.sha256((source / name).read_bytes()).hexdigest() != sha:
raise ValueError(f'Source provenance mismatch: {name}')
problems = json.loads((cache / 'problems.json').read_text())
model = LastLayer(source)
fit, validation = (load_split(cache, split) for split in ('fit', 'validation'))
for split, batch in [('fit', fit), ('validation', validation)]:
if batch['ids'].tolist() != [ex['id'] for ex in problems[split]]:
raise ValueError(f'Capture order differs for {split}')
heads = fit['donor'].shape[1]
eye = np.eye(heads, dtype=np.float32)
direct = np.concatenate((eye, np.zeros_like(eye)))
q = centered(features(fit), fit['lengths'])
y = centered(fit['teacher'], fit['lengths'])
linear = np.concatenate((solve(q[:, :heads], y), np.zeros_like(eye)))
weights = {'direct': direct, 'linear_donor': linear, 'linear_joint': solve(q, y)}
fit_loss = lambda w: candidate_loss(model, fit, w)
val_loss = lambda w: candidate_loss(model, validation, w)
grid = [(a, b, np.concatenate((a*eye, b*eye)))
for a in (.5, 1., 1.5) for b in (0., .25, .5, 1.)]
grid_scores = [(val_loss(w), a, b, w) for a, b, w in grid]
_, gain, local, weights['diagonal_grid'] = min(grid_scores, key=lambda r: r[0])
optimization = {'grid': [{'donor_gain': a, 'local_gain': b, 'loss': l}
for l, a, b, _ in grid_scores],
'selected_gains': [gain, local], 'searches': {}}
for method in ('hill', 'two_sided'):
for seed in SEARCH_SEEDS:
key = f'{method}_{seed}'
weights[key], optimization['searches'][key] = random_search(
fit_loss, val_loss, direct, seed, method)
print(key, 'selected step', optimization['searches'][key]['selected_step'], flush=True)
validation_scores = {key: val_loss(w) for key, w in weights.items()}
chosen = min(weights, key=validation_scores.get)
write_json(out / 'frozen.json', {'validation_winner': chosen,
'validation_nll': validation_scores, 'optimization': optimization,
'weights': {k: w.tolist() for k, w in weights.items()}})
result = {}
for split in SPLITS:
data = load_split(cache, split)
if data['ids'].tolist() != [ex['id'] for ex in problems[split]]:
raise ValueError(f'Capture order differs for {split}')
native = model.forward(data, data['teacher'])
err = float(np.max(np.abs(native - data['hidden'])))
if not np.allclose(native, data['hidden'], atol=3e-5, rtol=2e-5):
raise AssertionError(f'{split} native full-prefix vs last-query parity failed: {err}')
states = {'native': native, **{k: model.forward(data, transform(data, w))
for k, w in weights.items()}}
modes = list(states)
greedy = np.split(model.greedy(np.concatenate(list(states.values()))), len(states))
labels = data['labels']
gold = data['gold']
result[split] = {}
groups = {}
for i, ex in enumerate(problems[split]):
groups.setdefault(f"{ex['entries']}-entries", []).append(i)
groups.setdefault('duplicate' if ex['duplicate'] else 'unique', []).append(i)
for key, pred in zip(modes, greedy):
logits = states[key] @ model.digits(labels).T
losses = digit_losses(logits, gold)
correct = logits.argmax(axis=1) == gold
exact = pred == labels[gold]
result[split][key] = {'digit_accuracy': int(correct.sum()),
'greedy_exact_digit': int(exact.sum()),
'by_group': {g: {'n': len(ix), 'digit_accuracy': int(correct[ix].sum()),
'greedy_exact_digit': int(exact[ix].sum()),
'digit_nll': float(losses[ix].mean())}
for g, ix in groups.items()},
'n': len(gold), 'digit_nll': float(losses.mean()),
'loss_by_item': losses.tolist(), 'greedy_ids': pred.tolist(),
'digit_logits': logits.tolist()}
print(split, 'native parity max abs', err, flush=True)
write_json(out / 'metrics.json', result)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--source', required=True, type=Path)
parser.add_argument('--cache', required=True, type=Path)
parser.add_argument('--out', required=True, type=Path)
args = parser.parse_args()
args.out.mkdir()
run(args.source, args.cache, args.out)
if __name__ == '__main__':
main()
+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()
+73
View File
@@ -0,0 +1,73 @@
"""Reconstruct complete-answer scores from the saved token streams."""
import argparse
import json
from pathlib import Path
from tokenizers import Tokenizer
from crossqkv.lisa_full_answer import SCHEDULES, fingerprint, grade
from crossqkv.lisa_full_answer_train import audit
from functional.run import write_json
def verify(tokenizer, protocol, expected, rows, arms, allow_prefix=False):
"""Validate each recorded model answer against its frozen prompt and token IDs."""
if not rows or len(rows) > len(expected) or (not allow_prefix and len(rows) != len(expected)):
raise ValueError('Unexpected number of evaluated items')
stop_ids = {tokenizer.token_to_id(text) for text in protocol['stops']}
if None in stop_ids:
raise ValueError('Missing stop token in the frozen tokenizer')
for item, row in zip(expected, rows):
if (row['id'], row['task'], row['gold']) != (item['id'], item['task'], item['answer']):
raise ValueError(f"Unexpected row for {item['id']}")
if set(row['arms']) != set(arms):
raise ValueError(f"Unexpected arms for {item['id']}")
for arm in arms:
stored = row['arms'][arm]
tokens = stored['tokens']
if (not 0 < len(tokens) <= protocol['cap']
or any(type(token) is not int or tokenizer.id_to_token(token) is None
for token in tokens)
or any(token in stop_ids for token in tokens[:-1])):
raise ValueError(f"Invalid generated token stream for {item['id']} / {arm}")
ended = tokens[-1] in stop_ids
if not ended and len(tokens) != protocol['cap']:
raise ValueError(f"Generation ended before a stop or the cap for {item['id']} / {arm}")
score = grade(tokenizer, tokens, 'eos' if ended else 'max_new_tokens', item['answer'])
if stored != score:
raise ValueError(f"Archived score does not match the tokens for {item['id']} / {arm}")
def main():
parser = argparse.ArgumentParser(description=__doc__)
for name in ('tokenizer', 'frozen', 'rows', 'out'):
parser.add_argument('--'+name, required=True, type=Path)
parser.add_argument('--selection', type=Path, help='Verify the selected task on the test split')
parser.add_argument('--allow-screen-prefix', action='store_true')
args = parser.parse_args()
if args.selection and args.allow_screen_prefix:
parser.error('Test verification requires all frozen test rows')
frozen = json.loads(args.frozen.read_bytes())
protocol = frozen['protocol']
if fingerprint(args.tokenizer) != protocol['weights']['tokenizer.json']:
raise ValueError('Tokenizer differs from the frozen experiment')
rows = json.loads(args.rows.read_bytes())
tokenizer = Tokenizer.from_file(str(args.tokenizer))
report = {'frozen_sha256': fingerprint(args.frozen), 'rows_sha256': fingerprint(args.rows),
'rows_verified': len(rows)}
if args.selection:
chosen = json.loads(args.selection.read_bytes())
if chosen['frozen_sha256'] != report['frozen_sha256']:
raise ValueError('Selection points to a different frozen manifest')
expected = [item for item in frozen['problems']['test']
if item['task'] == chosen['chosen']['task']]
verify(tokenizer, protocol, expected, rows, ('native', 'direct', 'lisa'))
report['final_answer_audit'] = audit(rows)
else:
verify(tokenizer, protocol, frozen['problems']['screen'], rows, SCHEDULES,
allow_prefix=args.allow_screen_prefix)
write_json(args.out, report)
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)]
+200
View File
@@ -0,0 +1,200 @@
"""Capture Qwen sequences and train/evaluate the complete last-layer LiSA method."""
import argparse
import hashlib
import json
from pathlib import Path
import numpy as np
from crossqkv.forward_search import encode, problems, SEEDS
from crossqkv.lisa_pilot import DONOR, TARGET, Study
from functional.run import write_json
BATCH = 4
EPOCHS = 8
RANK = 40
def digest(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def capture(source, out):
from tokenizers import Tokenizer
model = Study(source / 'weights', json.loads((source / 'model_config.json').read_text()),
seconds=3600)
if TARGET != len(model.config['layer_types']) - 1:
raise ValueError('Exact cached training requires the final layer as the only recipient')
if any(model.config['layer_types'][i] != 'full_attention' for i in (DONOR, TARGET)):
raise ValueError('Both sites must be full attention layers')
model.capture_scores = True
tokenizer = Tokenizer.from_file(str(source / 'tokenizer.json'))
items = {split: problems(split) for split in SEEDS}
write_json(out / 'problems.json', items)
write_json(out / 'protocol.json', {
'source_sha256': {name: digest(source / name) for name in
('model_config.json', 'manifest.json', 'tokenizer.json')},
'donor': DONOR, 'target': TARGET, 'rank_per_head': RANK, 'epochs': EPOCHS,
'batch_size': BATCH, 'seed': 20261123, 'split_seeds': SEEDS,
'optimizer': 'AdamW', 'learning_rate': .0003, 'weight_decay': .1,
'objective': {'full_vocabulary_next_token_ce': .75, 'huber_delta_1': .25},
})
for split, rows in items.items():
for start in range(0, len(rows), BATCH):
batch = rows[start:start+BATCH]
prefixes, lengths, labels = encode(tokenizer, batch)
ids = np.pad(prefixes, ((0, 0), (0, 1)))
gold = np.array([r['gold'] - 1 for r in batch])
ids[np.arange(len(batch)), lengths] = np.asarray(labels)[gold]
native, saved = model.forward(ids, capture=[('attn', TARGET)])
rec = model.recipient
np.savez(out / f'{split}-{start:02}.npz', ids=ids, lengths=lengths + 1,
labels=labels, gold=gold, native=native, local=model.local,
inp=saved[f'attn_{TARGET}'], donor=model.donor, teacher=model.teacher,
values=rec['v'], gate=rec['gate'], residual=model.recipient_input)
print(split, 'captured', start + len(batch), '/', len(rows), flush=True)
def train(source, cache, out, linear_control):
import torch
from crossqkv.forward_search_fit import LastLayer
from crossqkv.lisa_train import (FrozenRecipient, LearnableSharingAttention, causal_attention,
language_model_loss, objective)
torch.set_num_threads(1)
torch.manual_seed(20261123)
protocol = json.loads((cache / 'protocol.json').read_text())
if any(digest(source / name) != sha for name, sha in protocol['source_sha256'].items()):
raise ValueError('The cache does not match the selected source checkpoint')
cfg = json.loads((source / 'model_config.json').read_text())['text_config']
heads, kv = cfg['num_attention_heads'], cfg['num_key_value_heads']
rp = cfg['rope_parameters']
frozen = LastLayer(source)
recipient = FrozenRecipient(frozen.weights, frozen.eps)
adapter = LearnableSharingAttention(cfg['hidden_size'], heads, kv, RANK,
rp['rope_theta'], rp['partial_rotary_factor'],
bias=cfg.get('attention_bias', False))
optimizer = torch.optim.AdamW(adapter.parameters(), lr=.0003, weight_decay=.1)
t = frozen.embedding
def vocabulary():
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):
for path in sorted(cache.glob(f'{split}-*.npz')):
with np.load(path, allow_pickle=False) as data:
yield {k: torch.from_numpy(data[k]) for k in data.files}
def adapter_scores(b):
return adapter(b['inp'], b['donor'], torch.arange(b['ids'].shape[1])[None, :])
def decode(b, s):
return recipient(causal_attention(s, b['values'], b['lengths']),
b['gate'], b['residual'])
def losses(b, s, h):
ce = language_model_loss(h, b['ids'], b['lengths'], vocabulary)
total, kd = objective(s, b['teacher'], b['lengths'], ce)
return total, ce, kd
def evaluate(split, modes, greedy=False):
totals = {mode: [] for mode in modes}
predictions = {mode: [] for mode in modes}
with torch.no_grad():
for b in batches(split):
answer_at = b['lengths'] - 2
valid = torch.arange(b['ids'].shape[1])[None, :] < b['lengths'][:, None]
states = []
for mode in modes:
if mode == 'native':
s = b['teacher']
elif mode == 'direct':
s = b['donor']
elif mode == 'linear_joint':
s = torch.einsum('bhts,hi->bits', torch.cat((b['donor'], b['local']), 1),
linear_matrix)
else:
s = adapter_scores(b)
h = decode(b, s)
if mode == 'native':
torch.testing.assert_close(h[valid], b['native'][valid], atol=4e-5, rtol=3e-5)
loss = losses(b, s, h)
totals[mode].append((int((b['lengths'] - 1).sum()),
sum(int(n)**2 for n in b['lengths']),
*map(float, loss)))
states.append(h[torch.arange(len(answer_at)), answer_at].numpy())
if greedy:
preds = np.split(frozen.greedy(np.concatenate(states)), len(modes))
labels = b['labels'][b['gold']].numpy()
for mode, pred in zip(modes, preds):
predictions[mode].extend((pred == labels).tolist())
results = {}
for mode, rows in totals.items():
if not rows:
raise ValueError(f'No complete capture batches for {split}')
n = sum(r[0] for r in rows)
pairs = sum(r[1] for r in rows)
ce = sum(r[0] * r[3] for r in rows) / n
kd = sum(r[1] * r[4] for r in rows) / pairs
results[mode] = {'ce': ce, 'huber': kd, 'objective': .75 * ce + .25 * kd,
'tokens': n, 'greedy_correct': sum(predictions[mode]),
'greedy_n': len(predictions[mode])}
return results
linear = json.loads(linear_control.read_text())['weights']['linear_joint']
linear_matrix = torch.tensor(linear, dtype=torch.float32)
trace = []
best = float('inf')
for epoch in range(EPOCHS):
step_losses = []
for batch in batches('fit'):
optimizer.zero_grad(set_to_none=True)
scores = adapter_scores(batch)
loss = losses(batch, scores, decode(batch, scores))
loss[0].backward()
if any(p.grad is None or not torch.isfinite(p.grad).all() for p in adapter.parameters()):
raise FloatingPointError('Invalid adapter gradient')
optimizer.step()
step_losses.append(list(map(lambda x: float(x.detach()), loss)))
validation = evaluate('validation', ('lisa',))['lisa']
trace.append({'epoch': epoch + 1, 'fit_batch_losses': step_losses, 'validation': validation})
if validation['objective'] < best:
best = validation['objective']
torch.save(adapter.state_dict(), out / 'best-adapter.pt')
write_json(out / 'trace.json', trace)
print('epoch', epoch + 1, 'validation', validation, flush=True)
adapter.load_state_dict(torch.load(out / 'best-adapter.pt', map_location='cpu', weights_only=True))
modes = ('native', 'direct', 'linear_joint', 'lisa')
result = {split: evaluate(split, modes, greedy=True) for split in ('validation', 'test')}
result['best_epoch'] = min(trace, key=lambda r: r['validation']['objective'])['epoch']
result['trainable_parameters'] = sum(p.numel() for p in adapter.parameters())
result['linear_control_sha256'] = digest(linear_control)
write_json(out / 'results.json', result)
print(result, flush=True)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('phase', choices=('capture', 'train'))
parser.add_argument('--source', required=True, type=Path)
parser.add_argument('--out', required=True, type=Path)
parser.add_argument('--cache', type=Path)
parser.add_argument('--linear-control', type=Path)
args = parser.parse_args()
if args.phase == 'train' and (args.cache is None or args.linear_control is None):
parser.error('train requires --cache and --linear-control')
args.out.mkdir()
if args.phase == 'capture':
capture(args.source, args.out)
else:
train(args.source, args.cache, args.out, args.linear_control)
if __name__ == '__main__':
main()
+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
+126
View File
@@ -0,0 +1,126 @@
"""Trainable LiSA attention adaptor for the Qwen text reference."""
import math
import torch
from torch import nn
from torch.nn import functional as F
class LearnableSharingAttention(nn.Module):
"""Map low-rank local scores and donor logits to recipient logits."""
def __init__(self, hidden_size, heads, kv_heads, rank, theta, rotary_fraction,
width=256, bias=False):
super().__init__()
rotary_dim = int(rank * rotary_fraction)
if heads % kv_heads or not 0 < rotary_dim <= rank or rotary_dim % 2:
raise ValueError('Expected grouped query heads and a positive even rotary dimension')
self.heads, self.kv_heads, self.rank = heads, kv_heads, rank
self.rotary_dim = rotary_dim
inv_freq = theta ** (-torch.arange(0, rotary_dim, 2, dtype=torch.float32) / rotary_dim)
self.register_buffer('inv_freq', inv_freq, persistent=False)
self.q_proj = nn.Linear(hidden_size, heads * rank, bias=bias)
self.k_proj = nn.Linear(hidden_size, kv_heads * rank, bias=bias)
self.fuse = nn.Sequential(nn.Linear(2 * heads, width, bias=bias), nn.ReLU(),
nn.Linear(width, heads, bias=bias))
def rotate(self, x, position_ids):
phase = position_ids[..., None] * self.inv_freq
angle = torch.cat((phase, phase), dim=-1).unsqueeze(2)
a, b = x[..., :self.rotary_dim].chunk(2, dim=-1)
first = torch.cat((a, b), dim=-1)
rotated = torch.cat((-b, a), dim=-1)
return torch.cat((first * angle.cos() + rotated * angle.sin(),
x[..., self.rotary_dim:]), dim=-1)
def forward(self, hidden, donor, position_ids):
b, t, _ = hidden.shape
q = self.rotate(self.q_proj(hidden).reshape(b, t, self.heads, self.rank), position_ids)
k = self.rotate(self.k_proj(hidden).reshape(b, t, self.kv_heads, self.rank), position_ids)
k = k.repeat_interleave(self.heads // self.kv_heads, dim=2)
delta = torch.einsum('bthd,bshd->btsh', q, k) / math.sqrt(self.rank)
return self.fuse(torch.cat((delta, donor.permute(0, 2, 3, 1)), dim=-1)).permute(0, 3, 1, 2)
def causal_attention(scores, values, lengths):
"""Apply recipient values after causal masking of the fused scores."""
positions = torch.arange(scores.shape[-1], device=scores.device)
valid = positions[None, :] < lengths[:, None]
causal = positions[:, None] >= positions[None, :]
allowed = valid[:, None, None, :] & causal
p = scores.masked_fill(~allowed, -torch.inf).softmax(dim=-1)
repeats = scores.shape[1] // values.shape[2]
return torch.einsum('bhts,bshd->bthd', p, values.repeat_interleave(repeats, dim=2))
def huber_distillation(scores, teacher, lengths):
"""Use raw pre-softmax scores and exclude sequence padding."""
positions = torch.arange(scores.shape[-1], device=scores.device)
valid = positions[None, :] < lengths[:, None]
pairs = valid[:, None, :, None] & valid[:, None, None, :]
return F.huber_loss(scores.masked_select(pairs), teacher.detach().masked_select(pairs),
delta=1.0)
def objective(scores, teacher, lengths, language_model_loss):
kd = huber_distillation(scores, teacher, lengths)
return 0.25 * kd + 0.75 * language_model_loss, kd
class FrozenRecipient(nn.Module):
"""The recipient's unchanged gated output projection, MLP and final norm."""
def __init__(self, weights, eps):
super().__init__()
for key in ('o', 'post', 'gate', 'up', 'down', 'final'):
self.register_buffer('w_' + key, torch.as_tensor(weights[key]).detach())
self.eps = eps
def norm(self, hidden, weight):
return hidden * (hidden.square().mean(dim=-1, keepdim=True) + self.eps).rsqrt() * (1 + weight)
def forward(self, context, gate, residual):
h = residual + F.linear((context * gate.sigmoid()).flatten(-2), self.w_o)
n = self.norm(h, self.w_post)
h = h + F.linear(F.silu(F.linear(n, self.w_gate)) * F.linear(n, self.w_up), self.w_down)
return self.norm(h, self.w_final)
class _FrozenVocabularyCE(torch.autograd.Function):
"""Exact full-vocabulary CE with a streamed frozen head in both passes."""
@staticmethod
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():
logits = F.linear(hidden, w)
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, weights)
ctx.vocabulary = vocabulary
return ((log_total - selected) * weights).sum() / weights.sum()
@staticmethod
def backward(ctx, gradient):
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 * weights[:, None] / weights.sum()), None, None, None
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]
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)
+40
View File
@@ -0,0 +1,40 @@
# 完整答案评估下的 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"
"$PYTHON" -B -m crossqkv.lisa_full_answer_verify --tokenizer "$SOURCE/tokenizer.json" \
--frozen "$SCREEN/frozen.json" --selection "$SCREEN/selection.json" \
--rows "$RESULT/test-items.json" --out "$RESULT/verified-test.json"
```
使用原目录运行相同命令即可续跑。筛选和测试将按已保存的题号继续。训练使用已保存的优化器和训练步。
服务器约有 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
}
}
}
}
+27
View File
@@ -0,0 +1,27 @@
# Qwen3.5-2B 注意力共享的线性拟合与无梯度搜索
保留 Qwen3.5-2B 底座和第 19→23 层的单点干预。检索题要求输出最新的记录值,部分题故意包含同一键的冲突记录。12 道拟合题、8 道验证题、16 道留出题均独立生成。留出含 8 道 10 项表。各方案在测试前冻结,随机搜索的整体候选由验证集 NLL 选出。
| 方法 | 留出全词表首个数字准确数 | 留出九数字 NLL |
| --- | ---: | ---: |
| 原模型 | 1/16 | 1.73505 |
| 原序直接共享 | 1/16 | 1.80085 |
| 供体头的线性拟合 | 1/16 | 1.75648 |
| 供体与接收层 32 个 Q/K 坐标联合拟合 | 1/16 | 1.74997 |
| 两系数网格 | 1/16 | 1.79451 |
| 加噪择优,种子 1701(验证集选中) | 2/16 | 1.72949 |
| 加噪择优,种子 1702 / 1703 | 1/16 / 1/16 | 1.76795 / 1.76090 |
| 双向扰动,种子 1701 / 1702 / 1703 | 均 1/16 | 1.78861 / 1.79510 / 1.79207 |
三个加噪择优种子的平均留出 NLL 为 1.75278,较直接共享低约 0.048。联合线性拟合得 1.74997。验证集选中的加噪种子多答对一道重复键的 6 项表题,另外两个种子未多答对题。所有配置在 10 项表均为 0/8。这组小样本支持加噪和线性修正都能改善相对直接共享的数字排序损失,准确率收益只有单题、单种子的证据。网格选中供体增益 1.5、接收端增益 0。
加噪择优每个种子有 25 次拟合前向,包含起点。双向扰动每种子有 73 次,包含正负扰动及接受判断。另有验证前向。该预算下双向扰动提升较小,两个搜索的前向预算不同。优化只改变小型头混合矩阵,底座权重冻结,无反向传播。闭式线性拟合用原模型内部注意力分数作为目标,不用答题标签。九数字 NLL 只在数字 1–9 上归一化。全词表准确率只检查首个答案 token。
## 验证和复现
- 在已授权的原 Qwen 远程 CPU 运行 12 项检查,全部通过。
- 原模型末层重放与完整前向的最大绝对差分别为拟合 5.25e-6、验证 5.72e-6、留出 7.63e-6。逐题数字 NLL已从归档 logits 独立复算。
- 小型合成检查点还覆盖了抓取、续跑、校准、冻结和评估的端到端流程。
- 完整真实激活缓存保留于服务器,仓库仅保存合成题、模型与代码指纹、适配器及轨迹和评测。未测自由生成整段答案、多层替换或运行时加速。
复现命令见 [crossqkv/README.md](../../crossqkv/README.md)。
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+260
View File
@@ -0,0 +1,260 @@
{
"fit": [
{
"prompt": "Records (oldest first): pine=6, cedar=5, maple=9, moss=5, yew=7, oak=2. What is the latest value of moss? Answer with one digit:",
"gold": 5,
"entries": 6,
"duplicate": false,
"id": "fit-00"
},
{
"prompt": "Records (oldest first): fir=2, maple=1, moss=1, fern=4, fern=1, elm=5. What is the latest value of fern? Answer with one digit:",
"gold": 1,
"entries": 6,
"duplicate": true,
"id": "fit-01"
},
{
"prompt": "Records (oldest first): pine=1, elm=4, ash=2, birch=7, moss=3, fir=4. What is the latest value of moss? Answer with one digit:",
"gold": 3,
"entries": 6,
"duplicate": false,
"id": "fit-02"
},
{
"prompt": "Records (oldest first): cedar=7, pine=8, elm=7, fern=5, yew=1, elm=3. What is the latest value of elm? Answer with one digit:",
"gold": 3,
"entries": 6,
"duplicate": true,
"id": "fit-03"
},
{
"prompt": "Records (oldest first): maple=5, fir=4, elm=4, moss=2, cedar=9, fern=4. What is the latest value of fir? Answer with one digit:",
"gold": 4,
"entries": 6,
"duplicate": false,
"id": "fit-04"
},
{
"prompt": "Records (oldest first): ash=2, ash=1, fir=7, yew=4, cedar=9, maple=9. What is the latest value of ash? Answer with one digit:",
"gold": 1,
"entries": 6,
"duplicate": true,
"id": "fit-05"
},
{
"prompt": "Records (oldest first): yew=4, fir=5, ash=1, elm=3, cedar=1, pine=5. What is the latest value of pine? Answer with one digit:",
"gold": 5,
"entries": 6,
"duplicate": false,
"id": "fit-06"
},
{
"prompt": "Records (oldest first): fern=3, reed=6, cedar=2, moss=1, fir=1, moss=9. What is the latest value of moss? Answer with one digit:",
"gold": 9,
"entries": 6,
"duplicate": true,
"id": "fit-07"
},
{
"prompt": "Records (oldest first): elm=5, reed=4, fern=5, fir=9, moss=9, cedar=6. What is the latest value of reed? Answer with one digit:",
"gold": 4,
"entries": 6,
"duplicate": false,
"id": "fit-08"
},
{
"prompt": "Records (oldest first): fern=8, ash=7, oak=9, maple=2, pine=5, pine=9. What is the latest value of pine? Answer with one digit:",
"gold": 9,
"entries": 6,
"duplicate": true,
"id": "fit-09"
},
{
"prompt": "Records (oldest first): maple=3, fir=1, birch=4, fern=6, yew=9, cedar=6. What is the latest value of fern? Answer with one digit:",
"gold": 6,
"entries": 6,
"duplicate": false,
"id": "fit-10"
},
{
"prompt": "Records (oldest first): yew=5, birch=4, birch=3, fir=8, oak=1, elm=9. What is the latest value of birch? Answer with one digit:",
"gold": 3,
"entries": 6,
"duplicate": true,
"id": "fit-11"
}
],
"validation": [
{
"prompt": "Records (oldest first): ash=7, fern=4, birch=9, yew=8, moss=9, cedar=9. What is the latest value of cedar? Answer with one digit:",
"gold": 9,
"entries": 6,
"duplicate": false,
"id": "validation-00"
},
{
"prompt": "Records (oldest first): fern=2, cedar=6, yew=6, fir=1, elm=8, fern=8. What is the latest value of fern? Answer with one digit:",
"gold": 8,
"entries": 6,
"duplicate": true,
"id": "validation-01"
},
{
"prompt": "Records (oldest first): birch=1, pine=2, yew=5, ash=1, fern=9, fir=3. What is the latest value of ash? Answer with one digit:",
"gold": 1,
"entries": 6,
"duplicate": false,
"id": "validation-02"
},
{
"prompt": "Records (oldest first): reed=6, maple=6, cedar=1, ash=3, yew=8, reed=4. What is the latest value of reed? Answer with one digit:",
"gold": 4,
"entries": 6,
"duplicate": true,
"id": "validation-03"
},
{
"prompt": "Records (oldest first): maple=5, pine=3, fern=7, oak=8, birch=6, yew=2. What is the latest value of oak? Answer with one digit:",
"gold": 8,
"entries": 6,
"duplicate": false,
"id": "validation-04"
},
{
"prompt": "Records (oldest first): cedar=6, birch=6, oak=6, cedar=4, ash=8, elm=6. What is the latest value of cedar? Answer with one digit:",
"gold": 4,
"entries": 6,
"duplicate": true,
"id": "validation-05"
},
{
"prompt": "Records (oldest first): maple=5, yew=5, fir=4, pine=4, elm=6, reed=3. What is the latest value of yew? Answer with one digit:",
"gold": 5,
"entries": 6,
"duplicate": false,
"id": "validation-06"
},
{
"prompt": "Records (oldest first): fir=4, yew=4, moss=4, moss=1, oak=3, reed=4. What is the latest value of moss? Answer with one digit:",
"gold": 1,
"entries": 6,
"duplicate": true,
"id": "validation-07"
}
],
"test": [
{
"prompt": "Records (oldest first): pine=4, ash=1, birch=9, maple=7, fern=6, fir=9. What is the latest value of pine? Answer with one digit:",
"gold": 4,
"entries": 6,
"duplicate": false,
"id": "test-00"
},
{
"prompt": "Records (oldest first): fir=9, pine=5, cedar=8, elm=9, maple=3, elm=8. What is the latest value of elm? Answer with one digit:",
"gold": 8,
"entries": 6,
"duplicate": true,
"id": "test-01"
},
{
"prompt": "Records (oldest first): yew=4, fir=6, maple=1, oak=9, moss=2, reed=2, cedar=4, elm=7, fern=5, pine=3. What is the latest value of reed? Answer with one digit:",
"gold": 2,
"entries": 10,
"duplicate": false,
"id": "test-02"
},
{
"prompt": "Records (oldest first): moss=5, ash=4, pine=6, reed=4, cedar=7, oak=7, elm=6, birch=8, fir=6, ash=6. What is the latest value of ash? Answer with one digit:",
"gold": 6,
"entries": 10,
"duplicate": true,
"id": "test-03"
},
{
"prompt": "Records (oldest first): maple=9, elm=7, oak=7, pine=5, reed=4, cedar=8. What is the latest value of elm? Answer with one digit:",
"gold": 7,
"entries": 6,
"duplicate": false,
"id": "test-04"
},
{
"prompt": "Records (oldest first): ash=7, fir=4, pine=5, fern=8, fern=9, oak=7. What is the latest value of fern? Answer with one digit:",
"gold": 9,
"entries": 6,
"duplicate": true,
"id": "test-05"
},
{
"prompt": "Records (oldest first): elm=5, reed=9, oak=4, yew=8, cedar=1, fir=1, ash=4, maple=5, fern=3, pine=7. What is the latest value of elm? Answer with one digit:",
"gold": 5,
"entries": 10,
"duplicate": false,
"id": "test-06"
},
{
"prompt": "Records (oldest first): moss=8, ash=7, pine=7, reed=7, yew=3, birch=4, elm=9, maple=3, ash=6, fir=9. What is the latest value of ash? Answer with one digit:",
"gold": 6,
"entries": 10,
"duplicate": true,
"id": "test-07"
},
{
"prompt": "Records (oldest first): birch=5, elm=9, yew=9, ash=3, cedar=9, reed=9. What is the latest value of yew? Answer with one digit:",
"gold": 9,
"entries": 6,
"duplicate": false,
"id": "test-08"
},
{
"prompt": "Records (oldest first): maple=7, yew=6, birch=3, reed=8, ash=6, maple=2. What is the latest value of maple? Answer with one digit:",
"gold": 2,
"entries": 6,
"duplicate": true,
"id": "test-09"
},
{
"prompt": "Records (oldest first): ash=9, cedar=3, maple=5, fern=4, oak=2, reed=3, birch=7, pine=5, moss=3, elm=6. What is the latest value of elm? Answer with one digit:",
"gold": 6,
"entries": 10,
"duplicate": false,
"id": "test-10"
},
{
"prompt": "Records (oldest first): elm=2, birch=3, moss=6, oak=2, fir=5, pine=9, yew=2, pine=2, cedar=7, fern=2. What is the latest value of pine? Answer with one digit:",
"gold": 2,
"entries": 10,
"duplicate": true,
"id": "test-11"
},
{
"prompt": "Records (oldest first): yew=2, pine=2, fir=2, elm=3, moss=4, reed=9. What is the latest value of yew? Answer with one digit:",
"gold": 2,
"entries": 6,
"duplicate": false,
"id": "test-12"
},
{
"prompt": "Records (oldest first): maple=8, birch=9, birch=2, oak=1, moss=8, cedar=2. What is the latest value of birch? Answer with one digit:",
"gold": 2,
"entries": 6,
"duplicate": true,
"id": "test-13"
},
{
"prompt": "Records (oldest first): fern=2, pine=4, maple=3, yew=4, ash=8, reed=1, birch=3, fir=5, elm=6, cedar=2. What is the latest value of birch? Answer with one digit:",
"gold": 3,
"entries": 10,
"duplicate": false,
"id": "test-14"
},
{
"prompt": "Records (oldest first): birch=7, yew=4, elm=5, cedar=3, pine=1, oak=8, fern=3, ash=7, reed=1, ash=8. What is the latest value of ash? Answer with one digit:",
"gold": 8,
"entries": 10,
"duplicate": true,
"id": "test-15"
}
]
}
+15
View File
@@ -0,0 +1,15 @@
{
"donor": 19,
"recipient": 23,
"seeds": {
"fit": 22301,
"validation": 22302,
"test": 22303
},
"capture_code_sha256": "5b9d218fccf1bb9c64a27425e37f2f7abe58164083b3e0fbdc699ede3f9ab7fd",
"source_files_sha256": {
"manifest.json": "28efbaf94a5034333339a35f08ead151459a7d20c6c2d2f07a451e7f3bf154de",
"model_config.json": "ed1c1723241f23f7f4e23430759cbd7dcfb4103cbdfe052bfe7626b57c2615b4",
"tokenizer.json": "5f9e4d4901a92b997e463c1f46055088b6cca5ca61a6522d1b9f64c4bb81cb42"
}
}
@@ -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
@@ -0,0 +1,94 @@
[
{
"id": "screen-lookup-000",
"task": "lookup",
"gold": 82,
"arms": {
"native": {
"tokens": [
23,
17,
248046
],
"response": "82<|im_end|>",
"stop": "eos",
"answer": 82,
"correct": true
},
"direct_3": {
"tokens": [
20,
248044
],
"response": "5<|endoftext|>",
"stop": "eos",
"answer": 5,
"correct": false
},
"direct_4": {
"tokens": [
16,
16,
16,
16,
16,
16,
16,
16,
16,
16,
16,
16,
16,
16,
16,
16,
16,
16,
16,
16,
16,
16,
16,
16
],
"response": "111111111111111111111111",
"stop": "max_new_tokens",
"answer": null,
"correct": false
},
"direct_5": {
"tokens": [
1206,
1423,
279,
4087,
11,
1042,
579,
1353,
506,
279,
1103,
314,
4947,
488,
3766,
25,
271,
332,
16,
13,
220,
16,
332,
198
],
"response": "To find the answer, let's look at the list of numbers you provided:\n\n**1. 1**\n",
"stop": "max_new_tokens",
"answer": null,
"correct": false
}
}
}
]
@@ -0,0 +1,5 @@
{
"frozen_sha256": "409cadff8b2ef2f0efcfa71bf0a94802391a341ed04cb6e374154b8b8ff1b545",
"rows_sha256": "630c27e010ac00677bd2e7a280f17e9076c802c245f4857ec8f6795418e00c3d",
"rows_verified": 1
}
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
}
+22
View File
@@ -0,0 +1,22 @@
# Qwen3.5-2B 单层 LiSA 方法复现
在冻结的 Qwen3.5-2B 上将实际第 19 层注意力 logits 共享给第 23 层。新增可学习的低秩 Q/K(每头 40 维)和 256 单元双层 ReLU 头融合。保持接收层的 V、gate、O、MLP 与归一化不变。使用官方实现的联合目标,0.25 × Huber(delta=1)注意力蒸馏和 0.75 × 全词表下一 token 交叉熵。对新增的 825,344 个参数执行反向传播和 AdamW。
| 方法 | 留出全词表 CE ↓ | 困惑度 ↓ | 首个答案 token 正确 |
| --- | ---: | ---: | ---: |
| 原模型 | 2.9298 | 18.72 | 1/16 |
| 直接共享 | 3.1380 | 23.06 | 1/16 |
| 上轮联合线性拟合 | 2.9601 | 19.30 | 1/16 |
| LiSA | 2.8605 | 17.47 | 1/16 |
留出损失覆盖 868 个有效下一 token 目标,包括题目文本以及答案。LiSA 将相对直接共享的 CE 降低约 0.278,也略低于原模型。四组均只答对一道,整段语言建模损失的改善未体现为答题准确率提升。
## 训练、验证和范围
- 使用与上一轮完全相同的 36 道合成题,按 12/8/16 划分拟合、验证和留出。训练 8 轮、24 次更新。按验证联合损失选择第 8 轮。
- 第 1 到第 8 轮的验证 Huber 从 6.0394 降至 0.9594,CE 从 3.2446 降至 3.1057。最终验证 CE 的同题原模型对照是 3.1723。混合目标的下降主要来自蒸馏项,困惑度只用 CE 计算。
- 远程两项数值检查通过。分块全词表 CE 和输入梯度与密集计算一致,因果遮罩和两个新增组件的梯度均已验证。真实前向评估中,原样重放与原模型的有效位置隐藏状态一致性检查通过。
- 这是 Qwen 混合架构上的单接收层方法复现。论文的 LLaMA 多层设置、42 亿训练 token、13 项基准、推理吞吐及 KV 缓存节省未重跑。
- 冻结检查点保存在原 CPU 服务器的 `/opt/exp-model-parameter-similarity/runs/lisa-full-results-20261123/best-adapter.pt`,SHA256 为 `91e8ab434581f9de3ee6ffa0cfdc17ff7f770563916a43839fb5bce4bcde74ae`。Git 归档可复现代码、训练轨迹、题目与统计,激活缓存和权重保留在服务器。
复现命令见 [crossqkv/README.md](../../crossqkv/README.md)。
@@ -0,0 +1,260 @@
{
"fit": [
{
"prompt": "Records (oldest first): pine=6, cedar=5, maple=9, moss=5, yew=7, oak=2. What is the latest value of moss? Answer with one digit:",
"gold": 5,
"entries": 6,
"duplicate": false,
"id": "fit-00"
},
{
"prompt": "Records (oldest first): fir=2, maple=1, moss=1, fern=4, fern=1, elm=5. What is the latest value of fern? Answer with one digit:",
"gold": 1,
"entries": 6,
"duplicate": true,
"id": "fit-01"
},
{
"prompt": "Records (oldest first): pine=1, elm=4, ash=2, birch=7, moss=3, fir=4. What is the latest value of moss? Answer with one digit:",
"gold": 3,
"entries": 6,
"duplicate": false,
"id": "fit-02"
},
{
"prompt": "Records (oldest first): cedar=7, pine=8, elm=7, fern=5, yew=1, elm=3. What is the latest value of elm? Answer with one digit:",
"gold": 3,
"entries": 6,
"duplicate": true,
"id": "fit-03"
},
{
"prompt": "Records (oldest first): maple=5, fir=4, elm=4, moss=2, cedar=9, fern=4. What is the latest value of fir? Answer with one digit:",
"gold": 4,
"entries": 6,
"duplicate": false,
"id": "fit-04"
},
{
"prompt": "Records (oldest first): ash=2, ash=1, fir=7, yew=4, cedar=9, maple=9. What is the latest value of ash? Answer with one digit:",
"gold": 1,
"entries": 6,
"duplicate": true,
"id": "fit-05"
},
{
"prompt": "Records (oldest first): yew=4, fir=5, ash=1, elm=3, cedar=1, pine=5. What is the latest value of pine? Answer with one digit:",
"gold": 5,
"entries": 6,
"duplicate": false,
"id": "fit-06"
},
{
"prompt": "Records (oldest first): fern=3, reed=6, cedar=2, moss=1, fir=1, moss=9. What is the latest value of moss? Answer with one digit:",
"gold": 9,
"entries": 6,
"duplicate": true,
"id": "fit-07"
},
{
"prompt": "Records (oldest first): elm=5, reed=4, fern=5, fir=9, moss=9, cedar=6. What is the latest value of reed? Answer with one digit:",
"gold": 4,
"entries": 6,
"duplicate": false,
"id": "fit-08"
},
{
"prompt": "Records (oldest first): fern=8, ash=7, oak=9, maple=2, pine=5, pine=9. What is the latest value of pine? Answer with one digit:",
"gold": 9,
"entries": 6,
"duplicate": true,
"id": "fit-09"
},
{
"prompt": "Records (oldest first): maple=3, fir=1, birch=4, fern=6, yew=9, cedar=6. What is the latest value of fern? Answer with one digit:",
"gold": 6,
"entries": 6,
"duplicate": false,
"id": "fit-10"
},
{
"prompt": "Records (oldest first): yew=5, birch=4, birch=3, fir=8, oak=1, elm=9. What is the latest value of birch? Answer with one digit:",
"gold": 3,
"entries": 6,
"duplicate": true,
"id": "fit-11"
}
],
"validation": [
{
"prompt": "Records (oldest first): ash=7, fern=4, birch=9, yew=8, moss=9, cedar=9. What is the latest value of cedar? Answer with one digit:",
"gold": 9,
"entries": 6,
"duplicate": false,
"id": "validation-00"
},
{
"prompt": "Records (oldest first): fern=2, cedar=6, yew=6, fir=1, elm=8, fern=8. What is the latest value of fern? Answer with one digit:",
"gold": 8,
"entries": 6,
"duplicate": true,
"id": "validation-01"
},
{
"prompt": "Records (oldest first): birch=1, pine=2, yew=5, ash=1, fern=9, fir=3. What is the latest value of ash? Answer with one digit:",
"gold": 1,
"entries": 6,
"duplicate": false,
"id": "validation-02"
},
{
"prompt": "Records (oldest first): reed=6, maple=6, cedar=1, ash=3, yew=8, reed=4. What is the latest value of reed? Answer with one digit:",
"gold": 4,
"entries": 6,
"duplicate": true,
"id": "validation-03"
},
{
"prompt": "Records (oldest first): maple=5, pine=3, fern=7, oak=8, birch=6, yew=2. What is the latest value of oak? Answer with one digit:",
"gold": 8,
"entries": 6,
"duplicate": false,
"id": "validation-04"
},
{
"prompt": "Records (oldest first): cedar=6, birch=6, oak=6, cedar=4, ash=8, elm=6. What is the latest value of cedar? Answer with one digit:",
"gold": 4,
"entries": 6,
"duplicate": true,
"id": "validation-05"
},
{
"prompt": "Records (oldest first): maple=5, yew=5, fir=4, pine=4, elm=6, reed=3. What is the latest value of yew? Answer with one digit:",
"gold": 5,
"entries": 6,
"duplicate": false,
"id": "validation-06"
},
{
"prompt": "Records (oldest first): fir=4, yew=4, moss=4, moss=1, oak=3, reed=4. What is the latest value of moss? Answer with one digit:",
"gold": 1,
"entries": 6,
"duplicate": true,
"id": "validation-07"
}
],
"test": [
{
"prompt": "Records (oldest first): pine=4, ash=1, birch=9, maple=7, fern=6, fir=9. What is the latest value of pine? Answer with one digit:",
"gold": 4,
"entries": 6,
"duplicate": false,
"id": "test-00"
},
{
"prompt": "Records (oldest first): fir=9, pine=5, cedar=8, elm=9, maple=3, elm=8. What is the latest value of elm? Answer with one digit:",
"gold": 8,
"entries": 6,
"duplicate": true,
"id": "test-01"
},
{
"prompt": "Records (oldest first): yew=4, fir=6, maple=1, oak=9, moss=2, reed=2, cedar=4, elm=7, fern=5, pine=3. What is the latest value of reed? Answer with one digit:",
"gold": 2,
"entries": 10,
"duplicate": false,
"id": "test-02"
},
{
"prompt": "Records (oldest first): moss=5, ash=4, pine=6, reed=4, cedar=7, oak=7, elm=6, birch=8, fir=6, ash=6. What is the latest value of ash? Answer with one digit:",
"gold": 6,
"entries": 10,
"duplicate": true,
"id": "test-03"
},
{
"prompt": "Records (oldest first): maple=9, elm=7, oak=7, pine=5, reed=4, cedar=8. What is the latest value of elm? Answer with one digit:",
"gold": 7,
"entries": 6,
"duplicate": false,
"id": "test-04"
},
{
"prompt": "Records (oldest first): ash=7, fir=4, pine=5, fern=8, fern=9, oak=7. What is the latest value of fern? Answer with one digit:",
"gold": 9,
"entries": 6,
"duplicate": true,
"id": "test-05"
},
{
"prompt": "Records (oldest first): elm=5, reed=9, oak=4, yew=8, cedar=1, fir=1, ash=4, maple=5, fern=3, pine=7. What is the latest value of elm? Answer with one digit:",
"gold": 5,
"entries": 10,
"duplicate": false,
"id": "test-06"
},
{
"prompt": "Records (oldest first): moss=8, ash=7, pine=7, reed=7, yew=3, birch=4, elm=9, maple=3, ash=6, fir=9. What is the latest value of ash? Answer with one digit:",
"gold": 6,
"entries": 10,
"duplicate": true,
"id": "test-07"
},
{
"prompt": "Records (oldest first): birch=5, elm=9, yew=9, ash=3, cedar=9, reed=9. What is the latest value of yew? Answer with one digit:",
"gold": 9,
"entries": 6,
"duplicate": false,
"id": "test-08"
},
{
"prompt": "Records (oldest first): maple=7, yew=6, birch=3, reed=8, ash=6, maple=2. What is the latest value of maple? Answer with one digit:",
"gold": 2,
"entries": 6,
"duplicate": true,
"id": "test-09"
},
{
"prompt": "Records (oldest first): ash=9, cedar=3, maple=5, fern=4, oak=2, reed=3, birch=7, pine=5, moss=3, elm=6. What is the latest value of elm? Answer with one digit:",
"gold": 6,
"entries": 10,
"duplicate": false,
"id": "test-10"
},
{
"prompt": "Records (oldest first): elm=2, birch=3, moss=6, oak=2, fir=5, pine=9, yew=2, pine=2, cedar=7, fern=2. What is the latest value of pine? Answer with one digit:",
"gold": 2,
"entries": 10,
"duplicate": true,
"id": "test-11"
},
{
"prompt": "Records (oldest first): yew=2, pine=2, fir=2, elm=3, moss=4, reed=9. What is the latest value of yew? Answer with one digit:",
"gold": 2,
"entries": 6,
"duplicate": false,
"id": "test-12"
},
{
"prompt": "Records (oldest first): maple=8, birch=9, birch=2, oak=1, moss=8, cedar=2. What is the latest value of birch? Answer with one digit:",
"gold": 2,
"entries": 6,
"duplicate": true,
"id": "test-13"
},
{
"prompt": "Records (oldest first): fern=2, pine=4, maple=3, yew=4, ash=8, reed=1, birch=3, fir=5, elm=6, cedar=2. What is the latest value of birch? Answer with one digit:",
"gold": 3,
"entries": 10,
"duplicate": false,
"id": "test-14"
},
{
"prompt": "Records (oldest first): birch=7, yew=4, elm=5, cedar=3, pine=1, oak=8, fern=3, ash=7, reed=1, ash=8. What is the latest value of ash? Answer with one digit:",
"gold": 8,
"entries": 10,
"duplicate": true,
"id": "test-15"
}
]
}
@@ -0,0 +1,25 @@
{
"source_sha256": {
"model_config.json": "ed1c1723241f23f7f4e23430759cbd7dcfb4103cbdfe052bfe7626b57c2615b4",
"manifest.json": "28efbaf94a5034333339a35f08ead151459a7d20c6c2d2f07a451e7f3bf154de",
"tokenizer.json": "5f9e4d4901a92b997e463c1f46055088b6cca5ca61a6522d1b9f64c4bb81cb42"
},
"donor": 19,
"target": 23,
"rank_per_head": 40,
"epochs": 8,
"batch_size": 4,
"seed": 20261123,
"split_seeds": {
"fit": 22301,
"validation": 22302,
"test": 22303
},
"optimizer": "AdamW",
"learning_rate": 0.0003,
"weight_decay": 0.1,
"objective": {
"full_vocabulary_next_token_ce": 0.75,
"huber_delta_1": 0.25
}
}
@@ -0,0 +1,73 @@
{
"validation": {
"native": {
"ce": 3.1722529108931377,
"huber": 0.0,
"objective": 2.3791896831698534,
"tokens": 369,
"greedy_correct": 3,
"greedy_n": 8
},
"direct": {
"ce": 3.3412215412470707,
"huber": 1.3496817071496994,
"objective": 2.8433365827227277,
"tokens": 369,
"greedy_correct": 3,
"greedy_n": 8
},
"linear_joint": {
"ce": 3.2096430021249827,
"huber": 1.3686958207991813,
"objective": 2.749406206793532,
"tokens": 369,
"greedy_correct": 2,
"greedy_n": 8
},
"lisa": {
"ce": 3.1057116765639967,
"huber": 0.9593932409738036,
"objective": 2.569132067666448,
"tokens": 369,
"greedy_correct": 3,
"greedy_n": 8
}
},
"test": {
"native": {
"ce": 2.9298480589818294,
"huber": 0.0,
"objective": 2.197386044236372,
"tokens": 868,
"greedy_correct": 1,
"greedy_n": 16
},
"direct": {
"ce": 3.138041972289986,
"huber": 1.358337819454631,
"objective": 2.6931159340811472,
"tokens": 868,
"greedy_correct": 1,
"greedy_n": 16
},
"linear_joint": {
"ce": 2.9600665113343623,
"huber": 1.414523463154858,
"objective": 2.573680749289486,
"tokens": 868,
"greedy_correct": 1,
"greedy_n": 16
},
"lisa": {
"ce": 2.860453250221393,
"huber": 0.9796017867318627,
"objective": 2.3902403843490103,
"tokens": 868,
"greedy_correct": 1,
"greedy_n": 16
}
},
"best_epoch": 8,
"trainable_parameters": 825344,
"linear_control_sha256": "38861f80bbf5c787ab3bcc5a2825167fdc504a432c04656250d205a742723305"
}
+226
View File
@@ -0,0 +1,226 @@
[
{
"epoch": 1,
"fit_batch_losses": [
[
4.240320205688477,
3.3694403171539307,
6.852958679199219
],
[
4.238736152648926,
3.441174030303955,
6.63142204284668
],
[
4.0119500160217285,
3.22914981842041,
6.360350131988525
]
],
"validation": {
"ce": 3.244636496231162,
"huber": 6.039419658543698,
"objective": 3.9433322868092957,
"tokens": 369,
"greedy_correct": 0,
"greedy_n": 0
}
},
{
"epoch": 2,
"fit_batch_losses": [
[
4.002936363220215,
3.331604242324829,
6.016933441162109
],
[
3.945413112640381,
3.3933796882629395,
5.601512908935547
],
[
3.6650333404541016,
3.191150188446045,
5.08668327331543
]
],
"validation": {
"ce": 3.2106871456311645,
"huber": 4.549601500568102,
"objective": 3.545415734365399,
"tokens": 369,
"greedy_correct": 0,
"greedy_n": 0
}
},
{
"epoch": 3,
"fit_batch_losses": [
[
3.5972979068756104,
3.294156312942505,
4.506722450256348
],
[
3.517723321914673,
3.362154722213745,
3.9844295978546143
],
[
3.265709400177002,
3.1815831661224365,
3.518087863922119
]
],
"validation": {
"ce": 3.206055250917347,
"huber": 3.1522311060280925,
"objective": 3.1925992146950337,
"tokens": 369,
"greedy_correct": 0,
"greedy_n": 0
}
},
{
"epoch": 4,
"fit_batch_losses": [
[
3.245277166366577,
3.2835733890533447,
3.1303882598876953
],
[
3.230419635772705,
3.3477752208709717,
2.8783535957336426
],
[
3.0425515174865723,
3.1663742065429688,
2.671083450317383
]
],
"validation": {
"ce": 3.1862243559302352,
"huber": 2.37091732447708,
"objective": 2.9823975980669464,
"tokens": 369,
"greedy_correct": 0,
"greedy_n": 0
}
},
{
"epoch": 5,
"fit_batch_losses": [
[
3.0486488342285156,
3.2668204307556152,
2.394134521484375
],
[
2.9993457794189453,
3.3244380950927734,
2.024068832397461
],
[
2.7900328636169434,
3.149345636367798,
1.7120943069458008
]
],
"validation": {
"ce": 3.17030225859748,
"huber": 1.4550986285551193,
"objective": 2.7415013510868893,
"tokens": 369,
"greedy_correct": 0,
"greedy_n": 0
}
},
{
"epoch": 6,
"fit_batch_losses": [
[
2.8061752319335938,
3.25311279296875,
1.4653630256652832
],
[
2.80643892288208,
3.3129684925079346,
1.2868504524230957
],
[
2.657257080078125,
3.1405460834503174,
1.207390308380127
]
],
"validation": {
"ce": 3.1583746939816773,
"huber": 1.162790216028888,
"objective": 2.65947857449348,
"tokens": 369,
"greedy_correct": 0,
"greedy_n": 0
}
},
{
"epoch": 7,
"fit_batch_losses": [
[
2.7146036624908447,
3.2380752563476562,
1.1441890001296997
],
[
2.7471532821655273,
3.2967944145202637,
1.0982303619384766
],
[
2.6067111492156982,
3.11966609954834,
1.0678465366363525
]
],
"validation": {
"ce": 3.13518099410101,
"huber": 1.0293640556892425,
"objective": 2.6087267594980683,
"tokens": 369,
"greedy_correct": 0,
"greedy_n": 0
}
},
{
"epoch": 8,
"fit_batch_losses": [
[
2.6548426151275635,
3.2067410945892334,
0.9991476535797119
],
[
2.6914961338043213,
3.2658684253692627,
0.9683787822723389
],
[
2.5550029277801514,
3.083840847015381,
0.9684897661209106
]
],
"validation": {
"ce": 3.1057116765639967,
"huber": 0.9593932409738036,
"objective": 2.569132067666448,
"tokens": 369,
"greedy_correct": 0,
"greedy_n": 0
}
}
]
+133
View File
@@ -0,0 +1,133 @@
"""Array-level controls for last-query replay and proposal acceptance."""
import json
from pathlib import Path
import struct
from tempfile import TemporaryDirectory
import unittest
from unittest.mock import patch
import numpy as np
from tokenizers import Tokenizer
from tokenizers.models import WordLevel
from tokenizers.pre_tokenizers import Whitespace
from crossqkv.forward_search import collect, problems
from crossqkv.forward_search_fit import LastLayer, random_search, run, SEARCH_STEPS
from functional.model import PREFIX, StreamingLM, attention, norm, sigmoid, silu
class ForwardSearchTests(unittest.TestCase):
def test_last_query_matches_full_causal_attention_and_mlp(self):
rng = np.random.default_rng(4)
def rand(*shape):
return rng.standard_normal(shape, dtype=np.float32) * .4
batch, seq, heads, width, hidden = 2, 6, 4, 2, 5
q = rand(batch, seq, heads, width)
k, v = [rand(batch, seq, heads // 2, width) for _ in range(2)]
gate, raw = rand(batch, seq, heads, width), rand(batch, seq, hidden)
model = LastLayer.__new__(LastLayer)
model.repeats, model.eps = 2, 1e-6
w = model.weights = {'o': rand(hidden, heads*width), 'post': rand(hidden),
'gate': rand(7, hidden), 'up': rand(7, hidden),
'down': rand(hidden, 7), 'final': rand(hidden)}
context, _ = attention(q, k, v)
h = raw + (context * sigmoid(gate)).reshape(batch, seq, -1) @ w['o'].T
n = norm(h, w['post'])
reference = norm(h + (silu(n @ w['gate'].T) * (n @ w['up'].T)) @ w['down'].T,
w['final'])
lengths = np.array([3, 6])
examples = np.arange(batch)
last = lengths - 1
scores = np.einsum('bhd,bshd->bhs', q[examples, last], np.repeat(k, 2, axis=2))
actual = model.forward({'lengths': lengths, 'gate': gate[examples, last],
'residual': raw[examples, last], 'values': v},
scores / np.float32(np.sqrt(width)))
np.testing.assert_allclose(actual, reference[examples, last], atol=1e-6, rtol=1e-6)
def test_search_respects_validation_and_improves_incumbent(self):
def loss(x):
return float(np.sum((x - .4) ** 2))
for method, cost in (('hill', 1), ('two_sided', 3)):
selected, rec = random_search(loss, loss, np.zeros((3, 3), np.float32),
1701, method)
incumbent = [loss(np.zeros((3, 3), np.float32))]
incumbent.extend(x['incumbent_loss'] for x in rec['trace'])
self.assertTrue(all(a >= b for a, b in zip(incumbent, incumbent[1:])))
self.assertLess(loss(selected), incumbent[0])
self.assertEqual(rec['fit_forward_evaluations'], 1 + SEARCH_STEPS * cost)
self.assertAlmostEqual(loss(selected), min(x['loss'] for x in rec['checkpoints']))
def test_task_labels_are_latest_values_and_splits_are_disjoint(self):
all_prompts = set()
for split in ('fit', 'validation', 'test'):
for row in problems(split):
prompt = row['prompt']
self.assertNotIn(prompt, all_prompts)
all_prompts.add(prompt)
records, suffix = prompt.split('. What is the latest value of ')
key = suffix.split('?')[0]
pairs = [x.split('=') for x in records.rsplit(': ', 1)[1].split(', ')]
matches = [int(value) for name, value in pairs if name == key]
self.assertEqual(len(matches), 2 if row['duplicate'] else 1)
self.assertEqual(matches[-1], row['gold'])
if row['duplicate']:
self.assertNotEqual(matches[0], matches[-1])
def test_capture_to_frozen_evaluation_on_tiny_checkpoint(self):
rng = np.random.default_rng(7)
with TemporaryDirectory() as temp:
root = Path(temp)
weights = root / 'weights'
weights.mkdir()
cfg = {'rms_norm_eps': 1e-6, 'num_attention_heads': 2,
'num_key_value_heads': 1, 'head_dim': 32,
'rope_parameters': {'rope_theta': 10000, 'partial_rotary_factor': .25},
'layer_types': ['full_attention'] * 24}
(root / 'model_config.json').write_text(json.dumps({'text_config': cfg}))
(root / 'manifest.json').write_text('{}\n')
tok = Tokenizer(WordLevel({'[UNK]': 0, **{str(i): i for i in range(1, 10)}},
unk_token='[UNK]'))
tok.pre_tokenizer = Whitespace()
tok.save(str(root / 'tokenizer.json'))
shapes = {'embed_tokens.weight': (10, 8), 'norm.weight': (8,)}
for layer in range(24):
for name, shape in {
'input_layernorm': (8,), 'post_attention_layernorm': (8,),
'self_attn.q_proj': (128, 8), 'self_attn.k_proj': (32, 8),
'self_attn.v_proj': (32, 8), 'self_attn.o_proj': (8, 64),
'self_attn.q_norm': (32,), 'self_attn.k_norm': (32,),
'mlp.gate_proj': (12, 8), 'mlp.up_proj': (12, 8),
'mlp.down_proj': (8, 12),
}.items():
shapes[f'layers.{layer}.{name}.weight'] = shape
header, chunks, offset = {}, [], 0
for name, shape in shapes.items():
raw = (rng.standard_normal(shape, dtype=np.float32) * .1).astype('<f4').tobytes()
header[PREFIX + name] = {'shape': shape, 'dtype': 'F32',
'data_offsets': [offset, offset + len(raw)]}
chunks.append(raw)
offset += len(raw)
metadata = json.dumps(header).encode()
(weights / 'tiny.safetensors').write_bytes(
struct.pack('<Q', len(metadata)) + metadata + b''.join(chunks))
cache, out = root / 'capture', root / 'evaluation'
cache.mkdir()
out.mkdir()
# Skip only Linux procfs monitoring for this local synthetic fixture.
with patch.object(StreamingLM, 'guard'), patch('builtins.print'):
collect(root, cache)
with patch.object(StreamingLM, 'forward', side_effect=AssertionError('cached')):
collect(root, cache, resume=True)
run(root, cache, out)
frozen = json.loads((out / 'frozen.json').read_text())
metrics = json.loads((out / 'metrics.json').read_text())
self.assertEqual(len(frozen['optimization']['searches']), 6)
self.assertEqual(set(metrics['test']), {'native'} | frozen['weights'].keys())
self.assertEqual(metrics['test']['native']['n'], 16)
self.assertIn(frozen['validation_winner'], metrics['test'])
+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)
+94
View File
@@ -0,0 +1,94 @@
"""Numerical checks for the exact CE and differentiable LiSA path."""
import unittest
import torch
from torch.nn import functional as F
from crossqkv.lisa_train import (FrozenRecipient, LearnableSharingAttention,
causal_attention, language_model_loss, objective)
class LiSATrainingTests(unittest.TestCase):
def test_streamed_ce_value_and_gradient_match_dense(self):
torch.manual_seed(8)
hidden = torch.randn(2, 5, 7, dtype=torch.float64, requires_grad=True)
head = torch.randn(11, 7, dtype=hidden.dtype)
ids = torch.randint(0, len(head), (2, 5))
lengths = torch.tensor([5, 3])
def vocab():
for start in range(0, len(head), 4):
yield start, head[start:start+4]
valid = torch.arange(1, 5) < lengths[:, None]
dense = F.cross_entropy(F.linear(hidden[:, :-1][valid], head), ids[:, 1:][valid])
streamed = language_model_loss(hidden, ids, lengths, vocab)
torch.testing.assert_close(streamed, dense)
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)
hidden = torch.randn(2, 4, 8)
donor, teacher = torch.randn(2, 2, 4, 4), torch.randn(2, 2, 4, 4)
lengths = torch.tensor([4, 3])
values, gate = torch.randn(2, 4, 1, 4), torch.randn(2, 4, 2, 4)
recipient = FrozenRecipient({
'o': torch.randn(8, 8), 'post': torch.zeros(8), 'gate': torch.randn(12, 8),
'up': torch.randn(12, 8), 'down': torch.randn(8, 12), 'final': torch.zeros(8),
}, 1e-6)
scores = a(hidden, donor, torch.arange(4)[None, :])
context = causal_attention(scores, values, lengths)
altered = values.clone()
altered[:, -1] += 10.
torch.testing.assert_close(context[:, :-1], causal_attention(scores, altered, lengths)[:, :-1])
out = recipient(context, gate, hidden)
head = torch.randn(12, 8)
ids = torch.randint(0, len(head), (2, 4))
def vocab():
yield 0, head[:6]
yield 6, head[6:]
total, kd = objective(scores, teacher, lengths,
language_model_loss(out, ids, lengths, vocab))
total.backward()
self.assertTrue(kd.isfinite())
for p in a.parameters():
self.assertGreater(p.grad.abs().sum().item(), 0)
self.assertFalse(list(recipient.parameters()))
if __name__ == '__main__':
unittest.main()