Reproduce trainable LiSA attention on Qwen3.5-2B
This commit is contained in:
@@ -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.
|
||||
|
||||
@@ -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()
|
||||
@@ -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)
|
||||
Reference in New Issue
Block a user