Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 67327d62d8 | |||
| 0df3b0bfe6 | |||
| f769de90c6 | |||
| 5dd3ab32c8 | |||
| 31a257ba17 |
@@ -40,3 +40,107 @@ All weights and caches stay on the server until explicit user deletion. Git cont
|
||||
all figure tables and the selected small probability matrices; large caches have exact
|
||||
paths/sizes/hashes in `external-caches.json`. Old validation texts were used in earlier
|
||||
experiments; the four fresh texts were fixed before the new cross-layer measurements.
|
||||
|
||||
## LiSA-style single-layer pilot
|
||||
|
||||
The pilot reuses layer 19's actual pre-softmax scores at layer 23, with the
|
||||
recipient's own values, output gate and output projection. It compares native
|
||||
attention, direct reuse, a frozen one-to-one head assignment, linear mixing
|
||||
of donor heads, a 32-coordinate recipient-only control, and joint donor/recipient
|
||||
mixing. The linear variants use a closed-form ridge fit to the native scores,
|
||||
centred within each causal key row. The recipient branch takes a fixed subset of
|
||||
post-RoPE coordinates rather than learning a low-rank Q/K projection. The
|
||||
calibration uses 12 synthetic prompts without answer labels. All checkpoint
|
||||
weights are frozen.
|
||||
|
||||
Evaluation scores the four candidate option tokens on 24 disjoint retrieval
|
||||
prompts, including 12 with more table entries than calibration. Choice NLL
|
||||
normalizes over those four tokens. Run against the retained checkpoint on the
|
||||
remote CPU environment:
|
||||
|
||||
```sh
|
||||
OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 venv/bin/python -B -m crossqkv.lisa_pilot \
|
||||
--source runs/cpu-qwen35-2b --out runs/NEW_LISA_DIRECTORY
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -0,0 +1,265 @@
|
||||
"""Single-site LiSA-style pilot on the retained Qwen3.5-2B checkpoint."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import random
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
from tokenizers import Tokenizer
|
||||
|
||||
from crossqkv.core import QKVModel, assignment
|
||||
from functional.model import PREFIX
|
||||
from functional.run import write_json
|
||||
from pilot.tensors import decode
|
||||
|
||||
DONOR, TARGET = 19, 23
|
||||
WIDTH = 32
|
||||
MODES = ('native', 'direct', 'permutation', 'mix', 'local32', 'mix_local32')
|
||||
|
||||
|
||||
def scores(q, k):
|
||||
keys = np.repeat(k, q.shape[2] // k.shape[2], axis=2)
|
||||
return np.einsum('bthd,bshd->bhts', q, keys) / np.float32(np.sqrt(q.shape[-1]))
|
||||
|
||||
|
||||
def probabilities(x):
|
||||
x = np.where(np.tri(x.shape[-1], dtype=bool), x, -np.inf)
|
||||
exp = np.exp(x - x.max(axis=-1, keepdims=True))
|
||||
return exp / exp.sum(axis=-1, keepdims=True)
|
||||
|
||||
|
||||
def centered_rows(x, lengths):
|
||||
values = []
|
||||
for i, length in enumerate(lengths):
|
||||
query, key = np.tril_indices(length)
|
||||
board = x[i, :, :length, :length]
|
||||
mean = np.where(np.tri(length, dtype=bool), board, 0).sum(-1) / np.arange(1, length + 1)
|
||||
centered = board - mean[..., None]
|
||||
values.append(centered[:, query, key].T)
|
||||
return np.concatenate(values).astype(np.float64)
|
||||
|
||||
|
||||
def solve(x, y):
|
||||
gram = x.T @ x
|
||||
ridge = 1e-3 * np.trace(gram) / gram.shape[0]
|
||||
return np.linalg.solve(gram + max(ridge, 1e-12) * np.eye(len(gram)), x.T @ y).astype(np.float32)
|
||||
|
||||
|
||||
def fit(donor, target, local):
|
||||
cost = np.mean((target[:, :, None] - donor[:, None, :]) ** 2, axis=0)
|
||||
perm = assignment(cost)
|
||||
return {
|
||||
'permutation': list(perm),
|
||||
'mix': solve(donor, target),
|
||||
'local32': solve(local, target),
|
||||
'mix_local32': solve(np.concatenate((donor, local), axis=1), target),
|
||||
}
|
||||
|
||||
|
||||
def predict(donor, local, mode, mapping):
|
||||
if mode == 'direct':
|
||||
return donor
|
||||
if mode == 'permutation':
|
||||
return donor[:, mapping[mode]]
|
||||
if mode == 'mix':
|
||||
inputs = donor
|
||||
elif mode == 'local32':
|
||||
inputs = local
|
||||
else:
|
||||
inputs = np.concatenate((donor, local), axis=1)
|
||||
return np.einsum('bhts,hi->bits', inputs, mapping[mode])
|
||||
|
||||
|
||||
class Study(QKVModel):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
dim = self.config['head_dim']
|
||||
if dim % WIDTH:
|
||||
raise ValueError('Expected head dimension divisible by fixed local width')
|
||||
# Deterministic channel sample in post-RoPE Q/K coordinates.
|
||||
self.coordinates = np.arange(0, dim, dim // WIDTH)
|
||||
self.capture_scores = False
|
||||
|
||||
def normalization(self, x, name):
|
||||
if self.capture_scores and name == f'layers.{TARGET}.input_layernorm':
|
||||
self.recipient_input = x
|
||||
return super().normalization(x, name)
|
||||
|
||||
def full_attention(self, h, layer, shared_p=None):
|
||||
if not self.capture_scores or layer not in (DONOR, TARGET):
|
||||
return super().full_attention(h, layer, shared_p)
|
||||
parts = self.parts(h, layer, heads=False)
|
||||
if layer == DONOR:
|
||||
self.donor = scores(parts['q'], parts['k'])
|
||||
else:
|
||||
q, k = parts['q'], parts['k']
|
||||
self.teacher = scores(q, k)
|
||||
self.local = scores(q[..., self.coordinates], k[..., self.coordinates])
|
||||
self.recipient = parts
|
||||
return parts['output'], parts['p']
|
||||
|
||||
def replay(self, modes):
|
||||
if TARGET != len(self.config['layer_types']) - 1:
|
||||
raise ValueError('Replay requires changing only the final layer')
|
||||
parts = self.recipient
|
||||
repeats = self.config['num_attention_heads'] // self.config['num_key_value_heads']
|
||||
values = np.repeat(parts['v'], repeats, axis=2)
|
||||
contexts = [np.einsum('bhts,bshd->bthd',
|
||||
probabilities(predict(self.donor, self.local, mode, self.mapping)),
|
||||
values) for mode in modes]
|
||||
context = np.concatenate([parts['context'], *contexts])
|
||||
gate = np.concatenate([parts['gate']] * (1 + len(modes)))
|
||||
residual = np.concatenate([self.recipient_input] * (1 + len(modes)))
|
||||
hidden = residual + self.project(context, gate, TARGET)
|
||||
mlp_input = self.normalization(hidden, f'layers.{TARGET}.post_attention_layernorm')
|
||||
return np.split(self.normalization(hidden + self.mlp(mlp_input, TARGET), 'norm'),
|
||||
1 + len(modes))
|
||||
|
||||
|
||||
def dataset(split, count):
|
||||
seed = {'calibration': 2026112201, 'test4': 2026112202, 'test8': 2026112203}[split]
|
||||
rng = random.Random(seed)
|
||||
size = 8 if split == 'test8' else 4
|
||||
words = ('amber', 'birch', 'cedar', 'dune', 'elm', 'fern', 'grove', 'heath',
|
||||
'iris', 'jade', 'kelp', 'larch', 'maple', 'nettle', 'olive', 'pine')
|
||||
examples = []
|
||||
answers = [i % 4 for i in range(count)]
|
||||
rng.shuffle(answers)
|
||||
for i, answer in enumerate(answers):
|
||||
keys = rng.sample(words, size)
|
||||
values = rng.sample(range(10, 100), size)
|
||||
index = i % size
|
||||
other = rng.sample([v for j, v in enumerate(values) if j != index], 3)
|
||||
other.insert(answer, values[index])
|
||||
items = '\n'.join(f'{k}: {v}' for k, v in zip(keys, values))
|
||||
options = '\n'.join(f'{j + 1}. {v}' for j, v in enumerate(other))
|
||||
prompt = (f'Use the lookup table. Answer with only the option number.\n{items}\n'
|
||||
f'Which option is the value for {keys[index]}?\n{options}\nAnswer:')
|
||||
examples.append({'id': f'{split}-{i:03}', 'prompt': prompt, 'answer_index': answer,
|
||||
'evidence_position': index, 'entries': size})
|
||||
return examples
|
||||
|
||||
|
||||
def batch(tokenizer, examples):
|
||||
encoded = []
|
||||
choices = None
|
||||
for ex in examples:
|
||||
continuations = [tokenizer.encode(f"{ex['prompt']} {i}", add_special_tokens=False).ids
|
||||
for i in range(1, 5)]
|
||||
prefix = continuations[0][:-1]
|
||||
labels = [row[-1] for row in continuations]
|
||||
if any(row[:-1] != prefix for row in continuations) or len(set(labels)) != 4:
|
||||
raise ValueError('Choices must differ only at the final token')
|
||||
if choices is not None and labels != choices:
|
||||
raise ValueError('Choice tokenization varies by prompt')
|
||||
encoded.append(prefix)
|
||||
choices = labels
|
||||
lengths = [len(ids) for ids in encoded]
|
||||
ids = np.array([row + [0] * (max(lengths) - len(row)) for row in encoded], dtype=np.int64)
|
||||
return ids, lengths, choices
|
||||
|
||||
|
||||
def evaluate(lm, tokenizer, examples, batch_size=4):
|
||||
results = {mode: [] for mode in MODES}
|
||||
for start in range(0, len(examples), batch_size):
|
||||
group = examples[start:start + batch_size]
|
||||
ids, lengths, choices = batch(tokenizer, group)
|
||||
n = len(group)
|
||||
lm.capture_scores = True
|
||||
native, _ = lm.forward(ids)
|
||||
lm.capture_scores = False
|
||||
replay_native, *replayed = lm.replay(MODES[1:])
|
||||
if not np.allclose(replay_native, native, atol=2e-5, rtol=1e-5):
|
||||
raise ValueError('Native last-layer replay parity failed')
|
||||
token_rows = lm.tensors[PREFIX + 'embed_tokens.weight']
|
||||
weight = decode(token_rows.raw.reshape(token_rows.shape)[choices], token_rows.dtype)
|
||||
token_rows.evict()
|
||||
for mode, hidden in zip(MODES, [native, *replayed]):
|
||||
logits = hidden[np.arange(n), np.array(lengths) - 1] @ weight.T
|
||||
for ex, row, length in zip(group, logits.astype(float), lengths):
|
||||
gold = ex['answer_index']
|
||||
results[mode].append({
|
||||
'id': ex['id'], 'length': length, 'gold': gold,
|
||||
'logits': row.tolist(), 'predicted': int(row.argmax()),
|
||||
'choice_nll': float(np.logaddexp.reduce(row) - row[gold]),
|
||||
'margin': float(row[gold] - np.max(np.delete(row, gold))),
|
||||
})
|
||||
print(f"{group[-1]['id']}: evaluated {n} prompts in all six modes", flush=True)
|
||||
return results
|
||||
|
||||
|
||||
def summarize(results):
|
||||
return {split: {mode: {
|
||||
'n': len(rows),
|
||||
'correct': sum(row['gold'] == row['predicted'] for row in rows),
|
||||
'mean_choice_nll': float(np.mean([row['choice_nll'] for row in rows])),
|
||||
'mean_margin': float(np.mean([row['margin'] for row in rows])),
|
||||
'prediction_agreement_with_native': sum(row['predicted'] == base['predicted']
|
||||
for row, base in zip(rows, modes['native'])),
|
||||
} for mode, rows in modes.items()} for split, modes in results.items()}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--source', type=Path, required=True)
|
||||
parser.add_argument('--out', type=Path, required=True)
|
||||
parser.add_argument('--calibration-run', type=Path, help='Reuse a matching completed calibration')
|
||||
parser.add_argument('--seconds', type=int, default=1800)
|
||||
args = parser.parse_args()
|
||||
start = time.monotonic()
|
||||
args.out.mkdir()
|
||||
source = args.source
|
||||
config = json.loads((source / 'model_config.json').read_text())
|
||||
tokenizer = Tokenizer.from_file(str(source / 'tokenizer.json'))
|
||||
lm = Study(source / 'weights', config, seconds=args.seconds)
|
||||
kinds = lm.config['layer_types']
|
||||
if any(kinds[i] != 'full_attention' for i in (DONOR, TARGET)):
|
||||
raise ValueError('Requires the retained architecture with full attention at 19 and 23')
|
||||
source_files = ['model_config.json', 'tokenizer.json', 'manifest.json']
|
||||
protocol = {'donor': DONOR, 'target': TARGET, 'local_coordinate_count': WIDTH,
|
||||
'modes': MODES, 'source': str(source),
|
||||
'source_sha256': {f: hashlib.sha256((source/f).read_bytes()).hexdigest() for f in source_files},
|
||||
'choice_nll_scope': 'normalized over four option-number logits only'}
|
||||
problems = {s: dataset(s, n) for s, n in [('calibration', 12), ('test4', 12), ('test8', 12)]}
|
||||
if len({e['prompt'] for entries in problems.values() for e in entries}) != 36:
|
||||
raise ValueError('Repeated prompt across pilot sample')
|
||||
write_json(args.out / 'protocol.json', protocol)
|
||||
write_json(args.out / 'problems.json', problems)
|
||||
|
||||
if args.calibration_run:
|
||||
previous = args.calibration_run
|
||||
if (json.loads((previous / 'protocol.json').read_text()) !=
|
||||
json.loads((args.out / 'protocol.json').read_text()) or
|
||||
json.loads((previous / 'problems.json').read_text()) != problems):
|
||||
raise ValueError('Calibration inputs or checkpoint provenance differ')
|
||||
lm.mapping = {k: np.asarray(v, dtype=np.int64 if k == 'permutation' else np.float32)
|
||||
for k, v in json.loads((previous / 'calibration.json').read_text()).items()}
|
||||
else:
|
||||
ids, lengths, _ = batch(tokenizer, problems['calibration'])
|
||||
lm.capture_scores = True
|
||||
native, _ = lm.forward(ids)
|
||||
measured = [centered_rows(x, lengths) for x in (lm.donor, lm.teacher, lm.local)]
|
||||
lm.capture_scores = False
|
||||
reference, _ = lm.forward(ids[:4])
|
||||
if not np.allclose(native[:4], reference, atol=1e-5, rtol=1e-5):
|
||||
raise ValueError('Capture path disagrees with the unmodified reference')
|
||||
lm.mapping = fit(*measured)
|
||||
print('Calibration ready', flush=True)
|
||||
write_json(args.out / 'calibration.json', {
|
||||
k: np.asarray(v).tolist() for k, v in lm.mapping.items()
|
||||
})
|
||||
results = {}
|
||||
for split in ('test4', 'test8'):
|
||||
results[split] = evaluate(lm, tokenizer, problems[split])
|
||||
print(split, summarize(results)[split], flush=True)
|
||||
write_json(args.out / 'results.json', results)
|
||||
write_json(args.out / 'summary.json', {'sets': summarize(results),
|
||||
'native_last_layer_replay_parity': True,
|
||||
'calibration_reused': bool(args.calibration_run),
|
||||
'seconds': time.monotonic() - start})
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -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)
|
||||
@@ -0,0 +1,23 @@
|
||||
# Qwen3.5-2B 跨层注意力共享先导实验
|
||||
|
||||
固定原 Qwen3.5-2B 检查点,测试第 19 层实际前向产生的 softmax 前注意力分数能否替代第 23 层的分数。层编号从零开始。所有替换保留接收端的 V、gate 和输出投影。
|
||||
|
||||
| 方法 | 4 项表正确 | 8 项表正确 | 合计选择 NLL |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| 原模型 | 12/12 | 12/12 | 0.145079 |
|
||||
| 原序直接共享 | 12/12 | 12/12 | 0.087006 |
|
||||
| 头重排后共享 | 12/12 | 12/12 | 0.093331 |
|
||||
| 共享分数的线性头混合 | 12/12 | 12/12 | 0.100784 |
|
||||
| 接收层 32 坐标,无共享 | 12/12 | 12/12 | 0.102878 |
|
||||
| 共享分数与接收层 32 坐标联合拟合 | 12/12 | 12/12 | 0.106184 |
|
||||
|
||||
选择 NLL 在四个选项 token 上归一化后按题取均值。直接共享在这 24 道题上保持准确率,也在每道题上降低了选择 NLL。更低的损失反映正确选项相对其余三个选项的得分,样本中的准确率已经达到上限。这个结果支持冻结权重的单层替换在这些合成检索题上可用。轻量拟合没有带来额外收益。
|
||||
|
||||
## 实验与检查
|
||||
|
||||
- 12 道 4 项表校准题用于冻结头排列、闭式岭回归映射。拟合只使用原模型内部注意力分数,不使用正确选项标签。全套 36 条提示词无重复。
|
||||
- Qwen 权重全程冻结。没有反向传播,也没有训练 LiSA 原版的非线性头对齐网络或低秩 Q/K 投影。32 坐标来自确定性下采样的接收层 post-RoPE Q/K。
|
||||
- 远程 CPU 的 8 项跨层回归测试通过。合成数值检查通过,覆盖排列方向、因果遮罩和联合拟合重建。校准时的原模型路径一致性检查以及六批留出题的末层原样重放一致性检查均通过。
|
||||
- 两次较慢的远程执行切换后保留旧目录,最终版本沿用第二次已完成的校准,并核对原检查点文件指纹及全部提示词。末层重放阶段耗时约 681 秒。逐题分数、答案和 NLL 已从原始 logits 独立复核,最终运行脚本 SHA256 为 `a64d1b50a10bdde893c4bc274365c0c072f13c0a2359b079cfa8421b9ce068f4`。
|
||||
|
||||
评测只覆盖一个模型、一个接收层、一类合成任务、约束于四个选项的读出。诊断仍计算原始 Q/K,未测吞吐、压缩率、自由生成或多层累积替换效果。实验方法和复现入口见 [crossqkv/README.md](../../crossqkv/README.md)。
|
||||
@@ -0,0 +1,338 @@
|
||||
{
|
||||
"permutation": [
|
||||
0,
|
||||
2,
|
||||
4,
|
||||
3,
|
||||
7,
|
||||
6,
|
||||
5,
|
||||
1
|
||||
],
|
||||
"mix": [
|
||||
[
|
||||
0.24426038563251495,
|
||||
0.055573295801877975,
|
||||
-0.12299608439207077,
|
||||
-0.09282179176807404,
|
||||
-0.047870442271232605,
|
||||
0.07772502303123474,
|
||||
-0.22192631661891937,
|
||||
0.29638272523880005
|
||||
],
|
||||
[
|
||||
0.03558433800935745,
|
||||
0.03896130993962288,
|
||||
-0.18795007467269897,
|
||||
0.002625135239213705,
|
||||
-0.16552278399467468,
|
||||
-0.023057416081428528,
|
||||
-0.39929720759391785,
|
||||
0.43178120255470276
|
||||
],
|
||||
[
|
||||
0.1871931552886963,
|
||||
0.44749122858047485,
|
||||
-0.04751807823777199,
|
||||
0.04143448546528816,
|
||||
0.23914210498332977,
|
||||
0.18653616309165955,
|
||||
0.12161331623792648,
|
||||
-0.20545999705791473
|
||||
],
|
||||
[
|
||||
-0.027203943580389023,
|
||||
-0.23345178365707397,
|
||||
-0.03906247019767761,
|
||||
0.0939483568072319,
|
||||
0.11926761269569397,
|
||||
-0.08872664719820023,
|
||||
0.14460818469524384,
|
||||
0.06796323508024216
|
||||
],
|
||||
[
|
||||
0.09347549825906754,
|
||||
0.2144748717546463,
|
||||
1.078420877456665,
|
||||
0.5173454880714417,
|
||||
0.5393254160881042,
|
||||
0.31546834111213684,
|
||||
0.7830604314804077,
|
||||
0.09864718466997147
|
||||
],
|
||||
[
|
||||
-0.015639908611774445,
|
||||
0.13545557856559753,
|
||||
0.20001526176929474,
|
||||
-0.0403873436152935,
|
||||
-0.14243841171264648,
|
||||
0.10669009387493134,
|
||||
0.22260507941246033,
|
||||
-0.008936765603721142
|
||||
],
|
||||
[
|
||||
0.2405557930469513,
|
||||
0.054704487323760986,
|
||||
0.011206595227122307,
|
||||
0.2406461238861084,
|
||||
-0.026383306831121445,
|
||||
0.25195246934890747,
|
||||
0.09300804138183594,
|
||||
0.10066510736942291
|
||||
],
|
||||
[
|
||||
0.02644052356481552,
|
||||
0.10034456104040146,
|
||||
0.07825803011655807,
|
||||
0.10650064051151276,
|
||||
0.3668587803840637,
|
||||
-0.007412006612867117,
|
||||
0.061572253704071045,
|
||||
-0.06577901542186737
|
||||
]
|
||||
],
|
||||
"local32": [
|
||||
[
|
||||
0.2867194414138794,
|
||||
0.06671284139156342,
|
||||
-0.2674592435359955,
|
||||
-0.3276604115962982,
|
||||
-0.4070841670036316,
|
||||
-0.006673475727438927,
|
||||
-0.2074313908815384,
|
||||
0.12887436151504517
|
||||
],
|
||||
[
|
||||
-0.0516749806702137,
|
||||
0.4364052712917328,
|
||||
0.4763493239879608,
|
||||
0.569825291633606,
|
||||
0.5895766019821167,
|
||||
0.23220211267471313,
|
||||
0.4529169201850891,
|
||||
0.020792270079255104
|
||||
],
|
||||
[
|
||||
0.030566174536943436,
|
||||
-0.0014433575561270118,
|
||||
0.9291507601737976,
|
||||
0.07762160897254944,
|
||||
0.09363061934709549,
|
||||
0.11929107457399368,
|
||||
0.6625307202339172,
|
||||
0.011318162083625793
|
||||
],
|
||||
[
|
||||
0.6921118497848511,
|
||||
0.3367474377155304,
|
||||
-0.20861877501010895,
|
||||
0.6061498522758484,
|
||||
0.4020693004131317,
|
||||
0.4614187479019165,
|
||||
-0.120954729616642,
|
||||
0.6977306008338928
|
||||
],
|
||||
[
|
||||
0.010575470514595509,
|
||||
0.03395608440041542,
|
||||
-0.17418035864830017,
|
||||
0.05686786770820618,
|
||||
0.3456997573375702,
|
||||
-0.16309495270252228,
|
||||
0.13770024478435516,
|
||||
-0.06023705378174782
|
||||
],
|
||||
[
|
||||
0.34056422114372253,
|
||||
0.3800618350505829,
|
||||
0.46083998680114746,
|
||||
0.379044771194458,
|
||||
0.38687247037887573,
|
||||
0.7362816333770752,
|
||||
0.2947295904159546,
|
||||
-0.053121648728847504
|
||||
],
|
||||
[
|
||||
0.03288573399186134,
|
||||
0.11208789050579071,
|
||||
0.5949627161026001,
|
||||
0.09720376133918762,
|
||||
0.012026847340166569,
|
||||
0.062014296650886536,
|
||||
0.8560540080070496,
|
||||
0.004886063747107983
|
||||
],
|
||||
[
|
||||
0.3228500783443451,
|
||||
0.3110385239124298,
|
||||
-0.03597158193588257,
|
||||
0.004630092531442642,
|
||||
0.1255260556936264,
|
||||
0.3001147508621216,
|
||||
-0.2873961925506592,
|
||||
0.7489231824874878
|
||||
]
|
||||
],
|
||||
"mix_local32": [
|
||||
[
|
||||
0.11679738759994507,
|
||||
0.06494305282831192,
|
||||
-0.07491274178028107,
|
||||
-0.10080373287200928,
|
||||
-0.02167605608701706,
|
||||
-0.05343199521303177,
|
||||
-0.1710113286972046,
|
||||
0.25583943724632263
|
||||
],
|
||||
[
|
||||
0.07517975568771362,
|
||||
0.04044078290462494,
|
||||
-0.06897048652172089,
|
||||
0.022282306104898453,
|
||||
-0.14309072494506836,
|
||||
0.033187106251716614,
|
||||
-0.3017081618309021,
|
||||
0.44381454586982727
|
||||
],
|
||||
[
|
||||
0.06857457011938095,
|
||||
0.3892330229282379,
|
||||
-0.10634169727563858,
|
||||
-0.019304350018501282,
|
||||
0.19891692698001862,
|
||||
0.07254264503717422,
|
||||
0.06347434967756271,
|
||||
-0.31816524267196655
|
||||
],
|
||||
[
|
||||
0.09148014336824417,
|
||||
-0.1973782479763031,
|
||||
0.152879536151886,
|
||||
0.11245211213827133,
|
||||
0.12135685235261917,
|
||||
0.12074458599090576,
|
||||
0.3753202259540558,
|
||||
0.044213682413101196
|
||||
],
|
||||
[
|
||||
0.07850243151187897,
|
||||
0.17286451160907745,
|
||||
0.8361716866493225,
|
||||
0.4728657901287079,
|
||||
0.4632956087589264,
|
||||
0.20232141017913818,
|
||||
0.5647081732749939,
|
||||
0.14378811419010162
|
||||
],
|
||||
[
|
||||
-0.08318367600440979,
|
||||
0.05281839147210121,
|
||||
-0.0541967898607254,
|
||||
-0.07725174725055695,
|
||||
-0.19812145829200745,
|
||||
-0.0031219127122312784,
|
||||
-0.04434914141893387,
|
||||
-0.08314008265733719
|
||||
],
|
||||
[
|
||||
0.21213339269161224,
|
||||
0.07709750533103943,
|
||||
0.045971959829330444,
|
||||
0.21323992311954498,
|
||||
0.025503091514110565,
|
||||
0.26300355792045593,
|
||||
0.12342528253793716,
|
||||
0.12137588858604431
|
||||
],
|
||||
[
|
||||
0.09544969350099564,
|
||||
0.0986594632267952,
|
||||
0.04683060944080353,
|
||||
0.12203476577997208,
|
||||
0.31474506855010986,
|
||||
0.005084820557385683,
|
||||
0.022342870011925697,
|
||||
-0.03607412800192833
|
||||
],
|
||||
[
|
||||
0.5112781524658203,
|
||||
0.1685691624879837,
|
||||
0.03565533459186554,
|
||||
-0.017969932407140732,
|
||||
-0.11261212080717087,
|
||||
0.21835851669311523,
|
||||
0.06214938685297966,
|
||||
0.369602233171463
|
||||
],
|
||||
[
|
||||
-0.40601295232772827,
|
||||
0.12985582649707794,
|
||||
-0.03226114436984062,
|
||||
0.0588277243077755,
|
||||
0.1966109573841095,
|
||||
-0.195071741938591,
|
||||
0.021230820566415787,
|
||||
-0.3407396376132965
|
||||
],
|
||||
[
|
||||
0.05574870482087135,
|
||||
0.002938202116638422,
|
||||
0.8687096834182739,
|
||||
0.05353480949997902,
|
||||
0.06125132739543915,
|
||||
0.1233755350112915,
|
||||
0.607818603515625,
|
||||
0.06634242087602615
|
||||
],
|
||||
[
|
||||
0.17747589945793152,
|
||||
-0.11643446981906891,
|
||||
-0.4716564118862152,
|
||||
0.21365293860435486,
|
||||
-0.053643301129341125,
|
||||
0.035281628370285034,
|
||||
-0.4258069097995758,
|
||||
0.28920620679855347
|
||||
],
|
||||
[
|
||||
-0.07137177139520645,
|
||||
-0.0010721894213929772,
|
||||
-0.30434563755989075,
|
||||
-0.04535682126879692,
|
||||
0.11665429919958115,
|
||||
-0.21108229458332062,
|
||||
-0.05042998865246773,
|
||||
-0.023268967866897583
|
||||
],
|
||||
[
|
||||
0.20552901923656464,
|
||||
0.10354588180780411,
|
||||
0.18191908299922943,
|
||||
0.15948699414730072,
|
||||
0.154840886592865,
|
||||
0.581689715385437,
|
||||
0.12202811241149902,
|
||||
-0.10293511301279068
|
||||
],
|
||||
[
|
||||
0.015075353905558586,
|
||||
0.04981930926442146,
|
||||
0.5468234419822693,
|
||||
0.05587880685925484,
|
||||
-0.008960379287600517,
|
||||
0.026398485526442528,
|
||||
0.831177294254303,
|
||||
0.0010817323345690966
|
||||
],
|
||||
[
|
||||
0.2027735859155655,
|
||||
0.22851699590682983,
|
||||
0.04834882915019989,
|
||||
-0.009833958931267262,
|
||||
0.15699052810668945,
|
||||
0.20191335678100586,
|
||||
-0.24067029356956482,
|
||||
0.5740934014320374
|
||||
]
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
{
|
||||
"calibration": [
|
||||
{
|
||||
"id": "calibration-000",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\nbirch: 19\nfern: 45\ndune: 31\nlarch: 86\nWhich option is the value for birch?\n1. 19\n2. 31\n3. 45\n4. 86\nAnswer:",
|
||||
"answer_index": 0,
|
||||
"evidence_position": 0,
|
||||
"entries": 4
|
||||
},
|
||||
{
|
||||
"id": "calibration-001",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\nnettle: 34\npine: 47\nmaple: 93\nkelp: 83\nWhich option is the value for pine?\n1. 34\n2. 93\n3. 47\n4. 83\nAnswer:",
|
||||
"answer_index": 2,
|
||||
"evidence_position": 1,
|
||||
"entries": 4
|
||||
},
|
||||
{
|
||||
"id": "calibration-002",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\nfern: 93\ncedar: 38\niris: 53\nnettle: 61\nWhich option is the value for iris?\n1. 61\n2. 53\n3. 93\n4. 38\nAnswer:",
|
||||
"answer_index": 1,
|
||||
"evidence_position": 2,
|
||||
"entries": 4
|
||||
},
|
||||
{
|
||||
"id": "calibration-003",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\nfern: 19\nelm: 52\ngrove: 13\nolive: 39\nWhich option is the value for olive?\n1. 13\n2. 19\n3. 52\n4. 39\nAnswer:",
|
||||
"answer_index": 3,
|
||||
"evidence_position": 3,
|
||||
"entries": 4
|
||||
},
|
||||
{
|
||||
"id": "calibration-004",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\nlarch: 24\ndune: 97\npine: 13\nolive: 57\nWhich option is the value for larch?\n1. 13\n2. 57\n3. 97\n4. 24\nAnswer:",
|
||||
"answer_index": 3,
|
||||
"evidence_position": 0,
|
||||
"entries": 4
|
||||
},
|
||||
{
|
||||
"id": "calibration-005",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\nfern: 90\nmaple: 72\nbirch: 81\nolive: 65\nWhich option is the value for maple?\n1. 65\n2. 72\n3. 81\n4. 90\nAnswer:",
|
||||
"answer_index": 1,
|
||||
"evidence_position": 1,
|
||||
"entries": 4
|
||||
},
|
||||
{
|
||||
"id": "calibration-006",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\nlarch: 19\nbirch: 40\ndune: 14\namber: 53\nWhich option is the value for dune?\n1. 14\n2. 40\n3. 53\n4. 19\nAnswer:",
|
||||
"answer_index": 0,
|
||||
"evidence_position": 2,
|
||||
"entries": 4
|
||||
},
|
||||
{
|
||||
"id": "calibration-007",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\nbirch: 47\nkelp: 15\niris: 95\nmaple: 25\nWhich option is the value for maple?\n1. 95\n2. 47\n3. 15\n4. 25\nAnswer:",
|
||||
"answer_index": 3,
|
||||
"evidence_position": 3,
|
||||
"entries": 4
|
||||
},
|
||||
{
|
||||
"id": "calibration-008",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\nelm: 78\niris: 49\njade: 61\npine: 46\nWhich option is the value for elm?\n1. 46\n2. 61\n3. 78\n4. 49\nAnswer:",
|
||||
"answer_index": 2,
|
||||
"evidence_position": 0,
|
||||
"entries": 4
|
||||
},
|
||||
{
|
||||
"id": "calibration-009",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\nbirch: 51\niris: 80\ncedar: 81\nfern: 54\nWhich option is the value for iris?\n1. 80\n2. 81\n3. 54\n4. 51\nAnswer:",
|
||||
"answer_index": 0,
|
||||
"evidence_position": 1,
|
||||
"entries": 4
|
||||
},
|
||||
{
|
||||
"id": "calibration-010",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\nheath: 69\ncedar: 80\nbirch: 37\ndune: 19\nWhich option is the value for birch?\n1. 69\n2. 80\n3. 37\n4. 19\nAnswer:",
|
||||
"answer_index": 2,
|
||||
"evidence_position": 2,
|
||||
"entries": 4
|
||||
},
|
||||
{
|
||||
"id": "calibration-011",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\nbirch: 89\njade: 86\nfern: 65\ncedar: 20\nWhich option is the value for cedar?\n1. 65\n2. 20\n3. 89\n4. 86\nAnswer:",
|
||||
"answer_index": 1,
|
||||
"evidence_position": 3,
|
||||
"entries": 4
|
||||
}
|
||||
],
|
||||
"test4": [
|
||||
{
|
||||
"id": "test4-000",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\ngrove: 25\namber: 97\ndune: 93\nheath: 80\nWhich option is the value for grove?\n1. 97\n2. 80\n3. 25\n4. 93\nAnswer:",
|
||||
"answer_index": 2,
|
||||
"evidence_position": 0,
|
||||
"entries": 4
|
||||
},
|
||||
{
|
||||
"id": "test4-001",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\nkelp: 50\nelm: 92\ngrove: 27\nnettle: 46\nWhich option is the value for elm?\n1. 27\n2. 50\n3. 92\n4. 46\nAnswer:",
|
||||
"answer_index": 2,
|
||||
"evidence_position": 1,
|
||||
"entries": 4
|
||||
},
|
||||
{
|
||||
"id": "test4-002",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\nmaple: 64\nolive: 99\nbirch: 95\nelm: 31\nWhich option is the value for birch?\n1. 64\n2. 31\n3. 99\n4. 95\nAnswer:",
|
||||
"answer_index": 3,
|
||||
"evidence_position": 2,
|
||||
"entries": 4
|
||||
},
|
||||
{
|
||||
"id": "test4-003",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\nkelp: 95\nmaple: 88\niris: 77\nlarch: 57\nWhich option is the value for larch?\n1. 77\n2. 57\n3. 95\n4. 88\nAnswer:",
|
||||
"answer_index": 1,
|
||||
"evidence_position": 3,
|
||||
"entries": 4
|
||||
},
|
||||
{
|
||||
"id": "test4-004",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\ndune: 51\ncedar: 55\nlarch: 98\nnettle: 94\nWhich option is the value for dune?\n1. 51\n2. 94\n3. 55\n4. 98\nAnswer:",
|
||||
"answer_index": 0,
|
||||
"evidence_position": 0,
|
||||
"entries": 4
|
||||
},
|
||||
{
|
||||
"id": "test4-005",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\nelm: 42\nolive: 46\nheath: 11\ndune: 54\nWhich option is the value for olive?\n1. 11\n2. 46\n3. 42\n4. 54\nAnswer:",
|
||||
"answer_index": 1,
|
||||
"evidence_position": 1,
|
||||
"entries": 4
|
||||
},
|
||||
{
|
||||
"id": "test4-006",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\nmaple: 94\ndune: 40\npine: 76\njade: 10\nWhich option is the value for pine?\n1. 10\n2. 94\n3. 76\n4. 40\nAnswer:",
|
||||
"answer_index": 2,
|
||||
"evidence_position": 2,
|
||||
"entries": 4
|
||||
},
|
||||
{
|
||||
"id": "test4-007",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\nkelp: 54\niris: 92\npine: 11\ncedar: 13\nWhich option is the value for cedar?\n1. 13\n2. 11\n3. 54\n4. 92\nAnswer:",
|
||||
"answer_index": 0,
|
||||
"evidence_position": 3,
|
||||
"entries": 4
|
||||
},
|
||||
{
|
||||
"id": "test4-008",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\nlarch: 40\nelm: 91\nbirch: 30\npine: 78\nWhich option is the value for larch?\n1. 30\n2. 40\n3. 78\n4. 91\nAnswer:",
|
||||
"answer_index": 1,
|
||||
"evidence_position": 0,
|
||||
"entries": 4
|
||||
},
|
||||
{
|
||||
"id": "test4-009",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\njade: 66\npine: 45\nkelp: 46\nheath: 52\nWhich option is the value for pine?\n1. 66\n2. 52\n3. 46\n4. 45\nAnswer:",
|
||||
"answer_index": 3,
|
||||
"evidence_position": 1,
|
||||
"entries": 4
|
||||
},
|
||||
{
|
||||
"id": "test4-010",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\namber: 93\ndune: 32\nheath: 72\njade: 46\nWhich option is the value for heath?\n1. 32\n2. 46\n3. 93\n4. 72\nAnswer:",
|
||||
"answer_index": 3,
|
||||
"evidence_position": 2,
|
||||
"entries": 4
|
||||
},
|
||||
{
|
||||
"id": "test4-011",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\nnettle: 99\nfern: 36\nbirch: 49\nolive: 25\nWhich option is the value for olive?\n1. 25\n2. 99\n3. 49\n4. 36\nAnswer:",
|
||||
"answer_index": 0,
|
||||
"evidence_position": 3,
|
||||
"entries": 4
|
||||
}
|
||||
],
|
||||
"test8": [
|
||||
{
|
||||
"id": "test8-000",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\ncedar: 53\ndune: 77\nelm: 44\nmaple: 93\nlarch: 39\nheath: 78\ngrove: 41\nbirch: 48\nWhich option is the value for cedar?\n1. 77\n2. 48\n3. 53\n4. 41\nAnswer:",
|
||||
"answer_index": 2,
|
||||
"evidence_position": 0,
|
||||
"entries": 8
|
||||
},
|
||||
{
|
||||
"id": "test8-001",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\nolive: 87\nnettle: 76\nbirch: 44\nmaple: 69\npine: 41\ncedar: 56\ndune: 45\nkelp: 94\nWhich option is the value for nettle?\n1. 76\n2. 56\n3. 41\n4. 94\nAnswer:",
|
||||
"answer_index": 0,
|
||||
"evidence_position": 1,
|
||||
"entries": 8
|
||||
},
|
||||
{
|
||||
"id": "test8-002",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\nmaple: 80\nbirch: 21\nfern: 75\ngrove: 52\ncedar: 59\niris: 73\njade: 32\npine: 83\nWhich option is the value for fern?\n1. 32\n2. 80\n3. 75\n4. 73\nAnswer:",
|
||||
"answer_index": 2,
|
||||
"evidence_position": 2,
|
||||
"entries": 8
|
||||
},
|
||||
{
|
||||
"id": "test8-003",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\nlarch: 91\nbirch: 39\nheath: 27\npine: 96\nkelp: 49\nolive: 85\nelm: 18\nmaple: 66\nWhich option is the value for pine?\n1. 66\n2. 96\n3. 49\n4. 18\nAnswer:",
|
||||
"answer_index": 1,
|
||||
"evidence_position": 3,
|
||||
"entries": 8
|
||||
},
|
||||
{
|
||||
"id": "test8-004",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\ncedar: 19\nbirch: 84\nkelp: 85\njade: 72\nnettle: 87\niris: 96\nmaple: 56\nheath: 95\nWhich option is the value for nettle?\n1. 85\n2. 87\n3. 95\n4. 19\nAnswer:",
|
||||
"answer_index": 1,
|
||||
"evidence_position": 4,
|
||||
"entries": 8
|
||||
},
|
||||
{
|
||||
"id": "test8-005",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\niris: 36\nnettle: 41\nfern: 96\nmaple: 84\nheath: 37\npine: 57\ndune: 17\nbirch: 46\nWhich option is the value for pine?\n1. 17\n2. 37\n3. 41\n4. 57\nAnswer:",
|
||||
"answer_index": 3,
|
||||
"evidence_position": 5,
|
||||
"entries": 8
|
||||
},
|
||||
{
|
||||
"id": "test8-006",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\nfern: 49\njade: 67\nnettle: 71\nmaple: 89\nbirch: 44\npine: 25\nkelp: 27\ngrove: 41\nWhich option is the value for kelp?\n1. 25\n2. 27\n3. 44\n4. 41\nAnswer:",
|
||||
"answer_index": 1,
|
||||
"evidence_position": 6,
|
||||
"entries": 8
|
||||
},
|
||||
{
|
||||
"id": "test8-007",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\nnettle: 71\nolive: 95\nmaple: 16\niris: 54\njade: 61\namber: 72\nfern: 38\ngrove: 13\nWhich option is the value for grove?\n1. 72\n2. 38\n3. 13\n4. 95\nAnswer:",
|
||||
"answer_index": 2,
|
||||
"evidence_position": 7,
|
||||
"entries": 8
|
||||
},
|
||||
{
|
||||
"id": "test8-008",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\njade: 98\nkelp: 18\nelm: 84\niris: 67\nbirch: 64\nfern: 10\nlarch: 79\nmaple: 76\nWhich option is the value for jade?\n1. 10\n2. 67\n3. 84\n4. 98\nAnswer:",
|
||||
"answer_index": 3,
|
||||
"evidence_position": 0,
|
||||
"entries": 8
|
||||
},
|
||||
{
|
||||
"id": "test8-009",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\ngrove: 66\nheath: 58\nfern: 59\nmaple: 97\nolive: 52\namber: 29\nkelp: 24\ndune: 67\nWhich option is the value for heath?\n1. 58\n2. 59\n3. 67\n4. 52\nAnswer:",
|
||||
"answer_index": 0,
|
||||
"evidence_position": 1,
|
||||
"entries": 8
|
||||
},
|
||||
{
|
||||
"id": "test8-010",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\nbirch: 52\namber: 72\ndune: 80\npine: 79\nfern: 32\nnettle: 14\nkelp: 84\nelm: 59\nWhich option is the value for dune?\n1. 52\n2. 84\n3. 72\n4. 80\nAnswer:",
|
||||
"answer_index": 3,
|
||||
"evidence_position": 2,
|
||||
"entries": 8
|
||||
},
|
||||
{
|
||||
"id": "test8-011",
|
||||
"prompt": "Use the lookup table. Answer with only the option number.\nfern: 26\ngrove: 47\nbirch: 58\ndune: 99\nmaple: 24\ncedar: 19\njade: 36\nkelp: 23\nWhich option is the value for dune?\n1. 99\n2. 36\n3. 23\n4. 58\nAnswer:",
|
||||
"answer_index": 0,
|
||||
"evidence_position": 3,
|
||||
"entries": 8
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"donor": 19,
|
||||
"target": 23,
|
||||
"local_coordinate_count": 32,
|
||||
"modes": [
|
||||
"native",
|
||||
"direct",
|
||||
"permutation",
|
||||
"mix",
|
||||
"local32",
|
||||
"mix_local32"
|
||||
],
|
||||
"source": "/opt/exp-model-parameter-similarity/runs/cpu-qwen35-2b",
|
||||
"source_sha256": {
|
||||
"model_config.json": "ed1c1723241f23f7f4e23430759cbd7dcfb4103cbdfe052bfe7626b57c2615b4",
|
||||
"tokenizer.json": "5f9e4d4901a92b997e463c1f46055088b6cca5ca61a6522d1b9f64c4bb81cb42",
|
||||
"manifest.json": "28efbaf94a5034333339a35f08ead151459a7d20c6c2d2f07a451e7f3bf154de"
|
||||
},
|
||||
"choice_nll_scope": "normalized over four option-number logits only"
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,95 @@
|
||||
{
|
||||
"sets": {
|
||||
"test4": {
|
||||
"native": {
|
||||
"n": 12,
|
||||
"correct": 12,
|
||||
"mean_choice_nll": 0.1577236725451122,
|
||||
"mean_margin": 2.6222333908081055,
|
||||
"prediction_agreement_with_native": 12
|
||||
},
|
||||
"direct": {
|
||||
"n": 12,
|
||||
"correct": 12,
|
||||
"mean_choice_nll": 0.09467621731363618,
|
||||
"mean_margin": 3.157541592915853,
|
||||
"prediction_agreement_with_native": 12
|
||||
},
|
||||
"permutation": {
|
||||
"n": 12,
|
||||
"correct": 12,
|
||||
"mean_choice_nll": 0.10225362466948813,
|
||||
"mean_margin": 3.069669246673584,
|
||||
"prediction_agreement_with_native": 12
|
||||
},
|
||||
"mix": {
|
||||
"n": 12,
|
||||
"correct": 12,
|
||||
"mean_choice_nll": 0.10946264729409035,
|
||||
"mean_margin": 2.9876694679260254,
|
||||
"prediction_agreement_with_native": 12
|
||||
},
|
||||
"local32": {
|
||||
"n": 12,
|
||||
"correct": 12,
|
||||
"mean_choice_nll": 0.11173090120474012,
|
||||
"mean_margin": 2.9486522674560547,
|
||||
"prediction_agreement_with_native": 12
|
||||
},
|
||||
"mix_local32": {
|
||||
"n": 12,
|
||||
"correct": 12,
|
||||
"mean_choice_nll": 0.1155495746250453,
|
||||
"mean_margin": 2.9375176429748535,
|
||||
"prediction_agreement_with_native": 12
|
||||
}
|
||||
},
|
||||
"test8": {
|
||||
"native": {
|
||||
"n": 12,
|
||||
"correct": 12,
|
||||
"mean_choice_nll": 0.13243424793047875,
|
||||
"mean_margin": 2.652334133783976,
|
||||
"prediction_agreement_with_native": 12
|
||||
},
|
||||
"direct": {
|
||||
"n": 12,
|
||||
"correct": 12,
|
||||
"mean_choice_nll": 0.07933497390150783,
|
||||
"mean_margin": 3.1618269284566245,
|
||||
"prediction_agreement_with_native": 12
|
||||
},
|
||||
"permutation": {
|
||||
"n": 12,
|
||||
"correct": 12,
|
||||
"mean_choice_nll": 0.08440917052410739,
|
||||
"mean_margin": 3.135169267654419,
|
||||
"prediction_agreement_with_native": 12
|
||||
},
|
||||
"mix": {
|
||||
"n": 12,
|
||||
"correct": 12,
|
||||
"mean_choice_nll": 0.09210604798693496,
|
||||
"mean_margin": 3.0242624282836914,
|
||||
"prediction_agreement_with_native": 12
|
||||
},
|
||||
"local32": {
|
||||
"n": 12,
|
||||
"correct": 12,
|
||||
"mean_choice_nll": 0.09402417229313187,
|
||||
"mean_margin": 2.9872288703918457,
|
||||
"prediction_agreement_with_native": 12
|
||||
},
|
||||
"mix_local32": {
|
||||
"n": 12,
|
||||
"correct": 12,
|
||||
"mean_choice_nll": 0.09681914153941336,
|
||||
"mean_margin": 2.970529397328695,
|
||||
"prediction_agreement_with_native": 12
|
||||
}
|
||||
}
|
||||
},
|
||||
"native_last_layer_replay_parity": true,
|
||||
"calibration_reused": true,
|
||||
"seconds": 681.1676366906613
|
||||
}
|
||||
@@ -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
@@ -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,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,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"
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -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'])
|
||||
@@ -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()
|
||||
Reference in New Issue
Block a user