From 67327d62d80034eb3627a4959aac74ecbfd9188f Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 23 Nov 2026 16:47:19 +0800 Subject: [PATCH] Reproduce trainable LiSA attention on Qwen3.5-2B --- crossqkv/README.md | 40 +++ crossqkv/lisa_reproduction.py | 200 ++++++++++++++ crossqkv/lisa_train.py | 121 +++++++++ results/lisa-full-reproduction/REPORT.md | 22 ++ results/lisa-full-reproduction/problems.json | 260 +++++++++++++++++++ results/lisa-full-reproduction/protocol.json | 25 ++ results/lisa-full-reproduction/results.json | 73 ++++++ results/lisa-full-reproduction/trace.json | 226 ++++++++++++++++ tests/test_lisa_train.py | 64 +++++ 9 files changed, 1031 insertions(+) create mode 100644 crossqkv/lisa_reproduction.py create mode 100644 crossqkv/lisa_train.py create mode 100644 results/lisa-full-reproduction/REPORT.md create mode 100644 results/lisa-full-reproduction/problems.json create mode 100644 results/lisa-full-reproduction/protocol.json create mode 100644 results/lisa-full-reproduction/results.json create mode 100644 results/lisa-full-reproduction/trace.json create mode 100644 tests/test_lisa_train.py diff --git a/crossqkv/README.md b/crossqkv/README.md index 7eee867..8f99f9d 100644 --- a/crossqkv/README.md +++ b/crossqkv/README.md @@ -104,3 +104,43 @@ 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. diff --git a/crossqkv/lisa_reproduction.py b/crossqkv/lisa_reproduction.py new file mode 100644 index 0000000..f6149d9 --- /dev/null +++ b/crossqkv/lisa_reproduction.py @@ -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() diff --git a/crossqkv/lisa_train.py b/crossqkv/lisa_train.py new file mode 100644 index 0000000..b57031b --- /dev/null +++ b/crossqkv/lisa_train.py @@ -0,0 +1,121 @@ +"""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, 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) + ctx.vocabulary = vocabulary + return (log_total - selected).mean() + + @staticmethod + def backward(ctx, gradient): + hidden, targets, log_total = ctx.saved_tensors + grad_hidden = torch.zeros_like(hidden) + for start, w in ctx.vocabulary(): + probs = (F.linear(hidden, w) - log_total[:, None]).exp() + belongs = (targets >= start) & (targets < start + w.shape[0]) + probs[belongs, targets[belongs] - start] -= 1 + grad_hidden.addmm_(probs, w) + return grad_hidden * (gradient / hidden.shape[0]), None, None + + +def language_model_loss(hidden, ids, lengths, vocabulary): + """Train on all valid next-token targets, avoiding padding and final positions.""" + positions = torch.arange(ids.shape[1] - 1, device=ids.device) + valid = positions[None, :] + 1 < lengths[:, None] + return _FrozenVocabularyCE.apply(hidden[:, :-1][valid], ids[:, 1:][valid], vocabulary) diff --git a/results/lisa-full-reproduction/REPORT.md b/results/lisa-full-reproduction/REPORT.md new file mode 100644 index 0000000..fc676f5 --- /dev/null +++ b/results/lisa-full-reproduction/REPORT.md @@ -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)。 diff --git a/results/lisa-full-reproduction/problems.json b/results/lisa-full-reproduction/problems.json new file mode 100644 index 0000000..22ef0e6 --- /dev/null +++ b/results/lisa-full-reproduction/problems.json @@ -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" + } + ] +} diff --git a/results/lisa-full-reproduction/protocol.json b/results/lisa-full-reproduction/protocol.json new file mode 100644 index 0000000..e218152 --- /dev/null +++ b/results/lisa-full-reproduction/protocol.json @@ -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 + } +} diff --git a/results/lisa-full-reproduction/results.json b/results/lisa-full-reproduction/results.json new file mode 100644 index 0000000..83df709 --- /dev/null +++ b/results/lisa-full-reproduction/results.json @@ -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" +} diff --git a/results/lisa-full-reproduction/trace.json b/results/lisa-full-reproduction/trace.json new file mode 100644 index 0000000..4d8a721 --- /dev/null +++ b/results/lisa-full-reproduction/trace.json @@ -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 + } + } +] diff --git a/tests/test_lisa_train.py b/tests/test_lisa_train.py new file mode 100644 index 0000000..ae659c7 --- /dev/null +++ b/tests/test_lisa_train.py @@ -0,0 +1,64 @@ +"""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_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() -- 2.52.0