Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 59072884ff | |||
| 1c8943a2e8 | |||
| 115e440455 | |||
| 67327d62d8 | |||
| 0df3b0bfe6 | |||
| f769de90c6 | |||
| 5dd3ab32c8 | |||
| 31a257ba17 | |||
| ea9bfd2a23 | |||
| 2f1113323e | |||
| 35090663e2 |
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
**[研究图册与固定在线副本](docs/FIGURE_GALLERY.md)**:连续分布、联合消融及原始PDF/SVG。
|
**[研究图册与固定在线副本](docs/FIGURE_GALLERY.md)**:连续分布、联合消融及原始PDF/SVG。
|
||||||
|
|
||||||
|
[两个实际2B检查点的参数球壳结论](docs/MODEL_SHELL_FINDINGS.md) · [完整数值报告](results/model-shell/REPORT.md) · [固定分组和均匀参照协议](model_shell/PROTOCOL.md)。
|
||||||
|
|
||||||
Research on repeated learned functions in **Qwen3.5-2B**: a completed static weight baseline
|
Research on repeated learned functions in **Qwen3.5-2B**: a completed static weight baseline
|
||||||
and a training-free CPU functional pilot. The CPU study found similar existing RMSNorm
|
and a training-free CPU functional pilot. The CPU study found similar existing RMSNorm
|
||||||
functions at layer indices 12/13, with a uniform analytic error bound and heldout substitution checks.
|
functions at layer indices 12/13, with a uniform analytic error bound and heldout substitution checks.
|
||||||
|
|||||||
@@ -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
|
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
|
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.
|
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,101 @@
|
|||||||
|
"""Incremental full-attention sites for measuring LiSA's real K/V allocation.
|
||||||
|
|
||||||
|
The scheduler supplies the earlier full-attention site's raw score row for
|
||||||
|
the same query. This file measures an attention site, excluding GDN, MLP,
|
||||||
|
embedding, and scheduler overhead.
|
||||||
|
"""
|
||||||
|
import math
|
||||||
|
|
||||||
|
import torch
|
||||||
|
|
||||||
|
from crossqkv.lisa_tail import TorchTail, rotate
|
||||||
|
|
||||||
|
|
||||||
|
class AttentionSiteCache:
|
||||||
|
def __init__(self, tail: TorchTail, layer, batch_size, capacity, adapter=None,
|
||||||
|
dtype=torch.float32):
|
||||||
|
self.tail, self.adapter = tail, adapter
|
||||||
|
self.name = f'layers.{layer}.self_attn.'
|
||||||
|
self.heads = tail.c['num_attention_heads']
|
||||||
|
self.kv_heads = tail.c['num_key_value_heads']
|
||||||
|
self.head_dim = tail.c['head_dim']
|
||||||
|
self.key_dim = adapter.rank if adapter is not None else self.head_dim
|
||||||
|
self.capacity = capacity
|
||||||
|
self.next_position = 0
|
||||||
|
self.k = torch.empty(batch_size, capacity, self.kv_heads, self.key_dim, dtype=dtype)
|
||||||
|
self.v = torch.empty(batch_size, capacity, self.kv_heads, self.head_dim, dtype=dtype)
|
||||||
|
rp = tail.c['rope_parameters']
|
||||||
|
n = int(self.head_dim * rp['partial_rotary_factor'])
|
||||||
|
self.rotary_frequency = rp['rope_theta'] ** (-torch.arange(0, n, 2, dtype=dtype) / n)
|
||||||
|
|
||||||
|
def reset(self):
|
||||||
|
self.next_position = 0
|
||||||
|
|
||||||
|
@property
|
||||||
|
def allocated_bytes(self):
|
||||||
|
return {'k': self.k.numel()*self.k.element_size(),
|
||||||
|
'v': self.v.numel()*self.v.element_size()}
|
||||||
|
|
||||||
|
def native_rotate(self, x, position):
|
||||||
|
angle = self.rotary_frequency * position
|
||||||
|
a, b = x[..., :2*len(angle)].chunk(2, -1)
|
||||||
|
angle = torch.cat((angle, angle))
|
||||||
|
return torch.cat((torch.cat((a, b), -1)*angle.cos()
|
||||||
|
+ torch.cat((-b, a), -1)*angle.sin(),
|
||||||
|
x[..., 2*len(self.rotary_frequency):]), -1)
|
||||||
|
|
||||||
|
@torch.no_grad()
|
||||||
|
def prefill(self, h):
|
||||||
|
"""Populate K/V from a fresh prefix without scoring its queries."""
|
||||||
|
n = h.shape[1]
|
||||||
|
if h.shape[0] != self.k.shape[0] or n > self.capacity:
|
||||||
|
raise ValueError('Prefix does not fit the attention cache')
|
||||||
|
base, name = self.tail, self.name
|
||||||
|
if self.adapter is None:
|
||||||
|
rp = base.c['rope_parameters']
|
||||||
|
k = base.linear(h, name+'k_proj').unflatten(-1, (self.kv_heads, self.head_dim))
|
||||||
|
k = rotate(base.norm(k, name+'k_norm'), rp['rope_theta'], rp['partial_rotary_factor'])
|
||||||
|
else:
|
||||||
|
a = self.adapter
|
||||||
|
k = a.k_proj(h).unflatten(-1, (self.kv_heads, self.key_dim))
|
||||||
|
k = a.rotate(k, torch.arange(n, device=h.device)[None, :])
|
||||||
|
self.k[:, :n].copy_(k)
|
||||||
|
self.v[:, :n].copy_(base.linear(h, name+'v_proj').unflatten(-1, (self.kv_heads, self.head_dim)))
|
||||||
|
self.next_position = n
|
||||||
|
|
||||||
|
@torch.no_grad()
|
||||||
|
def step(self, h, donor=None):
|
||||||
|
"""h has shape (batch, 1, hidden). Return output and unmasked score row."""
|
||||||
|
pos = self.next_position
|
||||||
|
if h.shape[:2] != (self.k.shape[0], 1) or pos >= self.capacity:
|
||||||
|
raise ValueError('Wrong input shape or full attention cache')
|
||||||
|
if self.adapter is not None and (donor is None or
|
||||||
|
donor.shape != (len(h), self.heads, 1, pos+1)):
|
||||||
|
raise ValueError('LiSA requires the upstream score row for its full prefix')
|
||||||
|
base = self.tail
|
||||||
|
name = self.name
|
||||||
|
if self.adapter is None:
|
||||||
|
packed = base.linear(h, name+'q_proj').unflatten(-1, (self.heads, 2*self.head_dim))
|
||||||
|
q, gate = packed.chunk(2, -1)
|
||||||
|
k = base.linear(h, name+'k_proj').unflatten(-1, (self.kv_heads, self.head_dim))
|
||||||
|
q = self.native_rotate(base.norm(q, name+'q_norm'), pos)
|
||||||
|
k = self.native_rotate(base.norm(k, name+'k_norm'), pos)
|
||||||
|
else:
|
||||||
|
a = self.adapter
|
||||||
|
position = torch.tensor([[pos]], device=h.device)
|
||||||
|
q = a.rotate(a.q_proj(h).unflatten(-1, (self.heads, self.key_dim)), position)
|
||||||
|
k = a.rotate(a.k_proj(h).unflatten(-1, (self.kv_heads, self.key_dim)), position)
|
||||||
|
gate = base.gate_only(h, name)
|
||||||
|
v = base.linear(h, name+'v_proj').unflatten(-1, (self.kv_heads, self.head_dim))
|
||||||
|
self.k[:, pos:pos+1].copy_(k)
|
||||||
|
self.v[:, pos:pos+1].copy_(v)
|
||||||
|
self.next_position += 1
|
||||||
|
groups = self.heads // self.kv_heads
|
||||||
|
keys = self.k[:, :pos+1].repeat_interleave(groups, 2)
|
||||||
|
values = self.v[:, :pos+1].repeat_interleave(groups, 2)
|
||||||
|
scores = torch.einsum('bthd,bshd->bhts', q, keys) / math.sqrt(self.key_dim)
|
||||||
|
if self.adapter is not None:
|
||||||
|
both = torch.cat((scores, donor), dim=1).permute(0, 2, 3, 1)
|
||||||
|
scores = self.adapter.fuse(both).permute(0, 3, 1, 2)
|
||||||
|
context = torch.einsum('bhts,bshd->bthd', scores.softmax(-1), values)
|
||||||
|
return base.linear((context * gate.sigmoid()).flatten(-2), name+'o_proj'), scores
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
"""Measure real K/V allocation and isolated incremental attention on Qwen."""
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
from statistics import median
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import torch
|
||||||
|
from torch.nn import functional as F
|
||||||
|
|
||||||
|
from crossqkv.lisa_decode import AttentionSiteCache
|
||||||
|
from crossqkv.lisa_tail import TorchTail, weight_chunks
|
||||||
|
from crossqkv.lisa_train import LearnableSharingAttention
|
||||||
|
from functional.model import PREFIX, StreamingLM
|
||||||
|
from functional.run import write_json
|
||||||
|
|
||||||
|
|
||||||
|
class TracedTail(TorchTail):
|
||||||
|
def full(self, h, layer, donor, lengths, mode, recipients, keep_teacher):
|
||||||
|
self.inputs[layer] = (h, donor)
|
||||||
|
return super().full(h, layer, donor, lengths, mode, recipients, keep_teacher)
|
||||||
|
|
||||||
|
|
||||||
|
class ResidentSite:
|
||||||
|
"""Keep one site's frozen projections resident to isolate compute latency."""
|
||||||
|
|
||||||
|
def __init__(self, tail, layer):
|
||||||
|
self.tail, self.c = tail, tail.c
|
||||||
|
self.name = f'layers.{layer}.self_attn.'
|
||||||
|
self.weights = {}
|
||||||
|
for k in ('q_proj', 'k_proj', 'v_proj', 'o_proj'):
|
||||||
|
t = tail.source.tensors[PREFIX + self.name + k + '.weight']
|
||||||
|
self.weights[self.name+k] = torch.cat(list(weight_chunks(t, 0, t.shape[0])))
|
||||||
|
w = self.weights[self.name+'q_proj']
|
||||||
|
heads, dim = self.c['num_attention_heads'], self.c['head_dim']
|
||||||
|
self.gate_weight = w.reshape(heads, 2*dim, -1)[:, dim:].reshape(heads*dim, -1).contiguous()
|
||||||
|
|
||||||
|
def linear(self, h, name, start=0, end=None):
|
||||||
|
return F.linear(h, self.weights[name][start:end])
|
||||||
|
|
||||||
|
def gate_only(self, h, name):
|
||||||
|
if name != self.name:
|
||||||
|
raise ValueError('Resident gate called for the wrong site')
|
||||||
|
return F.linear(h, self.gate_weight).unflatten(-1,
|
||||||
|
(self.c['num_attention_heads'], self.c['head_dim']))
|
||||||
|
|
||||||
|
def norm(self, *args):
|
||||||
|
return self.tail.norm(*args)
|
||||||
|
|
||||||
|
|
||||||
|
def timed_site(groups, h, donor, n, samples=3, rounds=4):
|
||||||
|
timings = {k: [] for k in groups}
|
||||||
|
states = {}
|
||||||
|
for i in range(rounds):
|
||||||
|
order = tuple(groups) if i % 2 == 0 else tuple(reversed(groups))
|
||||||
|
for mode in order:
|
||||||
|
cache = groups[mode]
|
||||||
|
cache.reset()
|
||||||
|
cache.prefill(h[:, :n-samples])
|
||||||
|
for pos in range(n-samples, n):
|
||||||
|
row = donor[:, :, pos:pos+1, :pos+1].contiguous() if mode == 'lisa' else None
|
||||||
|
start = time.perf_counter()
|
||||||
|
result, attention = cache.step(h[:, pos:pos+1], row)
|
||||||
|
elapsed = time.perf_counter() - start
|
||||||
|
if i:
|
||||||
|
timings[mode].append(elapsed)
|
||||||
|
if not torch.isfinite(result).all():
|
||||||
|
raise FloatingPointError('Invalid cached decode')
|
||||||
|
states[mode] = result, attention
|
||||||
|
return timings, states
|
||||||
|
|
||||||
|
|
||||||
|
def run(source, capture, checkpoint, out):
|
||||||
|
torch.set_num_threads(1)
|
||||||
|
spec = json.loads((capture/'selection.json').read_text())
|
||||||
|
sites = spec['sites']
|
||||||
|
source = StreamingLM(source/'weights', json.loads((source/'model_config.json').read_text()))
|
||||||
|
cfg = source.config
|
||||||
|
rope = cfg['rope_parameters']
|
||||||
|
adap = {i: LearnableSharingAttention(cfg['hidden_size'], cfg['num_attention_heads'],
|
||||||
|
cfg['num_key_value_heads'], 40, rope['rope_theta'], rope['partial_rotary_factor'],
|
||||||
|
bias=cfg.get('attention_bias', False)) for i in sites}
|
||||||
|
tail = TracedTail(source, sites[0], adap)
|
||||||
|
tail.adapters.load_state_dict(torch.load(checkpoint, map_location='cpu', weights_only=True))
|
||||||
|
with np.load(sorted(capture.glob('validation-*.npz'))[0], allow_pickle=False) as f:
|
||||||
|
n = int(f['lengths'][0])
|
||||||
|
data = {k: torch.from_numpy(f[k][:1]) for k in ('residual', 'donor', 'lengths')}
|
||||||
|
data['residual'] = data['residual'][:, :n]
|
||||||
|
data['donor'] = data['donor'][:, :, :n, :n]
|
||||||
|
tail.inputs = {}
|
||||||
|
measurements = {}
|
||||||
|
with torch.no_grad():
|
||||||
|
tail(data['residual'], data['donor'], data['lengths'], 'native', ())
|
||||||
|
for layer in sites:
|
||||||
|
h, donor = tail.inputs[layer]
|
||||||
|
groups = {'native': AttentionSiteCache(tail, layer, 1, n),
|
||||||
|
'lisa': AttentionSiteCache(tail, layer, 1, n, adap[layer])}
|
||||||
|
timings, reference = timed_site(groups, h, donor, n)
|
||||||
|
resident = ResidentSite(tail, layer)
|
||||||
|
resident_groups = {mode: AttentionSiteCache(resident, layer, 1, n,
|
||||||
|
adap[layer] if mode == 'lisa' else None) for mode in groups}
|
||||||
|
warm, checked = timed_site(resident_groups, h, donor, n)
|
||||||
|
for mode in groups:
|
||||||
|
for actual, expected in zip(checked[mode], reference[mode]):
|
||||||
|
torch.testing.assert_close(actual, expected, rtol=5e-5, atol=5e-5)
|
||||||
|
measurements[layer] = {'seconds_per_token': timings,
|
||||||
|
'resident_seconds_per_token': warm,
|
||||||
|
'resident_median_s_per_token': {k: median(v) for k,v in warm.items()},
|
||||||
|
'resident_matches_streamed': True,
|
||||||
|
'allocated_bytes': {k: v.allocated_bytes for k, v in groups.items()},
|
||||||
|
'lisa_input_score_row_bytes': (
|
||||||
|
cfg['num_attention_heads'] * n * h.element_size()),
|
||||||
|
'sequence_length': n}
|
||||||
|
write_json(out, {'scope': 'isolated full-attention recipient, FP32, frozen true activations; '
|
||||||
|
'excludes donor generation and full-model decode', 'sites': measurements,
|
||||||
|
'streamed_timings_include_weight_reads': True,
|
||||||
|
'resident_timings_exclude_projection_load': True})
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
p = argparse.ArgumentParser(description=__doc__)
|
||||||
|
for name in ('source', 'capture', 'checkpoint', 'out'):
|
||||||
|
p.add_argument('--'+name, type=Path, required=True)
|
||||||
|
a = p.parse_args()
|
||||||
|
run(a.source, a.capture, a.checkpoint, a.out)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
@@ -0,0 +1,296 @@
|
|||||||
|
"""Train matched multi-recipient sharing adapters and evaluate the frozen test set."""
|
||||||
|
import argparse
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from crossqkv.core import QKVModel
|
||||||
|
from crossqkv.lisa_effect_screen import TASKS
|
||||||
|
from crossqkv.lisa_pilot import batch, scores
|
||||||
|
from functional.model import PREFIX
|
||||||
|
from functional.run import write_json
|
||||||
|
|
||||||
|
CANDIDATES = ('linear', 'lisa', 'lisa_answer_weighted')
|
||||||
|
|
||||||
|
|
||||||
|
def selection(screen):
|
||||||
|
eligible = []
|
||||||
|
for task, modes in screen.items():
|
||||||
|
base = modes['native']
|
||||||
|
if base['correct'] < 5:
|
||||||
|
continue
|
||||||
|
for name, sites in [('direct_23', [23]), ('direct_19_23', [19, 23])]:
|
||||||
|
row = modes[name]
|
||||||
|
if row['native_wins_lost']:
|
||||||
|
eligible.append((row['native_wins_lost'], len(sites),
|
||||||
|
base['correct']-row['correct'], task, sites))
|
||||||
|
if not eligible:
|
||||||
|
raise ValueError('No task/schedule met the prespecified development eligibility rule')
|
||||||
|
_, _, _, task, sites = max(eligible)
|
||||||
|
return {'task': task, 'sites': sites}
|
||||||
|
|
||||||
|
|
||||||
|
class Capture(QKVModel):
|
||||||
|
def normalization(self, x, name):
|
||||||
|
if name == f'layers.{self.first}.input_layernorm':
|
||||||
|
self.residual = x
|
||||||
|
return super().normalization(x, name)
|
||||||
|
|
||||||
|
def full_attention(self, h, layer, shared_p=None):
|
||||||
|
if layer != self.first - 4:
|
||||||
|
return super().full_attention(h, layer, shared_p)
|
||||||
|
part = self.parts(h, layer, heads=False)
|
||||||
|
self.donor = scores(part['q'], part['k'])
|
||||||
|
return part['output'], part['p']
|
||||||
|
|
||||||
|
|
||||||
|
def capture(source, screen_dir, out, schedule):
|
||||||
|
from tokenizers import Tokenizer
|
||||||
|
|
||||||
|
fixed_path = screen_dir/'fixed-problems.json'
|
||||||
|
fixed = json.loads(fixed_path.read_text())
|
||||||
|
chosen = selection(json.loads((screen_dir/'screen-summary.json').read_text()))
|
||||||
|
if schedule == 'chain':
|
||||||
|
modes = json.loads((screen_dir/'screen-summary.json').read_text())[chosen['task']]
|
||||||
|
if not modes['direct_19_23']['native_wins_lost']:
|
||||||
|
raise ValueError('The development-selected task has no recorded losses under the chain')
|
||||||
|
chosen['sites'] = [19, 23]
|
||||||
|
model = Capture(source/'weights', json.loads((source/'model_config.json').read_text()),
|
||||||
|
seconds=7200)
|
||||||
|
model.first = chosen['sites'][0]
|
||||||
|
tok = Tokenizer.from_file(str(source/'tokenizer.json'))
|
||||||
|
sha = lambda path: hashlib.sha256(path.read_bytes()).hexdigest()
|
||||||
|
write_json(out/'selection.json', {**chosen, 'fixed_problems_sha256': sha(fixed_path),
|
||||||
|
'source_sha256': {n: sha(source/n) for n in
|
||||||
|
('manifest.json', 'model_config.json', 'tokenizer.json')}})
|
||||||
|
for split in ('fit', 'validation', 'test'):
|
||||||
|
selected = [ex for ex in fixed[split] if ex['task'] == chosen['task']]
|
||||||
|
for start in range(0, len(selected), 4):
|
||||||
|
group = selected[start:start+4]
|
||||||
|
ids, lengths, labels = batch(tok, group)
|
||||||
|
gold = np.array([r['answer_index'] for r in group])
|
||||||
|
ids = np.pad(ids, ((0, 0), (0, 1)))
|
||||||
|
ids[np.arange(len(group)), lengths] = np.asarray(labels)[gold]
|
||||||
|
h, _ = model.forward(ids)
|
||||||
|
pending = out/f'{split}-{start:03}.tmp.npz'
|
||||||
|
np.savez(pending, ids=ids, lengths=np.asarray(lengths)+1, labels=labels, gold=gold,
|
||||||
|
residual=model.residual, donor=model.donor, expected=h,
|
||||||
|
names=[x['id'] for x in group])
|
||||||
|
pending.replace(out/f'{split}-{start:03}.npz')
|
||||||
|
print('capture', split, start+len(group), '/', len(selected), flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
def train(source, cache, out, epochs, resume=False):
|
||||||
|
import torch
|
||||||
|
from torch import nn
|
||||||
|
from crossqkv.lisa_tail import TorchTail
|
||||||
|
from crossqkv.lisa_train import LearnableSharingAttention, huber_distillation, language_model_loss
|
||||||
|
from functional.model import StreamingLM
|
||||||
|
|
||||||
|
torch.set_num_threads(1)
|
||||||
|
torch.manual_seed(415005)
|
||||||
|
spec = json.loads((cache/'selection.json').read_text())
|
||||||
|
if any(hashlib.sha256((source/n).read_bytes()).hexdigest() != s
|
||||||
|
for n, s in spec['source_sha256'].items()):
|
||||||
|
raise ValueError('Checkpoint provenance mismatch')
|
||||||
|
expected_batches = {'fit':12, 'validation':12, 'test':32}
|
||||||
|
for split, count in expected_batches.items():
|
||||||
|
actual = 0
|
||||||
|
for p in cache.glob(f'{split}-*.npz'):
|
||||||
|
with np.load(p, allow_pickle=False) as b:
|
||||||
|
actual += len(b['names'])
|
||||||
|
if actual != count:
|
||||||
|
raise ValueError(f'Expected {count} {split} examples, found {actual}')
|
||||||
|
run_config = {'epochs': epochs, 'selection': spec, 'optimizer': 'AdamW',
|
||||||
|
'lr': .0003, 'weight_decay': .1, 'answer_weight': 16., 'seed': 415005}
|
||||||
|
config_path = out/'train-protocol.json'
|
||||||
|
if resume:
|
||||||
|
if json.loads(config_path.read_text()) != run_config:
|
||||||
|
raise ValueError('Training configuration differs from the original run')
|
||||||
|
else:
|
||||||
|
write_json(config_path, run_config)
|
||||||
|
model = StreamingLM(source/'weights', json.loads((source/'model_config.json').read_text()))
|
||||||
|
sites = tuple(spec['sites'])
|
||||||
|
cfg = model.config
|
||||||
|
heads = cfg['num_attention_heads']
|
||||||
|
rope = cfg['rope_parameters']
|
||||||
|
t = model.tensors[PREFIX+'embed_tokens.weight']
|
||||||
|
|
||||||
|
def vocab():
|
||||||
|
for start in range(0, t.shape[0], 1024):
|
||||||
|
end = min(start+1024, t.shape[0])
|
||||||
|
yield start, torch.from_numpy(t.read(slice(start*t.shape[1], end*t.shape[1]))
|
||||||
|
.reshape(end-start, t.shape[1]))
|
||||||
|
t.evict()
|
||||||
|
|
||||||
|
def batches(split, micro=False):
|
||||||
|
for path in sorted(cache.glob(f'{split}-*.npz')):
|
||||||
|
with np.load(path, allow_pickle=False) as f:
|
||||||
|
b = {k: torch.from_numpy(f[k]) for k in f.files if k != 'names'}
|
||||||
|
names = f['names'].tolist()
|
||||||
|
if not micro:
|
||||||
|
yield b, names
|
||||||
|
else:
|
||||||
|
for j, name in enumerate(names):
|
||||||
|
yield {k: v if k == 'labels' else v[j:j+1] for k, v in b.items()}, [name]
|
||||||
|
|
||||||
|
def make(candidate):
|
||||||
|
torch.manual_seed(415005)
|
||||||
|
if candidate == 'linear':
|
||||||
|
blocks = {i: nn.Linear(heads, heads, bias=False) for i in sites}
|
||||||
|
for value in blocks.values():
|
||||||
|
with torch.no_grad():
|
||||||
|
value.weight.copy_(torch.eye(heads))
|
||||||
|
else:
|
||||||
|
blocks = {i: LearnableSharingAttention(cfg['hidden_size'], heads,
|
||||||
|
cfg['num_key_value_heads'], 40, rope['rope_theta'],
|
||||||
|
rope['partial_rotary_factor'], bias=cfg.get('attention_bias', False))
|
||||||
|
for i in sites}
|
||||||
|
return TorchTail(model, sites[0], blocks)
|
||||||
|
|
||||||
|
def run(tail, b, mode, teacher=False):
|
||||||
|
return tail(b['residual'], b['donor'], b['lengths'], mode, sites, teacher)
|
||||||
|
|
||||||
|
def score(h, b):
|
||||||
|
index = b['lengths'] - 2
|
||||||
|
f = h[torch.arange(len(index)), index]
|
||||||
|
labels = b['labels'].tolist()
|
||||||
|
weights = np.stack([t.read(slice(i*t.shape[1], (i+1)*t.shape[1])) for i in labels])
|
||||||
|
t.evict()
|
||||||
|
logits = f @ torch.from_numpy(weights).T
|
||||||
|
nll = torch.logsumexp(logits, -1) - logits[torch.arange(len(index)), b['gold']]
|
||||||
|
return logits, nll
|
||||||
|
|
||||||
|
def evaluate(tail, split, mode):
|
||||||
|
rows = []
|
||||||
|
with torch.no_grad():
|
||||||
|
for b, names in batches(split):
|
||||||
|
h, _ = run(tail, b, mode)
|
||||||
|
if mode == 'native':
|
||||||
|
valid = torch.arange(h.shape[1])[None] < b['lengths'][:, None]
|
||||||
|
torch.testing.assert_close(h[valid], b['expected'][valid], rtol=7e-5, atol=8e-5)
|
||||||
|
logits, nll = score(h, b)
|
||||||
|
rows.extend({'id': name, 'gold': int(g), 'logits': x.tolist(),
|
||||||
|
'pred': int(x.argmax()), 'answer_nll': float(v)}
|
||||||
|
for name, g, x, v in zip(names, b['gold'], logits, nll))
|
||||||
|
if not rows:
|
||||||
|
raise ValueError(f'No cached rows for {split}')
|
||||||
|
return rows
|
||||||
|
|
||||||
|
def mean_nll(rows):
|
||||||
|
return sum(r['answer_nll'] for r in rows) / len(rows)
|
||||||
|
|
||||||
|
trace = {}
|
||||||
|
for candidate in CANDIDATES:
|
||||||
|
tail = make(candidate)
|
||||||
|
mode = 'linear' if candidate == 'linear' else 'lisa'
|
||||||
|
optim = torch.optim.AdamW(tail.parameters(), lr=.0003, weight_decay=.1)
|
||||||
|
ans_weight = 16.0 if candidate == 'lisa_answer_weighted' else 1.0
|
||||||
|
best = float('inf')
|
||||||
|
best_weights = None
|
||||||
|
trace[candidate] = []
|
||||||
|
last = out/f'{candidate}-resume.pt'
|
||||||
|
if resume and last.exists():
|
||||||
|
state = torch.load(last, weights_only=True, map_location='cpu')
|
||||||
|
tail.adapters.load_state_dict(state['parameters'])
|
||||||
|
optim.load_state_dict(state['optimizer'])
|
||||||
|
trace[candidate] = state['trace']
|
||||||
|
best = state['best']
|
||||||
|
best_weights = state['best_parameters']
|
||||||
|
for epoch in range(len(trace[candidate]), epochs):
|
||||||
|
loss_total = 0.
|
||||||
|
count = 0
|
||||||
|
for b, _ in batches('fit', micro=True):
|
||||||
|
optim.zero_grad(set_to_none=True)
|
||||||
|
h, layer = run(tail, b, mode, teacher=True)
|
||||||
|
kd = torch.stack([huber_distillation(*layer[i], b['lengths']) for i in sites]).mean()
|
||||||
|
ce = None if mode == 'linear' else language_model_loss(
|
||||||
|
h, b['ids'], b['lengths'], vocab, answer_weight=ans_weight)
|
||||||
|
loss = kd if ce is None else .25 * kd + .75 * ce
|
||||||
|
loss.backward()
|
||||||
|
if any(p.grad is None or not torch.isfinite(p.grad).all() for p in tail.parameters()):
|
||||||
|
raise FloatingPointError('Invalid adapter gradients')
|
||||||
|
optim.step()
|
||||||
|
loss_total += float(loss.detach())
|
||||||
|
count += 1
|
||||||
|
rows = evaluate(tail, 'validation', mode)
|
||||||
|
val = mean_nll(rows)
|
||||||
|
trace[candidate].append({'epoch': epoch+1, 'fit_loss': loss_total/count,
|
||||||
|
'validation_answer_nll': val})
|
||||||
|
if val < best:
|
||||||
|
best = val
|
||||||
|
best_weights = {k: v.detach().clone() for k, v in tail.adapters.state_dict().items()}
|
||||||
|
pending = last.with_suffix('.tmp')
|
||||||
|
torch.save({'parameters': tail.adapters.state_dict(), 'optimizer': optim.state_dict(),
|
||||||
|
'trace': trace[candidate], 'best': best, 'best_parameters': best_weights},
|
||||||
|
pending)
|
||||||
|
pending.replace(last)
|
||||||
|
write_json(out/'trace.json', trace)
|
||||||
|
print(candidate, epoch+1, 'validation answer NLL', val, flush=True)
|
||||||
|
selected = out/f'{candidate}.pt'
|
||||||
|
pending = selected.with_suffix('.tmp')
|
||||||
|
torch.save(best_weights, pending)
|
||||||
|
pending.replace(selected)
|
||||||
|
|
||||||
|
# All checkpoints are frozen before evaluating holdout. Native and direct
|
||||||
|
# go through the same path, including numerical parity with NumPy.
|
||||||
|
results = {}
|
||||||
|
empty = TorchTail(model, sites[0])
|
||||||
|
for mode in ('native', 'direct'):
|
||||||
|
results[mode] = evaluate(empty, 'test', mode)
|
||||||
|
for name in CANDIDATES:
|
||||||
|
tail = make(name)
|
||||||
|
tail.adapters.load_state_dict(torch.load(out/f'{name}.pt', map_location='cpu', weights_only=True))
|
||||||
|
results[name] = evaluate(tail, 'test', 'linear' if name == 'linear' else 'lisa')
|
||||||
|
write_json(out/'test-items.json', results)
|
||||||
|
|
||||||
|
b, _ = next(batches('validation'))
|
||||||
|
b = {k: v if k == 'labels' else v[:1] for k, v in b.items()}
|
||||||
|
trained = make('lisa')
|
||||||
|
trained.adapters.load_state_dict(torch.load(out/'lisa.pt', weights_only=True))
|
||||||
|
timing = {'native': [], 'direct': [], 'lisa': []}
|
||||||
|
with torch.no_grad():
|
||||||
|
for turn in range(4):
|
||||||
|
modes = list(timing)
|
||||||
|
for mode in modes[turn % 3:] + modes[:turn % 3]:
|
||||||
|
t0 = time.perf_counter()
|
||||||
|
_, _ = run(trained if mode == 'lisa' else empty, b, mode)
|
||||||
|
if turn:
|
||||||
|
timing[mode].append(time.perf_counter()-t0)
|
||||||
|
tokens = int(b['lengths'][0])
|
||||||
|
kv, d = cfg['num_key_value_heads'], cfg['head_dim']
|
||||||
|
cache_bytes = {'scope': 'formula for one sequence, BF16 keys and score buffers',
|
||||||
|
'native_recipient_key_bytes': len(sites)*tokens*kv*d*2,
|
||||||
|
'lisa_recipient_key_bytes': len(sites)*tokens*kv*40*2,
|
||||||
|
'one_shared_decode_score_row_bytes': heads*tokens*2,
|
||||||
|
'one_full_prefill_score_matrix_bytes': heads*tokens*tokens*2}
|
||||||
|
write_json(out/'performance.json', {'scope': 'cached-prefix last layers, prefill',
|
||||||
|
'seconds': timing, 'real_tokens': tokens, 'cache_estimate': cache_bytes})
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
p = argparse.ArgumentParser(description=__doc__)
|
||||||
|
p.add_argument('phase', choices=('capture', 'train'))
|
||||||
|
p.add_argument('--source', required=True, type=Path)
|
||||||
|
p.add_argument('--input', required=True, type=Path)
|
||||||
|
p.add_argument('--out', required=True, type=Path)
|
||||||
|
p.add_argument('--schedule', choices=('best','chain'), default='best')
|
||||||
|
p.add_argument('--epochs', type=int, default=2)
|
||||||
|
p.add_argument('--resume', action='store_true')
|
||||||
|
a = p.parse_args()
|
||||||
|
if a.epochs < 1:
|
||||||
|
p.error('--epochs must be positive')
|
||||||
|
if a.resume and a.phase != 'train':
|
||||||
|
p.error('--resume is for training with saved epoch checkpoints')
|
||||||
|
a.out.mkdir(exist_ok=a.resume)
|
||||||
|
if a.phase == 'capture':
|
||||||
|
capture(a.source, a.input, a.out, a.schedule)
|
||||||
|
else:
|
||||||
|
train(a.source, a.input, a.out, a.epochs, a.resume)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
"""Compare one vs two recipients on the same task using full-vocabulary answers."""
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import torch
|
||||||
|
from torch.nn import functional as F
|
||||||
|
|
||||||
|
from crossqkv.lisa_tail import TorchTail, weight_chunks
|
||||||
|
from crossqkv.lisa_train import LearnableSharingAttention
|
||||||
|
from functional.model import PREFIX, StreamingLM
|
||||||
|
from functional.run import write_json
|
||||||
|
|
||||||
|
|
||||||
|
def vocabulary_scores(hidden, targets, embedding):
|
||||||
|
n = len(hidden)
|
||||||
|
peak = hidden.new_full((n,), -torch.inf)
|
||||||
|
total = peak.clone()
|
||||||
|
top = torch.zeros(n, dtype=torch.int64)
|
||||||
|
true = torch.zeros_like(peak)
|
||||||
|
start = 0
|
||||||
|
for w in weight_chunks(embedding, 0, embedding.shape[0], rows=1024):
|
||||||
|
logits = F.linear(hidden, w)
|
||||||
|
total = torch.logaddexp(total, logits.logsumexp(dim=-1))
|
||||||
|
values, indices = logits.max(dim=-1)
|
||||||
|
top = torch.where(values > peak, indices + start, top)
|
||||||
|
peak = torch.maximum(values, peak)
|
||||||
|
local = (targets >= start) & (targets < start + len(w))
|
||||||
|
true[local] = logits[local, targets[local]-start]
|
||||||
|
start += len(w)
|
||||||
|
return top, total-true
|
||||||
|
|
||||||
|
|
||||||
|
def run(source, cache, trained, out):
|
||||||
|
torch.set_num_threads(1)
|
||||||
|
spec = json.loads((cache/'selection.json').read_text())
|
||||||
|
sites = tuple(spec['sites'])
|
||||||
|
stream = StreamingLM(source/'weights', json.loads((source/'model_config.json').read_text()))
|
||||||
|
cfg = stream.config
|
||||||
|
rp = cfg['rope_parameters']
|
||||||
|
heads, kv = cfg['num_attention_heads'], cfg['num_key_value_heads']
|
||||||
|
|
||||||
|
def loaded(mode):
|
||||||
|
if mode == 'linear':
|
||||||
|
from torch import nn
|
||||||
|
|
||||||
|
modules = {site: nn.Linear(heads, heads, bias=False) for site in sites}
|
||||||
|
else:
|
||||||
|
modules = {site: LearnableSharingAttention(cfg['hidden_size'], heads, kv, 40,
|
||||||
|
rp['rope_theta'], rp['partial_rotary_factor'],
|
||||||
|
bias=cfg.get('attention_bias', False)) for site in sites}
|
||||||
|
tail = TorchTail(stream, sites[0], modules)
|
||||||
|
tail.adapters.load_state_dict(torch.load(trained/f'{mode}.pt', weights_only=True,
|
||||||
|
map_location='cpu'))
|
||||||
|
return tail
|
||||||
|
|
||||||
|
empty = TorchTail(stream, sites[0])
|
||||||
|
fitted = loaded('lisa')
|
||||||
|
arms = [('native', empty, 'native', ()),
|
||||||
|
('direct_23', empty, 'direct', (sites[-1],)),
|
||||||
|
('lisa_23_ablation', fitted, 'lisa', (sites[-1],))]
|
||||||
|
if len(sites) > 1:
|
||||||
|
arms.extend([('direct_chain', empty, 'direct', sites),
|
||||||
|
('lisa_chain', fitted, 'lisa', sites)])
|
||||||
|
arms.extend([('linear', loaded('linear'), 'linear', sites),
|
||||||
|
('lisa_answer_weighted', loaded('lisa_answer_weighted'), 'lisa', sites)])
|
||||||
|
answers = {name: [] for name, *_ in arms}
|
||||||
|
ids, labels, options = [], [], []
|
||||||
|
with torch.no_grad():
|
||||||
|
for path in sorted(cache.glob('test-*.npz')):
|
||||||
|
with np.load(path, allow_pickle=False) as f:
|
||||||
|
b = {k: torch.from_numpy(f[k]) for k in f.files if k != 'names'}
|
||||||
|
ids.extend(f['names'].tolist())
|
||||||
|
labels.append(b['labels'][b['gold']])
|
||||||
|
options.append(b['labels'].expand(len(b['gold']), -1))
|
||||||
|
for name, tail, mode, chosen in arms:
|
||||||
|
h, _ = tail(b['residual'], b['donor'], b['lengths'], mode, chosen)
|
||||||
|
answers[name].append(h[torch.arange(len(h)), b['lengths']-2])
|
||||||
|
print('matched full-vocabulary audit', len(ids), flush=True)
|
||||||
|
if not ids:
|
||||||
|
raise ValueError('No captured holdout batches')
|
||||||
|
y = torch.cat(labels)
|
||||||
|
t = stream.tensors[PREFIX+'embed_tokens.weight']
|
||||||
|
hidden = torch.cat([torch.cat(answers[k]) for k in answers])
|
||||||
|
pred, nll = vocabulary_scores(hidden, y.repeat(len(answers)), t)
|
||||||
|
result = {}
|
||||||
|
opts = torch.cat(options)
|
||||||
|
for (name, h), p, v in zip(answers.items(), pred.split(len(y)), nll.split(len(y))):
|
||||||
|
option_w = torch.stack([torch.from_numpy(t.read(slice(i*t.shape[1], (i+1)*t.shape[1])))
|
||||||
|
for i in opts[0].tolist()])
|
||||||
|
if not torch.equal(opts, opts[0].expand_as(opts)):
|
||||||
|
raise ValueError('Option token IDs unexpectedly vary across items')
|
||||||
|
t.evict()
|
||||||
|
choice = opts[torch.arange(len(y)), F.linear(torch.cat(h), option_w).argmax(-1)]
|
||||||
|
result[name] = {'n': len(y), 'full_vocab_correct': int((p==y).sum()),
|
||||||
|
'four_choice_correct': int((choice==y).sum()),
|
||||||
|
'full_vocab_nll': float(v.mean()),
|
||||||
|
'rows': [{'id': key, 'gold_id': int(g), 'greedy_id': int(j),
|
||||||
|
'choice_id': int(c), 'nll': float(s)}
|
||||||
|
for key, g, j, c, s in zip(ids, y, p, choice, v)]}
|
||||||
|
write_json(out, {'single_lisa_is_ablation_of_joint_checkpoint': len(sites) > 1,
|
||||||
|
'candidate_sites': list(sites), 'arms': result})
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
p = argparse.ArgumentParser(description=__doc__)
|
||||||
|
for name in ('source', 'cache', 'trained', 'out'):
|
||||||
|
p.add_argument('--'+name, type=Path, required=True)
|
||||||
|
a = p.parse_args()
|
||||||
|
run(a.source, a.cache, a.trained, a.out)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
"""Independently validate frozen test outputs and report paired capability recovery."""
|
||||||
|
import argparse
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
from pathlib import Path
|
||||||
|
from statistics import median
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from functional.run import write_json
|
||||||
|
|
||||||
|
MODES = ('native', 'direct', 'linear', 'lisa', 'lisa_answer_weighted')
|
||||||
|
|
||||||
|
|
||||||
|
def paired_interval(delta):
|
||||||
|
rng = np.random.default_rng(415006)
|
||||||
|
draw = rng.integers(0, len(delta), size=(10000, len(delta)))
|
||||||
|
return np.quantile(delta[draw].mean(1), [.025, .975]).tolist()
|
||||||
|
|
||||||
|
|
||||||
|
def paired(native, direct, candidate):
|
||||||
|
damaged = native & ~direct
|
||||||
|
rescued = damaged & candidate
|
||||||
|
newly_lost = native & direct & ~candidate
|
||||||
|
candidate_only = ~direct & candidate
|
||||||
|
direct_only = direct & ~candidate
|
||||||
|
delta = candidate.astype(int) - direct.astype(int)
|
||||||
|
a, b = int(candidate_only.sum()), int(direct_only.sum())
|
||||||
|
k = a + b
|
||||||
|
p = min(1., 2. * sum(math.comb(k, i) for i in range(min(a, b)+1)) / 2**k)
|
||||||
|
return {'native_correct_lost_by_direct': int(damaged.sum()), 'rescued': int(rescued.sum()),
|
||||||
|
'newly_lost_among_native_and_direct_correct': int(newly_lost.sum()),
|
||||||
|
'candidate_correct_direct_wrong': a, 'direct_correct_candidate_wrong': b,
|
||||||
|
'accuracy_delta_vs_direct': float(delta.mean()),
|
||||||
|
'paired_prompt_bootstrap_95': paired_interval(delta), 'mcnemar_exact_p': p}
|
||||||
|
|
||||||
|
|
||||||
|
def loss_delta(losses, baseline):
|
||||||
|
delta = losses - baseline
|
||||||
|
return {'mean_delta': float(delta.mean()), 'paired_prompt_bootstrap_95': paired_interval(delta)}
|
||||||
|
|
||||||
|
|
||||||
|
def full_vocab_metrics(path, expected, sites, choices):
|
||||||
|
report = json.loads(path.read_text())
|
||||||
|
chain = len(sites) > 1
|
||||||
|
if (report['candidate_sites'] != sites
|
||||||
|
or report['single_lisa_is_ablation_of_joint_checkpoint'] != chain):
|
||||||
|
raise ValueError('Full-vocabulary layers differ from the locked schedule')
|
||||||
|
arms = report['arms']
|
||||||
|
mapped = {'native': 'native', 'linear': 'linear', 'lisa_answer_weighted': 'lisa_answer_weighted',
|
||||||
|
'direct_chain' if chain else 'direct_23': 'direct',
|
||||||
|
'lisa_chain' if chain else 'lisa_23_ablation': 'lisa'}
|
||||||
|
if set(arms) != set(mapped) | {'direct_23', 'lisa_23_ablation'}:
|
||||||
|
raise ValueError('Unexpected full-vocabulary arms')
|
||||||
|
expected_ids = [name for name, _ in expected]
|
||||||
|
correct, nll = {}, {}
|
||||||
|
gold_ids = [row['gold_id'] for row in arms['native']['rows']]
|
||||||
|
for mode, summary in arms.items():
|
||||||
|
rows = summary['rows']
|
||||||
|
if (summary['n'] != len(expected_ids) or [row['id'] for row in rows] != expected_ids
|
||||||
|
or [row['gold_id'] for row in rows] != gold_ids):
|
||||||
|
raise ValueError(f'{mode} vocabulary result does not match the locked rows')
|
||||||
|
correct[mode] = np.array([row['greedy_id'] == row['gold_id'] for row in rows])
|
||||||
|
nll[mode] = np.array([row['nll'] for row in rows])
|
||||||
|
choice_correct = np.array([row['choice_id'] == row['gold_id'] for row in rows])
|
||||||
|
if (not np.isfinite(nll[mode]).all() or (nll[mode] < 0).any()
|
||||||
|
or int(correct[mode].sum()) != summary['full_vocab_correct']
|
||||||
|
or int(choice_correct.sum()) != summary['four_choice_correct']
|
||||||
|
or not np.isclose(nll[mode].mean(), summary['full_vocab_nll'])):
|
||||||
|
raise ValueError(f'Invalid vocabulary metrics for {mode}')
|
||||||
|
if mode in mapped and not np.array_equal(choice_correct, choices[mapped[mode]]):
|
||||||
|
raise ValueError(f'{mode} choices differ across the two evaluations')
|
||||||
|
matches = {'lisa_23_ablation': 'direct_23',
|
||||||
|
'native': 'direct_chain' if chain else 'direct_23',
|
||||||
|
'linear': 'direct_chain' if chain else 'direct_23',
|
||||||
|
'lisa_answer_weighted': 'direct_chain' if chain else 'direct_23'}
|
||||||
|
if chain:
|
||||||
|
matches['lisa_chain'] = 'direct_chain'
|
||||||
|
return {
|
||||||
|
'arms': {mode: {'correct': int(correct[mode].sum()), 'answer_nll': float(nll[mode].mean())}
|
||||||
|
for mode in arms},
|
||||||
|
'matched_direct_comparisons': {
|
||||||
|
mode: {'baseline': direct, 'answer_nll_delta': loss_delta(nll[mode], nll[direct]),
|
||||||
|
**paired(correct['native'], correct[direct], correct[mode])}
|
||||||
|
for mode, direct in matches.items()},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def audit(fixed, selection, items, perf=None, decode=None, full_vocab=None):
|
||||||
|
spec = json.loads(selection.read_text())
|
||||||
|
if hashlib.sha256(fixed.read_bytes()).hexdigest() != spec['fixed_problems_sha256']:
|
||||||
|
raise ValueError('Fixed problems provenance mismatch')
|
||||||
|
problem = json.loads(fixed.read_text())
|
||||||
|
task = spec['task']
|
||||||
|
expected = [(r['id'], r['answer_index']) for r in problem['test'] if r['task'] == task]
|
||||||
|
data = json.loads(items.read_text())
|
||||||
|
if set(data) != set(MODES) or not expected:
|
||||||
|
raise ValueError('Unexpected test arms or empty selected split')
|
||||||
|
correct = {}
|
||||||
|
losses = {}
|
||||||
|
for mode, rows in data.items():
|
||||||
|
if [(r['id'], r['gold']) for r in rows] != expected:
|
||||||
|
raise ValueError(f'{mode} result does not match the locked challenge')
|
||||||
|
logits = np.array([r['logits'] for r in rows])
|
||||||
|
gold = np.array([r['gold'] for r in rows])
|
||||||
|
pred = np.array([r['pred'] for r in rows])
|
||||||
|
nll = np.logaddexp.reduce(logits, 1) - logits[np.arange(len(rows)), gold]
|
||||||
|
if (logits.shape != (len(rows), 4) or not np.isfinite(logits).all()
|
||||||
|
or not np.array_equal(logits.argmax(1), pred)):
|
||||||
|
raise ValueError(f'Invalid choice scores for {mode}')
|
||||||
|
np.testing.assert_allclose(nll, [row['answer_nll'] for row in rows], atol=3e-6, rtol=2e-6)
|
||||||
|
correct[mode], losses[mode] = pred == gold, nll
|
||||||
|
metrics = {'selected_task': task, 'sites': spec['sites'], 'n': len(expected),
|
||||||
|
'arms': {mode: {'correct': int(correct[mode].sum()),
|
||||||
|
'answer_nll_4': float(losses[mode].mean()),
|
||||||
|
'answer_nll_4_vs_direct': loss_delta(losses[mode], losses['direct']),
|
||||||
|
**paired(correct['native'], correct['direct'], correct[mode])}
|
||||||
|
for mode in MODES}}
|
||||||
|
if perf:
|
||||||
|
measured = json.loads(perf.read_text())
|
||||||
|
med = {k: median(v) for k,v in measured['seconds'].items()}
|
||||||
|
metrics['prefill'] = {'scope': measured['scope'], 'median_s': med,
|
||||||
|
'lisa_median_ratio_to_native': med['lisa']/med['native']}
|
||||||
|
if decode:
|
||||||
|
measured = json.loads(decode.read_text())
|
||||||
|
metrics['decode'] = {'scope': measured['scope'], 'sites': {}}
|
||||||
|
for layer, raw in measured['sites'].items():
|
||||||
|
times = {k: median(v) for k,v in raw['seconds_per_token'].items()}
|
||||||
|
mem = raw['allocated_bytes']
|
||||||
|
native = mem['native']['k'] + mem['native']['v']
|
||||||
|
lisa = mem['lisa']['k'] + mem['lisa']['v']
|
||||||
|
nn = raw['lisa_input_score_row_bytes']
|
||||||
|
assert mem['lisa']['v'] == mem['native']['v'] and mem['lisa']['k'] < mem['native']['k']
|
||||||
|
metrics['decode']['sites'][layer] = {
|
||||||
|
'median_s_per_token': times, 'measured_kv_bytes': {'native': native, 'lisa': lisa},
|
||||||
|
'lisa_upstream_score_row_bytes': nn, 'recipient_bytes_delta': lisa+nn-native,
|
||||||
|
}
|
||||||
|
if full_vocab:
|
||||||
|
metrics['full_vocab'] = full_vocab_metrics(full_vocab, expected, spec['sites'], correct)
|
||||||
|
return metrics
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
for name in ('fixed', 'selection', 'items', 'out'):
|
||||||
|
parser.add_argument('--'+name, type=Path, required=True)
|
||||||
|
parser.add_argument('--perf', type=Path)
|
||||||
|
parser.add_argument('--decode', type=Path)
|
||||||
|
parser.add_argument('--full-vocab', type=Path)
|
||||||
|
a = parser.parse_args()
|
||||||
|
report = audit(a.fixed, a.selection, a.items, a.perf, a.decode, a.full_vocab)
|
||||||
|
write_json(a.out, report)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
"""Screen task difficulty and joint sharing schedules without opening test results."""
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import random
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
from tokenizers import Tokenizer
|
||||||
|
|
||||||
|
from crossqkv.core import QKVModel
|
||||||
|
from crossqkv.lisa_pilot import batch
|
||||||
|
from functional.model import PREFIX
|
||||||
|
from functional.run import write_json
|
||||||
|
from pilot.tensors import decode
|
||||||
|
|
||||||
|
MODES = ('native', 'direct_23', 'direct_19_23')
|
||||||
|
SITES = (15, 19, 23)
|
||||||
|
TASKS = ('lookup8', 'lookup16', 'latest8', 'arithmetic')
|
||||||
|
SPLIT_SEEDS = {'screen': 415001, 'fit': 415002, 'validation': 415003, 'test': 415004}
|
||||||
|
WORDS = ('amber birch cedar dune elm fern grove heath iris jade kelp larch '
|
||||||
|
'maple nettle olive pine quartz reed slate thyme umber vine willow yew').split()
|
||||||
|
|
||||||
|
|
||||||
|
def problems(split, per_task):
|
||||||
|
rng = random.Random(SPLIT_SEEDS[split])
|
||||||
|
rows = []
|
||||||
|
for task in TASKS:
|
||||||
|
answers = [i % 4 for i in range(per_task)]
|
||||||
|
rng.shuffle(answers)
|
||||||
|
for i, answer in enumerate(answers):
|
||||||
|
if task == 'arithmetic':
|
||||||
|
a, b = rng.sample(range(12, 99), 2)
|
||||||
|
target = a + b
|
||||||
|
distractors = [target - 10, target + 10, target + rng.choice((-1, 1))]
|
||||||
|
question = f'What is {a} + {b}?'
|
||||||
|
else:
|
||||||
|
size = 16 if task == 'lookup16' else 8
|
||||||
|
keys, vals = rng.sample(WORDS, size), rng.sample(range(10, 100), size)
|
||||||
|
if task == 'latest8':
|
||||||
|
first = rng.randrange(size - 1)
|
||||||
|
last = rng.randrange(first + 1, size)
|
||||||
|
keys[last] = keys[first]
|
||||||
|
target = vals[last]
|
||||||
|
remaining = [v for j, v in enumerate(vals) if j not in (first, last)]
|
||||||
|
distractors = [vals[first], *rng.sample(remaining, 2)]
|
||||||
|
key = keys[first]
|
||||||
|
else:
|
||||||
|
match = rng.randrange(size)
|
||||||
|
target, key = vals[match], keys[match]
|
||||||
|
distractors = rng.sample([v for v in vals if v != target], 3)
|
||||||
|
table = '\n'.join(f'{k}: {v}' for k, v in zip(keys, vals))
|
||||||
|
request = 'latest value' if task == 'latest8' else 'value'
|
||||||
|
order = ' (oldest first)' if task == 'latest8' else ''
|
||||||
|
question = f'Use the lookup table{order}.\n{table}\nWhich option is the {request} for {key}?'
|
||||||
|
rng.shuffle(distractors)
|
||||||
|
distractors.insert(answer, target)
|
||||||
|
options = '\n'.join(f'{j+1}. {v}' for j, v in enumerate(distractors))
|
||||||
|
prompt = f'{question}\n{options}\nAnswer with only the option number.\nAnswer:'
|
||||||
|
rows.append({'id': f'{split}-{task}-{i:03}', 'task': task,
|
||||||
|
'prompt': prompt, 'answer_index': answer})
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
class ScreeningModel(QKVModel):
|
||||||
|
def normalization(self, h, name):
|
||||||
|
if getattr(self, 'capture_prefix', False) and name == 'layers.19.input_layernorm':
|
||||||
|
self.residual_19 = h
|
||||||
|
return super().normalization(h, name)
|
||||||
|
|
||||||
|
def full_attention(self, h, layer, shared_p=None):
|
||||||
|
if layer not in SITES:
|
||||||
|
return super().full_attention(h, layer, shared_p)
|
||||||
|
own = self.parts(h, layer, heads=False)
|
||||||
|
p = own['p'].copy()
|
||||||
|
if getattr(self, 'capture_prefix', False):
|
||||||
|
if layer == 15:
|
||||||
|
self.donor_15 = p
|
||||||
|
return own['output'], p
|
||||||
|
if layer == 19:
|
||||||
|
p[self.chain] = self.prior[self.chain]
|
||||||
|
elif layer == 23:
|
||||||
|
p[self.shared] = self.prior[self.shared]
|
||||||
|
self.prior = p
|
||||||
|
repeats = self.config['num_attention_heads'] // self.config['num_key_value_heads']
|
||||||
|
v = np.repeat(own['v'], repeats, axis=2)
|
||||||
|
out = self.project(np.einsum('bhts,bshd->bthd', p, v), own['gate'], layer)
|
||||||
|
return out, p
|
||||||
|
|
||||||
|
|
||||||
|
def evaluate(model, tokenizer, examples):
|
||||||
|
ids, lengths, labels = batch(tokenizer, examples)
|
||||||
|
n = len(examples)
|
||||||
|
model.chain = slice(2*n, 3*n)
|
||||||
|
model.shared = slice(n, 3*n)
|
||||||
|
if not getattr(model, 'reuse_prefix', False):
|
||||||
|
h, _ = model.forward(np.tile(ids, (len(MODES), 1)))
|
||||||
|
else:
|
||||||
|
model.capture_prefix = True
|
||||||
|
native, _ = model.forward(ids)
|
||||||
|
model.capture_prefix = False
|
||||||
|
h = np.concatenate([model.residual_19] * len(MODES))
|
||||||
|
model.prior = np.concatenate([model.donor_15] * len(MODES))
|
||||||
|
for layer, kind in enumerate(model.config['layer_types'][19:], 19):
|
||||||
|
model.guard()
|
||||||
|
p = f'layers.{layer}.'
|
||||||
|
n_h = model.normalization(h, p+'input_layernorm')
|
||||||
|
out = (model.full_attention(n_h, layer)[0] if kind == 'full_attention'
|
||||||
|
else model.linear_attention(n_h, layer))
|
||||||
|
h = h + out
|
||||||
|
h = h + model.mlp(model.normalization(h, p+'post_attention_layernorm'), layer)
|
||||||
|
h = model.normalization(h, 'norm')
|
||||||
|
np.testing.assert_allclose(h[:n], native, atol=4e-5, rtol=3e-5)
|
||||||
|
t = model.tensors[PREFIX + 'embed_tokens.weight']
|
||||||
|
digit_weights = decode(t.raw.reshape(t.shape)[labels], t.dtype)
|
||||||
|
t.evict()
|
||||||
|
scores = [x[np.arange(n), np.asarray(lengths) - 1] @ digit_weights.T
|
||||||
|
for x in np.split(h, len(MODES))]
|
||||||
|
rows = []
|
||||||
|
for i, ex in enumerate(examples):
|
||||||
|
gold = ex['answer_index']
|
||||||
|
item = {'id': ex['id'], 'task': ex['task'], 'gold': gold, 'scores': {}}
|
||||||
|
for mode, logits in zip(MODES, scores):
|
||||||
|
values = logits[i].astype(float)
|
||||||
|
item['scores'][mode] = {'pred': int(values.argmax()), 'logits': values.tolist(),
|
||||||
|
'nll': float(np.logaddexp.reduce(values) - values[gold])}
|
||||||
|
rows.append(item)
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
def summarize(rows):
|
||||||
|
table = {}
|
||||||
|
for task in TASKS:
|
||||||
|
group = [r for r in rows if r['task'] == task]
|
||||||
|
if not group:
|
||||||
|
continue
|
||||||
|
table[task] = {}
|
||||||
|
for mode in MODES:
|
||||||
|
table[task][mode] = {
|
||||||
|
'n': len(group),
|
||||||
|
'correct': sum(r['scores'][mode]['pred'] == r['gold'] for r in group),
|
||||||
|
'native_wins_lost': sum(r['scores']['native']['pred'] == r['gold']
|
||||||
|
and r['scores'][mode]['pred'] != r['gold'] for r in group),
|
||||||
|
'nll': float(np.mean([r['scores'][mode]['nll'] for r in group])),
|
||||||
|
}
|
||||||
|
return table
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument('--source', required=True, type=Path)
|
||||||
|
parser.add_argument('--out', required=True, type=Path)
|
||||||
|
parser.add_argument('--resume', action='store_true', help='Keep completed batches')
|
||||||
|
parser.add_argument('--reuse-prefix', action='store_true', help='Run layers 0–18 once per input')
|
||||||
|
args = parser.parse_args()
|
||||||
|
args.out.mkdir(exist_ok=args.resume)
|
||||||
|
model = ScreeningModel(args.source/'weights',
|
||||||
|
json.loads((args.source/'model_config.json').read_text()), seconds=3600)
|
||||||
|
if any(model.config['layer_types'][ix] != 'full_attention' for ix in SITES):
|
||||||
|
raise ValueError('Scheduled layers must all have full attention')
|
||||||
|
model.reuse_prefix = args.reuse_prefix
|
||||||
|
tok = Tokenizer.from_file(str(args.source/'tokenizer.json'))
|
||||||
|
data = {split: problems(split, n) for split, n in
|
||||||
|
[('screen', 8), ('fit', 12), ('validation', 12), ('test', 32)]}
|
||||||
|
prompts = [r['prompt'] for xs in data.values() for r in xs]
|
||||||
|
if len(set(prompts)) != len(prompts):
|
||||||
|
raise ValueError('Prompt sets overlap')
|
||||||
|
manifest = args.out/'fixed-problems.json'
|
||||||
|
collected = args.out/'screen-rows.json'
|
||||||
|
if args.resume and manifest.exists() and json.loads(manifest.read_text()) != data:
|
||||||
|
raise ValueError('Fixed prompts changed')
|
||||||
|
write_json(manifest, data)
|
||||||
|
rows = json.loads(collected.read_text()) if args.resume and collected.exists() else []
|
||||||
|
if len(rows) % 4 or [r['id'] for r in rows] != [r['id'] for r in data['screen'][:len(rows)]]:
|
||||||
|
raise ValueError('Existing screen does not match the fixed prompt sequence')
|
||||||
|
for i in range(len(rows), len(data['screen']), 4):
|
||||||
|
rows.extend(evaluate(model, tok, data['screen'][i:i+4]))
|
||||||
|
write_json(args.out/'screen-rows.json', rows)
|
||||||
|
print('screen', len(rows), flush=True)
|
||||||
|
write_json(args.out/'screen-summary.json', summarize(rows))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
@@ -0,0 +1,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,173 @@
|
|||||||
|
"""Differentiable Qwen text tail with streamed frozen weights and LiSA sites."""
|
||||||
|
import math
|
||||||
|
|
||||||
|
import torch
|
||||||
|
from torch import nn
|
||||||
|
from torch.nn import functional as F
|
||||||
|
from torch.utils.checkpoint import checkpoint
|
||||||
|
|
||||||
|
from crossqkv.lisa_train import causal_attention
|
||||||
|
from functional.model import PREFIX
|
||||||
|
|
||||||
|
|
||||||
|
def weight_chunks(tensor, start, end, rows=512):
|
||||||
|
width = tensor.shape[1]
|
||||||
|
for lo in range(start, end, rows):
|
||||||
|
hi = min(lo + rows, end)
|
||||||
|
yield torch.from_numpy(tensor.read(slice(lo * width, hi * width)).reshape(hi-lo, width))
|
||||||
|
tensor.evict()
|
||||||
|
|
||||||
|
|
||||||
|
class FrozenLinear(torch.autograd.Function):
|
||||||
|
"""Read only the requested output rows and stream them again for dX."""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def forward(ctx, hidden, weight, start, end):
|
||||||
|
ctx.weight, ctx.start, ctx.end = weight, start, end
|
||||||
|
return torch.cat([F.linear(hidden, w) for w in weight_chunks(weight, start, end)], dim=-1)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def backward(ctx, grad):
|
||||||
|
out = grad.new_zeros((*grad.shape[:-1], ctx.weight.shape[1]))
|
||||||
|
lo = 0
|
||||||
|
for w in weight_chunks(ctx.weight, ctx.start, ctx.end):
|
||||||
|
hi = lo + len(w)
|
||||||
|
out = out + grad[..., lo:hi] @ w
|
||||||
|
lo = hi
|
||||||
|
return out, None, None, None
|
||||||
|
|
||||||
|
|
||||||
|
def rotate(x, theta, fraction):
|
||||||
|
d = int(x.shape[-1] * fraction)
|
||||||
|
inv = theta ** (-torch.arange(0, d, 2, dtype=x.dtype, device=x.device) / d)
|
||||||
|
phase = torch.arange(x.shape[1], dtype=x.dtype, device=x.device)[:, None] * inv
|
||||||
|
angle = torch.cat((phase, phase), dim=-1)[None, :, None, :]
|
||||||
|
a, b = x[..., :d].chunk(2, dim=-1)
|
||||||
|
return torch.cat((x[..., :d] * angle.cos() + torch.cat((-b, a), -1) * angle.sin(),
|
||||||
|
x[..., d:]), dim=-1)
|
||||||
|
|
||||||
|
|
||||||
|
def gated_delta(q, k, v, g, beta):
|
||||||
|
q = q * (q.square().sum(-1, keepdim=True) + 1e-6).rsqrt() / math.sqrt(q.shape[-1])
|
||||||
|
k = k * (k.square().sum(-1, keepdim=True) + 1e-6).rsqrt()
|
||||||
|
state = v.new_zeros(v.shape[0], v.shape[2], k.shape[-1], v.shape[-1])
|
||||||
|
rows = []
|
||||||
|
for i in range(v.shape[1]):
|
||||||
|
qt, kt, vt = q[:, i], k[:, i], v[:, i]
|
||||||
|
state = state * g[:, i, :, None, None].exp()
|
||||||
|
delta = (vt - (state * kt.unsqueeze(-1)).sum(-2)) * beta[:, i, :, None]
|
||||||
|
state = state + kt.unsqueeze(-1) * delta.unsqueeze(-2)
|
||||||
|
rows.append((state * qt.unsqueeze(-1)).sum(-2))
|
||||||
|
return torch.stack(rows, dim=1)
|
||||||
|
|
||||||
|
|
||||||
|
class TorchTail(nn.Module):
|
||||||
|
"""Inputs start immediately before the first trainable recipient."""
|
||||||
|
|
||||||
|
def __init__(self, source_model, start, adapters=None):
|
||||||
|
super().__init__()
|
||||||
|
self.source = source_model
|
||||||
|
self.c = source_model.config
|
||||||
|
self.eps = source_model.eps
|
||||||
|
self.start = start
|
||||||
|
self.adapters = nn.ModuleDict({str(k): v for k, v in (adapters or {}).items()})
|
||||||
|
self._small = {}
|
||||||
|
|
||||||
|
def small(self, name):
|
||||||
|
if name not in self._small:
|
||||||
|
self._small[name] = torch.from_numpy(self.source.small(name))
|
||||||
|
return self._small[name]
|
||||||
|
|
||||||
|
def linear(self, h, name, start=0, end=None):
|
||||||
|
t = self.source.tensors[PREFIX + name + '.weight']
|
||||||
|
return FrozenLinear.apply(h, t, start, t.shape[0] if end is None else end)
|
||||||
|
|
||||||
|
def norm(self, x, name, centered=True):
|
||||||
|
w = self.small(name + '.weight')
|
||||||
|
return x * (x.square().mean(-1, keepdim=True) + self.eps).rsqrt() * (1+w if centered else w)
|
||||||
|
|
||||||
|
def gate_only(self, h, name):
|
||||||
|
heads, dim = self.c['num_attention_heads'], self.c['head_dim']
|
||||||
|
return torch.stack([self.linear(h, name+'q_proj', (2*j+1)*dim, (2*j+2)*dim)
|
||||||
|
for j in range(heads)], dim=2)
|
||||||
|
|
||||||
|
def native_scores(self, q, h, name):
|
||||||
|
c = self.c
|
||||||
|
k = self.linear(h, name+'k_proj').unflatten(-1, (c['num_key_value_heads'], c['head_dim']))
|
||||||
|
params = c['rope_parameters']
|
||||||
|
q = rotate(self.norm(q, name+'q_norm'), params['rope_theta'], params['partial_rotary_factor'])
|
||||||
|
k = rotate(self.norm(k, name+'k_norm'), params['rope_theta'], params['partial_rotary_factor'])
|
||||||
|
k = k.repeat_interleave(q.shape[2] // k.shape[2], dim=2)
|
||||||
|
return torch.einsum('bthd,bshd->bhts', q, k) / math.sqrt(q.shape[-1])
|
||||||
|
|
||||||
|
def full(self, h, layer, donor, lengths, mode, recipients, keep_teacher):
|
||||||
|
c = self.c
|
||||||
|
heads, kv_heads, dim = c['num_attention_heads'], c['num_key_value_heads'], c['head_dim']
|
||||||
|
name = f'layers.{layer}.self_attn.'
|
||||||
|
shared = layer in recipients and mode != 'native'
|
||||||
|
if not shared or keep_teacher:
|
||||||
|
packed = self.linear(h, name+'q_proj').unflatten(-1, (heads, 2*dim))
|
||||||
|
q, gate = packed.chunk(2, dim=-1)
|
||||||
|
if shared:
|
||||||
|
with torch.no_grad():
|
||||||
|
native = self.native_scores(q, h, name)
|
||||||
|
else:
|
||||||
|
native = self.native_scores(q, h, name)
|
||||||
|
else:
|
||||||
|
gate = self.gate_only(h, name)
|
||||||
|
native = None
|
||||||
|
if not shared:
|
||||||
|
scores = native
|
||||||
|
elif mode == 'direct':
|
||||||
|
scores = donor
|
||||||
|
elif mode == 'lisa':
|
||||||
|
pos = torch.arange(h.shape[1], device=h.device)[None, :]
|
||||||
|
scores = self.adapters[str(layer)](h, donor, pos)
|
||||||
|
elif mode == 'linear':
|
||||||
|
matrix = self.adapters[str(layer)]
|
||||||
|
scores = matrix(donor.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)
|
||||||
|
else:
|
||||||
|
raise ValueError(f'Unknown mode {mode}')
|
||||||
|
v = self.linear(h, name+'v_proj').unflatten(-1, (kv_heads, dim))
|
||||||
|
out = causal_attention(scores, v, lengths) * gate.sigmoid()
|
||||||
|
return self.linear(out.flatten(-2), name+'o_proj'), scores, native
|
||||||
|
|
||||||
|
def linear_attention(self, x, layer):
|
||||||
|
p = f'layers.{layer}.linear_attn.'
|
||||||
|
c = self.c
|
||||||
|
kh, vh = c['linear_num_key_heads'], c['linear_num_value_heads']
|
||||||
|
kd, vd = c['linear_key_head_dim'], c['linear_value_head_dim']
|
||||||
|
projected = self.linear(x, p+'in_proj_qkv').transpose(1, 2)
|
||||||
|
kernel = self.small(p+'conv1d.weight')
|
||||||
|
convolved = F.conv1d(projected, kernel, padding=kernel.shape[-1]-1,
|
||||||
|
groups=projected.shape[1])[..., :x.shape[1]]
|
||||||
|
q, k, v = F.silu(convolved.transpose(1, 2)).split((kh*kd, kh*kd, vh*vd), dim=-1)
|
||||||
|
q = q.unflatten(-1, (kh, kd)).repeat_interleave(vh//kh, dim=2)
|
||||||
|
k = k.unflatten(-1, (kh, kd)).repeat_interleave(vh//kh, dim=2)
|
||||||
|
v = v.unflatten(-1, (vh, vd))
|
||||||
|
gate = self.linear(x, p+'in_proj_z').unflatten(-1, (vh, vd))
|
||||||
|
beta = self.linear(x, p+'in_proj_b').sigmoid()
|
||||||
|
a = self.linear(x, p+'in_proj_a')
|
||||||
|
g = -self.small(p+'A_log').exp() * F.softplus(a + self.small(p+'dt_bias'))
|
||||||
|
out = gated_delta(q, k, v, g, beta)
|
||||||
|
return self.linear((self.norm(out, p+'norm', centered=False)*F.silu(gate)).flatten(-2),
|
||||||
|
p+'out_proj')
|
||||||
|
|
||||||
|
def forward(self, h, donor, lengths, mode, recipients, keep_teacher=False):
|
||||||
|
side = {}
|
||||||
|
for layer, kind in enumerate(self.c['layer_types'][self.start:], self.start):
|
||||||
|
p = f'layers.{layer}.'
|
||||||
|
n = self.norm(h, p+'input_layernorm')
|
||||||
|
if kind == 'full_attention':
|
||||||
|
out, donor, native = self.full(n, layer, donor, lengths, mode, recipients,
|
||||||
|
keep_teacher)
|
||||||
|
side[layer] = (donor, native)
|
||||||
|
elif torch.is_grad_enabled() and n.requires_grad:
|
||||||
|
out = checkpoint(self.linear_attention, n, layer, use_reentrant=True)
|
||||||
|
else:
|
||||||
|
out = self.linear_attention(n, layer)
|
||||||
|
h = h + out
|
||||||
|
n = self.norm(h, p+'post_attention_layernorm')
|
||||||
|
x = F.silu(self.linear(n, p+'mlp.gate_proj')) * self.linear(n, p+'mlp.up_proj')
|
||||||
|
h = h + self.linear(x, p+'mlp.down_proj')
|
||||||
|
return self.norm(h, 'norm'), side
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
"""Trainable LiSA attention adaptor for the Qwen text reference."""
|
||||||
|
import math
|
||||||
|
|
||||||
|
import torch
|
||||||
|
from torch import nn
|
||||||
|
from torch.nn import functional as F
|
||||||
|
|
||||||
|
|
||||||
|
class LearnableSharingAttention(nn.Module):
|
||||||
|
"""Map low-rank local scores and donor logits to recipient logits."""
|
||||||
|
|
||||||
|
def __init__(self, hidden_size, heads, kv_heads, rank, theta, rotary_fraction,
|
||||||
|
width=256, bias=False):
|
||||||
|
super().__init__()
|
||||||
|
rotary_dim = int(rank * rotary_fraction)
|
||||||
|
if heads % kv_heads or not 0 < rotary_dim <= rank or rotary_dim % 2:
|
||||||
|
raise ValueError('Expected grouped query heads and a positive even rotary dimension')
|
||||||
|
self.heads, self.kv_heads, self.rank = heads, kv_heads, rank
|
||||||
|
self.rotary_dim = rotary_dim
|
||||||
|
inv_freq = theta ** (-torch.arange(0, rotary_dim, 2, dtype=torch.float32) / rotary_dim)
|
||||||
|
self.register_buffer('inv_freq', inv_freq, persistent=False)
|
||||||
|
self.q_proj = nn.Linear(hidden_size, heads * rank, bias=bias)
|
||||||
|
self.k_proj = nn.Linear(hidden_size, kv_heads * rank, bias=bias)
|
||||||
|
self.fuse = nn.Sequential(nn.Linear(2 * heads, width, bias=bias), nn.ReLU(),
|
||||||
|
nn.Linear(width, heads, bias=bias))
|
||||||
|
|
||||||
|
def rotate(self, x, position_ids):
|
||||||
|
phase = position_ids[..., None] * self.inv_freq
|
||||||
|
angle = torch.cat((phase, phase), dim=-1).unsqueeze(2)
|
||||||
|
a, b = x[..., :self.rotary_dim].chunk(2, dim=-1)
|
||||||
|
first = torch.cat((a, b), dim=-1)
|
||||||
|
rotated = torch.cat((-b, a), dim=-1)
|
||||||
|
return torch.cat((first * angle.cos() + rotated * angle.sin(),
|
||||||
|
x[..., self.rotary_dim:]), dim=-1)
|
||||||
|
|
||||||
|
def forward(self, hidden, donor, position_ids):
|
||||||
|
b, t, _ = hidden.shape
|
||||||
|
q = self.rotate(self.q_proj(hidden).reshape(b, t, self.heads, self.rank), position_ids)
|
||||||
|
k = self.rotate(self.k_proj(hidden).reshape(b, t, self.kv_heads, self.rank), position_ids)
|
||||||
|
k = k.repeat_interleave(self.heads // self.kv_heads, dim=2)
|
||||||
|
delta = torch.einsum('bthd,bshd->btsh', q, k) / math.sqrt(self.rank)
|
||||||
|
return self.fuse(torch.cat((delta, donor.permute(0, 2, 3, 1)), dim=-1)).permute(0, 3, 1, 2)
|
||||||
|
|
||||||
|
|
||||||
|
def causal_attention(scores, values, lengths):
|
||||||
|
"""Apply recipient values after causal masking of the fused scores."""
|
||||||
|
positions = torch.arange(scores.shape[-1], device=scores.device)
|
||||||
|
valid = positions[None, :] < lengths[:, None]
|
||||||
|
causal = positions[:, None] >= positions[None, :]
|
||||||
|
allowed = valid[:, None, None, :] & causal
|
||||||
|
p = scores.masked_fill(~allowed, -torch.inf).softmax(dim=-1)
|
||||||
|
repeats = scores.shape[1] // values.shape[2]
|
||||||
|
return torch.einsum('bhts,bshd->bthd', p, values.repeat_interleave(repeats, dim=2))
|
||||||
|
|
||||||
|
|
||||||
|
def huber_distillation(scores, teacher, lengths):
|
||||||
|
"""Use raw pre-softmax scores and exclude sequence padding."""
|
||||||
|
positions = torch.arange(scores.shape[-1], device=scores.device)
|
||||||
|
valid = positions[None, :] < lengths[:, None]
|
||||||
|
pairs = valid[:, None, :, None] & valid[:, None, None, :]
|
||||||
|
return F.huber_loss(scores.masked_select(pairs), teacher.detach().masked_select(pairs),
|
||||||
|
delta=1.0)
|
||||||
|
|
||||||
|
|
||||||
|
def objective(scores, teacher, lengths, language_model_loss):
|
||||||
|
kd = huber_distillation(scores, teacher, lengths)
|
||||||
|
return 0.25 * kd + 0.75 * language_model_loss, kd
|
||||||
|
|
||||||
|
|
||||||
|
class FrozenRecipient(nn.Module):
|
||||||
|
"""The recipient's unchanged gated output projection, MLP and final norm."""
|
||||||
|
|
||||||
|
def __init__(self, weights, eps):
|
||||||
|
super().__init__()
|
||||||
|
for key in ('o', 'post', 'gate', 'up', 'down', 'final'):
|
||||||
|
self.register_buffer('w_' + key, torch.as_tensor(weights[key]).detach())
|
||||||
|
self.eps = eps
|
||||||
|
|
||||||
|
def norm(self, hidden, weight):
|
||||||
|
return hidden * (hidden.square().mean(dim=-1, keepdim=True) + self.eps).rsqrt() * (1 + weight)
|
||||||
|
|
||||||
|
def forward(self, context, gate, residual):
|
||||||
|
h = residual + F.linear((context * gate.sigmoid()).flatten(-2), self.w_o)
|
||||||
|
n = self.norm(h, self.w_post)
|
||||||
|
h = h + F.linear(F.silu(F.linear(n, self.w_gate)) * F.linear(n, self.w_up), self.w_down)
|
||||||
|
return self.norm(h, self.w_final)
|
||||||
|
|
||||||
|
|
||||||
|
class _FrozenVocabularyCE(torch.autograd.Function):
|
||||||
|
"""Exact full-vocabulary CE with a streamed frozen head in both passes."""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def forward(ctx, hidden, targets, weights, vocabulary):
|
||||||
|
log_total = hidden.new_full((hidden.shape[0],), -torch.inf)
|
||||||
|
selected = hidden.new_zeros(hidden.shape[0])
|
||||||
|
for start, w in vocabulary():
|
||||||
|
logits = F.linear(hidden, w)
|
||||||
|
log_total = torch.logaddexp(log_total, logits.logsumexp(dim=-1))
|
||||||
|
belongs = (targets >= start) & (targets < start + w.shape[0])
|
||||||
|
selected[belongs] = logits[belongs, targets[belongs] - start]
|
||||||
|
ctx.save_for_backward(hidden, targets, log_total, weights)
|
||||||
|
ctx.vocabulary = vocabulary
|
||||||
|
return ((log_total - selected) * weights).sum() / weights.sum()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def backward(ctx, gradient):
|
||||||
|
hidden, targets, log_total, weights = ctx.saved_tensors
|
||||||
|
grad_hidden = torch.zeros_like(hidden)
|
||||||
|
for start, w in ctx.vocabulary():
|
||||||
|
probs = (F.linear(hidden, w) - log_total[:, None]).exp()
|
||||||
|
belongs = (targets >= start) & (targets < start + w.shape[0])
|
||||||
|
probs[belongs, targets[belongs] - start] -= 1
|
||||||
|
grad_hidden.addmm_(probs, w)
|
||||||
|
return grad_hidden * (gradient * weights[:, None] / weights.sum()), None, None, None
|
||||||
|
|
||||||
|
|
||||||
|
def language_model_loss(hidden, ids, lengths, vocabulary, answer_weight=1.0):
|
||||||
|
"""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]
|
||||||
|
weights = torch.where(positions[None, :] + 2 == lengths[:, None], answer_weight, 1.0)
|
||||||
|
return _FrozenVocabularyCE.apply(hidden[:, :-1][valid], ids[:, 1:][valid],
|
||||||
|
weights[valid].to(dtype=hidden.dtype), vocabulary)
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
# 研究图册:Qwen3.5-2B 头贡献集中度
|
# 研究图册:Qwen3.5-2B 参数几何与头贡献
|
||||||
|
|
||||||
这份图册与原始PNG/PDF/SVG一同保存在Git中。图片文件已随PR #6合并到main;以下固定提交链接不依赖聊天附件或本机路径。
|
这份图册与原始PNG/PDF/SVG一同保存在Git中。头贡献基线图片已随PR #6合并到main;其固定提交链接不依赖聊天附件或本机路径。后续实验分别列于下方,可通过图册所在的Git提交查看对应版本。
|
||||||
|
|
||||||
原始结果提交:`098ea8650c7d0e06339c66e3a0509e38b85b3d7d`;模型revision:`15852e8c16360a2fea060d615a32b45270f8a8fc`。
|
原始结果提交:`098ea8650c7d0e06339c66e3a0509e38b85b3d7d`;模型revision:`15852e8c16360a2fea060d615a32b45270f8a8fc`。
|
||||||
|
|
||||||
@@ -43,3 +43,15 @@
|
|||||||

|

|
||||||
|
|
||||||
[条件定理、反例与数据说明](../results/sparse-shell/REPORT.md) · [PDF](../results/sparse-shell/sparse_shell_controls.pdf) · [SVG](../results/sparse-shell/sparse_shell_controls.svg)
|
[条件定理、反例与数据说明](../results/sparse-shell/REPORT.md) · [PDF](../results/sparse-shell/sparse_shell_controls.pdf) · [SVG](../results/sparse-shell/sparse_shell_controls.svg)
|
||||||
|
|
||||||
|
## 两个实际2B检查点的参数球壳检验
|
||||||
|
|
||||||
|
[结论与解释](MODEL_SHELL_FINDINGS.md) · [实测报告、分组数量与限制](../results/model-shell/REPORT.md) · [固定协议](../model_shell/PROTOCOL.md) · [指标源表](../results/model-shell/metrics.csv) · [校验清单](../results/model-shell/audit.json)
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
[微调前后配对图](../results/model-shell/figures/finetune_paired_radii.png) · [有限样本参与率](../results/model-shell/figures/participation_reference.png)。每幅图同目录均保存PDF/SVG,完整CDF及参照数据保存在`profiles.json.gz`,实测范数保存在`measured_radii.npz`;均随本次成果进入Git。
|
||||||
|
|||||||
@@ -0,0 +1,154 @@
|
|||||||
|
# LiSA effect reproduction on Qwen3.5-2B
|
||||||
|
|
||||||
|
The earlier single-layer training verified the method but used an evaluation
|
||||||
|
where the frozen 2B model answered only one of sixteen items. This protocol
|
||||||
|
measures retention of an existing capability and the cost of exercising it.
|
||||||
|
|
||||||
|
## Comparison with the published experiment
|
||||||
|
|
||||||
|
The 96.44% in Table 2 is the average performance retained by LLaMA2-13B
|
||||||
|
with 22 recipient layers across the reported benchmarks excluding LAMBADA.
|
||||||
|
At the same 22 layers, direct score sharing retained 46.76% and the direct
|
||||||
|
sharing plus LoRA baseline retained 65.95%. The published main uptraining
|
||||||
|
used 4.2 billion sampled RedPajama tokens on eight A800 GPUs. This experiment
|
||||||
|
uses a frozen Qwen3.5-2B backbone, two recipient layers, 12 synthetic fit
|
||||||
|
prompts and a single CPU runner. The comparable effect is an improvement
|
||||||
|
over direct sharing under a fixed layer schedule. The magnitude on a
|
||||||
|
32-item lookup test and the timing of CPU attention should be interpreted
|
||||||
|
within those settings. [Mu et al., Table 2 and Appendix C.1](https://aclanthology.org/2026.tacl-1.30.pdf)
|
||||||
|
|
||||||
|
## Task and layer screening
|
||||||
|
|
||||||
|
All four tasks, answer-position balances, and generators are fixed in
|
||||||
|
`crossqkv/lisa_effect_screen.py`. The screening split is used only for
|
||||||
|
selecting a primary task family and the schedule. Fit, validation, and test
|
||||||
|
prompts have disjoint fixed seeds. The screen must finish before opening
|
||||||
|
test metrics.
|
||||||
|
|
||||||
|
Test original attention, 19→23 direct reuse, and a chained 15→19→23
|
||||||
|
configuration, with each donor providing its actual scores in the current
|
||||||
|
run. Primary eligibility on the development screen requires original accuracy
|
||||||
|
at least 5/8 and at least one original-correct item lost under shared
|
||||||
|
attention. Compare candidate schedules by the count of native-correct items
|
||||||
|
lost, preferring the two-receiver schedule among ties and recording net
|
||||||
|
accuracy and four-option NLL. If none qualify, retain the screen and expand
|
||||||
|
development coverage before choosing a new task; never pick based on test
|
||||||
|
errors. The fixed test also reports all outcomes on the chosen task, including
|
||||||
|
native-incorrect items.
|
||||||
|
|
||||||
|
## Performance comparison
|
||||||
|
|
||||||
|
Compare native, direct, fit-only linear calibration and trainable LiSA on
|
||||||
|
identical prompts. Preserve Qwen recipient gates, V, and output projection.
|
||||||
|
Compare the published 0.25 Huber and 0.75 next-token CE objective with an
|
||||||
|
explicit answer-weighted variant. All adaptation and model selection use
|
||||||
|
only fit/validation. Record the whole-sequence training loss. On held-out prompts, report
|
||||||
|
answer-only loss, correctly recovered and newly lost questions, net
|
||||||
|
accuracy, and performance at one and two recipients. A measured failure to recover is a valid outcome.
|
||||||
|
|
||||||
|
For speed, use a path that actually skips dense Q/K at shared sites, keeping
|
||||||
|
gate rows. Verify against a reference first. With identical prompts,
|
||||||
|
checkpoint and runner, report measured latency for the implemented prefill
|
||||||
|
or decode path and its true scope. Account for both the reduced K storage
|
||||||
|
and additional score tensors. Do not call analytical estimates measured
|
||||||
|
speed or apply paper throughput figures to this CPU implementation.
|
||||||
|
|
||||||
|
The incremental recipient benchmark uses actual K/V buffers and compares the
|
||||||
|
shared implementation with native attention at the same prefix length and FP32
|
||||||
|
storage format. Numerical tests compare incremental scores and outputs with
|
||||||
|
batched causal attention at every query position. Report observed allocation
|
||||||
|
for K/V and the donor score row separately from end-to-end prefill or decode.
|
||||||
|
It does not include upstream score generation or the rest of the decoder.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python -B -m crossqkv.lisa_decode_bench --source runs/cpu-qwen35-2b \
|
||||||
|
--capture runs/LISA_EFFECT_CAPTURE --checkpoint runs/LISA_EFFECT_RESULTS/lisa.pt \
|
||||||
|
--out runs/LISA_EFFECT_RESULTS/decode.json
|
||||||
|
```
|
||||||
|
|
||||||
|
An interrupted development screen can resume with the same fixed prompt set
|
||||||
|
using `--resume`. Use `--reuse-prefix` to compute the frozen prefix once per
|
||||||
|
prompt. The replay checks original-mode parity before accepting results.
|
||||||
|
|
||||||
|
## Recorded development selection
|
||||||
|
|
||||||
|
The fixed screen completed with 32 prompts. The prespecified eligibility rule
|
||||||
|
selected the 16-entry lookup task with recipients at layers 19 and 23. Native
|
||||||
|
and one-recipient direct sharing each scored 8/8. Two-recipient direct sharing
|
||||||
|
scored 7/8 and lost one native-correct answer. The selected configuration,
|
||||||
|
all screened logits, and the disjoint prompt manifest are archived under
|
||||||
|
`results/lisa-effect-reproduction/`. This was selection evidence only.
|
||||||
|
|
||||||
|
The held-out analysis records rescue of native-correct errors, newly introduced
|
||||||
|
errors, paired uncertainty and answer NLL. A second pass streams the complete
|
||||||
|
vocabulary at the same answer positions and compares one- and two-recipient
|
||||||
|
forward paths. In the one-recipient LiSA ablation the final adapter comes from
|
||||||
|
the joint checkpoint. It is evaluated unchanged, with the earlier recipient
|
||||||
|
restored to native attention.
|
||||||
|
|
||||||
|
Training also saves each finished epoch's adapter, AdamW state, validation
|
||||||
|
history and selected weights atomically per variant. For interrupted training,
|
||||||
|
re-run the same command with `--resume` and the same output directory and epoch
|
||||||
|
budget. Resume verifies the frozen training configuration, preserves finished
|
||||||
|
epochs and re-scores the locked test set from the validation-selected weights.
|
||||||
|
The separate selected checkpoints retain the original weights-only schema.
|
||||||
|
|
||||||
|
The development error was `screen-lookup16-005`. Its correct choice was
|
||||||
|
option 4. Across native, single-recipient direct reuse and chained direct reuse,
|
||||||
|
the four-choice probability of option 4 was 0.706, 0.815 and 0.403,
|
||||||
|
respectively. Its correct-versus-best-distractor logit margins were
|
||||||
|
+1.265, +1.861 and −0.258. The chained result chose option 2. These are
|
||||||
|
development observations that describe the selected condition, not test
|
||||||
|
results or a basis for changing the frozen prompts.
|
||||||
|
|
||||||
|
## Reproduction commands
|
||||||
|
|
||||||
|
Run from the project code root on the confirmed remote CPU environment.
|
||||||
|
Choose new output directories. Keep the same source checkpoint across all
|
||||||
|
commands. The fixed manifest contains all four split definitions, and capture
|
||||||
|
writes an independent selection record and source fingerprints.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
export OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1
|
||||||
|
PYTHON=venv/bin/python
|
||||||
|
SOURCE=runs/cpu-qwen35-2b
|
||||||
|
SCREEN=runs/NEW_EFFECT_SCREEN
|
||||||
|
CAPTURE=runs/NEW_EFFECT_CAPTURE
|
||||||
|
RESULT=runs/NEW_EFFECT_RESULT
|
||||||
|
|
||||||
|
"$PYTHON" -B -m crossqkv.lisa_effect_screen --source "$SOURCE" --out "$SCREEN" --reuse-prefix
|
||||||
|
"$PYTHON" -B -m crossqkv.lisa_effect capture --source "$SOURCE" --input "$SCREEN" --out "$CAPTURE"
|
||||||
|
"$PYTHON" -B -m crossqkv.lisa_effect train --source "$SOURCE" --input "$CAPTURE" --out "$RESULT" --epochs 2
|
||||||
|
"$PYTHON" -B -m crossqkv.lisa_decode_bench --source "$SOURCE" --capture "$CAPTURE" \
|
||||||
|
--checkpoint "$RESULT/lisa.pt" --out "$RESULT/decode.json"
|
||||||
|
"$PYTHON" -B -m crossqkv.lisa_effect_answer_audit --source "$SOURCE" --cache "$CAPTURE" \
|
||||||
|
--trained "$RESULT" --out "$RESULT/full-vocab-answers.json"
|
||||||
|
"$PYTHON" -B -m crossqkv.lisa_effect_audit --fixed "$SCREEN/fixed-problems.json" \
|
||||||
|
--selection "$CAPTURE/selection.json" --items "$RESULT/test-items.json" \
|
||||||
|
--perf "$RESULT/performance.json" --decode "$RESULT/decode.json" \
|
||||||
|
--full-vocab "$RESULT/full-vocab-answers.json" --out "$RESULT/paired-audit.json"
|
||||||
|
```
|
||||||
|
|
||||||
|
The paired audit defines a rescue as a native-correct item made wrong by
|
||||||
|
direct sharing and made correct again by the tested adapter. It reports
|
||||||
|
newly lost native-and-direct-correct items separately. An improvement in
|
||||||
|
mean four-option answer NLL, including among items already answered
|
||||||
|
correctly, does not by itself establish a rescue. The audit computes paired
|
||||||
|
intervals for NLL differences and checks that common arms have identical
|
||||||
|
four-choice correctness in the primary test and the full-vocabulary pass.
|
||||||
|
|
||||||
|
Training scores *all* valid shifted tokens with exact full-vocabulary CE
|
||||||
|
and uses the validation four-option answer loss to freeze checkpoints. The
|
||||||
|
answer audit scores only the answer position over the whole vocabulary.
|
||||||
|
It does not report whole-prompt CE for the held-out items or free-form
|
||||||
|
multi-token answer accuracy. That distinction is important for interpreting
|
||||||
|
the previous experiment, in which those two losses moved in opposite
|
||||||
|
directions.
|
||||||
|
|
||||||
|
For the isolated incremental attention timing, report both streamed
|
||||||
|
checkpoint projections and an otherwise identical timing with only that
|
||||||
|
site's frozen projections resident in memory. Verify output and raw score
|
||||||
|
parity before interpreting the pair of timings. The resident measurements
|
||||||
|
exclude weight-load time, and both timings exclude upstream computation and
|
||||||
|
other decoder blocks. K/V and upstream score-row allocation are itemized
|
||||||
|
separately; neither timing is an end-to-end server throughput claim.
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
# 实际2B参数:比均匀参照更靠里吗?
|
||||||
|
|
||||||
|
**在明确的“校准最大半径以内”口径下,是;但数据同时显示更宽的径向分布,不能概括为整团参数向内收缩。此次GSM8K微调几乎没有改变这些几何指标。**
|
||||||
|
|
||||||
|
这轮直接读取了保留的Qwen3.5-2B权重和同一底座的已有纯LoRA GRPO检查点,在8.211.154.134上使用CPU完成。没有训练、推理或删除权重。
|
||||||
|
|
||||||
|
## 一个模型有多少组高维分布?
|
||||||
|
|
||||||
|
按事先固定的参数矩阵行/列与语言注意力头视图规则,每个模型有 **1,558组**:554个矩阵视图、1,004个按头视图。它们有重叠,不是模型固有的唯一分布数量。
|
||||||
|
|
||||||
|
主要汇总使用1,521个样本充足、未抽取坐标的视图。另有36个小样本视图和1个坐标抽样视图,全部单列并保留数据。整个检查点包括语言、视觉与MTP,共632个参数张量;319个一维张量和18个低维卷积核不满足这次“高维向量云”的规则。
|
||||||
|
|
||||||
|
## 有更多内侧质量,但也有更长的外尾
|
||||||
|
|
||||||
|
每组最多512个参数向量,一半校准中心及半径,另一半测量。对照也使用同样的校准规则;没有用所有向量的最大范数事后包住全部数据。
|
||||||
|
|
||||||
|
以原点为中心,比较归一化半径 `r / R_cal <= 0.9`:
|
||||||
|
|
||||||
|
|视图|组数|相对均匀球的内侧质量差中位数|相对匹配均值、逐坐标方差的均匀盒的质量差中位数|
|
||||||
|
|---|---:|---:|---:|
|
||||||
|
|矩阵行/列|517|+98.0个百分点|+97.7个百分点|
|
||||||
|
|按头|1,004|+97.3个百分点|+97.3个百分点|
|
||||||
|
|
||||||
|
改用校准均值作为中心,结果仍有约96.9–97.7个百分点的差异。因此,这个现象并非仅来自中心放在原点。
|
||||||
|
|
||||||
|
但最大半径很容易受到少数大范数向量影响。换成各自的校准RMS尺度,并比较完整CDF后,**93.8%的矩阵视图和87.8%的头视图同时存在超过10个百分点的内尾、外尾差异**。去均值后分别为94.4%和86.4%。这说明两尾同时增加是普遍现象,比“所有向量整体更靠内”更符合这些数据。
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
这三组示例按模块角色固定:GDN的Q头、全注意力的Q头、MLP上投影行。上排用校准最大半径,下排用RMS;它们只是帮助读图,不代替全量统计。
|
||||||
|
|
||||||
|
## 是否说明稀疏或低维?
|
||||||
|
|
||||||
|
还不能如此推断。采样视图的逐组精确零值率中位数为0;点坐标能量参与率除以维度的中位数约0.31。径向内侧质量、坐标能量集中和样本间的有效维数是不同的测量对象。
|
||||||
|
|
||||||
|
本轮同时记录了有限样本Gram参与率,并与同样本数的均匀参照比较。它受校准样本秩上限限制,不能作为真实内在维度的直接估计。盒参照也只匹配边际范围或逐坐标矩,并未匹配相关结构。因此,本轮没有单独识别“稀疏支持”导致的效应。
|
||||||
|
|
||||||
|
## 微调前后改变了吗?
|
||||||
|
|
||||||
|
LoRA实际改变72个投影矩阵,影响972个视图,其中936个属于主要汇总。只对这些受影响的主要视图配对,以免大量未改动参数稀释差异。
|
||||||
|
|
||||||
|
原点中心下,逐组中位 `r/R_cal` 的配对变化中位数为 **6.30×10⁻⁷**,最大绝对变化 **4.03×10⁻⁴**。去均值后的结论相近。90%半径质量差在原点中心口径下未跨越当前经验CDF的分辨率;这不表示两套权重完全相同。
|
||||||
|
|
||||||
|
因此,这两个检查点不能支持“微调后、更好的模型更靠内”的结论;本轮也没有测任务质量。参数几何中的宽径向结构可以继续挖掘,但它本身还不是功能重复或可互相替代的证据。
|
||||||
|
|
||||||
|
## 数据与核验
|
||||||
|
|
||||||
|
[完整数值报告](../results/model-shell/REPORT.md) · [冻结协议](../model_shell/PROTOCOL.md) · [复现方式](../model_shell/README.md) · [指标CSV](../results/model-shell/metrics.csv) · [摘要JSON](../results/model-shell/summary.json) · [审计SHA](../results/model-shell/audit.json)
|
||||||
|
|
||||||
|
6,232个模型×中心×视图组合全部核验;CDF从保留的校准/留出范数复算,检查有限样本秩上限,原模型和适配器SHA均与既有记录一致。远程4项测试通过,覆盖索引、LoRA读取、中心与尺度、均匀球校准和稀疏贴壳反例。图表、完整CDF及对照摘要、实测范数一同保存。结论为描述性统计:视图相关且重叠,没有将其当作独立重复实验进行显著性检验。
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
# Actual-model parameter clouds: frozen grouping and null protocol
|
||||||
|
|
||||||
|
Assets: retained Qwen3.5-2B original15852e8c16360a2fea060d615a32b45270f8a8fc,
|
||||||
|
and pure GSM8K GRPO LoRA seed0 at HF038d8be9bd0edd3883fa019651b02bdf65609468.
|
||||||
|
Use the established read-only FP32 W+2BA wrapper. No training, GPU, new models,
|
||||||
|
weight mutation, inference requirement or deletion. Every retained asset stays.
|
||||||
|
|
||||||
|
## What constitutes a distribution
|
||||||
|
|
||||||
|
A model has no unique canonical number of parameter distributions. Enumerate a
|
||||||
|
fixed family, not "all possible distributions":
|
||||||
|
1. Each ndim>=2 tensor flattened as [axis0, product(other axes)]: row vectors
|
||||||
|
and column vectors, when point count>=16 and feature dimension>=32.
|
||||||
|
2. Decoder language/MTP full-attention Q and interleaved gate rows per query
|
||||||
|
head; K/V rows per KV head. GDN concatenated Q/K/V rows per corresponding head.
|
||||||
|
No claim that these groups are disjoint or iid; whole-matrix views overlap.
|
||||||
|
3. Primary sample-size stratum has >=64 available points;16..63 is small-sample
|
||||||
|
descriptive only. One-dimensional norm/bias vectors have no cloud of vectors;
|
||||||
|
GDN kernel row dimension4 is low dimensional and excluded with explicit reason.
|
||||||
|
Vision parameters are covered by matrix/flattened views, not vision-head splits.
|
||||||
|
|
||||||
|
Include all checkpoint components (language, vision and MTP). Per view choose
|
||||||
|
up to512 point indices without replacement, split deterministically into calibration
|
||||||
|
and held-out halves. Use full vector coordinates up to dimension8192; only larger
|
||||||
|
vectors use a fixed random coordinate subset, labelled projected rather than full.
|
||||||
|
Use identical indices, coordinates and null random draws for original/FT.
|
||||||
|
No overlap-group parameter savings or total distribution counts are additive.
|
||||||
|
|
||||||
|
## Centers and radius/scaling
|
||||||
|
|
||||||
|
Analyze origin and calibration-mean centers separately. Fit R_max using calibration
|
||||||
|
norms only; do not silently clip held-out points outside R_max. Also fit calibration
|
||||||
|
RMS radius. Store held-out maximum, outside-radius mass and radial spread.
|
||||||
|
|
||||||
|
Null A: uniform d-dimensional ball. Simulate the SAME center-fitting and calibration
|
||||||
|
maximum/RMS fitting before held-out evaluation. For origin, also retain exact
|
||||||
|
expected max-fitted null CDF a^d*n_cal/(n_cal+1), a<=1; log probabilities remain
|
||||||
|
available and zero Monte Carlo hits are not exact zeros.
|
||||||
|
Null B: independent coordinate-uniform box bounded by calibration min/max,
|
||||||
|
including asymmetric coordinates. Fit its center/radii using its own calibration
|
||||||
|
sample by exactly the same procedure. Record energy/range mismatch and held-out
|
||||||
|
coordinate violations; this null is conditional on fitted bounds, not a statement
|
||||||
|
that all real vectors lie inside that box.
|
||||||
|
Null C: independent coordinate-uniform box with calibration mean mu and standard
|
||||||
|
deviation sigma, bounds mu +/- sqrt(3)*sigma (sample variance ddof1). This matches
|
||||||
|
first and diagonal second moments in its generating law. Use its own calibration
|
||||||
|
and held-out center/max/RMS fits too; RMS-normalized comparisons target shape
|
||||||
|
rather than a change of global scale. Matching diagonal moments is not covariance
|
||||||
|
matching and does not preserve correlations.
|
||||||
|
|
||||||
|
Use512 validation null draws (not iid model observations), same calibration count
|
||||||
|
as each data cloud. Reuse isotropic-ball nulls only for identical dimension/count
|
||||||
|
and center-fitting rules. Monte Carlo resolution/error must be stated. Fit both
|
||||||
|
centers from the same raw draws where applicable; paired FT uses common randomness.
|
||||||
|
|
||||||
|
## Metrics and interpretation
|
||||||
|
|
||||||
|
Retain measured norm arrays, empirical CDF grids, max-normalized interior fractions
|
||||||
|
at0.5/0.75/0.9/0.95/0.99 and outside1, RMS-normalized CDF from0.5 to1.5,
|
||||||
|
median radial ratios and radial spread. Prefer probability-point differences over
|
||||||
|
astronomical ratios against tiny a^d. Inspect positive AND negative CDF gaps:
|
||||||
|
more inner tail plus more outer tail is not global inward stochastic dominance.
|
||||||
|
|
||||||
|
Record exact zeros, coordinate energy participation (sum squares)^2/sum fourths,
|
||||||
|
coordinate-variance participation, empirical covariance/second-moment participation
|
||||||
|
via calibration Gram matrices. Label sample rank ceiling n_cal-1 (mean centered)
|
||||||
|
or n_cal (origin); compare to equally sampled nulls, do not interpret the raw
|
||||||
|
finite-sample participation as true intrinsic dimension.
|
||||||
|
|
||||||
|
Report both full-radius and moment-controlled results for each center, whole-view
|
||||||
|
and head subgroups, primary versus small sample/projection strata, original and
|
||||||
|
changed72-LoRA-target groups. Unchanged parameter views can reuse identical results
|
||||||
|
with explicit references rather than re-read/recompute. Results describe parameters,
|
||||||
|
not activations, model quality, functional duplicates, or pruning gains.
|
||||||
|
|
||||||
|
Execution budget: one CPU, 512 MiB RSS ceiling, 7200 seconds per invocation;
|
||||||
|
checkpoint every group, resume without replacing completed groups. Any incomplete
|
||||||
|
coverage is reported before interpretation. No numerical analysis runs locally.
|
||||||
|
|
||||||
|
Illustrative radial CDFs use these fixed original/origin views, selected by module
|
||||||
|
role before the census completes, not by the resulting similarity/interior score:
|
||||||
|
language layer0 linear-attention Q head0, layer3 full-attention Q head0, and layer0
|
||||||
|
MLP up-projection rows. Their plots are illustrations, not independent replications.
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
# Actual-model shell census
|
||||||
|
|
||||||
|
Read [PROTOCOL.md](PROTOCOL.md) before interpreting the results. This analyzes
|
||||||
|
retained parameter arrays, not model activations or task accuracy.
|
||||||
|
|
||||||
|
Run only on the authorized CPU server from the repository root:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 venv/bin/python -m unittest model_shell.test_analysis -v
|
||||||
|
OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 venv/bin/python -m model_shell.analyze
|
||||||
|
OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 venv/bin/python -m model_shell.report
|
||||||
|
```
|
||||||
|
|
||||||
|
Inputs are the already retained `runs/cpu-qwen35-2b/weights` and
|
||||||
|
`runs/finetune-head-comparison/adapter.safetensors` with their existing JSON
|
||||||
|
configuration and metadata. The adapter is evaluated as FP32 W+2BA. No weights
|
||||||
|
are modified, no training or inference is run, and no files are deleted.
|
||||||
|
|
||||||
|
`runs/model-shell/checkpoints` is a resumable group ledger. Re-running skips
|
||||||
|
completed groups; do not reuse a ledger after changing its protocol/code/inputs.
|
||||||
|
One invocation stops at 7,200 seconds, RSS above 512 MiB or available memory below
|
||||||
|
128 MiB. Resume after addressing a resource stop; do not relax guards silently.
|
||||||
|
|
||||||
|
`results/model-shell` contains the report, group inventory, per-profile metric
|
||||||
|
CSV, compressed complete CDF/control summaries, and measured calibration/held-out
|
||||||
|
radii. The NPZ keys are `GROUPINDEX_MODEL_CENTER_cal` / `_eval`, with zero-based
|
||||||
|
group indices into `inventory.json`. Unchanged fine-tune profiles explicitly
|
||||||
|
reference the original profiles in `profiles.json.gz`; the CSV expands both.
|
||||||
|
Raw null draws are reproducible from the recorded deterministic seeds; null CDFs,
|
||||||
|
scales and participation summaries are stored. `audit.json` verifies coverage,
|
||||||
|
recomputes empirical CDFs from the saved norms, checks finite-sample rank limits,
|
||||||
|
verifies the original asset SHA256 values, and hashes the output artifacts.
|
||||||
|
`example_radii.npz` also saves calibration/held-out radii for the three fixed role
|
||||||
|
examples and their regenerated nulls; their grid CDFs are checked against the
|
||||||
|
original ledger before plotting full empirical step curves from radius zero.
|
||||||
|
|
||||||
|
The count of views is defined by the protocol and is not a unique number of
|
||||||
|
distributions inherent in a neural network. These overlapping views are equally
|
||||||
|
weighted for description; they are not independent replicates. The box nulls
|
||||||
|
match fitted marginal ranges or moments, not correlations. The maximum fitted
|
||||||
|
radius is not the unknown support boundary. Quantities near numerical or Monte
|
||||||
|
Carlo resolution cannot support a definitive population statement.
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
"""CPU-only, read-only parameter cloud census with paired uniform references."""
|
||||||
|
import argparse, hashlib, json, math, os, time
|
||||||
|
from pathlib import Path
|
||||||
|
from types import SimpleNamespace
|
||||||
|
import numpy as np
|
||||||
|
from pilot.tensors import load_tensors
|
||||||
|
from finetune_compare.lora import install
|
||||||
|
from model_shell.groups import enumerate_groups
|
||||||
|
|
||||||
|
MAX_GRID=np.array([.5,.75,.9,.95,.99,1.,1.05,1.1,1.25])
|
||||||
|
RMS_GRID=np.linspace(.5,1.5,41)
|
||||||
|
|
||||||
|
def seed(key):return int.from_bytes(hashlib.sha256(key.encode()).digest()[:8],'little')
|
||||||
|
|
||||||
|
def guard(start):
|
||||||
|
mem=dict((s.split(':')[0],int(s.split()[1])) for s in Path('/proc/meminfo').read_text().splitlines() if s.startswith('MemAvailable:'))
|
||||||
|
rss=int(Path('/proc/self/statm').read_text().split()[1])*os.sysconf('SC_PAGE_SIZE')
|
||||||
|
if rss>512*1024**2 or mem['MemAvailable']<128*1024 or time.monotonic()-start>7200:
|
||||||
|
raise RuntimeError(f'Resource guard: RSS={rss}, available_kB={mem}, elapsed={time.monotonic()-start:.0f}')
|
||||||
|
|
||||||
|
def sample(t,g):
|
||||||
|
rng=np.random.default_rng(seed(g['id']+'/indices'))
|
||||||
|
n=min(512,g['population']);d=min(8192,g['dimension'])
|
||||||
|
points=np.sort(rng.choice(g['population'],n,replace=False))
|
||||||
|
features=np.sort(rng.choice(g['dimension'],d,replace=False)) if d<g['dimension'] else np.arange(d)
|
||||||
|
width=math.prod(t.shape[1:]);out=np.empty((n,d),np.float32)
|
||||||
|
if g['orientation']=='rows':
|
||||||
|
for j,i in enumerate(points):
|
||||||
|
row=i+g['start'];out[j]=t.read(slice(row*width,(row+1)*width))[features]
|
||||||
|
if j%32==0:t.evict()
|
||||||
|
else:
|
||||||
|
for j,i in enumerate(features):
|
||||||
|
out[:,j]=t.read(slice(i*width,(i+1)*width))[points]
|
||||||
|
if j%32==0:t.evict()
|
||||||
|
t.evict();out=out[rng.permutation(n)]
|
||||||
|
digest=hashlib.sha256(points.tobytes()+features.tobytes()).hexdigest()
|
||||||
|
return out,digest
|
||||||
|
|
||||||
|
def participation(y):
|
||||||
|
gram=y@y.T;energy=float(np.trace(gram));den=float(np.square(gram).sum())
|
||||||
|
return energy**2/den if den else 0.
|
||||||
|
|
||||||
|
def geometry(x,ncal,center,raw=False):
|
||||||
|
# Float64 arithmetic; bounded sample matrix, no model-wide conversion.
|
||||||
|
z=x.astype(np.float64);mu=z[:ncal].mean(0) if center=='mean' else np.zeros(z.shape[1])
|
||||||
|
y=z-mu;norm=np.linalg.norm(y,axis=1);cal=norm[:ncal];r=norm[ncal:]
|
||||||
|
maximum=float(cal.max());rms=float(np.sqrt(np.mean(cal**2)))
|
||||||
|
valid=maximum>0 and rms>0
|
||||||
|
a=r/maximum if maximum else np.zeros_like(r);b=r/rms if rms else np.zeros_like(r)
|
||||||
|
coordvar=z[:ncal].var(0,ddof=1);cv=float(coordvar.sum()**2/np.square(coordvar).sum()) if coordvar.any() else 0.
|
||||||
|
e=np.square(y[ncal:]);den=np.square(e).sum(1)
|
||||||
|
pe=np.divide(e.sum(1)**2,den,out=np.zeros(len(e)),where=den>0)
|
||||||
|
out=dict(valid=bool(valid),ncal=ncal,neval=len(r),d=z.shape[1],rmax=maximum,rms=rms,
|
||||||
|
median_max=float(np.median(a)),median_rms=float(np.median(b)),
|
||||||
|
p10_rms=float(np.quantile(b,.1)),p90_rms=float(np.quantile(b,.9)),
|
||||||
|
outside=float(np.mean(a>1)),cdf_max=[float(np.mean(a<=v)) for v in MAX_GRID],
|
||||||
|
cdf_rms=[float(np.mean(b<=v)) for v in RMS_GRID],
|
||||||
|
covariance_participation=participation(y[:ncal]),rank_ceiling=ncal-(center=='mean'),
|
||||||
|
coordinate_variance_participation=cv,point_energy_participation_median=float(np.median(pe)),
|
||||||
|
zero_fraction=float(np.mean(z==0)))
|
||||||
|
if raw:out.update(cal_norm=cal.tolist(),eval_norm=r.tolist())
|
||||||
|
return out
|
||||||
|
|
||||||
|
BALL_CACHE={}
|
||||||
|
def references(x,ncal,key):
|
||||||
|
d=x.shape[1];cachekey=(d,ncal)
|
||||||
|
if cachekey not in BALL_CACHE:
|
||||||
|
rng=np.random.default_rng(seed(f'ball/{d}/{ncal}'))
|
||||||
|
y=rng.standard_normal((ncal+512,d),dtype=np.float32)
|
||||||
|
y*=((rng.random(len(y))**(1/d))/np.linalg.norm(y,axis=1))[:,None]
|
||||||
|
BALL_CACHE[cachekey]={c:geometry(y,ncal,c) for c in ('origin','mean')}
|
||||||
|
cal=x[:ncal].astype(np.float64);lo=cal.min(0);hi=cal.max(0);mu=cal.mean(0);sd=cal.std(0,ddof=1)
|
||||||
|
rng=np.random.default_rng(seed(key+'/uniform'))
|
||||||
|
u=rng.random((ncal+512,d),dtype=np.float32)
|
||||||
|
refs={'ball':BALL_CACHE[cachekey]}
|
||||||
|
for name,left,right in [('range_box',lo,hi),('moment_box',mu-np.sqrt(3)*sd,mu+np.sqrt(3)*sd)]:
|
||||||
|
y=(left+(right-left)*u).astype(np.float32)
|
||||||
|
refs[name]={c:geometry(y,ncal,c) for c in ('origin','mean')}
|
||||||
|
return refs,dict(heldout_outside_coordinate_range=float(np.mean((x[ncal:]<lo)|(x[ncal:]>hi))),
|
||||||
|
range_box_expected_energy=float(np.sum((lo**2+lo*hi+hi**2)/3)),
|
||||||
|
observed_cal_energy=float(np.mean(np.sum(cal**2,axis=1))))
|
||||||
|
|
||||||
|
def analyze(x,key):
|
||||||
|
ncal=len(x)//2;refs,extra=references(x,ncal,key);out={}
|
||||||
|
for center in ('origin','mean'):
|
||||||
|
p=geometry(x,ncal,center,True);p['references']=refs; p.update(extra)
|
||||||
|
p['comparisons']={}
|
||||||
|
for name,bycenter in refs.items():
|
||||||
|
ref=bycenter[center];diff=np.array(p['cdf_rms'])-ref['cdf_rms']
|
||||||
|
p['comparisons'][name]=dict(interior90_gap=p['cdf_max'][2]-ref['cdf_max'][2],
|
||||||
|
interior95_gap=p['cdf_max'][3]-ref['cdf_max'][3],
|
||||||
|
rms_cdf_positive_gap=float(max(0,diff.max())),rms_cdf_negative_gap=float(max(0,-diff.min())),
|
||||||
|
median_rms_delta=p['median_rms']-ref['median_rms'],
|
||||||
|
participation_ratio=p['covariance_participation']/ref['covariance_participation'] if ref['covariance_participation'] else None)
|
||||||
|
p['ball_origin_log_expected_cdf90']=float(x.shape[1]*np.log(.9)+np.log(ncal/(ncal+1)))
|
||||||
|
out[center]=p
|
||||||
|
return out
|
||||||
|
|
||||||
|
def main():
|
||||||
|
ap=argparse.ArgumentParser();ap.add_argument('--root',default='runs');ap.add_argument('--out',default='runs/model-shell');args=ap.parse_args()
|
||||||
|
root=Path(args.root);out=Path(args.out);out.mkdir(exist_ok=True,parents=True);(out/'checkpoints').mkdir(exist_ok=True)
|
||||||
|
cfg=json.loads((root/'cpu-qwen35-2b/model_config.json').read_text())['text_config']
|
||||||
|
base=load_tensors(root/'cpu-qwen35-2b/weights');ft=SimpleNamespace(tensors=dict(base),config=cfg)
|
||||||
|
meta=json.loads((root/'finetune-head-comparison/adapter_meta.json').read_text())
|
||||||
|
pairs,scale=install(ft,root/'finetune-head-comparison',meta)
|
||||||
|
groups,skips=enumerate_groups(base,cfg)
|
||||||
|
manifest=dict(groups=groups,skips=skips,total_tensors=len(base),parameters=sum(t.numel for t in base.values()),changed_tensors=sorted(pairs),adapter_meta=meta,
|
||||||
|
max_grid=MAX_GRID.tolist(),rms_grid=RMS_GRID.tolist(),null_eval=512,point_cap=512,feature_cap=8192)
|
||||||
|
(out/'inventory.json').write_text(json.dumps(manifest,indent=2));start=time.monotonic()
|
||||||
|
for i,g in enumerate(groups):
|
||||||
|
target=out/'checkpoints'/f'{i:04d}.json'
|
||||||
|
if target.exists():continue
|
||||||
|
guard(start);x,digest=sample(base[g['tensor']],g);p=analyze(x,g['id']);del x
|
||||||
|
changed=g['tensor'] in pairs
|
||||||
|
if changed:
|
||||||
|
guard(start);x,digest2=sample(ft.tensors[g['tensor']],g);assert digest==digest2
|
||||||
|
q=analyze(x,g['id']);del x
|
||||||
|
else:q=None
|
||||||
|
record=dict(group=g,sampling_sha256=digest,changed=changed,original=p,finetuned=q,finetuned_reuses_original=not changed)
|
||||||
|
temp=target.with_suffix('.tmp');temp.write_text(json.dumps(record,allow_nan=False));temp.replace(target)
|
||||||
|
if i%10==0:print(f'{i+1}/{len(groups)} elapsed={time.monotonic()-start:.1f}s',flush=True)
|
||||||
|
print('COMPLETE',len(groups),flush=True)
|
||||||
|
|
||||||
|
if __name__=='__main__':main()
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
"""Deterministic finite family of matrix/vector clouds; no data-dependent choice."""
|
||||||
|
import math,re
|
||||||
|
|
||||||
|
def enumerate_groups(tensors,cfg):
|
||||||
|
groups=[];skips=[]
|
||||||
|
for name,t in sorted(tensors.items()):
|
||||||
|
if len(t.shape)<2:skips.append({'name':name,'reason':'one vector, no vector cloud','shape':t.shape});continue
|
||||||
|
rows=t.shape[0];cols=math.prod(t.shape[1:]);count=0
|
||||||
|
for axis,n,d in [('rows',rows,cols),('columns',cols,rows)]:
|
||||||
|
if n>=16 and d>=32:
|
||||||
|
groups.append({'id':name+'::'+axis,'tensor':name,'kind':'matrix','orientation':axis,'start':0,'stop':rows,'population':n,'dimension':d,'stratum':'primary' if n>=64 else 'small_sample'});count+=1
|
||||||
|
if not count:skips.append({'name':name,'reason':'insufficient points or dimension <32','shape':t.shape})
|
||||||
|
if not (name.startswith('model.language_model.layers.') or name.startswith('mtp.layers.')):continue
|
||||||
|
segments=[]
|
||||||
|
if name.endswith('.linear_attn.in_proj_qkv.weight'):
|
||||||
|
kh,kd,vh,vd=[cfg[k] for k in ('linear_num_key_heads','linear_key_head_dim','linear_num_value_heads','linear_value_head_dim')]
|
||||||
|
for role,num,dim,offset in [('Q',kh,kd,0),('K',kh,kd,kh*kd),('V',vh,vd,2*kh*kd)]:
|
||||||
|
for h in range(num):segments.append((role,h,offset+h*dim,offset+(h+1)*dim))
|
||||||
|
elif name.endswith('.self_attn.q_proj.weight'):
|
||||||
|
dim=cfg['head_dim'];assert rows==cfg['num_attention_heads']*2*dim
|
||||||
|
for h in range(cfg['num_attention_heads']):
|
||||||
|
for role,offset in [('Q',0),('gate',dim)]:segments.append((role,h,h*2*dim+offset,h*2*dim+offset+dim))
|
||||||
|
elif name.endswith(('.self_attn.k_proj.weight','.self_attn.v_proj.weight')):
|
||||||
|
role='K' if '.k_proj.' in name else 'V';dim=cfg['head_dim'];assert rows==cfg['num_key_value_heads']*dim
|
||||||
|
for h in range(cfg['num_key_value_heads']):segments.append((role,h,h*dim,(h+1)*dim))
|
||||||
|
for role,h,start,stop in segments:
|
||||||
|
assert stop<=rows
|
||||||
|
groups.append({'id':name+f'::{role}_head{h}','tensor':name,'kind':'head_rows','orientation':'rows','start':start,'stop':stop,'population':stop-start,'dimension':cols,'stratum':'primary' if stop-start>=64 else 'small_sample'})
|
||||||
|
return groups,skips
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
"""Validate complete checkpoints; write compact scientific data, figures and report."""
|
||||||
|
import argparse,csv,gzip,hashlib,json,platform,sys
|
||||||
|
from pathlib import Path
|
||||||
|
import numpy as np
|
||||||
|
import matplotlib
|
||||||
|
matplotlib.use('Agg')
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
from model_shell.analyze import MAX_GRID,RMS_GRID,sample,seed
|
||||||
|
from pilot.tensors import load_tensors
|
||||||
|
|
||||||
|
def sha(p):
|
||||||
|
h=hashlib.sha256()
|
||||||
|
with p.open('rb') as f:
|
||||||
|
for b in iter(lambda:f.read(1024*1024),b''):h.update(b)
|
||||||
|
return h.hexdigest()
|
||||||
|
|
||||||
|
def main():
|
||||||
|
ap=argparse.ArgumentParser();ap.add_argument('--input',default='runs/model-shell');ap.add_argument('--out',default='results/model-shell');a=ap.parse_args()
|
||||||
|
source=Path(a.input);out=Path(a.out);out.mkdir(parents=True,exist_ok=True);figdir=out/'figures';figdir.mkdir(exist_ok=True)
|
||||||
|
inventory=json.loads((source/'inventory.json').read_text());groups=inventory['groups'];records=[];rows=[];radii={}
|
||||||
|
for i,g in enumerate(groups):
|
||||||
|
r=json.loads((source/'checkpoints'/f'{i:04d}.json').read_text());assert r['group']==g
|
||||||
|
assert r['changed']==(g['tensor'] in inventory['changed_tensors'])
|
||||||
|
for model in ('original','finetuned'):
|
||||||
|
profiles=r[model] if r[model] is not None else r['original']
|
||||||
|
for center,p in profiles.items():
|
||||||
|
if center=='origin':
|
||||||
|
p['ball_log_expected_max_cdf']=[float(p['d']*np.log(z)+np.log(p['ncal']/(p['ncal']+1))) for z in MAX_GRID if z<=1]
|
||||||
|
assert p['valid'] and p['d']==min(8192,g['dimension'])
|
||||||
|
assert p['covariance_participation']<=p['rank_ceiling']+1e-6
|
||||||
|
v=np.asarray(p['eval_norm']);cal=np.asarray(p['cal_norm'])
|
||||||
|
assert abs(p['rmax']-cal.max())<1e-12
|
||||||
|
assert abs(p['outside']-np.mean(v>p['rmax']))<1e-12
|
||||||
|
np.testing.assert_allclose(p['cdf_max'],[np.mean(v<=z*p['rmax']) for z in MAX_GRID])
|
||||||
|
np.testing.assert_allclose(p['cdf_rms'],[np.mean(v<=z*p['rms']) for z in RMS_GRID])
|
||||||
|
key=f'{i}_{model}_{center}';radii[key+'_cal']=cal;radii[key+'_eval']=v
|
||||||
|
row=dict(group_index=i,group=g['id'],model=model,center=center,kind=g['kind'],stratum=g['stratum'],changed=r['changed'],projected=g['dimension']>8192,
|
||||||
|
dimension=g['dimension'],analyzed_dimension=p['d'],population=g['population'],ncal=p['ncal'],neval=p['neval'],sampling_sha256=r['sampling_sha256'])
|
||||||
|
for k in ('median_max','median_rms','p10_rms','p90_rms','outside','rmax','rms','covariance_participation','rank_ceiling','coordinate_variance_participation','point_energy_participation_median','zero_fraction','heldout_outside_coordinate_range'):
|
||||||
|
row[k]=p[k]
|
||||||
|
for name,c in p['comparisons'].items():
|
||||||
|
for k,vv in c.items():row[name+'_'+k]=vv
|
||||||
|
rows.append(row)
|
||||||
|
# Compact profiles keep CDF and controls; raw measured radii live in NPZ.
|
||||||
|
for model in ('original','finetuned'):
|
||||||
|
if r[model] is not None:
|
||||||
|
for p in r[model].values():p.pop('cal_norm');p.pop('eval_norm')
|
||||||
|
records.append(r)
|
||||||
|
with gzip.open(out/'profiles.json.gz','wt',encoding='utf-8') as f:json.dump(records,f,allow_nan=False)
|
||||||
|
np.savez_compressed(out/'measured_radii.npz',**radii)
|
||||||
|
with (out/'metrics.csv').open('w',newline='') as f:
|
||||||
|
w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)
|
||||||
|
(out/'inventory.json').write_text(json.dumps(inventory,indent=2))
|
||||||
|
def subset(model='original',center='origin',kind=None,changed=None):
|
||||||
|
return [r for r in rows if r['model']==model and r['center']==center and r['stratum']=='primary' and not r['projected'] and (kind is None or r['kind']==kind) and (changed is None or r['changed']==changed)]
|
||||||
|
summary={}
|
||||||
|
for center in ('origin','mean'):
|
||||||
|
for kind in ('matrix','head_rows'):
|
||||||
|
rs=subset(center=center,kind=kind);s={'n':len(rs),
|
||||||
|
'median_zero_fraction':float(np.median([r['zero_fraction'] for r in rs])),
|
||||||
|
'median_coordinate_energy_participation_fraction':float(np.median([r['point_energy_participation_median']/r['analyzed_dimension'] for r in rs])),
|
||||||
|
'median_coordinate_variance_participation_fraction':float(np.median([r['coordinate_variance_participation']/r['analyzed_dimension'] for r in rs]))}
|
||||||
|
for ref in ('ball','range_box','moment_box'):
|
||||||
|
gap=np.array([r[ref+'_interior90_gap'] for r in rs]);pos=np.array([r[ref+'_rms_cdf_positive_gap'] for r in rs]);neg=np.array([r[ref+'_rms_cdf_negative_gap'] for r in rs])
|
||||||
|
s[ref]=dict(median_interior90_gap=float(np.median(gap)),fraction_gap_gt10pp=float(np.mean(gap>.1)),median_positive_rms_gap=float(np.median(pos)),median_negative_rms_gap=float(np.median(neg)),
|
||||||
|
fraction_two_sided_rms_gt10pp=float(np.mean((pos>.1)&(neg>.1))),median_participation_ratio=float(np.median([r[ref+'_participation_ratio'] for r in rs])))
|
||||||
|
summary[center+'/'+kind]=s
|
||||||
|
paired={}
|
||||||
|
for center in ('origin','mean'):
|
||||||
|
b=subset(center=center,changed=True);t=subset(model='finetuned',center=center,changed=True);assert [r['group'] for r in b]==[r['group'] for r in t]
|
||||||
|
paired[center]={'n':len(b)}
|
||||||
|
for field in ('median_max','median_rms','covariance_participation','moment_box_interior90_gap'):
|
||||||
|
delta=np.array([q[field]-p[field] for p,q in zip(b,t)])
|
||||||
|
paired[center][field]=dict(median=float(np.median(delta)),p10=float(np.quantile(delta,.1)),p90=float(np.quantile(delta,.9)),max_abs=float(np.max(abs(delta))))
|
||||||
|
secondary=[]
|
||||||
|
for model in ('original','finetuned'):
|
||||||
|
for center in ('origin','mean'):
|
||||||
|
for label in ('small_sample','projected'):
|
||||||
|
ss=[r for r in rows if r['model']==model and r['center']==center and (r['stratum']=='small_sample' if label=='small_sample' else r['projected'])]
|
||||||
|
secondary.append(dict(model=model,center=center,stratum=label,n=len(ss),median_max=float(np.median([r['median_max'] for r in ss])),moment_interior90_gap=float(np.median([r['moment_box_interior90_gap'] for r in ss]))))
|
||||||
|
(out/'summary.json').write_text(json.dumps(dict(strata=summary,paired_changed=paired,secondary=secondary),indent=2))
|
||||||
|
plt.rcParams.update({'font.size':10,'axes.spines.top':False,'axes.spines.right':False})
|
||||||
|
def save(fig,name):
|
||||||
|
fig.tight_layout()
|
||||||
|
for ext in ('png','pdf','svg'):fig.savefig(figdir/(name+'.'+ext),dpi=180,bbox_inches='tight')
|
||||||
|
plt.close(fig)
|
||||||
|
fig,axs=plt.subplots(2,2,figsize=(11,7),sharex=True,sharey=True)
|
||||||
|
for i,center in enumerate(('origin','mean')):
|
||||||
|
for j,kind in enumerate(('matrix','head_rows')):
|
||||||
|
rs=subset(center=center,kind=kind);ax=axs[i,j]
|
||||||
|
for ref,label in [('ball','Uniform ball'),('range_box','Range-matched box'),('moment_box','Moment-matched box')]:
|
||||||
|
v=np.sort([r[ref+'_interior90_gap'] for r in rs]);ax.plot(v,np.arange(1,len(v)+1)/len(v),label=label)
|
||||||
|
ax.axvline(0,color='gray',lw=.8);ax.set_title(f'{center} center / {kind}, n={len(rs)}');ax.set_xlabel('F(data r/Rcal <= 0.9) - F(null)');ax.set_ylabel('Fraction of sampled groups')
|
||||||
|
axs[0,0].legend(fontsize=8);fig.suptitle('Actual Qwen3.5-2B: interior mass depends on the reference');save(fig,'interior_reference_sensitivity')
|
||||||
|
fig,axs=plt.subplots(1,2,figsize=(11,4.3))
|
||||||
|
for ax,center in zip(axs,('origin','mean')):
|
||||||
|
for kind,marker in [('matrix','o'),('head_rows','.')]:
|
||||||
|
rs=subset(center=center,kind=kind);ax.scatter([r['moment_box_rms_cdf_positive_gap'] for r in rs],[r['moment_box_rms_cdf_negative_gap'] for r in rs],s=10,alpha=.25,label=kind,marker=marker)
|
||||||
|
ax.axvline(.1,color='gray',lw=.7);ax.axhline(.1,color='gray',lw=.7);ax.set(xlabel='Largest positive CDF gap (more inner tail)',ylabel='Largest negative CDF gap (more outer tail)',title=f'{center} / moment-matched box',xlim=(-.02,1),ylim=(-.02,1));ax.legend()
|
||||||
|
fig.suptitle('RMS-normalized radial shape: both tails can grow together');save(fig,'radial_shape_two_tails')
|
||||||
|
fig,axs=plt.subplots(1,2,figsize=(11,4.3))
|
||||||
|
for ax,center in zip(axs,('origin','mean')):
|
||||||
|
b=subset(center=center,changed=True);t=subset(model='finetuned',center=center,changed=True)
|
||||||
|
x=[r['median_max'] for r in b];y=[r['median_max'] for r in t];ax.scatter(x,y,s=10,alpha=.3);low=min(x+y);high=max(x+y);ax.plot([low,high],[low,high],color='gray',lw=1)
|
||||||
|
ax.set(xlabel='Original median r/Rcal',ylabel='GRPO-LoRA median r/Rcal',title=f'{center}, changed primary groups n={len(b)}')
|
||||||
|
fig.suptitle('Paired same-index comparison; unchanged groups excluded');save(fig,'finetune_paired_radii')
|
||||||
|
fig,axs=plt.subplots(1,2,figsize=(11,4.3))
|
||||||
|
for ax,center in zip(axs,('origin','mean')):
|
||||||
|
for kind in ('matrix','head_rows'):
|
||||||
|
rs=subset(center=center,kind=kind);v=np.sort([r['moment_box_participation_ratio'] for r in rs]);ax.plot(v,np.arange(1,len(v)+1)/len(v),label=kind)
|
||||||
|
ax.set(xlabel='Empirical participation / equal-sample moment-box reference',ylabel='Fraction of groups',title=center);ax.axvline(1,color='gray',lw=.8);ax.legend()
|
||||||
|
fig.suptitle('Finite-sample participation is not the true intrinsic dimension');save(fig,'participation_reference')
|
||||||
|
examples=[('model.language_model.layers.0.linear_attn.in_proj_qkv.weight::Q_head0','L0 GDN Q head0'),
|
||||||
|
('model.language_model.layers.3.self_attn.q_proj.weight::Q_head0','L3 full-attention Q head0'),
|
||||||
|
('model.language_model.layers.0.mlp.up_proj.weight::rows','L0 MLP up rows')]
|
||||||
|
fig,axs=plt.subplots(2,3,figsize=(13,7),sharey=True)
|
||||||
|
byid={r['group']['id']:r for r in records}
|
||||||
|
indices={g['id']:i for i,g in enumerate(groups)}
|
||||||
|
base=load_tensors(Path('runs/cpu-qwen35-2b/weights'));example_radii={}
|
||||||
|
for j,(gid,label) in enumerate(examples):
|
||||||
|
p=byid[gid]['original']['origin']
|
||||||
|
g=byid[gid]['group'];x,digest=sample(base[g['tensor']],g);assert digest==byid[gid]['sampling_sha256']
|
||||||
|
ncal=len(x)//2;d=x.shape[1];cal=x[:ncal].astype(np.float64)
|
||||||
|
rng=np.random.default_rng(seed(gid+'/uniform'));u=rng.random((ncal+512,d),dtype=np.float32)
|
||||||
|
mu=cal.mean(0);sd=cal.std(0,ddof=1);lo=mu-np.sqrt(3)*sd;hi=mu+np.sqrt(3)*sd
|
||||||
|
moment=(lo+(hi-lo)*u).astype(np.float32)
|
||||||
|
rng=np.random.default_rng(seed(f'ball/{d}/{ncal}'));ball=rng.standard_normal((ncal+512,d),dtype=np.float32)
|
||||||
|
ball*=((rng.random(len(ball))**(1/d))/np.linalg.norm(ball,axis=1))[:,None]
|
||||||
|
arrays={'Actual weights':(radii[f'{indices[gid]}_original_origin_cal'],radii[f'{indices[gid]}_original_origin_eval'])}
|
||||||
|
for name,ref,raw in [('Uniform ball','ball',ball),('Moment box','moment_box',moment)]:
|
||||||
|
nr=np.linalg.norm(raw.astype(np.float64),axis=1);arrays[name]=(nr[:ncal],nr[ncal:])
|
||||||
|
np.testing.assert_allclose([np.mean(nr[ncal:]/nr[:ncal].max()<=z) for z in MAX_GRID],p['references'][ref]['origin']['cdf_max'])
|
||||||
|
np.testing.assert_allclose([np.mean(nr[ncal:]/np.sqrt(np.mean(nr[:ncal]**2))<=z) for z in RMS_GRID],p['references'][ref]['origin']['cdf_rms'])
|
||||||
|
for name,(nc,ne) in arrays.items():example_radii[f'example{j}_{name.replace(" ","_")}_cal']=nc;example_radii[f'example{j}_{name.replace(" ","_")}_eval']=ne
|
||||||
|
for i,(field,grid) in enumerate([('cdf_max',MAX_GRID),('cdf_rms',RMS_GRID)]):
|
||||||
|
ax=axs[i,j]
|
||||||
|
for name,(nc,ne) in arrays.items():
|
||||||
|
scale=nc.max() if i==0 else np.sqrt(np.mean(nc**2));v=np.sort(ne/scale)
|
||||||
|
ax.step(np.r_[0,v, max(1.5,float(v[-1]))],np.r_[0,np.arange(1,len(v)+1)/len(v),1],where='post',label=name,lw=1.8,ls='-' if name=='Actual weights' else '--')
|
||||||
|
ax.set(title=label,xlabel='r / calibration '+('maximum' if i==0 else 'RMS'),ylabel='Held-out CDF',ylim=(-.03,1.03),xlim=(0,1.5));ax.legend(fontsize=8)
|
||||||
|
np.savez_compressed(out/'example_radii.npz',**example_radii)
|
||||||
|
fig.suptitle('Fixed role examples: maximum-radius and RMS normalization');save(fig,'fixed_role_radial_cdfs')
|
||||||
|
lines=['# 两个实际2B检查点:参数云的球壳检验','',f'完整覆盖:{len(groups)}组/模型,{len(rows)}个模型×中心组合。632个参数张量,2,274,069,824个参数(包含语言、视觉和MTP)。',
|
||||||
|
'','## 分布计数与范围','', '固定规则给出554个矩阵行/列视图、1,004个语言/MTP头视图;视图互相重叠,不能相加成参数节省量。1,522组有至少64个可用点,36组只有16个点;1组高维嵌入列视图使用8,192个抽样坐标。主表只汇总样本充足且没有投影的1,521组。319个一维张量和18个低维卷积核不构成此规则下的高维样本云。',
|
||||||
|
'','## 原模型结果(逐组等权,非独立观测)','', '|中心|视图|组数|相对均匀球:90%半径内质量差中位数|相对矩匹配均匀盒:质量差中位数|矩匹配且RMS归一后,内外两尾差均>10个百分点的组占比|','|---|---|---:|---:|---:|---:|']
|
||||||
|
for key,s in summary.items():
|
||||||
|
c,k=key.split('/');lines.append(f'|{c}|{k}|{s["n"]}|{s["ball"]["median_interior90_gap"]:.3f}|{s["moment_box"]["median_interior90_gap"]:.3f}|{s["moment_box"]["fraction_two_sided_rms_gt10pp"]:.1%}|')
|
||||||
|
lines+=['','这些是描述性质量差,不是显著性检验。正差表示所指定半径以内有更多样本;不能将其自动解释为整条径向分布向内平移。若RMS归一后内外尾均变多,更准确的解释是径向分布更宽。',
|
||||||
|
'', '|中心/视图|逐组零值率中位数|点坐标能量参与率÷维度,中位数|坐标方差参与率÷维度,中位数|','|---|---:|---:|---:|']
|
||||||
|
for key,s in summary.items():lines.append(f'|{key}|{s["median_zero_fraction"]:.6g}|{s["median_coordinate_energy_participation_fraction"]:.4f}|{s["median_coordinate_variance_participation_fraction"]:.4f}|')
|
||||||
|
lines+=['','能量参与率衡量坐标能量集中程度,依赖坐标基;有限样本Gram参与率反映样本间几何,另见图。两者均不是精确非零坐标计数,也不是模型功能的有效维度。',
|
||||||
|
'','## 微调前后','', '原模型是官方Qwen3.5-2B;第二个模型是在同一revision上进行GSM8K GRPO的已有纯LoRA检查点,不是另一个完整模型。72个投影矩阵使用只读W+2BA展开,其余参数共享。972个视图受影响;其中936个属于主分析。未改变视图复用完全相同的分析结果。','', '|中心|指标|配对变化中位数|P10|P90|最大绝对变化|','|---|---|---:|---:|---:|---:|']
|
||||||
|
for c,p in paired.items():
|
||||||
|
for k,v in p.items():
|
||||||
|
if k!='n':lines.append(f'|{c}|{k}|{v["median"]:.6g}|{v["p10"]:.6g}|{v["p90"]:.6g}|{v["max_abs"]:.6g}|')
|
||||||
|
lines+=['','## 单独描述的小样本与坐标抽样组','', '|模型|中心|类别|组数|中位r/Rcal的组间中位数|相对矩匹配盒的90%半径质量差中位数|','|---|---|---|---:|---:|---:|']
|
||||||
|
for s in secondary:lines.append(f'|{s["model"]}|{s["center"]}|{s["stratum"]}|{s["n"]}|{s["median_max"]:.4f}|{s["moment_interior90_gap"]:.4f}|')
|
||||||
|
lines+=['','## 如何读图','', '1. `interior_reference_sensitivity`:不同均匀参照下,90%校准半径内质量差的组间CDF。横轴向右表示更多内侧质量。','2. `radial_shape_two_tails`:匹配矩且按各自校准RMS归一后的最大正/负CDF差。右上角同时增加两尾,并非单纯向内。','3. `finetune_paired_radii`:同一视图的微调前后中位半径;对角线表示不变。','4. `participation_reference`:Gram矩阵参与率相对同样本量参照的比值。受样本秩上限影响,不能当作真实内在维度。',
|
||||||
|
'5. `fixed_role_radial_cdfs`:预先按角色固定的GDN Q、全注意力Q和MLP上投影示例,上排按校准最大半径、下排按RMS归一化。不是按结果挑选最明显的组。',
|
||||||
|
'','## 方法与限制','', '每组最多512个不同参数向量,一半校准、一半留出;模型固定,留出指未用于拟合中心/半径的参数向量,不是独立训练模型。对照每组512个验证向量,最坏单项二项标准误约2.21个百分点;模型留出样本的误差还取决于样本数,且参数向量不保证独立。10个百分点仅是描述性筛选尺度,没有多重检验或总体显著性结论。',
|
||||||
|
'','均匀球、坐标范围均匀盒、匹配均值和逐坐标方差的均匀盒都按同一规则拟合自身中心、最大半径及RMS。均匀球原点中心的精确拟合半径CDF为a^d*ncal/(ncal+1),保留其对数以避免把模拟零命中误报成零概率。盒对照不是协方差匹配。校准最大半径不是已知总体支撑边界;留出越界率已记录。',
|
||||||
|
'','`origin`保留坐标均值贡献;`mean`使用校准向量均值。没有使用所有数据来选边界、训练或推理;没有删除模型。坐标稀疏性、有限样本参与率与径向内侧质量分别测量,不能相互代替。该实验不能证明更好的模型更靠里,也不能证明功能重复、可剪枝或可复用。',
|
||||||
|
'','复现:`OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 venv/bin/python -m model_shell.analyze`,完成后 `... python -m model_shell.report`。只在已授权CPU服务器运行。分组协议见 `model_shell/PROTOCOL.md`;全量指标在metrics.csv,完整CDF/参照在profiles.json.gz,实测范数在measured_radii.npz。']
|
||||||
|
(out/'REPORT.md').write_text('\n'.join(lines)+'\n')
|
||||||
|
sources={'base':Path('runs/cpu-qwen35-2b/weights/model.safetensors-00001-of-00001.safetensors'),'adapter':Path('runs/finetune-head-comparison/adapter.safetensors'),
|
||||||
|
'config':Path('runs/cpu-qwen35-2b/model_config.json'),'adapter_meta':Path('runs/finetune-head-comparison/adapter_meta.json')}
|
||||||
|
sourcehash={k:dict(path=str(p),bytes=p.stat().st_size,sha256=sha(p)) for k,p in sources.items()}
|
||||||
|
(out/'environment.json').write_text(json.dumps(dict(python=sys.version,platform=platform.platform(),numpy=np.__version__,matplotlib=matplotlib.__version__,
|
||||||
|
source_code_sha256={str(p):sha(p) for p in sorted(Path('model_shell').glob('*.py'))},protocol_sha256=sha(Path('model_shell/PROTOCOL.md')),seed='first 8 SHA256 bytes, little endian; group id plus purpose suffix',
|
||||||
|
thread_limit=1,server='8.211.154.134',training=False,inference=False,gpu=False),indent=2))
|
||||||
|
assert sourcehash['base']['sha256']=='aa33250c4fc64891ddfaba3a314fd9542ea371843c387178b425fbcc5ed680b1'
|
||||||
|
assert sourcehash['adapter']['sha256']=='93a3f43a4356f84da0d13ecc622fee13e41ba15d237cdaad6094f243899c62d6'
|
||||||
|
audit=dict(complete_groups=len(groups),profile_rows=len(rows),all_finite=True,cdf_recomputed=True,sample_rank_checked=True,sources=sourcehash,files={str(p.relative_to(out)):sha(p) for p in sorted(out.rglob('*')) if p.is_file() and p.name!='audit.json'})
|
||||||
|
(out/'audit.json').write_text(json.dumps(audit,indent=2));print(json.dumps(dict(summary=summary,paired=paired),indent=2))
|
||||||
|
|
||||||
|
if __name__=='__main__':main()
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
"""Run on the authorized CPU server: python -m unittest model_shell.test_analysis."""
|
||||||
|
import unittest
|
||||||
|
import numpy as np
|
||||||
|
from model_shell.analyze import sample,geometry,analyze,seed
|
||||||
|
from finetune_compare.lora import EffectiveWeight
|
||||||
|
|
||||||
|
class ArrayTensor:
|
||||||
|
def __init__(self,x):self.x=x;self.shape=x.shape;self.numel=x.size;self.dtype='F32'
|
||||||
|
def read(self,s=slice(None)):return self.x.reshape(-1)[s].copy()
|
||||||
|
def evict(self):pass
|
||||||
|
|
||||||
|
class Checks(unittest.TestCase):
|
||||||
|
def test_sampling_and_lora(self):
|
||||||
|
rng=np.random.default_rng(17);w=rng.normal(size=(80,64)).astype('f');a=rng.normal(size=(2,64)).astype('f');b=rng.normal(size=(80,2)).astype('f')
|
||||||
|
effective=EffectiveWeight(ArrayTensor(w),a,b,2);explicit=ArrayTensor(w+2*b@a)
|
||||||
|
for axis,n,d,start,stop in [('rows',80,64,0,80),('columns',64,80,0,80),('rows',32,64,16,48)]:
|
||||||
|
g=dict(id=axis+str(start),orientation=axis,population=n,dimension=d,start=start,stop=stop)
|
||||||
|
x,h=sample(effective,g);y,k=sample(explicit,g);np.testing.assert_allclose(x,y,atol=2e-6,rtol=1e-5);self.assertEqual(h,k)
|
||||||
|
self.assertEqual(x.shape,(n,d))
|
||||||
|
rr=np.random.default_rng(seed(g['id']+'/indices'));indices=np.sort(rr.choice(n,n,replace=False));order=rr.permutation(n)
|
||||||
|
cloud=explicit.x[start:stop] if axis=='rows' else explicit.x.T
|
||||||
|
np.testing.assert_allclose(y,cloud[indices][order],atol=0,rtol=0)
|
||||||
|
def test_center_scale_and_rank(self):
|
||||||
|
rng=np.random.default_rng(5);x=rng.normal(size=(128,96)).astype('f')
|
||||||
|
for center in ('origin','mean'):
|
||||||
|
p=geometry(x,64,center);q=geometry(x*3,64,center)
|
||||||
|
np.testing.assert_allclose(p['cdf_rms'],q['cdf_rms']);self.assertLessEqual(p['covariance_participation'],p['rank_ceiling']+1e-6)
|
||||||
|
p=geometry(x,64,'mean');q=geometry(x+4,64,'mean');np.testing.assert_allclose(p['median_rms'],q['median_rms'],rtol=1e-6)
|
||||||
|
self.assertFalse(geometry(np.zeros((32,64)),16,'mean')['valid'])
|
||||||
|
def test_ball_fit_and_sparse_counterexample(self):
|
||||||
|
rng=np.random.default_rng(33);d=32;ncal=256
|
||||||
|
# Analytic expectation over independent calibration maxima.
|
||||||
|
c=rng.random((20000,ncal))**(1/d);v=rng.random(20000)**(1/d)
|
||||||
|
observed=np.mean(v<=.99*c.max(1));expected=.99**d*ncal/(ncal+1)
|
||||||
|
self.assertLess(abs(observed-expected),.015)
|
||||||
|
radii=rng.random(512)**(1/d);x=np.zeros((512,d),dtype='f');x[:,0]=radii
|
||||||
|
p=geometry(x,256,'origin');self.assertGreater(p['median_max'],.9)
|
||||||
|
# Sparse support alone retains the full-dimensional radial law.
|
||||||
|
self.assertLess(p['cdf_max'][2],.08)
|
||||||
|
x[:,0]=rng.random(512)**.5
|
||||||
|
self.assertGreater(geometry(x,256,'origin')['cdf_max'][2],.65)
|
||||||
|
sphere=rng.normal(size=(512,d));sphere/=np.linalg.norm(sphere,axis=1)[:,None]
|
||||||
|
self.assertEqual(geometry(sphere,256,'origin')['cdf_max'][2],0.)
|
||||||
|
def test_reproducible_controls(self):
|
||||||
|
x=np.random.default_rng(7).normal(size=(32,40)).astype('f');a=analyze(x,'test');b=analyze(x,'test')
|
||||||
|
self.assertEqual(a,b)
|
||||||
|
self.assertTrue(a['mean']['valid'])
|
||||||
|
|
||||||
|
if __name__=='__main__':unittest.main()
|
||||||
@@ -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"
|
||||||
|
}
|
||||||
@@ -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,10 @@
|
|||||||
|
{
|
||||||
|
"task": "lookup16",
|
||||||
|
"source": "frozen Qwen3.5-2B hidden states at the answer position from native forward",
|
||||||
|
"metric": "4-option accuracy and mean NLL over four option logits",
|
||||||
|
"frozen_native_reference": {
|
||||||
|
"fit": {"samples": 12, "native_correct": 12, "choice_nll": 0.13035377124382475},
|
||||||
|
"validation": {"samples": 12, "native_correct": 12, "choice_nll": 0.13171539331834095}
|
||||||
|
},
|
||||||
|
"test_predictions_opened": false
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"date": "2026-11-23",
|
||||||
|
"task": "lookup16",
|
||||||
|
"item": "fit-lookup16-000",
|
||||||
|
"recipient_layers": [19, 23],
|
||||||
|
"sample_tokens_including_answer": 158,
|
||||||
|
"native_hidden_max_abs_error_against_streaming_reference": 0.000020503997802734375,
|
||||||
|
"skipped_dense_qk_max_abs_difference": 0.0,
|
||||||
|
"finite_nonzero_huber_gradients_for_all_adapter_parameters": true,
|
||||||
|
"peak_rss_kib": 555036,
|
||||||
|
"scope": "One real Qwen3.5-2B fit sample, synthetic task; the backward path used attention distillation only."
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
{
|
||||||
|
"runtime": "3.14.4",
|
||||||
|
"platform": "Linux",
|
||||||
|
"machine": "x86_64",
|
||||||
|
"logical_cpus": 2,
|
||||||
|
"cpu": "Intel(R) Xeon(R) Platinum",
|
||||||
|
"numpy": "2.5.4",
|
||||||
|
"torch": "2.15.0+cpu",
|
||||||
|
"tokenizers": "0.23.3",
|
||||||
|
"main_code_sha256": {
|
||||||
|
"lisa_effect.py": "8a3ecad71f23e3e8b8faf4a7c21c0c93f00fd0bffe14bdee6117921b548dce8a",
|
||||||
|
"lisa_tail.py": "4bd2c3c8690a8ae30cc1a9573ec17b7bbe25edf43a33507482719dc03cfeb9af",
|
||||||
|
"lisa_train.py": "d9b96258111e13a3c72483c954714b9ee56e1f308ec4371bafe47026246051a5",
|
||||||
|
"lisa_decode.py": "9c723fa245ee4dd8f4d0f9a0d7a3d15e3db3ae40db3fa82ea413ecd24fe20f06",
|
||||||
|
"lisa_decode_bench.py": "979e566a3391b9418b49beb10c200a48aac706ee95c145510850c929bcc2885a",
|
||||||
|
"lisa_effect_screen.py": "8aaf515d888f921e60082b69d898cb5037a160c5d09a584db2599f197c4aa74b"
|
||||||
|
},
|
||||||
|
"audit_code_sha256": {
|
||||||
|
"lisa_effect_audit.py": "75c3445d96521daa2832ee96eb128383fc81f6914d491c2804a9337d1d6af35b",
|
||||||
|
"lisa_effect_answer_audit.py": "e1d70b10863dab1e13dfa9573c0d87fc6ca017039c3cf9b90f7628f3e7fe5664"
|
||||||
|
},
|
||||||
|
"local_code_match": {
|
||||||
|
"lisa_effect.py": true,
|
||||||
|
"lisa_tail.py": true,
|
||||||
|
"lisa_train.py": true,
|
||||||
|
"lisa_decode.py": true,
|
||||||
|
"lisa_decode_bench.py": true,
|
||||||
|
"lisa_effect_screen.py": true,
|
||||||
|
"lisa_effect_audit.py": true,
|
||||||
|
"lisa_effect_answer_audit.py": true
|
||||||
|
},
|
||||||
|
"phase_updates": {
|
||||||
|
"lisa_decode_bench.py": {
|
||||||
|
"initial_unexecuted_benchmark_sha256": "0b9867b3f17dbe6373627fa3901c2ea113fc7e0d690b4a358350cfaae62ef223",
|
||||||
|
"validated_remote_benchmark_sha256": "979e566a3391b9418b49beb10c200a48aac706ee95c145510850c929bcc2885a",
|
||||||
|
"reason": "Measure compute with resident projections separately from streamed execution",
|
||||||
|
"remote_numeric_tests": "4 passed; resident projection outputs compared with streamed output"
|
||||||
|
},
|
||||||
|
"lisa_effect_audit.py": {
|
||||||
|
"verified_audit_sha256": "2d7feb79c23bed05d4d961ead7cbdfcff61b5425f1c3ef88192c2c3cd5afecb4",
|
||||||
|
"reason": "Cross-check the four-choice arms against the full-vocabulary pass and quantify paired answer-loss changes",
|
||||||
|
"remote_numeric_tests": "4 passed in an isolated source directory",
|
||||||
|
"outputs": {
|
||||||
|
"paired-audit.json": "original audit hash in audit_code_sha256",
|
||||||
|
"verified-audit.json": "verified_audit_sha256"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
{
|
||||||
|
"lookup8": {
|
||||||
|
"native": {
|
||||||
|
"n": 8,
|
||||||
|
"correct": 8,
|
||||||
|
"native_wins_lost": 0,
|
||||||
|
"nll": 0.22260868260464628
|
||||||
|
},
|
||||||
|
"direct_23": {
|
||||||
|
"n": 8,
|
||||||
|
"correct": 8,
|
||||||
|
"native_wins_lost": 0,
|
||||||
|
"nll": 0.15405775362854435
|
||||||
|
},
|
||||||
|
"direct_19_23": {
|
||||||
|
"n": 8,
|
||||||
|
"correct": 8,
|
||||||
|
"native_wins_lost": 0,
|
||||||
|
"nll": 0.1474619847851022
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"lookup16": {
|
||||||
|
"native": {
|
||||||
|
"n": 8,
|
||||||
|
"correct": 8,
|
||||||
|
"native_wins_lost": 0,
|
||||||
|
"nll": 0.137068848385562
|
||||||
|
},
|
||||||
|
"direct_23": {
|
||||||
|
"n": 8,
|
||||||
|
"correct": 8,
|
||||||
|
"native_wins_lost": 0,
|
||||||
|
"nll": 0.08428237400849126
|
||||||
|
},
|
||||||
|
"direct_19_23": {
|
||||||
|
"n": 8,
|
||||||
|
"correct": 7,
|
||||||
|
"native_wins_lost": 1,
|
||||||
|
"nll": 0.17225019742912862
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"latest8": {
|
||||||
|
"native": {
|
||||||
|
"n": 8,
|
||||||
|
"correct": 6,
|
||||||
|
"native_wins_lost": 0,
|
||||||
|
"nll": 0.5951684205201615
|
||||||
|
},
|
||||||
|
"direct_23": {
|
||||||
|
"n": 8,
|
||||||
|
"correct": 6,
|
||||||
|
"native_wins_lost": 0,
|
||||||
|
"nll": 0.5312782958402527
|
||||||
|
},
|
||||||
|
"direct_19_23": {
|
||||||
|
"n": 8,
|
||||||
|
"correct": 7,
|
||||||
|
"native_wins_lost": 0,
|
||||||
|
"nll": 0.5573033796086375
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"arithmetic": {
|
||||||
|
"native": {
|
||||||
|
"n": 8,
|
||||||
|
"correct": 3,
|
||||||
|
"native_wins_lost": 0,
|
||||||
|
"nll": 1.2998106862759977
|
||||||
|
},
|
||||||
|
"direct_23": {
|
||||||
|
"n": 8,
|
||||||
|
"correct": 3,
|
||||||
|
"native_wins_lost": 0,
|
||||||
|
"nll": 1.2773446956117458
|
||||||
|
},
|
||||||
|
"direct_19_23": {
|
||||||
|
"n": 8,
|
||||||
|
"correct": 4,
|
||||||
|
"native_wins_lost": 0,
|
||||||
|
"nll": 1.2912787564044454
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
{
|
||||||
|
"task": "lookup16",
|
||||||
|
"sites": [
|
||||||
|
19,
|
||||||
|
23
|
||||||
|
],
|
||||||
|
"fixed_problems_sha256": "34252a9e02e79c0e0d786ee8b90bb0c5a4fe22e97852929fedf73db7b6dc7826",
|
||||||
|
"source_sha256": {
|
||||||
|
"manifest.json": "28efbaf94a5034333339a35f08ead151459a7d20c6c2d2f07a451e7f3bf154de",
|
||||||
|
"model_config.json": "ed1c1723241f23f7f4e23430759cbd7dcfb4103cbdfe052bfe7626b57c2615b4",
|
||||||
|
"tokenizer.json": "5f9e4d4901a92b997e463c1f46055088b6cca5ca61a6522d1b9f64c4bb81cb42"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,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)。
|
||||||
@@ -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,73 @@
|
|||||||
|
# 两个实际2B检查点:参数云的球壳检验
|
||||||
|
|
||||||
|
完整覆盖:1558组/模型,6232个模型×中心组合。632个参数张量,2,274,069,824个参数(包含语言、视觉和MTP)。
|
||||||
|
|
||||||
|
## 分布计数与范围
|
||||||
|
|
||||||
|
固定规则给出554个矩阵行/列视图、1,004个语言/MTP头视图;视图互相重叠,不能相加成参数节省量。1,522组有至少64个可用点,36组只有16个点;1组高维嵌入列视图使用8,192个抽样坐标。主表只汇总样本充足且没有投影的1,521组。319个一维张量和18个低维卷积核不构成此规则下的高维样本云。
|
||||||
|
|
||||||
|
## 原模型结果(逐组等权,非独立观测)
|
||||||
|
|
||||||
|
|中心|视图|组数|相对均匀球:90%半径内质量差中位数|相对矩匹配均匀盒:质量差中位数|矩匹配且RMS归一后,内外两尾差均>10个百分点的组占比|
|
||||||
|
|---|---|---:|---:|---:|---:|
|
||||||
|
|origin|matrix|517|0.980|0.977|93.8%|
|
||||||
|
|origin|head_rows|1004|0.973|0.973|87.8%|
|
||||||
|
|mean|matrix|517|0.977|0.977|94.4%|
|
||||||
|
|mean|head_rows|1004|0.969|0.969|86.4%|
|
||||||
|
|
||||||
|
这些是描述性质量差,不是显著性检验。正差表示所指定半径以内有更多样本;不能将其自动解释为整条径向分布向内平移。若RMS归一后内外尾均变多,更准确的解释是径向分布更宽。
|
||||||
|
|
||||||
|
|中心/视图|逐组零值率中位数|点坐标能量参与率÷维度,中位数|坐标方差参与率÷维度,中位数|
|
||||||
|
|---|---:|---:|---:|
|
||||||
|
|origin/matrix|0|0.3067|0.9346|
|
||||||
|
|origin/head_rows|0|0.3117|0.9055|
|
||||||
|
|mean/matrix|0|0.3072|0.9346|
|
||||||
|
|mean/head_rows|0|0.3118|0.9055|
|
||||||
|
|
||||||
|
能量参与率衡量坐标能量集中程度,依赖坐标基;有限样本Gram参与率反映样本间几何,另见图。两者均不是精确非零坐标计数,也不是模型功能的有效维度。
|
||||||
|
|
||||||
|
## 微调前后
|
||||||
|
|
||||||
|
原模型是官方Qwen3.5-2B;第二个模型是在同一revision上进行GSM8K GRPO的已有纯LoRA检查点,不是另一个完整模型。72个投影矩阵使用只读W+2BA展开,其余参数共享。972个视图受影响;其中936个属于主分析。未改变视图复用完全相同的分析结果。
|
||||||
|
|
||||||
|
|中心|指标|配对变化中位数|P10|P90|最大绝对变化|
|
||||||
|
|---|---|---:|---:|---:|---:|
|
||||||
|
|origin|median_max|6.30233e-07|-3.20939e-05|3.49557e-05|0.000402869|
|
||||||
|
|origin|median_rms|-2.02235e-06|-4.00888e-05|3.91646e-05|0.000121968|
|
||||||
|
|origin|covariance_participation|0.00011293|-0.0007975|0.00116302|0.0136976|
|
||||||
|
|origin|moment_box_interior90_gap|0|0|0|0|
|
||||||
|
|mean|median_max|3.08748e-07|-3.29473e-05|3.37828e-05|0.000395056|
|
||||||
|
|mean|median_rms|-1.97695e-06|-4.08665e-05|3.90134e-05|0.000306282|
|
||||||
|
|mean|covariance_participation|0.000126928|-0.000792364|0.00112596|0.0127131|
|
||||||
|
|mean|moment_box_interior90_gap|0|0|0|0.00390625|
|
||||||
|
|
||||||
|
## 单独描述的小样本与坐标抽样组
|
||||||
|
|
||||||
|
|模型|中心|类别|组数|中位r/Rcal的组间中位数|相对矩匹配盒的90%半径质量差中位数|
|
||||||
|
|---|---|---|---:|---:|---:|
|
||||||
|
|original|origin|small_sample|36|0.7490|0.7500|
|
||||||
|
|original|origin|projected|1|0.4199|0.9961|
|
||||||
|
|original|mean|small_sample|36|0.8109|0.6875|
|
||||||
|
|original|mean|projected|1|0.4245|0.9961|
|
||||||
|
|finetuned|origin|small_sample|36|0.7490|0.7500|
|
||||||
|
|finetuned|origin|projected|1|0.4199|0.9961|
|
||||||
|
|finetuned|mean|small_sample|36|0.8110|0.6875|
|
||||||
|
|finetuned|mean|projected|1|0.4245|0.9961|
|
||||||
|
|
||||||
|
## 如何读图
|
||||||
|
|
||||||
|
1. `interior_reference_sensitivity`:不同均匀参照下,90%校准半径内质量差的组间CDF。横轴向右表示更多内侧质量。
|
||||||
|
2. `radial_shape_two_tails`:匹配矩且按各自校准RMS归一后的最大正/负CDF差。右上角同时增加两尾,并非单纯向内。
|
||||||
|
3. `finetune_paired_radii`:同一视图的微调前后中位半径;对角线表示不变。
|
||||||
|
4. `participation_reference`:Gram矩阵参与率相对同样本量参照的比值。受样本秩上限影响,不能当作真实内在维度。
|
||||||
|
5. `fixed_role_radial_cdfs`:预先按角色固定的GDN Q、全注意力Q和MLP上投影示例,上排按校准最大半径、下排按RMS归一化。不是按结果挑选最明显的组。
|
||||||
|
|
||||||
|
## 方法与限制
|
||||||
|
|
||||||
|
每组最多512个不同参数向量,一半校准、一半留出;模型固定,留出指未用于拟合中心/半径的参数向量,不是独立训练模型。对照每组512个验证向量,最坏单项二项标准误约2.21个百分点;模型留出样本的误差还取决于样本数,且参数向量不保证独立。10个百分点仅是描述性筛选尺度,没有多重检验或总体显著性结论。
|
||||||
|
|
||||||
|
均匀球、坐标范围均匀盒、匹配均值和逐坐标方差的均匀盒都按同一规则拟合自身中心、最大半径及RMS。均匀球原点中心的精确拟合半径CDF为a^d*ncal/(ncal+1),保留其对数以避免把模拟零命中误报成零概率。盒对照不是协方差匹配。校准最大半径不是已知总体支撑边界;留出越界率已记录。
|
||||||
|
|
||||||
|
`origin`保留坐标均值贡献;`mean`使用校准向量均值。没有使用所有数据来选边界、训练或推理;没有删除模型。坐标稀疏性、有限样本参与率与径向内侧质量分别测量,不能相互代替。该实验不能证明更好的模型更靠里,也不能证明功能重复、可剪枝或可复用。
|
||||||
|
|
||||||
|
复现:`OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 venv/bin/python -m model_shell.analyze`,完成后 `... python -m model_shell.report`。只在已授权CPU服务器运行。分组协议见 `model_shell/PROTOCOL.md`;全量指标在metrics.csv,完整CDF/参照在profiles.json.gz,实测范数在measured_radii.npz。
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
1/1558 elapsed=25.4s
|
||||||
|
11/1558 elapsed=65.2s
|
||||||
|
21/1558 elapsed=75.1s
|
||||||
|
31/1558 elapsed=84.5s
|
||||||
|
41/1558 elapsed=93.3s
|
||||||
|
51/1558 elapsed=102.0s
|
||||||
|
61/1558 elapsed=115.8s
|
||||||
|
71/1558 elapsed=137.8s
|
||||||
|
81/1558 elapsed=149.6s
|
||||||
|
91/1558 elapsed=159.8s
|
||||||
|
101/1558 elapsed=169.0s
|
||||||
|
111/1558 elapsed=178.5s
|
||||||
|
121/1558 elapsed=193.0s
|
||||||
|
131/1558 elapsed=215.0s
|
||||||
|
141/1558 elapsed=225.0s
|
||||||
|
151/1558 elapsed=234.5s
|
||||||
|
161/1558 elapsed=243.4s
|
||||||
|
171/1558 elapsed=252.9s
|
||||||
|
181/1558 elapsed=262.7s
|
||||||
|
191/1558 elapsed=283.8s
|
||||||
|
201/1558 elapsed=297.3s
|
||||||
|
211/1558 elapsed=305.0s
|
||||||
|
221/1558 elapsed=311.2s
|
||||||
|
231/1558 elapsed=328.1s
|
||||||
|
241/1558 elapsed=337.7s
|
||||||
|
251/1558 elapsed=348.0s
|
||||||
|
261/1558 elapsed=359.5s
|
||||||
|
271/1558 elapsed=368.0s
|
||||||
|
281/1558 elapsed=382.3s
|
||||||
|
291/1558 elapsed=405.5s
|
||||||
|
301/1558 elapsed=414.4s
|
||||||
|
311/1558 elapsed=424.6s
|
||||||
|
321/1558 elapsed=433.5s
|
||||||
|
331/1558 elapsed=442.5s
|
||||||
|
341/1558 elapsed=455.7s
|
||||||
|
351/1558 elapsed=476.6s
|
||||||
|
361/1558 elapsed=485.6s
|
||||||
|
371/1558 elapsed=494.2s
|
||||||
|
381/1558 elapsed=503.4s
|
||||||
|
391/1558 elapsed=512.8s
|
||||||
|
401/1558 elapsed=524.4s
|
||||||
|
411/1558 elapsed=544.7s
|
||||||
|
421/1558 elapsed=557.9s
|
||||||
|
431/1558 elapsed=565.7s
|
||||||
|
441/1558 elapsed=571.8s
|
||||||
|
451/1558 elapsed=586.9s
|
||||||
|
461/1558 elapsed=596.2s
|
||||||
|
471/1558 elapsed=605.1s
|
||||||
|
481/1558 elapsed=614.1s
|
||||||
|
491/1558 elapsed=623.4s
|
||||||
|
501/1558 elapsed=637.7s
|
||||||
|
511/1558 elapsed=660.1s
|
||||||
|
521/1558 elapsed=668.4s
|
||||||
|
531/1558 elapsed=677.4s
|
||||||
|
541/1558 elapsed=686.7s
|
||||||
|
551/1558 elapsed=696.0s
|
||||||
|
561/1558 elapsed=709.0s
|
||||||
|
571/1558 elapsed=730.0s
|
||||||
|
581/1558 elapsed=738.9s
|
||||||
|
591/1558 elapsed=747.4s
|
||||||
|
601/1558 elapsed=757.0s
|
||||||
|
611/1558 elapsed=766.0s
|
||||||
|
621/1558 elapsed=775.5s
|
||||||
|
631/1558 elapsed=797.3s
|
||||||
|
641/1558 elapsed=810.4s
|
||||||
|
651/1558 elapsed=818.2s
|
||||||
|
661/1558 elapsed=823.8s
|
||||||
|
671/1558 elapsed=840.0s
|
||||||
|
681/1558 elapsed=850.1s
|
||||||
|
691/1558 elapsed=859.5s
|
||||||
|
701/1558 elapsed=868.9s
|
||||||
|
711/1558 elapsed=878.3s
|
||||||
|
721/1558 elapsed=891.7s
|
||||||
|
731/1558 elapsed=913.7s
|
||||||
|
741/1558 elapsed=922.2s
|
||||||
|
751/1558 elapsed=931.2s
|
||||||
|
761/1558 elapsed=941.2s
|
||||||
|
771/1558 elapsed=951.8s
|
||||||
|
781/1558 elapsed=968.3s
|
||||||
|
791/1558 elapsed=989.6s
|
||||||
|
801/1558 elapsed=999.1s
|
||||||
|
811/1558 elapsed=1009.5s
|
||||||
|
821/1558 elapsed=1018.5s
|
||||||
|
831/1558 elapsed=1027.4s
|
||||||
|
841/1558 elapsed=1037.3s
|
||||||
|
851/1558 elapsed=1056.4s
|
||||||
|
861/1558 elapsed=1071.4s
|
||||||
|
871/1558 elapsed=1081.0s
|
||||||
|
881/1558 elapsed=1089.9s
|
||||||
|
891/1558 elapsed=1099.9s
|
||||||
|
901/1558 elapsed=1109.1s
|
||||||
|
911/1558 elapsed=1131.1s
|
||||||
|
921/1558 elapsed=1143.5s
|
||||||
|
931/1558 elapsed=1152.5s
|
||||||
|
941/1558 elapsed=1159.0s
|
||||||
|
951/1558 elapsed=1174.1s
|
||||||
|
961/1558 elapsed=1182.3s
|
||||||
|
971/1558 elapsed=1188.2s
|
||||||
|
981/1558 elapsed=1196.0s
|
||||||
|
991/1558 elapsed=1211.6s
|
||||||
|
1001/1558 elapsed=1220.8s
|
||||||
|
1011/1558 elapsed=1230.4s
|
||||||
|
1021/1558 elapsed=1239.1s
|
||||||
|
1031/1558 elapsed=1248.8s
|
||||||
|
1041/1558 elapsed=1267.3s
|
||||||
|
1051/1558 elapsed=1285.1s
|
||||||
|
1061/1558 elapsed=1293.8s
|
||||||
|
1071/1558 elapsed=1303.3s
|
||||||
|
1081/1558 elapsed=1311.9s
|
||||||
|
1091/1558 elapsed=1321.5s
|
||||||
|
1101/1558 elapsed=1338.0s
|
||||||
|
1111/1558 elapsed=1356.8s
|
||||||
|
1121/1558 elapsed=1366.6s
|
||||||
|
1131/1558 elapsed=1375.4s
|
||||||
|
1141/1558 elapsed=1384.4s
|
||||||
|
1151/1558 elapsed=1393.2s
|
||||||
|
1161/1558 elapsed=1406.7s
|
||||||
|
1171/1558 elapsed=1430.1s
|
||||||
|
1181/1558 elapsed=1438.1s
|
||||||
|
1191/1558 elapsed=1444.4s
|
||||||
|
1201/1558 elapsed=1451.6s
|
||||||
|
1211/1558 elapsed=1467.4s
|
||||||
|
1221/1558 elapsed=1477.1s
|
||||||
|
1231/1558 elapsed=1489.0s
|
||||||
|
1241/1558 elapsed=1501.1s
|
||||||
|
1251/1558 elapsed=1513.7s
|
||||||
|
1261/1558 elapsed=1538.7s
|
||||||
|
1271/1558 elapsed=1564.9s
|
||||||
|
1281/1558 elapsed=1576.8s
|
||||||
|
1291/1558 elapsed=1587.4s
|
||||||
|
1301/1558 elapsed=1598.2s
|
||||||
|
1311/1558 elapsed=1610.2s
|
||||||
|
1321/1558 elapsed=1628.9s
|
||||||
|
1331/1558 elapsed=1641.2s
|
||||||
|
1341/1558 elapsed=1649.6s
|
||||||
|
1351/1558 elapsed=1659.0s
|
||||||
|
1361/1558 elapsed=1670.9s
|
||||||
|
1371/1558 elapsed=1680.2s
|
||||||
|
1381/1558 elapsed=1688.9s
|
||||||
|
1391/1558 elapsed=1698.7s
|
||||||
|
1401/1558 elapsed=1709.4s
|
||||||
|
1411/1558 elapsed=1718.6s
|
||||||
|
1421/1558 elapsed=1727.1s
|
||||||
|
1431/1558 elapsed=1736.3s
|
||||||
|
1441/1558 elapsed=1749.4s
|
||||||
|
1451/1558 elapsed=1757.2s
|
||||||
|
1461/1558 elapsed=1765.7s
|
||||||
|
1471/1558 elapsed=1775.4s
|
||||||
|
1481/1558 elapsed=1786.3s
|
||||||
|
1491/1558 elapsed=1794.9s
|
||||||
|
1501/1558 elapsed=1803.7s
|
||||||
|
1511/1558 elapsed=1812.9s
|
||||||
|
1521/1558 elapsed=1826.2s
|
||||||
|
1531/1558 elapsed=1844.9s
|
||||||
|
1541/1558 elapsed=1852.7s
|
||||||
|
1551/1558 elapsed=1858.5s
|
||||||
|
COMPLETE 1558
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
{
|
||||||
|
"complete_groups": 1558,
|
||||||
|
"profile_rows": 6232,
|
||||||
|
"all_finite": true,
|
||||||
|
"cdf_recomputed": true,
|
||||||
|
"sample_rank_checked": true,
|
||||||
|
"sources": {
|
||||||
|
"base": {
|
||||||
|
"path": "runs/cpu-qwen35-2b/weights/model.safetensors-00001-of-00001.safetensors",
|
||||||
|
"bytes": 4548221488,
|
||||||
|
"sha256": "aa33250c4fc64891ddfaba3a314fd9542ea371843c387178b425fbcc5ed680b1"
|
||||||
|
},
|
||||||
|
"adapter": {
|
||||||
|
"path": "runs/finetune-head-comparison/adapter.safetensors",
|
||||||
|
"bytes": 18932336,
|
||||||
|
"sha256": "93a3f43a4356f84da0d13ecc622fee13e41ba15d237cdaad6094f243899c62d6"
|
||||||
|
},
|
||||||
|
"config": {
|
||||||
|
"path": "runs/cpu-qwen35-2b/model_config.json",
|
||||||
|
"bytes": 2908,
|
||||||
|
"sha256": "ed1c1723241f23f7f4e23430759cbd7dcfb4103cbdfe052bfe7626b57c2615b4"
|
||||||
|
},
|
||||||
|
"adapter_meta": {
|
||||||
|
"path": "runs/finetune-head-comparison/adapter_meta.json",
|
||||||
|
"bytes": 573,
|
||||||
|
"sha256": "b8d4737a5b940bcdfed72258600227a89f883dc863e9724bf84e457b46a53703"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"files": {
|
||||||
|
"REPORT.md": "43c644d2cf1e1100cb547377e5407db606e04e568bdaa1ba0deb0e9e70fe3ff6",
|
||||||
|
"analysis-output.txt": "a6905d3ec23d68fa4c2ff1b1a4ea6b19e6b94b93aef65ca220dca3823cd87fd4",
|
||||||
|
"environment.json": "7ccc05cb9ee75302982886d1e6746d5e97753ca91c10629a69f6acde68848a41",
|
||||||
|
"example_radii.npz": "787fb0e986ed621604b64e704ce9f7cd6c37a04c70475d1611fcb8f986c27b51",
|
||||||
|
"figures/finetune_paired_radii.pdf": "80a0b5b90b04104bf89ea90676b6694af6ebe4e41101ccf4b771414b870bfa56",
|
||||||
|
"figures/finetune_paired_radii.png": "1ba80adfa87ac69537fa74cbe1c4b2237a5fca9d3a536319bb630fd84b59b534",
|
||||||
|
"figures/finetune_paired_radii.svg": "9f65fa49e08cb93e4467f15c2beb2a499f29267392a531db86ec98e3fce9a689",
|
||||||
|
"figures/fixed_role_radial_cdfs.pdf": "cbb200dcc5f0812181720ad62047a07b4310eea35d32dc0652d891d86eeecac5",
|
||||||
|
"figures/fixed_role_radial_cdfs.png": "c7175229b3d9637774635db8a6fef313bba83351f87c6e6916b8d065b5200891",
|
||||||
|
"figures/fixed_role_radial_cdfs.svg": "09194a9734f496b12f8e699083e494c35ff6f2d95f70fac683aa3e528e0c4684",
|
||||||
|
"figures/interior_reference_sensitivity.pdf": "b6b77c5b02e0a133db884297cbb5f939df82f67db2bccfb0efc142627d032b8f",
|
||||||
|
"figures/interior_reference_sensitivity.png": "f3f612974c19841aa960d14824dfbf713304a60b74af87bade35cfe70dd1f86f",
|
||||||
|
"figures/interior_reference_sensitivity.svg": "b61ee318190c584c389f051023796edc3111cb288d5790059b94e54cdd01e2ac",
|
||||||
|
"figures/participation_reference.pdf": "ea500a0838178b1747fe4d9325c927f8a19557b26de266cd0171ada2bc04da1c",
|
||||||
|
"figures/participation_reference.png": "89782ec43f88874b6b822e91a90ff4b8f5cb40edeae5229286c80781c5336bab",
|
||||||
|
"figures/participation_reference.svg": "f24de314649ea9d8b2b6ce66187515857f5b0eb10e68d8f8e0437fee2fcf6272",
|
||||||
|
"figures/radial_shape_two_tails.pdf": "36d6e9df0db1c1986da949330cc22daf04dac7a3e524778447a68fbd9adac359",
|
||||||
|
"figures/radial_shape_two_tails.png": "3b6149a4b0ef154f58c06f518e8a6a972f1ff6c913d0058c5698e64ae74213eb",
|
||||||
|
"figures/radial_shape_two_tails.svg": "f665d434b5511ad480a32a565e0ce433a1dfaf6b9855b6caa524b0fab24a1a75",
|
||||||
|
"inventory.json": "fe7c88d5d4ae58dcd45709b44041e3d216953fae64dfc4e22961b7051727f83a",
|
||||||
|
"measured_radii.npz": "bc2a8298aa94e3c9481474f91400f16a119a5083f8112145727cbab080ebd075",
|
||||||
|
"metrics.csv": "d4176fa88b9126c00ba7e56bb54a031828a7481e9049a03c5058c58d0e8c1c30",
|
||||||
|
"profiles.json.gz": "7a97cf2dccd4993e2e5318ace39536bbd592d133bc3d393e7631f3911e500faf",
|
||||||
|
"summary.json": "7320790885813d2afa9b688685efcf8c9ed72ef7f7e97557658602cf2008eef2",
|
||||||
|
"test-output.txt": "3794ae58181c17343dc3660a54b70c53f4f75dbd25fa6637e5f185553fe094d4"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"python": "3.14.4 (main, Aug 20 2026, 10:41:58) [GCC 15.2.0]",
|
||||||
|
"platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43",
|
||||||
|
"numpy": "2.5.4",
|
||||||
|
"matplotlib": "3.11.2",
|
||||||
|
"source_code_sha256": {
|
||||||
|
"model_shell/analyze.py": "e791368b5ef9094ee6b3a1d4603fe11b0161b647353fa4d25c52aadfae914fe2",
|
||||||
|
"model_shell/groups.py": "eafbce2f0eeac89cfd3c63c57e91d1b7a260f4de4a1dd38be0aaceda5f317b15",
|
||||||
|
"model_shell/report.py": "af0617373a2b06cbe5728330157c1d2e60615eb7577cf3dd95be699a4b27ae19",
|
||||||
|
"model_shell/test_analysis.py": "a837d787d00e5a6302ae46ca4079bbaabe3f548cc71705cce514c92acd0943e7"
|
||||||
|
},
|
||||||
|
"protocol_sha256": "dfece26a7f2779c511d7a8f9a6c62c1ed49fec2dc5a3aa8c112681a52189d366",
|
||||||
|
"seed": "first 8 SHA256 bytes, little endian; group id plus purpose suffix",
|
||||||
|
"thread_limit": 1,
|
||||||
|
"server": "8.211.154.134",
|
||||||
|
"training": false,
|
||||||
|
"inference": false,
|
||||||
|
"gpu": false
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 136 KiB |
|
After Width: | Height: | Size: 314 KiB |
|
After Width: | Height: | Size: 240 KiB |
|
After Width: | Height: | Size: 162 KiB |
|
After Width: | Height: | Size: 167 KiB |
|
After Width: | Height: | Size: 111 KiB |
|
After Width: | Height: | Size: 114 KiB |
|
After Width: | Height: | Size: 89 KiB |
|
After Width: | Height: | Size: 293 KiB |
|
After Width: | Height: | Size: 500 KiB |
@@ -0,0 +1,246 @@
|
|||||||
|
{
|
||||||
|
"strata": {
|
||||||
|
"origin/matrix": {
|
||||||
|
"n": 517,
|
||||||
|
"median_zero_fraction": 0.0,
|
||||||
|
"median_coordinate_energy_participation_fraction": 0.30673555734079716,
|
||||||
|
"median_coordinate_variance_participation_fraction": 0.934645955851128,
|
||||||
|
"ball": {
|
||||||
|
"median_interior90_gap": 0.98046875,
|
||||||
|
"fraction_gap_gt10pp": 0.9806576402321083,
|
||||||
|
"median_positive_rms_gap": 0.37109375,
|
||||||
|
"median_negative_rms_gap": 0.3515625,
|
||||||
|
"fraction_two_sided_rms_gt10pp": 0.9516441005802708,
|
||||||
|
"median_participation_ratio": 0.8297024600513981
|
||||||
|
},
|
||||||
|
"range_box": {
|
||||||
|
"median_interior90_gap": 0.96875,
|
||||||
|
"fraction_gap_gt10pp": 0.9806576402321083,
|
||||||
|
"median_positive_rms_gap": 0.32421875,
|
||||||
|
"median_negative_rms_gap": 0.310546875,
|
||||||
|
"fraction_two_sided_rms_gt10pp": 0.9090909090909091,
|
||||||
|
"median_participation_ratio": 1.3431227073360341
|
||||||
|
},
|
||||||
|
"moment_box": {
|
||||||
|
"median_interior90_gap": 0.9765625,
|
||||||
|
"fraction_gap_gt10pp": 0.9806576402321083,
|
||||||
|
"median_positive_rms_gap": 0.34375,
|
||||||
|
"median_negative_rms_gap": 0.330078125,
|
||||||
|
"fraction_two_sided_rms_gt10pp": 0.9381044487427466,
|
||||||
|
"median_participation_ratio": 0.8524481165697501
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"origin/head_rows": {
|
||||||
|
"n": 1004,
|
||||||
|
"median_zero_fraction": 0.0,
|
||||||
|
"median_coordinate_energy_participation_fraction": 0.31172156343430024,
|
||||||
|
"median_coordinate_variance_participation_fraction": 0.9055279134912191,
|
||||||
|
"ball": {
|
||||||
|
"median_interior90_gap": 0.97265625,
|
||||||
|
"fraction_gap_gt10pp": 0.99800796812749,
|
||||||
|
"median_positive_rms_gap": 0.578125,
|
||||||
|
"median_negative_rms_gap": 0.265625,
|
||||||
|
"fraction_two_sided_rms_gt10pp": 0.896414342629482,
|
||||||
|
"median_participation_ratio": 0.7070664507223768
|
||||||
|
},
|
||||||
|
"range_box": {
|
||||||
|
"median_interior90_gap": 0.96875,
|
||||||
|
"fraction_gap_gt10pp": 0.99800796812749,
|
||||||
|
"median_positive_rms_gap": 0.55078125,
|
||||||
|
"median_negative_rms_gap": 0.244140625,
|
||||||
|
"fraction_two_sided_rms_gt10pp": 0.852589641434263,
|
||||||
|
"median_participation_ratio": 1.1235217859798587
|
||||||
|
},
|
||||||
|
"moment_box": {
|
||||||
|
"median_interior90_gap": 0.97265625,
|
||||||
|
"fraction_gap_gt10pp": 0.99800796812749,
|
||||||
|
"median_positive_rms_gap": 0.56640625,
|
||||||
|
"median_negative_rms_gap": 0.251953125,
|
||||||
|
"fraction_two_sided_rms_gt10pp": 0.8784860557768924,
|
||||||
|
"median_participation_ratio": 0.7369770671990965
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"mean/matrix": {
|
||||||
|
"n": 517,
|
||||||
|
"median_zero_fraction": 0.0,
|
||||||
|
"median_coordinate_energy_participation_fraction": 0.30718321338258303,
|
||||||
|
"median_coordinate_variance_participation_fraction": 0.934645955851128,
|
||||||
|
"ball": {
|
||||||
|
"median_interior90_gap": 0.9765625,
|
||||||
|
"fraction_gap_gt10pp": 0.9787234042553191,
|
||||||
|
"median_positive_rms_gap": 0.46484375,
|
||||||
|
"median_negative_rms_gap": 0.37109375,
|
||||||
|
"fraction_two_sided_rms_gt10pp": 0.9922630560928434,
|
||||||
|
"median_participation_ratio": 0.8366753780099343
|
||||||
|
},
|
||||||
|
"range_box": {
|
||||||
|
"median_interior90_gap": 0.97265625,
|
||||||
|
"fraction_gap_gt10pp": 0.9787234042553191,
|
||||||
|
"median_positive_rms_gap": 0.3359375,
|
||||||
|
"median_negative_rms_gap": 0.32421875,
|
||||||
|
"fraction_two_sided_rms_gt10pp": 0.9303675048355899,
|
||||||
|
"median_participation_ratio": 0.868224555240548
|
||||||
|
},
|
||||||
|
"moment_box": {
|
||||||
|
"median_interior90_gap": 0.9765625,
|
||||||
|
"fraction_gap_gt10pp": 0.9787234042553191,
|
||||||
|
"median_positive_rms_gap": 0.33984375,
|
||||||
|
"median_negative_rms_gap": 0.3359375,
|
||||||
|
"fraction_two_sided_rms_gt10pp": 0.9439071566731141,
|
||||||
|
"median_participation_ratio": 0.8465704560846329
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"mean/head_rows": {
|
||||||
|
"n": 1004,
|
||||||
|
"median_zero_fraction": 0.0,
|
||||||
|
"median_coordinate_energy_participation_fraction": 0.31181881259530586,
|
||||||
|
"median_coordinate_variance_participation_fraction": 0.9055279134912191,
|
||||||
|
"ball": {
|
||||||
|
"median_interior90_gap": 0.96875,
|
||||||
|
"fraction_gap_gt10pp": 0.9970119521912351,
|
||||||
|
"median_positive_rms_gap": 0.62109375,
|
||||||
|
"median_negative_rms_gap": 0.296875,
|
||||||
|
"fraction_two_sided_rms_gt10pp": 0.9322709163346613,
|
||||||
|
"median_participation_ratio": 0.7143476292983669
|
||||||
|
},
|
||||||
|
"range_box": {
|
||||||
|
"median_interior90_gap": 0.96875,
|
||||||
|
"fraction_gap_gt10pp": 0.9970119521912351,
|
||||||
|
"median_positive_rms_gap": 0.560546875,
|
||||||
|
"median_negative_rms_gap": 0.248046875,
|
||||||
|
"fraction_two_sided_rms_gt10pp": 0.8615537848605578,
|
||||||
|
"median_participation_ratio": 0.7194449549938213
|
||||||
|
},
|
||||||
|
"moment_box": {
|
||||||
|
"median_interior90_gap": 0.96875,
|
||||||
|
"fraction_gap_gt10pp": 0.9970119521912351,
|
||||||
|
"median_positive_rms_gap": 0.5625,
|
||||||
|
"median_negative_rms_gap": 0.25,
|
||||||
|
"fraction_two_sided_rms_gt10pp": 0.8635458167330677,
|
||||||
|
"median_participation_ratio": 0.7159821443435122
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"paired_changed": {
|
||||||
|
"origin": {
|
||||||
|
"n": 936,
|
||||||
|
"median_max": {
|
||||||
|
"median": 6.302327853480172e-07,
|
||||||
|
"p10": -3.2093888658157876e-05,
|
||||||
|
"p90": 3.49557393942157e-05,
|
||||||
|
"max_abs": 0.0004028694837374669
|
||||||
|
},
|
||||||
|
"median_rms": {
|
||||||
|
"median": -2.0223542534503203e-06,
|
||||||
|
"p10": -4.008879155420475e-05,
|
||||||
|
"p90": 3.916460868902405e-05,
|
||||||
|
"max_abs": 0.00012196820638044059
|
||||||
|
},
|
||||||
|
"covariance_participation": {
|
||||||
|
"median": 0.00011293028622105794,
|
||||||
|
"p10": -0.0007975000317692604,
|
||||||
|
"p90": 0.0011630175829182576,
|
||||||
|
"max_abs": 0.01369755006576412
|
||||||
|
},
|
||||||
|
"moment_box_interior90_gap": {
|
||||||
|
"median": 0.0,
|
||||||
|
"p10": 0.0,
|
||||||
|
"p90": 0.0,
|
||||||
|
"max_abs": 0.0
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"mean": {
|
||||||
|
"n": 936,
|
||||||
|
"median_max": {
|
||||||
|
"median": 3.087481980079687e-07,
|
||||||
|
"p10": -3.294732610958917e-05,
|
||||||
|
"p90": 3.3782823366856896e-05,
|
||||||
|
"max_abs": 0.0003950555852355597
|
||||||
|
},
|
||||||
|
"median_rms": {
|
||||||
|
"median": -1.9769477522801893e-06,
|
||||||
|
"p10": -4.086651887480475e-05,
|
||||||
|
"p90": 3.901337185857612e-05,
|
||||||
|
"max_abs": 0.00030628174134661457
|
||||||
|
},
|
||||||
|
"covariance_participation": {
|
||||||
|
"median": 0.00012692754527421357,
|
||||||
|
"p10": -0.000792364212092167,
|
||||||
|
"p90": 0.0011259624874320195,
|
||||||
|
"max_abs": 0.012713060927119102
|
||||||
|
},
|
||||||
|
"moment_box_interior90_gap": {
|
||||||
|
"median": 0.0,
|
||||||
|
"p10": 0.0,
|
||||||
|
"p90": 0.0,
|
||||||
|
"max_abs": 0.00390625
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"secondary": [
|
||||||
|
{
|
||||||
|
"model": "original",
|
||||||
|
"center": "origin",
|
||||||
|
"stratum": "small_sample",
|
||||||
|
"n": 36,
|
||||||
|
"median_max": 0.7489558868770938,
|
||||||
|
"moment_interior90_gap": 0.75
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"model": "original",
|
||||||
|
"center": "origin",
|
||||||
|
"stratum": "projected",
|
||||||
|
"n": 1,
|
||||||
|
"median_max": 0.41986786500966855,
|
||||||
|
"moment_interior90_gap": 0.99609375
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"model": "original",
|
||||||
|
"center": "mean",
|
||||||
|
"stratum": "small_sample",
|
||||||
|
"n": 36,
|
||||||
|
"median_max": 0.8109468212379675,
|
||||||
|
"moment_interior90_gap": 0.6875
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"model": "original",
|
||||||
|
"center": "mean",
|
||||||
|
"stratum": "projected",
|
||||||
|
"n": 1,
|
||||||
|
"median_max": 0.4244519268106477,
|
||||||
|
"moment_interior90_gap": 0.99609375
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"model": "finetuned",
|
||||||
|
"center": "origin",
|
||||||
|
"stratum": "small_sample",
|
||||||
|
"n": 36,
|
||||||
|
"median_max": 0.7489607494253279,
|
||||||
|
"moment_interior90_gap": 0.75
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"model": "finetuned",
|
||||||
|
"center": "origin",
|
||||||
|
"stratum": "projected",
|
||||||
|
"n": 1,
|
||||||
|
"median_max": 0.41986786500966855,
|
||||||
|
"moment_interior90_gap": 0.99609375
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"model": "finetuned",
|
||||||
|
"center": "mean",
|
||||||
|
"stratum": "small_sample",
|
||||||
|
"n": 36,
|
||||||
|
"median_max": 0.8110356927186851,
|
||||||
|
"moment_interior90_gap": 0.6875
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"model": "finetuned",
|
||||||
|
"center": "mean",
|
||||||
|
"stratum": "projected",
|
||||||
|
"n": 1,
|
||||||
|
"median_max": 0.4244519268106477,
|
||||||
|
"moment_interior90_gap": 0.99609375
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
test_ball_fit_and_sparse_counterexample (model_shell.test_analysis.Checks.test_ball_fit_and_sparse_counterexample) ... ok
|
||||||
|
test_center_scale_and_rank (model_shell.test_analysis.Checks.test_center_scale_and_rank) ... ok
|
||||||
|
test_reproducible_controls (model_shell.test_analysis.Checks.test_reproducible_controls) ... ok
|
||||||
|
test_sampling_and_lora (model_shell.test_analysis.Checks.test_sampling_and_lora) ... ok
|
||||||
|
|
||||||
|
----------------------------------------------------------------------
|
||||||
|
Ran 4 tests in 0.394s
|
||||||
|
|
||||||
|
OK
|
||||||
@@ -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,66 @@
|
|||||||
|
"""Check answer-only metrics and isolate recovery from newly lost items."""
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
from tempfile import TemporaryDirectory
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import torch
|
||||||
|
from torch.nn import functional as F
|
||||||
|
|
||||||
|
from crossqkv.lisa_effect_answer_audit import vocabulary_scores
|
||||||
|
from crossqkv.lisa_effect_audit import MODES, full_vocab_metrics, loss_delta, paired
|
||||||
|
from tests.test_lisa_tail import Tensor
|
||||||
|
|
||||||
|
|
||||||
|
class EffectAuditTests(unittest.TestCase):
|
||||||
|
def test_loss_interval_uses_paired_differences(self):
|
||||||
|
direct = np.array([0.5, 1.0, 4.0, 9.0])
|
||||||
|
result = loss_delta(direct - 0.25, direct)
|
||||||
|
self.assertEqual(result, {'mean_delta': -0.25,
|
||||||
|
'paired_prompt_bootstrap_95': [-0.25, -0.25]})
|
||||||
|
|
||||||
|
def test_full_vocab_compares_each_recipient_schedule_to_matched_direct(self):
|
||||||
|
mapped = ('native', 'linear', 'direct_chain', 'lisa_chain', 'lisa_answer_weighted',
|
||||||
|
'direct_23', 'lisa_23_ablation')
|
||||||
|
payload = {'candidate_sites': [19, 23], 'single_lisa_is_ablation_of_joint_checkpoint': True,
|
||||||
|
'arms': {}}
|
||||||
|
for name in mapped:
|
||||||
|
correct = name not in ('direct_chain', 'direct_23')
|
||||||
|
payload['arms'][name] = {
|
||||||
|
'n': 1, 'full_vocab_correct': int(correct), 'four_choice_correct': 1,
|
||||||
|
'full_vocab_nll': 0.25 if correct else 2.0,
|
||||||
|
'rows': [{'id': 'test-a', 'gold_id': 3, 'greedy_id': 3 if correct else 4,
|
||||||
|
'choice_id': 3, 'nll': 0.25 if correct else 2.0}],
|
||||||
|
}
|
||||||
|
choices = {name: np.array([True]) for name in MODES}
|
||||||
|
with TemporaryDirectory() as scratch:
|
||||||
|
path = Path(scratch) / 'answers.json'
|
||||||
|
path.write_text(json.dumps(payload))
|
||||||
|
measured = full_vocab_metrics(path, [('test-a', 0)], [19, 23], choices)
|
||||||
|
comparisons = measured['matched_direct_comparisons']
|
||||||
|
self.assertEqual(comparisons['lisa_chain']['baseline'], 'direct_chain')
|
||||||
|
self.assertEqual(comparisons['lisa_23_ablation']['baseline'], 'direct_23')
|
||||||
|
self.assertEqual(comparisons['lisa_chain']['rescued'], 1)
|
||||||
|
self.assertEqual(comparisons['lisa_chain']['answer_nll_delta']['mean_delta'], -1.75)
|
||||||
|
choices['lisa'] = np.array([False])
|
||||||
|
with self.assertRaisesRegex(ValueError, 'lisa_chain choices differ'):
|
||||||
|
full_vocab_metrics(path, [('test-a', 0)], [19, 23], choices)
|
||||||
|
|
||||||
|
def test_paired_rescue_excludes_natively_wrong_items(self):
|
||||||
|
native, direct, candidate = (np.array(x, dtype=bool) for x in
|
||||||
|
[(1, 1, 1, 0), (0, 0, 1, 1), (1, 0, 0, 1)])
|
||||||
|
result = paired(native, direct, candidate)
|
||||||
|
self.assertEqual(result['native_correct_lost_by_direct'], 2)
|
||||||
|
self.assertEqual(result['rescued'], 1)
|
||||||
|
self.assertEqual(result['newly_lost_among_native_and_direct_correct'], 1)
|
||||||
|
self.assertEqual(result['accuracy_delta_vs_direct'], 0)
|
||||||
|
|
||||||
|
def test_streamed_answer_scores_match_full_reference(self):
|
||||||
|
g = torch.Generator().manual_seed(9)
|
||||||
|
h, w = torch.randn(4, 6, generator=g), torch.randn(1033, 6, generator=g)
|
||||||
|
target = torch.tensor([2, 1032, 22, 1024])
|
||||||
|
actual, loss = vocabulary_scores(h, target, Tensor(w.numpy()))
|
||||||
|
logits = F.linear(h, w)
|
||||||
|
torch.testing.assert_close(actual, logits.argmax(-1))
|
||||||
|
torch.testing.assert_close(loss, F.cross_entropy(logits, target, reduction='none'))
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
"""Check exact epoch resume through the actual LiSA training entry point."""
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
from tempfile import TemporaryDirectory
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import torch
|
||||||
|
|
||||||
|
from crossqkv.lisa_effect import train
|
||||||
|
from functional.model import PREFIX
|
||||||
|
from functional.reference_check import ArrayLM
|
||||||
|
from tests.test_lisa_tail import Tensor
|
||||||
|
|
||||||
|
|
||||||
|
class TrainingResumeTests(unittest.TestCase):
|
||||||
|
def test_checkpoint_resume_preserves_all_selected_outputs(self):
|
||||||
|
rng = np.random.default_rng(22)
|
||||||
|
|
||||||
|
def rand(shape):
|
||||||
|
return (.13*rng.standard_normal(shape)).astype('f4')
|
||||||
|
|
||||||
|
torch.set_num_threads(1)
|
||||||
|
c = {'rms_norm_eps': 1e-6, 'layer_types': ['full_attention'], 'hidden_size': 8,
|
||||||
|
'num_attention_heads': 2, 'num_key_value_heads': 1, 'head_dim': 8,
|
||||||
|
'rope_parameters': {'rope_theta': 10000., 'partial_rotary_factor': .5}}
|
||||||
|
shapes = {'input_layernorm': (8,), 'post_attention_layernorm': (8,),
|
||||||
|
'self_attn.q_proj': (32, 8), 'self_attn.k_proj': (8, 8),
|
||||||
|
'self_attn.v_proj': (8, 8), 'self_attn.o_proj': (8, 16),
|
||||||
|
'self_attn.q_norm': (8,), 'self_attn.k_norm': (8,),
|
||||||
|
'mlp.gate_proj': (13, 8), 'mlp.up_proj': (13, 8), 'mlp.down_proj': (8, 13)}
|
||||||
|
weights = {f'layers.0.{k}.weight': rand(v) for k, v in shapes.items()}
|
||||||
|
weights.update({'embed_tokens.weight': rand((12,8)), 'norm.weight': rand((8,))})
|
||||||
|
model = ArrayLM(weights, c)
|
||||||
|
model.tensors = {PREFIX+k: Tensor(v) for k,v in weights.items()}
|
||||||
|
with TemporaryDirectory() as directory:
|
||||||
|
p = Path(directory)
|
||||||
|
cache, out = p/'cache', p/'out'
|
||||||
|
cache.mkdir()
|
||||||
|
out.mkdir()
|
||||||
|
(p/'model_config.json').write_text(json.dumps(c))
|
||||||
|
(cache/'selection.json').write_text(json.dumps({'sites':[0], 'task':'fixture',
|
||||||
|
'source_sha256':{}}))
|
||||||
|
labels = np.arange(1, 5, dtype=np.int64)
|
||||||
|
for split, count in [('fit',12), ('validation',12), ('test',32)]:
|
||||||
|
for i in range(0, count, 4):
|
||||||
|
ids = rng.integers(1, 12, size=(4, 4))
|
||||||
|
gold = rng.integers(0, 4, size=4)
|
||||||
|
ids[:, -1] = labels[gold]
|
||||||
|
expected, _ = model.forward(ids)
|
||||||
|
np.savez(cache/f'{split}-{i:03}.npz', ids=ids, lengths=np.full(4,4),
|
||||||
|
labels=labels, gold=gold, residual=model.embedding(ids),
|
||||||
|
donor=rand((4,2,4,4)), expected=expected,
|
||||||
|
names=[f'{split}-{k}' for k in range(i,i+4)])
|
||||||
|
with patch('functional.model.StreamingLM', return_value=model), patch('builtins.print'):
|
||||||
|
train(p, cache, out, 1)
|
||||||
|
before = (out/'test-items.json').read_bytes()
|
||||||
|
lines = (out/'trace.json').read_bytes()
|
||||||
|
train(p, cache, out, 1, resume=True)
|
||||||
|
self.assertEqual(before, (out/'test-items.json').read_bytes())
|
||||||
|
self.assertEqual(lines, (out/'trace.json').read_bytes())
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
"""Prove shared-prefix replay matches the original replicated-batch screen."""
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
from tokenizers import Tokenizer
|
||||||
|
from tokenizers.models import WordLevel
|
||||||
|
from tokenizers.pre_tokenizers import Whitespace
|
||||||
|
|
||||||
|
from crossqkv.lisa_effect_screen import MODES, ScreeningModel, evaluate, problems
|
||||||
|
from functional.model import PREFIX
|
||||||
|
from functional.reference_check import ArrayLM
|
||||||
|
|
||||||
|
|
||||||
|
class ArrayTensor:
|
||||||
|
def __init__(self, values):
|
||||||
|
self.raw = values
|
||||||
|
self.shape = values.shape
|
||||||
|
self.dtype = 'F32'
|
||||||
|
|
||||||
|
def evict(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class TinyScreen(ScreeningModel, ArrayLM):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class ScreenTests(unittest.TestCase):
|
||||||
|
def test_replay_preserves_all_three_arms(self):
|
||||||
|
rng = np.random.default_rng(11)
|
||||||
|
cfg = {'rms_norm_eps': 1e-6, 'layer_types': ['full_attention']*24,
|
||||||
|
'num_attention_heads': 2, 'num_key_value_heads': 1, 'head_dim': 8,
|
||||||
|
'rope_parameters': {'rope_theta': 10000., 'partial_rotary_factor': .5}}
|
||||||
|
rand = lambda shape: (.12*rng.standard_normal(shape)).astype('f4')
|
||||||
|
weights = {'norm.weight': rand((8,)), 'embed_tokens.weight': rand((15, 8))}
|
||||||
|
shapes = {'input_layernorm': (8,), 'post_attention_layernorm': (8,),
|
||||||
|
'self_attn.q_proj': (32, 8), 'self_attn.k_proj': (8, 8),
|
||||||
|
'self_attn.v_proj': (8, 8), 'self_attn.o_proj': (8, 16),
|
||||||
|
'self_attn.q_norm': (8,), 'self_attn.k_norm': (8,),
|
||||||
|
'mlp.gate_proj': (13, 8), 'mlp.up_proj': (13, 8), 'mlp.down_proj': (8, 13)}
|
||||||
|
weights.update({f'layers.{i}.{k}.weight': rand(v) for i in range(24) for k,v in shapes.items()})
|
||||||
|
model = TinyScreen(weights, cfg)
|
||||||
|
model.tensors = {PREFIX+k: ArrayTensor(v) for k,v in weights.items()}
|
||||||
|
tok = Tokenizer(WordLevel({'[UNK]': 0, **{str(i): i for i in range(1, 10)}}, unk_token='[UNK]'))
|
||||||
|
tok.pre_tokenizer = Whitespace()
|
||||||
|
examples = problems('screen', 2)
|
||||||
|
originals = evaluate(model, tok, examples)
|
||||||
|
model.reuse_prefix = True
|
||||||
|
replay = evaluate(model, tok, examples)
|
||||||
|
for orig, new in zip(originals, replay):
|
||||||
|
for key in MODES:
|
||||||
|
np.testing.assert_allclose(orig['scores'][key]['logits'],
|
||||||
|
new['scores'][key]['logits'], atol=1e-6)
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
"""Check streamed frozen gradients and the Torch tail against the CPU reference."""
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import torch
|
||||||
|
from torch.nn import functional as F
|
||||||
|
|
||||||
|
from crossqkv.lisa_decode import AttentionSiteCache
|
||||||
|
from crossqkv.lisa_decode_bench import ResidentSite, timed_site
|
||||||
|
from crossqkv.lisa_tail import FrozenLinear, TorchTail, gated_delta, rotate
|
||||||
|
from crossqkv.lisa_train import LearnableSharingAttention
|
||||||
|
from functional.model import PREFIX, delta_rule, rope
|
||||||
|
from functional.reference_check import ArrayLM
|
||||||
|
|
||||||
|
|
||||||
|
class Tensor:
|
||||||
|
def __init__(self, value):
|
||||||
|
self.value = value
|
||||||
|
self.shape = value.shape
|
||||||
|
|
||||||
|
def read(self, selection):
|
||||||
|
return self.value.ravel()[selection]
|
||||||
|
|
||||||
|
def evict(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class TailTests(unittest.TestCase):
|
||||||
|
def test_frozen_rows_and_input_gradient(self):
|
||||||
|
torch.manual_seed(4)
|
||||||
|
x = torch.randn(2, 3, 5, requires_grad=True)
|
||||||
|
w = torch.randn(14, 5)
|
||||||
|
actual = FrozenLinear.apply(x, Tensor(w.numpy()), 2, 11)
|
||||||
|
dense = F.linear(x, w[2:11])
|
||||||
|
torch.testing.assert_close(actual, dense)
|
||||||
|
torch.testing.assert_close(torch.autograd.grad(actual.square().sum(), x)[0],
|
||||||
|
torch.autograd.grad(dense.square().sum(), x)[0])
|
||||||
|
|
||||||
|
def test_rotary_and_gated_delta(self):
|
||||||
|
rng = np.random.default_rng(8)
|
||||||
|
q, k, v = [rng.normal(size=(2, 5, 2, 8)).astype('f4') for _ in range(3)]
|
||||||
|
g = -np.abs(rng.normal(size=(2, 5, 2)).astype('f4'))
|
||||||
|
b = rng.uniform(size=(2, 5, 2)).astype('f4')
|
||||||
|
tx = torch.tensor(q)
|
||||||
|
torch.testing.assert_close(rotate(tx, 10000000., .5),
|
||||||
|
torch.tensor(rope(q, 10000000., .5)))
|
||||||
|
actual = gated_delta(*map(torch.tensor, (q, k, v, g, b)))
|
||||||
|
torch.testing.assert_close(actual, torch.tensor(delta_rule(q, k, v, g, b)[0]))
|
||||||
|
|
||||||
|
def test_two_recipient_forward_parity_and_both_get_gradients(self):
|
||||||
|
rng = np.random.default_rng(5)
|
||||||
|
cfg = {'rms_norm_eps': 1e-6, 'layer_types': ['full_attention', 'linear_attention',
|
||||||
|
'full_attention'], 'num_attention_heads': 2, 'num_key_value_heads': 1,
|
||||||
|
'head_dim': 8, 'linear_num_key_heads': 1, 'linear_num_value_heads': 2,
|
||||||
|
'linear_key_head_dim': 4, 'linear_value_head_dim': 4,
|
||||||
|
'rope_parameters': {'rope_theta': 10000., 'partial_rotary_factor': .5}}
|
||||||
|
|
||||||
|
def rand(*shape):
|
||||||
|
return (rng.normal(size=shape) * .2).astype('f4')
|
||||||
|
|
||||||
|
a = {'norm.weight': rand(8), 'embed_tokens.weight': rand(10, 8)}
|
||||||
|
for i, kind in enumerate(cfg['layer_types']):
|
||||||
|
names = {'input_layernorm': (8,), 'post_attention_layernorm': (8,),
|
||||||
|
'mlp.gate_proj': (12, 8), 'mlp.up_proj': (12, 8), 'mlp.down_proj': (8, 12)}
|
||||||
|
if kind == 'full_attention':
|
||||||
|
names.update({'self_attn.q_proj': (32, 8), 'self_attn.k_proj': (8, 8),
|
||||||
|
'self_attn.v_proj': (8, 8), 'self_attn.o_proj': (8, 16),
|
||||||
|
'self_attn.q_norm': (8,), 'self_attn.k_norm': (8,)})
|
||||||
|
else:
|
||||||
|
names.update({'linear_attn.in_proj_qkv': (16, 8), 'linear_attn.in_proj_z': (8, 8),
|
||||||
|
'linear_attn.in_proj_b': (2, 8), 'linear_attn.in_proj_a': (2, 8),
|
||||||
|
'linear_attn.out_proj': (8, 8), 'linear_attn.norm': (4,),
|
||||||
|
'linear_attn.conv1d': (16, 1, 3)})
|
||||||
|
a[f'layers.{i}.linear_attn.A_log'] = rand(2)
|
||||||
|
a[f'layers.{i}.linear_attn.dt_bias'] = rand(2)
|
||||||
|
a.update({f'layers.{i}.{name}.weight': rand(*shape) for name, shape in names.items()})
|
||||||
|
original = ArrayLM(a, cfg)
|
||||||
|
original.tensors = {PREFIX+k: Tensor(v) for k,v in a.items()}
|
||||||
|
ids = rng.integers(0, 10, (2, 5))
|
||||||
|
h = torch.tensor(original.embedding(ids))
|
||||||
|
expected, _ = original.forward(ids)
|
||||||
|
adapters = {i: LearnableSharingAttention(8, 2, 1, 4, 10000., .5, 16)
|
||||||
|
for i in (0, 2)}
|
||||||
|
tail = TorchTail(original, 0, adapters)
|
||||||
|
lengths = torch.tensor([5, 5])
|
||||||
|
native, _ = tail(h, None, lengths, 'native', ())
|
||||||
|
torch.testing.assert_close(native, torch.tensor(expected), atol=2e-5, rtol=2e-5)
|
||||||
|
donor = torch.tensor(rand(2, 2, 5, 5))
|
||||||
|
run, _ = tail(h, donor, lengths, 'lisa', (0,2), keep_teacher=False)
|
||||||
|
ref, _ = tail(h, donor, lengths, 'lisa', (0,2), keep_teacher=True)
|
||||||
|
torch.testing.assert_close(run, ref)
|
||||||
|
run.square().sum().backward()
|
||||||
|
self.assertTrue(all(p.grad is not None and p.grad.abs().sum() > 0 for p in tail.parameters()))
|
||||||
|
|
||||||
|
|
||||||
|
def test_decode_uses_rotary_offsets_and_compact_key_cache(self):
|
||||||
|
rng = np.random.default_rng(252)
|
||||||
|
cfg = {'rms_norm_eps': 1e-6, 'layer_types': ['full_attention'],
|
||||||
|
'num_attention_heads': 2, 'num_key_value_heads': 1, 'head_dim': 16,
|
||||||
|
'rope_parameters': {'rope_theta': 10000., 'partial_rotary_factor': .5}}
|
||||||
|
names = {'q_proj': (64, 8), 'k_proj': (16, 8), 'v_proj': (16, 8),
|
||||||
|
'o_proj': (8, 32), 'q_norm': (16,), 'k_norm': (16,)}
|
||||||
|
weights = {'layers.0.self_attn.' + k + '.weight':
|
||||||
|
rng.normal(0, .2, shape).astype('f4') for k, shape in names.items()}
|
||||||
|
source = ArrayLM(weights, cfg)
|
||||||
|
source.tensors = {PREFIX+k: Tensor(v) for k,v in weights.items()}
|
||||||
|
adapter = LearnableSharingAttention(8, 2, 1, 4, 10000., .5, width=12)
|
||||||
|
tail = TorchTail(source, 0, {0: adapter})
|
||||||
|
hidden = torch.tensor(rng.normal(0, .8, (2, 5, 8)).astype('f4'))
|
||||||
|
donor = torch.tensor(rng.normal(0, 1, (2, 2, 5, 5)).astype('f4'))
|
||||||
|
lengths = torch.tensor([5, 5])
|
||||||
|
native = AttentionSiteCache(tail, 0, 2, 5)
|
||||||
|
shared = AttentionSiteCache(tail, 0, 2, 5, adapter)
|
||||||
|
for mode, cache in [('native', native), ('lisa', shared)]:
|
||||||
|
out, raw, _ = tail.full(hidden, 0, donor, lengths, mode, (0,), False)
|
||||||
|
for pos in range(hidden.shape[1]):
|
||||||
|
row = donor[:, :, pos:pos+1, :pos+1] if mode == 'lisa' else None
|
||||||
|
actual, scores = cache.step(hidden[:, pos:pos+1], row)
|
||||||
|
torch.testing.assert_close(actual, out[:, pos:pos+1], atol=2e-6, rtol=2e-5)
|
||||||
|
torch.testing.assert_close(scores, raw[:, :, pos:pos+1, :pos+1],
|
||||||
|
atol=2e-6, rtol=2e-5)
|
||||||
|
cache.reset()
|
||||||
|
cache.prefill(hidden[:, :4])
|
||||||
|
row = donor[:, :, 4:5, :] if mode == 'lisa' else None
|
||||||
|
actual, scores = cache.step(hidden[:, 4:5], row)
|
||||||
|
torch.testing.assert_close(actual, out[:, 4:5], atol=2e-6, rtol=2e-5)
|
||||||
|
torch.testing.assert_close(scores, raw[:, :, 4:5, :], atol=2e-6, rtol=2e-5)
|
||||||
|
self.assertEqual(shared.allocated_bytes['v'], native.allocated_bytes['v'])
|
||||||
|
self.assertEqual(shared.allocated_bytes['k']*4, native.allocated_bytes['k'])
|
||||||
|
resident = ResidentSite(tail, 0)
|
||||||
|
_, original_states = timed_site({'native': native, 'lisa': shared}, hidden, donor, 5,
|
||||||
|
samples=2, rounds=2)
|
||||||
|
_, warm_states = timed_site({'native': AttentionSiteCache(resident, 0, 2, 5),
|
||||||
|
'lisa': AttentionSiteCache(resident, 0, 2, 5, adapter)},
|
||||||
|
hidden, donor, 5, samples=2, rounds=2)
|
||||||
|
for mode in ('native', 'lisa'):
|
||||||
|
for old, new in zip(original_states[mode], warm_states[mode]):
|
||||||
|
torch.testing.assert_close(old, new, atol=2e-6, rtol=2e-5)
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
"""Numerical checks for the exact CE and differentiable LiSA path."""
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
import torch
|
||||||
|
from torch.nn import functional as F
|
||||||
|
|
||||||
|
from crossqkv.lisa_train import (FrozenRecipient, LearnableSharingAttention,
|
||||||
|
causal_attention, language_model_loss, objective)
|
||||||
|
|
||||||
|
|
||||||
|
class LiSATrainingTests(unittest.TestCase):
|
||||||
|
def test_streamed_ce_value_and_gradient_match_dense(self):
|
||||||
|
torch.manual_seed(8)
|
||||||
|
hidden = torch.randn(2, 5, 7, dtype=torch.float64, requires_grad=True)
|
||||||
|
head = torch.randn(11, 7, dtype=hidden.dtype)
|
||||||
|
ids = torch.randint(0, len(head), (2, 5))
|
||||||
|
lengths = torch.tensor([5, 3])
|
||||||
|
|
||||||
|
def vocab():
|
||||||
|
for start in range(0, len(head), 4):
|
||||||
|
yield start, head[start:start+4]
|
||||||
|
|
||||||
|
valid = torch.arange(1, 5) < lengths[:, None]
|
||||||
|
dense = F.cross_entropy(F.linear(hidden[:, :-1][valid], head), ids[:, 1:][valid])
|
||||||
|
streamed = language_model_loss(hidden, ids, lengths, vocab)
|
||||||
|
torch.testing.assert_close(streamed, dense)
|
||||||
|
torch.testing.assert_close(torch.autograd.grad(streamed, hidden)[0],
|
||||||
|
torch.autograd.grad(dense, hidden)[0])
|
||||||
|
|
||||||
|
def test_answer_weighted_ce_matches_dense(self):
|
||||||
|
torch.manual_seed(12)
|
||||||
|
h = torch.randn((2, 4, 3), dtype=torch.float64, requires_grad=True)
|
||||||
|
w = torch.randn((5, 3), dtype=h.dtype)
|
||||||
|
ids = torch.randint(0, 5, (2, 4))
|
||||||
|
lengths = torch.tensor([4, 3])
|
||||||
|
valid = torch.arange(1, 4) < lengths[:, None]
|
||||||
|
answer = torch.arange(2, 5) == lengths[:, None]
|
||||||
|
weights = torch.where(answer, 16., 1.)[valid]
|
||||||
|
ce = F.cross_entropy(F.linear(h[:, :-1][valid], w), ids[:, 1:][valid], reduction='none')
|
||||||
|
dense = (ce * weights).sum() / weights.sum()
|
||||||
|
streamed = language_model_loss(h, ids, lengths, lambda: iter([(0, w)]), answer_weight=16.)
|
||||||
|
torch.testing.assert_close(streamed, dense)
|
||||||
|
torch.testing.assert_close(torch.autograd.grad(streamed, h)[0],
|
||||||
|
torch.autograd.grad(dense, h)[0])
|
||||||
|
|
||||||
|
def test_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()
|
||||||