Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f769de90c6 | |||
| 5dd3ab32c8 |
@@ -66,3 +66,41 @@ OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 venv/bin/python -B -m crossqkv.lisa_pil
|
|||||||
The diagnostic forward still computes native full Q/K and does not measure
|
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
|
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.
|
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.
|
||||||
|
|||||||
@@ -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,27 @@
|
|||||||
|
# Qwen3.5-2B 注意力共享的线性拟合与无梯度搜索
|
||||||
|
|
||||||
|
保留 Qwen3.5-2B 底座和第 19→23 层的单点干预。检索题要求输出最新的记录值,部分题故意包含同一键的冲突记录。12 道拟合题、8 道验证题、16 道留出题均独立生成。留出含 8 道 10 项表。各方案在测试前冻结,随机搜索的整体候选由验证集 NLL 选出。
|
||||||
|
|
||||||
|
| 方法 | 留出全词表首个数字准确数 | 留出九数字 NLL |
|
||||||
|
| --- | ---: | ---: |
|
||||||
|
| 原模型 | 1/16 | 1.73505 |
|
||||||
|
| 原序直接共享 | 1/16 | 1.80085 |
|
||||||
|
| 供体头的线性拟合 | 1/16 | 1.75648 |
|
||||||
|
| 供体与接收层 32 个 Q/K 坐标联合拟合 | 1/16 | 1.74997 |
|
||||||
|
| 两系数网格 | 1/16 | 1.79451 |
|
||||||
|
| 加噪择优,种子 1701(验证集选中) | 2/16 | 1.72949 |
|
||||||
|
| 加噪择优,种子 1702 / 1703 | 1/16 / 1/16 | 1.76795 / 1.76090 |
|
||||||
|
| 双向扰动,种子 1701 / 1702 / 1703 | 均 1/16 | 1.78861 / 1.79510 / 1.79207 |
|
||||||
|
|
||||||
|
三个加噪择优种子的平均留出 NLL 为 1.75278,较直接共享低约 0.048。联合线性拟合得 1.74997。验证集选中的加噪种子多答对一道重复键的 6 项表题,另外两个种子未多答对题。所有配置在 10 项表均为 0/8。这组小样本支持加噪和线性修正都能改善相对直接共享的数字排序损失,准确率收益只有单题、单种子的证据。网格选中供体增益 1.5、接收端增益 0。
|
||||||
|
|
||||||
|
加噪择优每个种子有 25 次拟合前向,包含起点。双向扰动每种子有 73 次,包含正负扰动及接受判断。另有验证前向。该预算下双向扰动提升较小,两个搜索的前向预算不同。优化只改变小型头混合矩阵,底座权重冻结,无反向传播。闭式线性拟合用原模型内部注意力分数作为目标,不用答题标签。九数字 NLL 只在数字 1–9 上归一化。全词表准确率只检查首个答案 token。
|
||||||
|
|
||||||
|
## 验证和复现
|
||||||
|
|
||||||
|
- 在已授权的原 Qwen 远程 CPU 运行 12 项检查,全部通过。
|
||||||
|
- 原模型末层重放与完整前向的最大绝对差分别为拟合 5.25e-6、验证 5.72e-6、留出 7.63e-6。逐题数字 NLL已从归档 logits 独立复算。
|
||||||
|
- 小型合成检查点还覆盖了抓取、续跑、校准、冻结和评估的端到端流程。
|
||||||
|
- 完整真实激活缓存保留于服务器,仓库仅保存合成题、模型与代码指纹、适配器及轨迹和评测。未测自由生成整段答案、多层替换或运行时加速。
|
||||||
|
|
||||||
|
复现命令见 [crossqkv/README.md](../../crossqkv/README.md)。
|
||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,260 @@
|
|||||||
|
{
|
||||||
|
"fit": [
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): pine=6, cedar=5, maple=9, moss=5, yew=7, oak=2. What is the latest value of moss? Answer with one digit:",
|
||||||
|
"gold": 5,
|
||||||
|
"entries": 6,
|
||||||
|
"duplicate": false,
|
||||||
|
"id": "fit-00"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): fir=2, maple=1, moss=1, fern=4, fern=1, elm=5. What is the latest value of fern? Answer with one digit:",
|
||||||
|
"gold": 1,
|
||||||
|
"entries": 6,
|
||||||
|
"duplicate": true,
|
||||||
|
"id": "fit-01"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): pine=1, elm=4, ash=2, birch=7, moss=3, fir=4. What is the latest value of moss? Answer with one digit:",
|
||||||
|
"gold": 3,
|
||||||
|
"entries": 6,
|
||||||
|
"duplicate": false,
|
||||||
|
"id": "fit-02"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): cedar=7, pine=8, elm=7, fern=5, yew=1, elm=3. What is the latest value of elm? Answer with one digit:",
|
||||||
|
"gold": 3,
|
||||||
|
"entries": 6,
|
||||||
|
"duplicate": true,
|
||||||
|
"id": "fit-03"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): maple=5, fir=4, elm=4, moss=2, cedar=9, fern=4. What is the latest value of fir? Answer with one digit:",
|
||||||
|
"gold": 4,
|
||||||
|
"entries": 6,
|
||||||
|
"duplicate": false,
|
||||||
|
"id": "fit-04"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): ash=2, ash=1, fir=7, yew=4, cedar=9, maple=9. What is the latest value of ash? Answer with one digit:",
|
||||||
|
"gold": 1,
|
||||||
|
"entries": 6,
|
||||||
|
"duplicate": true,
|
||||||
|
"id": "fit-05"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): yew=4, fir=5, ash=1, elm=3, cedar=1, pine=5. What is the latest value of pine? Answer with one digit:",
|
||||||
|
"gold": 5,
|
||||||
|
"entries": 6,
|
||||||
|
"duplicate": false,
|
||||||
|
"id": "fit-06"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): fern=3, reed=6, cedar=2, moss=1, fir=1, moss=9. What is the latest value of moss? Answer with one digit:",
|
||||||
|
"gold": 9,
|
||||||
|
"entries": 6,
|
||||||
|
"duplicate": true,
|
||||||
|
"id": "fit-07"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): elm=5, reed=4, fern=5, fir=9, moss=9, cedar=6. What is the latest value of reed? Answer with one digit:",
|
||||||
|
"gold": 4,
|
||||||
|
"entries": 6,
|
||||||
|
"duplicate": false,
|
||||||
|
"id": "fit-08"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): fern=8, ash=7, oak=9, maple=2, pine=5, pine=9. What is the latest value of pine? Answer with one digit:",
|
||||||
|
"gold": 9,
|
||||||
|
"entries": 6,
|
||||||
|
"duplicate": true,
|
||||||
|
"id": "fit-09"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): maple=3, fir=1, birch=4, fern=6, yew=9, cedar=6. What is the latest value of fern? Answer with one digit:",
|
||||||
|
"gold": 6,
|
||||||
|
"entries": 6,
|
||||||
|
"duplicate": false,
|
||||||
|
"id": "fit-10"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): yew=5, birch=4, birch=3, fir=8, oak=1, elm=9. What is the latest value of birch? Answer with one digit:",
|
||||||
|
"gold": 3,
|
||||||
|
"entries": 6,
|
||||||
|
"duplicate": true,
|
||||||
|
"id": "fit-11"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"validation": [
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): ash=7, fern=4, birch=9, yew=8, moss=9, cedar=9. What is the latest value of cedar? Answer with one digit:",
|
||||||
|
"gold": 9,
|
||||||
|
"entries": 6,
|
||||||
|
"duplicate": false,
|
||||||
|
"id": "validation-00"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): fern=2, cedar=6, yew=6, fir=1, elm=8, fern=8. What is the latest value of fern? Answer with one digit:",
|
||||||
|
"gold": 8,
|
||||||
|
"entries": 6,
|
||||||
|
"duplicate": true,
|
||||||
|
"id": "validation-01"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): birch=1, pine=2, yew=5, ash=1, fern=9, fir=3. What is the latest value of ash? Answer with one digit:",
|
||||||
|
"gold": 1,
|
||||||
|
"entries": 6,
|
||||||
|
"duplicate": false,
|
||||||
|
"id": "validation-02"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): reed=6, maple=6, cedar=1, ash=3, yew=8, reed=4. What is the latest value of reed? Answer with one digit:",
|
||||||
|
"gold": 4,
|
||||||
|
"entries": 6,
|
||||||
|
"duplicate": true,
|
||||||
|
"id": "validation-03"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): maple=5, pine=3, fern=7, oak=8, birch=6, yew=2. What is the latest value of oak? Answer with one digit:",
|
||||||
|
"gold": 8,
|
||||||
|
"entries": 6,
|
||||||
|
"duplicate": false,
|
||||||
|
"id": "validation-04"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): cedar=6, birch=6, oak=6, cedar=4, ash=8, elm=6. What is the latest value of cedar? Answer with one digit:",
|
||||||
|
"gold": 4,
|
||||||
|
"entries": 6,
|
||||||
|
"duplicate": true,
|
||||||
|
"id": "validation-05"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): maple=5, yew=5, fir=4, pine=4, elm=6, reed=3. What is the latest value of yew? Answer with one digit:",
|
||||||
|
"gold": 5,
|
||||||
|
"entries": 6,
|
||||||
|
"duplicate": false,
|
||||||
|
"id": "validation-06"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): fir=4, yew=4, moss=4, moss=1, oak=3, reed=4. What is the latest value of moss? Answer with one digit:",
|
||||||
|
"gold": 1,
|
||||||
|
"entries": 6,
|
||||||
|
"duplicate": true,
|
||||||
|
"id": "validation-07"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"test": [
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): pine=4, ash=1, birch=9, maple=7, fern=6, fir=9. What is the latest value of pine? Answer with one digit:",
|
||||||
|
"gold": 4,
|
||||||
|
"entries": 6,
|
||||||
|
"duplicate": false,
|
||||||
|
"id": "test-00"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): fir=9, pine=5, cedar=8, elm=9, maple=3, elm=8. What is the latest value of elm? Answer with one digit:",
|
||||||
|
"gold": 8,
|
||||||
|
"entries": 6,
|
||||||
|
"duplicate": true,
|
||||||
|
"id": "test-01"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): yew=4, fir=6, maple=1, oak=9, moss=2, reed=2, cedar=4, elm=7, fern=5, pine=3. What is the latest value of reed? Answer with one digit:",
|
||||||
|
"gold": 2,
|
||||||
|
"entries": 10,
|
||||||
|
"duplicate": false,
|
||||||
|
"id": "test-02"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): moss=5, ash=4, pine=6, reed=4, cedar=7, oak=7, elm=6, birch=8, fir=6, ash=6. What is the latest value of ash? Answer with one digit:",
|
||||||
|
"gold": 6,
|
||||||
|
"entries": 10,
|
||||||
|
"duplicate": true,
|
||||||
|
"id": "test-03"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): maple=9, elm=7, oak=7, pine=5, reed=4, cedar=8. What is the latest value of elm? Answer with one digit:",
|
||||||
|
"gold": 7,
|
||||||
|
"entries": 6,
|
||||||
|
"duplicate": false,
|
||||||
|
"id": "test-04"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): ash=7, fir=4, pine=5, fern=8, fern=9, oak=7. What is the latest value of fern? Answer with one digit:",
|
||||||
|
"gold": 9,
|
||||||
|
"entries": 6,
|
||||||
|
"duplicate": true,
|
||||||
|
"id": "test-05"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): elm=5, reed=9, oak=4, yew=8, cedar=1, fir=1, ash=4, maple=5, fern=3, pine=7. What is the latest value of elm? Answer with one digit:",
|
||||||
|
"gold": 5,
|
||||||
|
"entries": 10,
|
||||||
|
"duplicate": false,
|
||||||
|
"id": "test-06"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): moss=8, ash=7, pine=7, reed=7, yew=3, birch=4, elm=9, maple=3, ash=6, fir=9. What is the latest value of ash? Answer with one digit:",
|
||||||
|
"gold": 6,
|
||||||
|
"entries": 10,
|
||||||
|
"duplicate": true,
|
||||||
|
"id": "test-07"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): birch=5, elm=9, yew=9, ash=3, cedar=9, reed=9. What is the latest value of yew? Answer with one digit:",
|
||||||
|
"gold": 9,
|
||||||
|
"entries": 6,
|
||||||
|
"duplicate": false,
|
||||||
|
"id": "test-08"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): maple=7, yew=6, birch=3, reed=8, ash=6, maple=2. What is the latest value of maple? Answer with one digit:",
|
||||||
|
"gold": 2,
|
||||||
|
"entries": 6,
|
||||||
|
"duplicate": true,
|
||||||
|
"id": "test-09"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): ash=9, cedar=3, maple=5, fern=4, oak=2, reed=3, birch=7, pine=5, moss=3, elm=6. What is the latest value of elm? Answer with one digit:",
|
||||||
|
"gold": 6,
|
||||||
|
"entries": 10,
|
||||||
|
"duplicate": false,
|
||||||
|
"id": "test-10"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): elm=2, birch=3, moss=6, oak=2, fir=5, pine=9, yew=2, pine=2, cedar=7, fern=2. What is the latest value of pine? Answer with one digit:",
|
||||||
|
"gold": 2,
|
||||||
|
"entries": 10,
|
||||||
|
"duplicate": true,
|
||||||
|
"id": "test-11"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): yew=2, pine=2, fir=2, elm=3, moss=4, reed=9. What is the latest value of yew? Answer with one digit:",
|
||||||
|
"gold": 2,
|
||||||
|
"entries": 6,
|
||||||
|
"duplicate": false,
|
||||||
|
"id": "test-12"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): maple=8, birch=9, birch=2, oak=1, moss=8, cedar=2. What is the latest value of birch? Answer with one digit:",
|
||||||
|
"gold": 2,
|
||||||
|
"entries": 6,
|
||||||
|
"duplicate": true,
|
||||||
|
"id": "test-13"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): fern=2, pine=4, maple=3, yew=4, ash=8, reed=1, birch=3, fir=5, elm=6, cedar=2. What is the latest value of birch? Answer with one digit:",
|
||||||
|
"gold": 3,
|
||||||
|
"entries": 10,
|
||||||
|
"duplicate": false,
|
||||||
|
"id": "test-14"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"prompt": "Records (oldest first): birch=7, yew=4, elm=5, cedar=3, pine=1, oak=8, fern=3, ash=7, reed=1, ash=8. What is the latest value of ash? Answer with one digit:",
|
||||||
|
"gold": 8,
|
||||||
|
"entries": 10,
|
||||||
|
"duplicate": true,
|
||||||
|
"id": "test-15"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"donor": 19,
|
||||||
|
"recipient": 23,
|
||||||
|
"seeds": {
|
||||||
|
"fit": 22301,
|
||||||
|
"validation": 22302,
|
||||||
|
"test": 22303
|
||||||
|
},
|
||||||
|
"capture_code_sha256": "5b9d218fccf1bb9c64a27425e37f2f7abe58164083b3e0fbdc699ede3f9ab7fd",
|
||||||
|
"source_files_sha256": {
|
||||||
|
"manifest.json": "28efbaf94a5034333339a35f08ead151459a7d20c6c2d2f07a451e7f3bf154de",
|
||||||
|
"model_config.json": "ed1c1723241f23f7f4e23430759cbd7dcfb4103cbdfe052bfe7626b57c2615b4",
|
||||||
|
"tokenizer.json": "5f9e4d4901a92b997e463c1f46055088b6cca5ca61a6522d1b9f64c4bb81cb42"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,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'])
|
||||||
Reference in New Issue
Block a user