Compare commits

..

37 Commits

Author SHA1 Message Date
codex-bot 398b97a1df Explain counterfactual lookup errors and active rank budgets 2026-11-26 00:14:47 +08:00
codex-bot ce4c0e404b Replay verified frozen prefix inputs for reference trajectory distillation 2026-11-25 23:08:14 +08:00
codex-bot c577bb740a Track answers recovered or lost against both rank study controls 2026-11-25 21:24:53 +08:00
codex-bot 8ae5e8c2f7 Archive verified layer restoration answers and lock LiSA ranks 2026-11-25 19:04:47 +08:00
codex-bot 23386797c4 Reuse streamed vocabulary blocks for teacher and student projections 2026-11-25 16:33:19 +08:00
codex-bot 1f3ee3cbff Score gold answer tokens across single-layer restorations 2026-11-25 16:06:00 +08:00
codex-bot d1e87446d3 Run matched rank allocation and trajectory distillation experiments for LiSA 2026-11-25 15:23:47 +08:00
Zayden-Jung e7a7015b55 Merge pull request 'Evaluate LiSA recovery with complete answers at 3–5 attention layers' (#14) from codex/lisa-full-answer into main
Reviewed-on: #14
2026-11-25 06:45:56 +00:00
codex-bot 6aa66b29a1 Archive verified LiSA full-answer recovery results 2026-11-25 11:11:13 +08:00
codex-bot 4e66b5d5ba Archive LiSA fit capture verification 2026-11-25 05:00:09 +08:00
codex-bot 4291cc207f Archive full-answer screening and lock the LiSA schedule 2026-11-25 02:15:38 +08:00
codex-bot 2d1d28c331 Resume answer screening with verified paired batching 2026-11-24 18:47:30 +08:00
codex-bot 0f4c0a982c Verify complete answers from archived generation tokens 2026-11-24 16:34:33 +08:00
codex-bot c53d78b4aa Keep deep sharing generation within host memory guards 2026-11-24 16:12:37 +08:00
codex-bot 453b2ff787 Screen deeper LiSA sharing with complete autoregressive answers 2026-11-24 15:58:43 +08:00
Zayden-Jung 38545d4217 Merge pull request '复现 Qwen3.5-2B 双层 LiSA 的任务与缓存效果' (#13) from codex/lisa-effect-reproduction into main
Reviewed-on: #13
2026-11-23 18:48:15 +00:00
codex-bot 78f3869060 Verify LiSA full-vocabulary results and report scope 2026-11-24 01:39:44 +08:00
codex-bot c2aa23f32f Record LiSA task and CPU performance results 2026-11-24 01:16:08 +08:00
codex-bot 59072884ff Cross-check LiSA held-out metrics across scoring paths 2026-11-24 00:06:58 +08:00
codex-bot 1c8943a2e8 Add controlled two-layer LiSA reproduction on Qwen 2026-11-24 00:00:42 +08:00
Zayden-Jung 115e440455 Merge pull request '复现 Qwen3.5-2B 的可训练 LiSA 注意力共享' (#12) from codex/lisa-full-reproduction into main
Reviewed-on: #12
2026-11-23 09:01:22 +00:00
codex-bot 67327d62d8 Reproduce trainable LiSA attention on Qwen3.5-2B 2026-11-23 16:47:19 +08:00
Zayden-Jung 0df3b0bfe6 Merge pull request '评估 Qwen3.5-2B 注意力共享的线性拟合和无梯度搜索' (#11) from codex/lisa-forward-search into main
Reviewed-on: #11
2026-11-23 07:05:47 +00:00
codex-bot f769de90c6 Evaluate linear and forward-only optimization for attention sharing 2026-11-23 15:01:47 +08:00
Zayden-Jung 5dd3ab32c8 Merge pull request '验证 Qwen3.5-2B 的免训练注意力共享和 LiSA 式轻量校准' (#10) from codex/lisa-attention-pilot into main
Reviewed-on: #10
2026-11-22 14:12:34 +00:00
codex-bot 31a257ba17 Evaluate training-free attention reuse and LiSA-style calibration 2026-11-22 20:20:25 +08:00
Zayden-Jung ea9bfd2a23 Merge pull request '实测两个Qwen3.5-2B检查点的参数球壳与微调变化' (#9) from codex/model-shell into main
Reviewed-on: #9
2026-11-11 16:29:43 +00:00
codex-bot 2f1113323e Measure parameter shell geometry in paired Qwen3.5-2B checkpoints 2026-11-12 00:24:30 +08:00
Zayden-Jung 35090663e2 Merge pull request '验证稀疏低维球的内部概率与径向反例' (#8) from codex/sparse-shell into main
Reviewed-on: #8
2026-11-11 15:26:17 +00:00
codex-bot e1514f4952 Verify sparse-ball shell probabilities with radial controls 2026-11-11 23:21:53 +08:00
Zayden-Jung 9e0e659287 Merge pull request '固定科研图册并比较GSM8K LoRA微调前后的有效头数' (#7) from codex/finetune-head-dominance into main
Reviewed-on: #7
2026-11-10 16:33:45 +00:00
codex-bot 52e6d13fe5 Archive research charts and compare GSM8K LoRA head concentration 2026-11-11 00:06:15 +08:00
Zayden-Jung d6d985487c Merge pull request '量化相邻层注意力头的影响集中度与联合消融效果' (#6) from codex/head-dominance into main
Reviewed-on: #6
2026-11-10 15:16:18 +00:00
codex-bot 098ea8650c Quantify adjacent-layer head influence concentration on CPU 2026-11-10 22:38:15 +08:00
Zayden-Jung cd260a2483 Merge pull request '测量全部24层输出通道块的激活率与能量集中度' (#5) from codex/block-activation into main
Reviewed-on: #5
2026-11-10 13:43:17 +00:00
codex-bot 419c7cb195 Measure CPU block activation sparsity and energy concentration 2026-11-10 19:32:38 +08:00
Zayden-Jung 0934079ed9 Merge pull request '跨层 QKV 功能验证与条件性检索重合' (#4) from codex/cross-layer-qkv into main
Reviewed-on: #4
2026-11-09 08:03:31 +00:00
436 changed files with 216973 additions and 2 deletions
+3
View File
@@ -4,3 +4,6 @@ results/** -text
results/**/*.csv -whitespace
results/**/*.svg -whitespace
results/**/*.log -whitespace
# Preserve captured scientific stdout byte-for-byte, including blank final lines.
results/head-dominance/*-output.txt -whitespace
+21
View File
@@ -1,5 +1,9 @@
# Model parameter similarity experiments
**[研究图册与固定在线副本](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
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.
@@ -38,3 +42,20 @@ block scales are alternative partitions and their savings must not be summed.
Dependencies are pinned in `requirements.txt`; install only prebuilt wheels on the remote host.
Full resolved versions and run provenance accompany each result. See the SOP for commands.
## CPU block activation measurements
See [measurement definitions](activation/README.md) and [observed activation report](results/block-activation/REPORT.md) for all 24 layers, contiguous output-channel blocks, exact/near-zero rates and output energy concentration. This is an observational SiLU-gated study, not a pruning or reuse quality claim.
## Adjacent-layer head influence concentration
The CPU study measures all 23 adjacent transitions, observation-wise effective
head counts and Q/K/V influence shares, with equal-size weak/strong/random joint
removal controls. See [definitions and reproduction](dominance/README.md),
[fixed protocol](dominance/PROTOCOL.md), and [measured report](results/head-dominance/REPORT.md).
These are descriptive intervention effects, not additive contribution probabilities
or validated final-LM pruning gains.
## Existing GSM8K task-finetuning comparison
[Paired study and reproduction](finetune_compare/README.md) · [Fixed protocol](finetune_compare/PROTOCOL.md) · [Results](results/finetune-comparison/REPORT.md). This compares an existing pure-LoRA GRPO checkpoint to exactly the same original release; no training is performed here.
+45
View File
@@ -0,0 +1,45 @@
# Observed block activation, CPU only
Measures the retained Qwen3.5-2B checkpoint without training or substitutions.
This model uses SiLU-gated MLPs and sigmoid attention gates, not ReLU.
Leaky ReLU also does not generally create exact zero on negative inputs.
The probe records every linear projection in all 24 layers, plus MLP SiLU
and gate-times-up intermediates and full-attention sigmoid gates. It does not
record every internal recurrent state, convolution output or attention probability.
A block means contiguous **output channels** (64 or 128), hence contiguous
rows of a projection matrix; it is not a Transformer layer or arbitrary 2D tile.
MLP gated-product channels correspond to columns consumed by down_proj.
It is incorrect to call an individual weight active/inactive based only on its value.
For every sample, module and block, metrics.csv reports:
- exact zero and negative element fractions;
- near-zero fractions at |x| <= 0.01 RMS and <= 0.1 RMS;
- fraction of channels ever above 0.01 RMS over the 32 tokens;
- minimum fraction of channels carrying 90% squared-output energy.
RMS is computed within each observed sample/module/block; width=0 records the
whole module. Thus thresholds are explicitly relative and are not shared absolute
cutoffs across layers or blocks. Activation rate at a threshold is 1-near-zero rate.
A small value or an energy-concentrated output does not prove that a block can
be skipped, removed or shared without affecting LM quality. Exact zero is measured
in this FP32 streaming implementation of BF16 source weights; other execution dtypes
can have different underflow rates.
Four prior authored Chinese/English texts, 32 tokens each, descriptive measurements
only. No training, fresh-generalization claim, GPU, weight download or cleanup.
The existing streaming implementation was checked against the official implementation
in the earlier CPU study; this experiment changes only observation, not model equations.
Remote commands (authorized server 8.211.154.134):
```
OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 venv/bin/python -B -m activation.run --source runs/cpu-qwen35-2b --out runs/NEW_ACTIVATION_DIR
OPENBLAS_NUM_THREADS=1 venv/bin/python -B -m unittest tests.test_activation -v
venv/bin/python -B activation/report.py runs/NEW_ACTIVATION_DIR
```
run.py measures; report.py plots saved rows and derives aggregates;
__init__.py marks the package; tests/test_activation.py checks exact sparsity,
ever-active behavior, all-zero inputs and scale invariance. Raw activations are
not saved or needed for these descriptive statistics. Existing caches and weights
are retained untouched. Full sample token IDs and CPU time/RSS appear in summary.json.
View File
+28
View File
@@ -0,0 +1,28 @@
"""Audit recorded scope, metrics and reproducibility files; no model execution."""
import csv,json,hashlib
from pathlib import Path
import sys
p=Path(sys.argv[1]);r=list(csv.DictReader((p/'metrics.csv').open()));s=json.loads((p/'summary.json').read_text())
assert s['completed'] and len(r)==s['rows']==4*20904
assert len({x['sample'] for x in r})==4
assert {int(x['module'].split('.')[1]) for x in r}==set(range(24))
for x in r:
for k in ['zero_rate','negative_rate','near_001_rms','near_01_rms','ever_active_001','energy90_channel_fraction']:assert 0<=float(x[k])<=1,(x,k)
assert float(x['zero_rate'])<=float(x['near_001_rms'])<=float(x['near_01_rms'])
assert int(x['channels'])==int(x['stop'])-int(x['start'])
a=json.loads((p/'aggregates.json').read_text());lines=['# 实测激活率:SiLU 门控模型','', '覆盖24层、4条中英文文本,每条32 token;所有投影输出及 MLP 门控中间量,按64/128输出通道分块。','', '| 输出 | 精确零比例均值 | 0.01 RMS以下均值 | 0.1 RMS以下均值 | 32 token内曾活跃通道比例均值 | 90%能量所需通道比例均值 |','|---|---:|---:|---:|---:|---:|']
for k,v in a.items():
cols=[v[m]['mean']*100 for m in ['zero_rate','near_001_rms','near_01_rms','ever_active_001','energy90_channel_fraction']]
lines.append('| '+k+' | '+' | '.join(f'{z:.4f}%' for z in cols)+' |')
blocks=[x for x in r if x['width']=='128']; dead=sum(float(x['zero_rate'])==1 for x in blocks)
lines+=['',f'128通道块×文本观测共{len(blocks)}条,整个32 token窗口全为精确零的块观测数为{dead}。', '', '表中是整模块逐文本统计再取均值;每个分块的独立统计见 metrics.csv。阈值是各自RMS的比例;阈值下激活率=1−近零比例。能量集中不等于可删除或可替换。', '', '仅测该模型、四条短文本;不推断所有语言/长上下文。SiLU不把负值整体截零,负数不等于静默。未执行删块/跳算的质量验证。权重和既有缓存全部保留。', '',f"CPU测量耗时{s['elapsed_seconds']:.1f}秒,峰值RSS{s['peak_rss_kib']/1024:.1f} MiB。"]
(p/'REPORT.md').write_text('\n'.join(lines)+'\n')
lines_extra=[]
for suffix in ['mlp.gated_product','self_attn.q_proj.output','self_attn.k_proj.output','self_attn.v_proj.output']:
rr=[x for x in blocks if x['module'].endswith(suffix)]
act=sorted(1-float(x['near_01_rms']) for x in rr)
lines_extra.append(f'{suffix}: 128通道块在0.1 RMS阈值上的激活率范围 {100*act[0]:.2f}%–{100*act[-1]:.2f}%。')
with (p/'REPORT.md').open('a') as f:f.write('\n'+'\n'.join(lines_extra)+'\n')
(p/'audit.json').write_text(json.dumps({'passed':True,'rows':len(r),'layers':24,'samples':4,'all_zero_128_blocks':dead},indent=2))
files=[x for x in p.rglob('*') if x.is_file() and x.name!='checksums.json'];(p/'checksums.json').write_text(json.dumps({str(x.relative_to(p)):hashlib.sha256(x.read_bytes()).hexdigest() for x in sorted(files)},indent=2))
print((p/'REPORT.md').read_text())
+38
View File
@@ -0,0 +1,38 @@
"""Render scientific figures from recorded CPU measurements."""
import csv,json
from pathlib import Path
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import sys
root=Path(sys.argv[1]); rows=list(csv.DictReader((root/'metrics.csv').open()))
full=[r for r in rows if r['width']=='0']
fig,axs=plt.subplots(1,3,figsize=(15,4.5),layout='constrained')
for suffix,label in [('gate_proj.output','gate preactivation'),('silu_gate','SiLU gate'),('gated_product','gated product')]:
selected=[r for r in full if r['module'].endswith('mlp.'+suffix)]
for ax,key in zip(axs,['zero_rate','near_001_rms','near_01_rms']):
xs=[];ys=[]
for layer in range(24):
z=[float(r[key]) for r in selected if r['module'].startswith(f'layers.{layer}.')];xs.append(layer);ys.append(np.mean(z))
ax.plot(xs,ys,label=label)
for ax,title in zip(axs,['Exact zero fraction','Near zero: |x| <= 0.01 RMS','Near zero: |x| <= 0.1 RMS']):
ax.set(title=title,xlabel='Layer index',ylabel='Fraction');ax.set_ylim(bottom=0);ax.grid(alpha=.2)
axs[-1].legend();fig.suptitle('Observed MLP activation sparsity: four texts, 32 tokens each; no training')
root.joinpath('figures').mkdir(exist_ok=True)
for ext in ('png','pdf','svg'):fig.savefig(root/'figures'/('mlp_activation.'+ext),dpi=180)
plt.close(fig)
blocks=[r for r in rows if r['width']=='128' and r['module'].endswith('mlp.gated_product')]
fig,axs=plt.subplots(1,2,figsize=(12,4.5),layout='constrained')
for ax,key,title in zip(axs,['near_01_rms','energy90_channel_fraction'],['Near-zero fraction at 0.1 block RMS','Fraction of channels carrying 90% energy']):
matrix=[]
for layer in range(24):
rr=[r for r in blocks if r['module'].startswith(f'layers.{layer}.')]; starts=sorted(set(int(r['start']) for r in rr));matrix.append([np.mean([float(r[key]) for r in rr if int(r['start'])==s]) for s in starts])
im=ax.imshow(matrix,aspect='auto',vmin=0,vmax=1);ax.set(title=title,xlabel='Contiguous 128-channel block',ylabel='Layer index');fig.colorbar(im,ax=ax)
fig.suptitle('MLP gated-product blocks: average over four observed texts')
for ext in ('png','pdf','svg'):fig.savefig(root/'figures'/('block_activity.'+ext),dpi=180)
agg={}
for suffix in ['mlp.gate_proj.output','mlp.silu_gate','mlp.gated_product','self_attn.q_proj.output','self_attn.k_proj.output','self_attn.v_proj.output']:
rr=[r for r in full if r['module'].endswith(suffix)]
agg[suffix]={'observations':len(rr),**{key:{'min':min(float(r[key]) for r in rr),'mean':float(np.mean([float(r[key]) for r in rr])),'max':max(float(r[key]) for r in rr)} for key in ['zero_rate','negative_rate','near_001_rms','near_01_rms','ever_active_001','energy90_channel_fraction']}}
(root/'aggregates.json').write_text(json.dumps(agg,indent=2))
+48
View File
@@ -0,0 +1,48 @@
"""CPU-only observed activation sparsity; no checkpoint changes or training."""
import json,csv,time,resource,hashlib
from pathlib import Path
import numpy as np
from tokenizers import Tokenizer
from functional.model import StreamingLM,silu,sigmoid
def metrics(x):
x=np.asarray(x,dtype=np.float64).reshape(-1,x.shape[-1]); a=np.abs(x); energy=np.square(x).sum(0); total=energy.sum()
rms=float(np.sqrt(np.mean(x*x))); cutoff=.01*rms
ordered=np.sort(energy)[::-1]; n90=int(np.searchsorted(np.cumsum(ordered),.9*total)+1) if total else 0
return dict(elements=x.size,channels=x.shape[-1],rms=rms,zero_rate=float(np.mean(x==0)),negative_rate=float(np.mean(x<0)),near_001_rms=float(np.mean(a<=cutoff)),near_01_rms=float(np.mean(a<=.1*rms)),ever_active_001=float(np.mean(np.any(a>cutoff,axis=0))),channels_for_90pct_energy=n90,energy90_channel_fraction=n90/x.shape[-1])
class Probe(StreamingLM):
def record(self,x,name):
for width in (0,64,128):
for start in range(0,x.shape[-1],width or x.shape[-1]):
stop=min(start+(width or x.shape[-1]),x.shape[-1]); z=x[...,start:stop]
self.rows.append(dict(sample=self.sample,module=name,width=width,start=start,stop=stop,**metrics(z)))
def linear(self,x,name,rows=256):
y=super().linear(x,name,rows); self.record(y,name+'.output')
if name.endswith('self_attn.q_proj'):
dim=self.config['head_dim']; mixed=y.reshape(*y.shape[:-1],-1,2*dim)
self.record(sigmoid(mixed[...,dim:]).reshape(*y.shape[:-1],-1),name+'.sigmoid_gate')
return y
def mlp(self,h,layer):
p=f'layers.{layer}.mlp.'; pre=self.linear(h,p+'gate_proj'); g=silu(pre); u=self.linear(h,p+'up_proj')
self.record(g,p+'silu_gate'); self.record(g*u,p+'gated_product')
return self.linear(g*u,p+'down_proj')
def main():
import argparse
p=argparse.ArgumentParser();p.add_argument('--source',type=Path,required=True);p.add_argument('--out',type=Path,required=True);a=p.parse_args();a.out.mkdir(parents=True,exist_ok=False)
started=time.monotonic();cfg=json.loads((a.source/'model_config.json').read_text()); lm=Probe(a.source/'weights',cfg,seconds=3600);lm.rows=[]
samples=json.loads(Path('crossqkv/fresh_samples.json').read_text())['samples'];tok=Tokenizer.from_file(str(a.source/'tokenizer.json'))
for s in samples:
lm.sample=s['id']; ids=tok.encode(s['text']).ids[:32];s['token_ids']=ids
lm.forward(np.array([ids],dtype=np.int64))
first=not (a.out/'metrics.csv').exists()
with (a.out/'metrics.csv').open('a') as f:
w=csv.DictWriter(f,fieldnames=list(lm.rows[0]))
if first:w.writeheader()
w.writerows(lm.rows)
print('completed',s['id'],len(lm.rows),flush=True);lm.rows.clear()
summary={'completed':True,'elapsed_seconds':time.monotonic()-started,'peak_rss_kib':resource.getrusage(resource.RUSAGE_SELF).ru_maxrss,'config_activation':lm.config.get('hidden_act'),'layer_count':len(lm.config['layer_types']),'samples':samples,'rows':sum(1 for _ in (a.out/'metrics.csv').open())-1,'block_widths':[64,128],'threshold_reference':'RMS within each sample/module/block, thresholds 0.01 and 0.1; exact zero measured separately','training':False,'weights_deleted':False,'limits':['4 short texts, 32 tokens each, descriptive only','Block is contiguous output channels, not Transformer block','Small output does not prove removable computation or parameter interchangeability','All samples previously used; no generalization claim','Relative threshold differs between blocks; width=0 is whole module reference']}
(a.out/'summary.json').write_text(json.dumps(summary,indent=2))
if __name__=='__main__':main()
+104
View File
@@ -40,3 +40,107 @@ All weights and caches stay on the server until explicit user deletion. Git cont
all figure tables and the selected small probability matrices; large caches have exact
paths/sizes/hashes in `external-caches.json`. Old validation texts were used in earlier
experiments; the four fresh texts were fixed before the new cross-layer measurements.
## LiSA-style single-layer pilot
The pilot reuses layer 19's actual pre-softmax scores at layer 23, with the
recipient's own values, output gate and output projection. It compares native
attention, direct reuse, a frozen one-to-one head assignment, linear mixing
of donor heads, a 32-coordinate recipient-only control, and joint donor/recipient
mixing. The linear variants use a closed-form ridge fit to the native scores,
centred within each causal key row. The recipient branch takes a fixed subset of
post-RoPE coordinates rather than learning a low-rank Q/K projection. The
calibration uses 12 synthetic prompts without answer labels. All checkpoint
weights are frozen.
Evaluation scores the four candidate option tokens on 24 disjoint retrieval
prompts, including 12 with more table entries than calibration. Choice NLL
normalizes over those four tokens. Run against the retained checkpoint on the
remote CPU environment:
```sh
OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 venv/bin/python -B -m crossqkv.lisa_pilot \
--source runs/cpu-qwen35-2b --out runs/NEW_LISA_DIRECTORY
```
The diagnostic forward still computes native full Q/K and does not measure
latency or parameter savings. Refer to LiSA (arXiv:2408.01890, §5.1) for its
learned nonlinear head aligner and learned low-rank Q/K projections.
## Forward-only calibration and search
This follow-up keeps the final-layer intervention at 19→23 and changes the
task to generating the latest value of a key. Some prompts contain two
conflicting records for that key. The fit, validation and test splits contain
12, 8 and 16 prompts, respectively. The test set adds longer lists. All
checkpoints and grid settings are selected using validation loss before test
replay. Each prompt's final-query scores, values, gate and residual are captured
from a single native forward. Substitutions replay only the final query of the
last layer and check the native replay against full-prefix activations.
The conditions cover direct sharing, a closed-form linear layer over the donor
heads, a linear layer with a small current-layer Q/K branch, a two-coefficient
diagonal grid, and two forward-only optimizers. The latter each start at
direct sharing and run three fixed seeds. One proposes additive Gaussian
perturbations and keeps improvements. The other proposes a bounded update
from a two-sided directional estimate and applies the same acceptance rule.
These methods fit only the small adapter. The backbone is frozen, and there
is no autograd. Search traces expose forward-call budgets and selected steps.
From the confirmed remote workspace containing the code and retained weights:
```sh
OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 venv/bin/python -B -m crossqkv.forward_search capture \
--source runs/cpu-qwen35-2b --out runs/NEW_SEARCH_CACHE
OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 venv/bin/python -B -m crossqkv.forward_search_fit \
--source runs/cpu-qwen35-2b --cache runs/NEW_SEARCH_CACHE --out runs/NEW_SEARCH_EVAL
```
The main optimization metric is nine-digit NLL. Evaluation also reports
full-vocabulary greedy exact digit at the first answer token, and strata by
list length and duplicate key. Each perturbation reuses fixed lower-layer
activations, so its forward objective computes the exact affected final query
without repeatedly forwarding the whole backbone. For interrupted captures,
`--resume` checks source and code fingerprints and keeps finished batches.
This is a single-site
comparison, not an evaluation of full-model fine-tuning or measured speedup.
## LiSA with the published trainable modules and loss
`lisa_train.py` implements the two-layer 256-unit ReLU head fusion and
learned low-rank grouped Q/K branch. The objective is the published
0.25 Huber (delta 1) attention-score distillation plus 0.75 next-token
full-vocabulary cross-entropy. The loss and gradient stream the frozen
vocabulary head in chunks. This avoids allocating the whole embedding
matrix or retaining dense vocabulary logits across backward.
The Qwen-specific run shares scores from layer 19 at layer 23, using
zero-based numbering. The recipient's V, output gate, projection, MLP
and final norm are preserved and frozen. The low-rank branch uses
40 coordinates per head and Qwen text-mode partial RoPE. Earlier layers
are frozen, and only the final layer is replaced, so training on cached
recipient inputs evaluates the same next-token objective as rerunning
the frozen prefix. The teacher path computes native scores and checks
final hidden states against the original model. The comparison includes
native, direct sharing, and the previous joint linear mapping.
The dataset is the fixed 36-prompt retrieval study with each gold digit
appended as a next-token target. Training uses every valid shifted token
of the fit sequences, and early model selection uses the validation
objective before the test set. The evaluation also measures exact greedy
digit at the answer position. This is a single-recipient port of the method.
The paper's LLaMA configurations, RedPajama training budget, and 13-task
results are separate experimental conditions.
```sh
OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 venv/bin/python -B -m crossqkv.lisa_reproduction capture \
--source runs/cpu-qwen35-2b --out runs/NEW_LISA_FULL_CACHE
OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 venv/bin/python -B -m crossqkv.lisa_reproduction train \
--source runs/cpu-qwen35-2b --cache runs/NEW_LISA_FULL_CACHE --out runs/NEW_LISA_FULL_RESULT \
--linear-control results/lisa-forward-search/frozen.json
```
References: [paper §5 and Appendix C](https://arxiv.org/html/2408.01890v2) and
[authors' implementation](https://github.com/takagi97/lisa). The official
code names its distillation weight `mse_loss_weight` but computes Huber,
consistent with the paper.
+119
View File
@@ -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()
+249
View File
@@ -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()
+122
View File
@@ -0,0 +1,122 @@
"""Evaluate all predeclared models on fresh counterfactual pairs."""
import argparse
import json
from pathlib import Path
from time import monotonic
import numpy as np
import torch
from tokenizers import Tokenizer
from crossqkv.lisa_combination_screen import ADAPTER_SHA, SITES
from crossqkv.lisa_full_answer import evaluate, fingerprint
from crossqkv.lisa_full_answer_verify import verify
from crossqkv.lisa_rank_compare import make_adapters
from functional.model import StreamingLM
from functional.run import write_json
def changed_answers(questions, comparisons, local_uniform):
"""Identify net gains that hide different sets of corrected and lost answers."""
ids = np.array([item['id'] for item in questions]).reshape(local_uniform.shape)
pairwise = {}
for name, delta in comparisons.items():
if name != 'rank-interaction':
pairwise[name] = {'corrected': ids[delta > 0].tolist(),
'lost': ids[delta < 0].tolist()}
versus_share = comparisons['rank-vs-uniform']
versus_allocation = comparisons['rank-vs-local']
both = {}
for name, sign in [('corrected_against_both', 1), ('lost_against_both', -1)]:
mask = (versus_share == sign) & (versus_allocation == sign)
both[name] = [{'id': item_id, 'local_uniform_correct': bool(correct)}
for item_id, correct in zip(ids[mask].tolist(), local_uniform[mask])]
return {'pairwise': pairwise, 'rank_combination': both}
def main():
parser = argparse.ArgumentParser(description=__doc__)
for name in ('source','prior','out'):
parser.add_argument('--'+name, type=Path, required=True)
args = parser.parse_args()
torch.set_num_threads(1)
path = args.out/'protocol.json'
if fingerprint(path) != '6858dbc64db0b989e8112e9dbea70662a2a05f66f11b180e8f2c668c74c43aef':
raise ValueError('Frozen protocol mismatch')
questions = json.loads(path.read_text())['splits']['test']
prior_protocol = json.loads((args.prior/'frozen.json').read_text())['protocol']
config = json.loads((args.source/'model_config.json').read_text())
tok = Tokenizer.from_file(str(args.source/'tokenizer.json'))
out = args.out/'holdout'
out.mkdir(exist_ok=True)
scores = {}
generation = {}
for arm in ('native','direct','prior-lisa','trajectory-student','trajectory-reference',
'shared-uniform','shared-allocated','shared-reversed','local-uniform','local-allocated'):
model = StreamingLM(args.source/'weights', config, seconds=172800,process_swap_limit_kib=None)
sites = () if arm=='native' else SITES
adapters = None
if arm not in ('native','direct'):
ranks = dict.fromkeys(SITES,40)
shared = True
if arm=='prior-lisa':
weights = args.prior/'final/lisa.pt'
if fingerprint(weights) != ADAPTER_SHA:
raise ValueError('Incorrect starting checkpoint')
elif arm.startswith('trajectory-'):
weights = args.out/arm/'adapter.pt'
else:
spec = json.loads((args.out/arm/'config.json').read_text())
ranks = {int(k):v for k,v in spec['ranks'].items()}
shared = spec['shared']
weights = args.out/arm/'lisa.pt'
adapters = make_adapters(model.config,ranks,shared)
torch.nn.ModuleDict({str(i):v for i,v in adapters.items()}).load_state_dict(
torch.load(weights,weights_only=True,map_location='cpu'))
digest = fingerprint(weights)
else:
digest = prior_protocol['weights']['manifest.json']
lock = out/(arm+'-source.json')
if lock.exists() and json.loads(lock.read_text()) != digest:
raise ValueError('Cannot resume with changed weights')
write_json(lock,digest)
path = out/(arm+'.json')
rows = json.loads(path.read_text()) if path.exists() else []
if rows:
verify(tok,prior_protocol,questions,rows,(arm,),allow_prefix=True)
for start in range(len(rows),len(questions),2):
batch = questions[start:start+2]
before = monotonic()
generated = evaluate(model,tok,batch,{arm:sites},adapters)
seconds = monotonic() - before
verify(tok,prior_protocol,batch,generated,(arm,))
generated[0]['batch_seconds'] = seconds
rows.extend(generated)
write_json(path,rows)
print(arm,len(rows),'/',len(questions),flush=True)
scores[arm] = np.array([x['arms'][arm]['correct'] for x in rows],dtype=int).reshape(-1,2)
generation[arm] = {'generated_tokens':sum(len(row['arms'][arm]['tokens']) for row in rows),
'seconds':sum(row['batch_seconds'] for row in rows[::2])}
comparisons = {'rank-vs-uniform':scores['shared-allocated']-scores['shared-uniform'],
'rank-vs-reversed':scores['shared-allocated']-scores['shared-reversed'],
'rank-vs-local':scores['shared-allocated']-scores['local-allocated'],
'rank-interaction':scores['shared-allocated']-scores['shared-uniform']
-scores['local-allocated']+scores['local-uniform'],
'student-vs-prior':scores['trajectory-student']-scores['prior-lisa'],
'student-vs-reference':scores['trajectory-student']-scores['trajectory-reference']}
rng = np.random.default_rng(72505)
sample = rng.integers(0,len(questions)//2,size=(10000,len(questions)//2))
audit = {'questions':len(questions),
'generation':generation,
'changed_answers':changed_answers(questions,comparisons,scores['local-uniform']),
'correct':{k:int(v.sum()) for k,v in scores.items()},
'pairs_both_correct':{k:int(v.all(1).sum()) for k,v in scores.items()},
'paired_differences':{k:{'delta':float(v.mean()),
'interval_95':np.quantile(v.mean(1)[sample].mean(1),[.025,.975]).tolist()}
for k,v in comparisons.items()}}
write_json(out/'audit.json',audit)
if __name__=='__main__':
main()
+90
View File
@@ -0,0 +1,90 @@
"""Freeze paired lookup questions and restore individual native attention layers."""
import argparse
import hashlib
import json
import random
from pathlib import Path
import torch
from tokenizers import Tokenizer
from crossqkv.lisa_effect_screen import WORDS
from crossqkv.lisa_full_answer import evaluate
from crossqkv.lisa_train import LearnableSharingAttention
from functional.model import StreamingLM
from functional.run import write_json
SITES = (15, 19, 23)
ADAPTER_SHA = 'c82db5af7fa42cf58a349f3e53961da2360b211a7ed606f53a728860c64f6f29'
def paired_questions(split, pairs, seed):
rng = random.Random(seed)
rows = []
for i in range(pairs):
keys = rng.sample(WORDS, 12)
values = rng.sample(range(20, 100), 12)
target, foil = rng.sample(range(12), 2)
for variant in range(2):
records = ', '.join(f'{k}={v}' for k, v in zip(keys, values))
rows.append({'id': f'{split}-{i:03}-{variant}', 'task': 'lookup',
'question': f'Records in time order: {records}.\nWhat is the recorded number for {keys[target]}?',
'answer': values[target]})
values[target], values[foil] = values[foil], values[target]
return rows
def main():
p = argparse.ArgumentParser(description=__doc__)
for name in ('source', 'prior', 'out'):
p.add_argument('--'+name, type=Path, required=True)
args = p.parse_args()
args.out.mkdir(exist_ok=True, parents=True)
previous = json.loads((args.prior/'frozen.json').read_text())
splits = {s: paired_questions(s, n, seed) for s, n, seed in (
('diagnostic', 8, 72501), ('validation', 8, 72502), ('test', 32, 72503))}
seen = {r['question'] for rows in previous['problems'].values() for r in rows}
for rows in splits.values():
for row in rows:
if row['question'] in seen:
raise ValueError('Repeated question')
seen.add(row['question'])
spec = {'splits': splits, 'base_adapter': ADAPTER_SHA, 'sites': SITES,
'rank_budget': [32, 40, 48], 'uniform_rank': 40, 'cap': 24,
'rank_selection': 'Order layers by increase in complete-answer correct count upon single restoration; ties by ascending layer index, earlier gets higher rank.',
'primary_metric': 'complete answer accuracy; paired uncertainty resamples counterfactual pairs',
'secondary_metric': 'both members of pair correct'}
spec_path = args.out/'protocol.json'
if spec_path.exists() and json.loads(spec_path.read_text()) != json.loads(json.dumps(spec)):
raise ValueError('Protocol changed')
write_json(spec_path, spec)
weight_path = args.prior/'final/lisa.pt'
if hashlib.sha256(weight_path.read_bytes()).hexdigest() != ADAPTER_SHA:
raise ValueError('Prior adapter mismatch')
torch.set_num_threads(1)
c = json.loads((args.source/'model_config.json').read_text())
model = StreamingLM(args.source/'weights', c, seconds=172800, process_swap_limit_kib=None)
c = model.config
tok = Tokenizer.from_file(str(args.source/'tokenizer.json'))
adapters = torch.nn.ModuleDict({str(i): LearnableSharingAttention(c['hidden_size'],
c['num_attention_heads'], c['num_key_value_heads'], 40, c['rope_parameters']['rope_theta'],
c['rope_parameters']['partial_rotary_factor'], bias=c.get('attention_bias', False)) for i in SITES})
adapters.load_state_dict(torch.load(weight_path, weights_only=True, map_location='cpu'))
for restored in (None, *SITES):
active = tuple(i for i in SITES if i != restored)
label = 'baseline' if restored is None else f'restore-{restored}'
path = args.out/(label+'.json')
rows = json.loads(path.read_text()) if path.exists() else []
questions = splits['diagnostic']
if [r['id'] for r in rows] != [q['id'] for q in questions[:len(rows)]]:
raise ValueError('Diagnostic prefix mismatch')
for start in range(len(rows), len(questions), 2):
rows.extend(evaluate(model, tok, questions[start:start+2], {label: active},
{i: adapters[str(i)] for i in active}))
write_json(path, rows)
print(label, len(rows), flush=True)
if __name__ == '__main__':
main()
+101
View File
@@ -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
+130
View File
@@ -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()
+296
View File
@@ -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()
+115
View File
@@ -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()
+157
View File
@@ -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()
+183
View File
@@ -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()
+221
View File
@@ -0,0 +1,221 @@
"""Freeze numeric tasks and screen the effect of sharing on complete answers."""
import argparse
from hashlib import sha256
import json
from pathlib import Path
import random
import re
import torch
from tokenizers import Tokenizer
from crossqkv.lisa_effect_screen import WORDS
from crossqkv.lisa_generate import GenerationDecoder, generate
from crossqkv.lisa_tail import TorchTail
from functional.model import StreamingLM
from functional.run import write_json
TASKS = ('lookup', 'latest', 'addition', 'count')
SEEDS = {'screen': 621001, 'fit': 621002, 'validation': 621003, 'test': 621004}
COUNTS = {'screen': 8, 'fit': 24, 'validation': 8, 'test': 32}
SCHEDULES = {'native': (), 'direct_3': (15, 19, 23),
'direct_4': (11, 15, 19, 23), 'direct_5': (7, 11, 15, 19, 23)}
STOP_TEXT = ('<|im_end|>', '<|endoftext|>')
MAX_NEW_TOKENS = 24
def fixed_problems():
output = {}
for split, seed in SEEDS.items():
rng = random.Random(seed)
rows = []
for task in TASKS:
for i in range(COUNTS[split]):
if task in ('lookup', 'latest'):
keys = rng.sample(WORDS, 12)
values = rng.sample(range(20, 100), 12)
pos = rng.randrange(len(keys))
key = keys[pos]
if task == 'latest':
later = rng.randrange(1, len(keys))
earlier = rng.randrange(later)
keys[earlier] = keys[later]
pos, key = later, keys[later]
schedule = ', '.join(f'{k}={v}' for k, v in zip(keys, values))
descriptor = 'last recorded' if task == 'latest' else 'recorded'
question = f'Records in time order: {schedule}.\nWhat is the {descriptor} number for {key}?'
answer = values[pos]
elif task == 'addition':
a, b = sorted((rng.randint(20, 89), rng.randint(20, 89)))
question = f'What is {a} plus {b}?'
answer = a + b
else:
first, second = rng.sample(WORDS, 2)
answer = rng.randint(10, 15)
values = [first] * answer + [second] * rng.randint(3, 9)
rng.shuffle(values)
question = f"Items: {', '.join(values)}.\nHow many items are exactly '{first}'?"
rows.append({'id': f'{split}-{task}-{i:03}', 'task': task,
'question': question, 'answer': answer})
output[split] = rows
# Arithmetic questions can repeat across independently seeded splits.
# Keep the first generated occurrence and fill duplicates with new disjoint sums.
used = set()
replacement = random.Random(621005)
for rows in output.values():
for row in rows:
while row['task'] == 'addition' and row['question'] in used:
a, b = sorted((replacement.randint(20, 89), replacement.randint(20, 89)))
row.update(question=f'What is {a} plus {b}?', answer=a+b)
if row['question'] in used:
raise ValueError('Prompt repeated across the frozen set')
used.add(row['question'])
return output
def prompt(question):
return ('<|im_start|>user\n' + question + '\nReply with the integer and no other text.'
'<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n')
def final_integer(text):
# Only completed reasoning prefixes precede an answer.
text = re.sub(r'\A\s*(?:<think>.*?</think>\s*)+', '', text, flags=re.S).strip()
if '<think>' in text or '</think>' in text:
return None
match = re.fullmatch(r'(?:[Ff]inal answer:\s*|[Aa]nswer:\s*)?([+-]?\d+)\.?', text)
if not match:
match = re.search(r'(?:^|\n)\s*(?:[Ff]inal answer|[Aa]nswer):\s*([+-]?\d+)\.?\s*\Z', text)
return int(match[1]) if match else None
def grade(tokenizer, tokens, stop, expected):
whole = tokenizer.decode(tokens, skip_special_tokens=False)
body = tokenizer.decode(tokens[:-1] if stop == 'eos' else tokens,
skip_special_tokens=False)
value = final_integer(body) if stop == 'eos' else None
return {'tokens': tokens, 'response': whole, 'stop': stop, 'answer': value,
'correct': value == expected}
def evaluate(model, tokenizer, examples, arms, adapters=None):
stop_ids = {tokenizer.token_to_id(text) for text in STOP_TEXT}
if None in stop_ids or len(stop_ids) != len(STOP_TEXT):
raise ValueError('Unexpected tokenizer stop tokens')
ids = [tokenizer.encode(prompt(x['question']), add_special_tokens=False).ids for x in examples]
expanded = [x for x in ids for _ in arms]
schedules = list(arms.values()) * len(examples)
predictions = iter(generate(model, expanded, schedules, stop_ids, MAX_NEW_TOKENS, adapters))
return [{'id': x['id'], 'task': x['task'], 'gold': x['answer'],
'arms': {mode: grade(tokenizer, *next(predictions), x['answer']) for mode in arms}}
for x in examples]
def summarize(rows):
results = {}
for task in TASKS:
group = [row for row in rows if row['task'] == task]
results[task] = {}
for name in SCHEDULES:
original_correct = lambda row: row['arms']['native']['correct']
produced_wrong = lambda row: row['arms'][name]['answer'] is not None and not row['arms'][name]['correct']
results[task][name] = {
'n': len(group),
'correct': sum(row['arms'][name]['correct'] for row in group),
'unscored': sum(row['arms'][name]['answer'] is None for row in group),
'native_correct_to_wrong_integer': [
row['id'] for row in group if original_correct(row) and produced_wrong(row)],
}
return results
def choose(summary):
options = []
for task, arms in summary.items():
if arms['native']['correct'] >= 6:
for arm in ('direct_3', 'direct_4', 'direct_5'):
losses = arms[arm]['native_correct_to_wrong_integer']
if len(losses) >= 2:
options.append((len(losses), arms['native']['correct'],
len(SCHEDULES[arm]), task, arm))
if not options:
return None
_, _, _, task, arm = max(options)
return {'task': task, 'arm': arm, 'recipients': list(SCHEDULES[arm])}
def fingerprint(path):
return sha256(path.read_bytes()).hexdigest()
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('--seconds', default=21600, type=int)
parser.add_argument('--batch-prompts', default=2, type=int, choices=(1, 2))
parser.add_argument('--execution-batch-prompts', type=int, choices=(1, 2),
help='Use a different execution batch on resume after replaying completed rows')
parser.add_argument('--preflight', action='store_true')
args = parser.parse_args()
torch.set_num_threads(1)
args.out.mkdir(exist_ok=True)
files = {name: fingerprint(args.source/name) for name in
('manifest.json', 'model_config.json', 'tokenizer.json')}
protocol = {'weights': files, 'schedules': SCHEDULES, 'cap': MAX_NEW_TOKENS,
'stops': STOP_TEXT, 'batch_prompts': args.batch_prompts,
'decode': 'full vocabulary greedy, closed thinking prefix'}
manifest = args.out/'frozen.json'
frozen = {'protocol': protocol, 'problems': fixed_problems()}
frozen = json.loads(json.dumps(frozen))
if manifest.exists() and json.loads(manifest.read_text()) != frozen:
raise ValueError('Frozen protocol or prompts changed')
write_json(manifest, frozen)
model = StreamingLM(args.source/'weights', json.loads((args.source/'model_config.json').read_text()),
seconds=args.seconds, process_swap_limit_kib=None)
tokenizer = Tokenizer.from_file(str(args.source/'tokenizer.json'))
examples = frozen['problems']['screen']
if args.preflight:
ids = torch.tensor([tokenizer.encode(prompt(examples[0]['question']),
add_special_tokens=False).ids])
hidden = torch.from_numpy(model.embedding(ids.numpy()))
with torch.no_grad():
expected, _ = TorchTail(model, 0)(hidden, None, torch.tensor([ids.shape[1]]),
'native', ())
decoder = GenerationDecoder(model, [()], [0])
decoder.advance(ids[:, :-2])
actual = decoder.advance(ids[:, -2:])
ref = expected[:, -2:]
torch.testing.assert_close(actual, ref, atol=8e-5, rtol=7e-5)
write_json(args.out/'preflight.json', {'prompt_id': examples[0]['id'],
'prompt_tokens': ids.shape[1], 'tail_hidden_max_abs': float((actual-ref).abs().max())})
return
path = args.out/'screen-rows.json'
rows = json.loads(path.read_text()) if path.exists() else []
if [r['id'] for r in rows] != [x['id'] for x in examples[:len(rows)]]:
raise ValueError('Existing screen results do not match frozen prompts')
batch = args.execution_batch_prompts or args.batch_prompts
if batch != args.batch_prompts:
if len(rows) < batch:
raise ValueError('The alternate batch requires enough already evaluated prompts for replay')
replay = evaluate(model, tokenizer, examples[:batch], SCHEDULES)
if replay != rows[:batch]:
raise ValueError('Alternate batch changed the first completed token streams')
write_json(args.out/'execution-batch-replay.json',
{'frozen_sha256': fingerprint(manifest), 'batch_prompts': batch,
'matched_rows': [row['id'] for row in replay]})
print('validated execution batch', batch, flush=True)
for start in range(len(rows), len(examples), batch):
rows.extend(evaluate(model, tokenizer, examples[start:start+batch], SCHEDULES))
write_json(path, rows)
print('screen complete', len(rows), '/', len(examples), flush=True)
summary = summarize(rows)
write_json(args.out/'screen-summary.json', summary)
write_json(args.out/'selection.json', {'frozen_sha256': fingerprint(manifest),
'screen_sha256': fingerprint(path),
'chosen': choose(summary)})
if __name__ == '__main__':
main()
+223
View File
@@ -0,0 +1,223 @@
"""Fit LiSA on a development-selected schedule, then evaluate fresh continuations."""
import argparse
import json
from pathlib import Path
import numpy as np
import torch
from tokenizers import Tokenizer
from crossqkv.lisa_effect_audit import paired
from crossqkv.lisa_full_answer import (SCHEDULES, STOP_TEXT, choose, evaluate, fingerprint,
prompt, summarize)
from crossqkv.lisa_tail import TorchTail, weight_chunks
from crossqkv.lisa_train import LearnableSharingAttention, huber_distillation, language_model_loss
from functional.model import PREFIX, StreamingLM
from functional.run import write_json
class FitCapture(TorchTail):
def norm(self, x, name, centered=True):
if name == f'layers.{self.sites[0]}.input_layernorm':
self.residual = x
return super().norm(x, name, centered)
def load_locked(source, screen):
fixed = screen/'frozen.json'
rows = screen/'screen-rows.json'
chosen = json.loads((screen/'selection.json').read_text())
if (chosen['frozen_sha256'] != fingerprint(fixed)
or chosen['screen_sha256'] != fingerprint(rows)):
raise ValueError('Locked screening hashes do not match')
manifest = json.loads(fixed.read_text())
screen_rows = json.loads(rows.read_text())
expected = [(x['id'], x['task'], x['answer']) for x in manifest['problems']['screen']]
if [(x['id'], x['task'], x['gold']) for x in screen_rows] != expected:
raise ValueError('Screening did not evaluate the frozen development set')
expected_selection = choose(summarize(screen_rows))
if expected_selection is None or chosen['chosen'] != expected_selection:
raise ValueError('Development screen did not produce a qualifying schedule')
for name, digest in manifest['protocol']['weights'].items():
if fingerprint(source/name) != digest:
raise ValueError(f'Model input {name} changed')
return chosen, manifest
def verified_fit_captures(source, fit):
"""Verify the frozen fit inputs and return their archives by question ID."""
captures = source/'fit-capture'
receipt = source/'verified-fit-capture.json'
if fingerprint(receipt) != '682bc035a5bed9f9245f589cacf3e9616300e8bf5e85d3743b1264a56360fa55':
raise ValueError('Capture receipt mismatch')
records = json.loads(receipt.read_text())['records']
if ([r['id'] for r in records] != [r['id'] for r in fit] or
sorted(x.name for x in captures.glob('*.npz')) != [r['file'] for r in records]):
raise ValueError('Unexpected capture set')
for row in records:
if fingerprint(captures/row['file']) != row['sha256']:
raise ValueError('Fit capture mismatch')
return {r['id']: captures/r['file'] for r in records}
@torch.no_grad()
def capture(model, tokenizer, fit_examples, directory):
directory.mkdir(exist_ok=True)
teacher = FitCapture(model, 0)
teacher.sites = model.sites
for i, row in enumerate(fit_examples):
path = directory/f'{i:03}.npz'
if path.exists():
continue
text = prompt(row['question'])
base = tokenizer.encode(text, add_special_tokens=False).ids
complete = tokenizer.encode(text + str(row['answer']) + STOP_TEXT[0],
add_special_tokens=False).ids
if complete[:len(base)] != base or len(complete) <= len(base):
raise ValueError('Answer did not tokenize as an extension of the frozen prompt')
ids = np.array([complete])
model.guard()
hidden = torch.from_numpy(model.embedding(ids))
_, side = teacher(hidden, None, torch.tensor([len(complete)]), 'native', ())
pending = path.with_suffix('.tmp.npz')
np.savez(pending, ids=ids, start=[len(base)], residual=teacher.residual.numpy(),
donor=side[model.sites[0]-4][0].numpy(),
teacher=np.stack([side[i][0].numpy() for i in model.sites]))
pending.replace(path)
print('fit capture', i+1, '/', len(fit_examples), flush=True)
def checkpoint(path, obj):
pending = path.with_suffix('.tmp')
torch.save(obj, pending)
pending.replace(path)
def train(model, tokenizer, out, split, epochs, rank, *, adapters=None, captures=None):
if adapters is None:
c = model.config
rope = c['rope_parameters']
adapters = {i: LearnableSharingAttention(c['hidden_size'], c['num_attention_heads'],
c['num_key_value_heads'], rank, rope['rope_theta'], rope['partial_rotary_factor'],
bias=c.get('attention_bias', False)) for i in model.sites}
tail = TorchTail(model, model.sites[0], adapters)
optim = torch.optim.AdamW(tail.parameters(), lr=.0003, weight_decay=.1)
last = out/'resume.pt'
selected = out/'lisa.pt'
state = {'epoch': 0, 'steps': [], 'trace': [], 'best_correct': -1}
if 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'])
embedding = model.tensors[PREFIX+'embed_tokens.weight']
def vocab():
start = 0
for w in weight_chunks(embedding, 0, embedding.shape[0], rows=1024):
yield start, w
start += len(w)
paths = sorted((captures or out/'fit-capture').glob('*.npz'))
for epoch in range(state['epoch'], epochs):
for path in paths[len(state['steps']):]:
with np.load(path, allow_pickle=False) as entry:
b = {key: torch.from_numpy(entry[key]) for key in entry.files}
lengths = torch.tensor([b['ids'].shape[1]])
optim.zero_grad(set_to_none=True)
h, side = tail(b['residual'], b['donor'], lengths, 'lisa', model.sites)
kd = torch.stack([huber_distillation(side[i][0], t, lengths)
for i, t in zip(model.sites, b['teacher'])]).mean()
ce = language_model_loss(h, b['ids'], lengths, vocab, completion_starts=b['start'])
loss = .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('Nonfinite LiSA gradient')
optim.step()
state['steps'].append({'capture': path.name, 'huber': float(kd.detach()),
'completion_ce': float(ce.detach())})
checkpoint(last, {**state, 'parameters': tail.adapters.state_dict(),
'optimizer': optim.state_dict()})
print('fit epoch', epoch+1, 'step', len(state['steps']), '/', len(paths), flush=True)
val = []
for start in range(0, len(split['validation']), 2):
val.extend(evaluate(model, tokenizer, split['validation'][start:start+2],
{'lisa': model.sites}, adapters))
correct = sum(x['arms']['lisa']['correct'] for x in val)
if correct > state['best_correct']:
state['best_correct'] = correct
state['best_epoch'] = epoch+1
state['best_parameters'] = {
name: param.detach().clone() for name, param in tail.adapters.state_dict().items()
}
state['trace'].append({'epoch': epoch+1, 'steps': state['steps'], 'validation': val})
state['steps'] = []
state['epoch'] = epoch+1
checkpoint(last, {**state, 'parameters': tail.adapters.state_dict(),
'optimizer': optim.state_dict()})
write_json(out/'trace.json', {'selected_epoch': state['best_epoch'], 'epochs': state['trace']})
checkpoint(selected, state['best_parameters'])
tail.adapters.load_state_dict(state['best_parameters'])
return adapters
def audit(rows):
correct = {name: np.array([r['arms'][name]['correct'] for r in rows])
for name in ('native', 'direct', 'lisa')}
bad_value = [r for r in rows if r['arms']['native']['correct']
and r['arms']['direct']['answer'] is not None and not r['arms']['direct']['correct']]
return {'n': len(rows), 'correct': {name: int(x.sum()) for name, x in correct.items()},
'substantive_loss_ids': [r['id'] for r in bad_value],
'substantive_rescued_ids': [r['id'] for r in bad_value if r['arms']['lisa']['correct']],
'unscored': {name: sum(r['arms'][name]['answer'] is None for r in rows) for name in correct},
**paired(correct['native'], correct['direct'], correct['lisa'])}
def main():
p = argparse.ArgumentParser(description=__doc__)
for path in ('source', 'screen', 'out'):
p.add_argument('--'+path, type=Path, required=True)
p.add_argument('--epochs', type=int, default=2)
args = p.parse_args()
if args.epochs < 1:
p.error('--epochs must be positive')
torch.set_num_threads(1)
torch.manual_seed(621011)
locked, manifest = load_locked(args.source, args.screen)
selection = locked['chosen']
sites = tuple(selection['recipients'])
if sites != SCHEDULES[selection['arm']]:
raise ValueError('Unexpected selected schedule')
spec = {'screen': locked, 'epochs': args.epochs, 'rank': 40, 'seed': 621011,
'objective': '0.25 teacher attention Huber + 0.75 full-vocabulary completion CE'}
args.out.mkdir(exist_ok=True)
run = args.out/'train-spec.json'
if run.exists() and json.loads(run.read_text()) != spec:
raise ValueError('Cannot resume with a different experiment definition')
write_json(run, spec)
tasks = {name: [r for r in rows if r['task'] == selection['task']]
for name, rows in manifest['problems'].items()}
model = StreamingLM(args.source/'weights', json.loads((args.source/'model_config.json').read_text()),
seconds=86400, process_swap_limit_kib=None)
model.sites = sites
tokenizer = Tokenizer.from_file(str(args.source/'tokenizer.json'))
capture(model, tokenizer, tasks['fit'], args.out/'fit-capture')
adapters = train(model, tokenizer, args.out, tasks, args.epochs, spec['rank'])
output = args.out/'test-items.json'
rows = json.loads(output.read_text()) if output.exists() else []
if [r['id'] for r in rows] != [x['id'] for x in tasks['test'][:len(rows)]]:
raise ValueError('Test continuation does not match the frozen rows')
for start in range(len(rows), len(tasks['test']), 2):
batch = tasks['test'][start:start+2]
base = evaluate(model, tokenizer, batch, {'native': (), 'direct': sites})
lisa = evaluate(model, tokenizer, batch, {'lisa': sites}, adapters)
for x, y in zip(base, lisa):
x['arms'].update(y['arms'])
rows.extend(base)
write_json(output, rows)
print('test complete', len(rows), '/', len(tasks['test']), flush=True)
write_json(args.out/'test-audit.json', audit(rows))
if __name__ == '__main__':
main()
+73
View File
@@ -0,0 +1,73 @@
"""Reconstruct complete-answer scores from the saved token streams."""
import argparse
import json
from pathlib import Path
from tokenizers import Tokenizer
from crossqkv.lisa_full_answer import SCHEDULES, fingerprint, grade
from crossqkv.lisa_full_answer_train import audit
from functional.run import write_json
def verify(tokenizer, protocol, expected, rows, arms, allow_prefix=False):
"""Validate each recorded model answer against its frozen prompt and token IDs."""
if not rows or len(rows) > len(expected) or (not allow_prefix and len(rows) != len(expected)):
raise ValueError('Unexpected number of evaluated items')
stop_ids = {tokenizer.token_to_id(text) for text in protocol['stops']}
if None in stop_ids:
raise ValueError('Missing stop token in the frozen tokenizer')
for item, row in zip(expected, rows):
if (row['id'], row['task'], row['gold']) != (item['id'], item['task'], item['answer']):
raise ValueError(f"Unexpected row for {item['id']}")
if set(row['arms']) != set(arms):
raise ValueError(f"Unexpected arms for {item['id']}")
for arm in arms:
stored = row['arms'][arm]
tokens = stored['tokens']
if (not 0 < len(tokens) <= protocol['cap']
or any(type(token) is not int or tokenizer.id_to_token(token) is None
for token in tokens)
or any(token in stop_ids for token in tokens[:-1])):
raise ValueError(f"Invalid generated token stream for {item['id']} / {arm}")
ended = tokens[-1] in stop_ids
if not ended and len(tokens) != protocol['cap']:
raise ValueError(f"Generation ended before a stop or the cap for {item['id']} / {arm}")
score = grade(tokenizer, tokens, 'eos' if ended else 'max_new_tokens', item['answer'])
if stored != score:
raise ValueError(f"Archived score does not match the tokens for {item['id']} / {arm}")
def main():
parser = argparse.ArgumentParser(description=__doc__)
for name in ('tokenizer', 'frozen', 'rows', 'out'):
parser.add_argument('--'+name, required=True, type=Path)
parser.add_argument('--selection', type=Path, help='Verify the selected task on the test split')
parser.add_argument('--allow-screen-prefix', action='store_true')
args = parser.parse_args()
if args.selection and args.allow_screen_prefix:
parser.error('Test verification requires all frozen test rows')
frozen = json.loads(args.frozen.read_bytes())
protocol = frozen['protocol']
if fingerprint(args.tokenizer) != protocol['weights']['tokenizer.json']:
raise ValueError('Tokenizer differs from the frozen experiment')
rows = json.loads(args.rows.read_bytes())
tokenizer = Tokenizer.from_file(str(args.tokenizer))
report = {'frozen_sha256': fingerprint(args.frozen), 'rows_sha256': fingerprint(args.rows),
'rows_verified': len(rows)}
if args.selection:
chosen = json.loads(args.selection.read_bytes())
if chosen['frozen_sha256'] != report['frozen_sha256']:
raise ValueError('Selection points to a different frozen manifest')
expected = [item for item in frozen['problems']['test']
if item['task'] == chosen['chosen']['task']]
verify(tokenizer, protocol, expected, rows, ('native', 'direct', 'lisa'))
report['final_answer_audit'] = audit(rows)
else:
verify(tokenizer, protocol, frozen['problems']['screen'], rows, SCHEDULES,
allow_prefix=args.allow_screen_prefix)
write_json(args.out, report)
if __name__ == '__main__':
main()
+131
View File
@@ -0,0 +1,131 @@
"""Cached autoregressive Qwen text generation for the LiSA comparisons."""
import math
import torch
from torch.nn import functional as F
from crossqkv.lisa_tail import TorchTail, rotate, weight_chunks
from functional.model import PREFIX
class GenerationDecoder(TorchTail):
"""Share the previous full-attention layer's actual scores per batch lane."""
def __init__(self, source, schedules, padding, adapters=None):
super().__init__(source, 0, adapters)
full = [i for i, kind in enumerate(self.c['layer_types']) if kind == 'full_attention']
if (len(schedules) != len(padding) or not schedules
or any(set(sites) - set(full[1:]) for sites in schedules)):
raise ValueError('Recipients need an earlier full-attention layer')
if self.adapters and any(tuple(sites) != tuple(map(int, self.adapters)) for sites in schedules):
raise ValueError('LiSA decoding requires one shared schedule for the batch')
self.padding = torch.tensor(padding)
self.share = {i: torch.tensor([i in sites for sites in schedules])[:, None, None, None]
for i in set().union(*schedules)}
self.position = 0
self.states = {}
def attention_chunk(self, h, layer, positions, allowed, donor):
heads, kv, dim = (self.c[k] for k in
('num_attention_heads', 'num_key_value_heads', 'head_dim'))
p = f'layers.{layer}.self_attn.'
adapter = self.adapters[str(layer)] if str(layer) in self.adapters else None
if adapter is None:
q, gate = self.linear(h, p+'q_proj').unflatten(-1, (heads, 2*dim)).chunk(2, -1)
k = self.linear(h, p+'k_proj').unflatten(-1, (kv, dim))
rope = self.c['rope_parameters']
q = rotate(self.norm(q, p+'q_norm'), rope['rope_theta'],
rope['partial_rotary_factor'], positions)
k = rotate(self.norm(k, p+'k_norm'), rope['rope_theta'],
rope['partial_rotary_factor'], positions)
else:
gate = self.gate_only(h, p)
q = adapter.rotate(adapter.q_proj(h).unflatten(-1, (heads, adapter.rank)), positions)
k = adapter.rotate(adapter.k_proj(h).unflatten(-1, (kv, adapter.rank)), positions)
v = self.linear(h, p+'v_proj').unflatten(-1, (kv, dim))
if layer in self.states:
prior_k, prior_v = self.states[layer]
k = torch.cat((prior_k, k), dim=1)
v = torch.cat((prior_v, v), dim=1)
self.states[layer] = k, v
repeats = heads // kv
scores = torch.einsum('bthd,bshd->bhts', q, k.repeat_interleave(repeats, 2))
scores = scores / math.sqrt(q.shape[-1])
if adapter is not None:
both = torch.cat((scores, donor), dim=1).permute(0, 2, 3, 1)
scores = adapter.fuse(both).permute(0, 3, 1, 2)
elif layer in self.share:
scores = torch.where(self.share[layer], donor, scores)
weights = scores.masked_fill(~allowed, -torch.inf).softmax(dim=-1)
context = torch.einsum('bhts,bshd->bthd', weights, v.repeat_interleave(repeats, 2))
return self.linear((context * gate.sigmoid()).flatten(-2), p+'o_proj'), scores
@torch.no_grad()
def advance(self, ids):
"""Consume a prompt or continuation and return the final-normalized states."""
stop = self.position + ids.shape[1]
queries = torch.arange(self.position, stop)
keys = torch.arange(stop)
positions = (queries[None, :] - self.padding[:, None]).clamp_min(0)
q_valid = queries[None, :] >= self.padding[:, None]
k_valid = keys[None, :] >= self.padding[:, None]
allowed = (queries[:, None] >= keys)[None, None] & (
k_valid[:, None, None, :] | ~q_valid[:, None, :, None])
h = torch.from_numpy(self.source.embedding(ids.numpy())) * q_valid[..., None]
donor = None
trim = getattr(self.source, 'malloc_trim', None)
for layer, kind in enumerate(self.c['layer_types']):
if hasattr(self.source, 'guard'):
self.source.guard()
p = f'layers.{layer}.'
n = self.norm(h, p+'input_layernorm')
if kind == 'full_attention':
out, donor = self.attention_chunk(n, layer, positions, allowed, donor)
else:
out, self.states[layer] = self.linear_attention_chunk(n, layer, self.states.get(layer))
h = h + out
n = self.norm(h, p+'post_attention_layernorm')
activation = F.silu(self.linear(n, p+'mlp.gate_proj')) * self.linear(n, p+'mlp.up_proj')
h = h + self.linear(activation, p+'mlp.down_proj')
del n, out, activation
if trim is not None:
trim(0)
self.position = stop
return self.norm(h, 'norm')
def greedy_tokens(hidden, embedding):
"""Take the argmax over the complete tied vocabulary in bounded blocks."""
peak = hidden.new_full((len(hidden),), -torch.inf)
ids = torch.zeros(len(hidden), dtype=torch.long)
start = 0
for weight in weight_chunks(embedding, 0, embedding.shape[0], rows=1024):
score, arg = F.linear(hidden, weight).max(dim=-1)
ids = torch.where(score > peak, arg + start, ids)
peak = torch.maximum(peak, score)
start += len(weight)
if not torch.isfinite(peak).all():
raise FloatingPointError('Non-finite next-token score')
return ids
@torch.no_grad()
def generate(source, prompts, schedules, stop_tokens, max_new_tokens, adapters=None):
width = max(map(len, prompts))
padding = [width - len(prompt) for prompt in prompts]
seed = torch.tensor([[0] * n + prompt for prompt, n in zip(prompts, padding)])
decoder = GenerationDecoder(source, schedules, padding, adapters)
head = source.tensors[PREFIX+'embed_tokens.weight']
state = decoder.advance(seed)[:, -1]
output = [[] for _ in prompts]
finished = [False] * len(prompts)
for step in range(max_new_tokens):
ids = greedy_tokens(state, head)
for row, token in enumerate(ids.tolist()):
if not finished[row]:
output[row].append(token)
finished[row] = token in stop_tokens
if all(finished) or step + 1 == max_new_tokens:
break
state = decoder.advance(ids[:, None])[:, -1]
return [(tokens, 'eos' if done else 'max_new_tokens') for tokens, done in zip(output, finished)]
+265
View File
@@ -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()
+153
View File
@@ -0,0 +1,153 @@
"""Compare diagnostic rank allocation and uniform ranks under matched training."""
import argparse
import json
from pathlib import Path
import torch
from tokenizers import Tokenizer
from crossqkv.lisa_combination_screen import ADAPTER_SHA, SITES
from crossqkv.lisa_effect_answer_audit import vocabulary_scores
from crossqkv.lisa_full_answer import STOP_TEXT, fingerprint, prompt
from crossqkv.lisa_full_answer_train import FitCapture, load_locked, train, verified_fit_captures
from crossqkv.lisa_tail import TorchTail
from crossqkv.lisa_train import LearnableSharingAttention
from functional.model import PREFIX, StreamingLM
from functional.run import write_json
def assignments(protocol, directory):
expected = [(q['id'], q['answer']) for q in protocol['splits']['diagnostic']]
scores = {}
for label in ('baseline', *(f'restore-{i}' for i in SITES)):
rows = json.loads((directory/(label+'.json')).read_text())
if [(r['id'], r['gold']) for r in rows] != expected:
raise ValueError(f'Incomplete diagnostic arm {label}')
scores[label] = sum(r['arms'][label]['correct'] for r in rows)
ordered = sorted(SITES, key=lambda i: (-scores[f'restore-{i}'], i))
selected = dict(zip(ordered, reversed(protocol['rank_budget'])))
reverse = dict(zip(ordered, protocol['rank_budget']))
return scores, {'allocated':selected, 'reversed':reverse, 'uniform':dict.fromkeys(SITES, 40)}
def local_scores_only(module, args):
local, donor = args[0].chunk(2, dim=-1)
return (torch.cat((local, torch.zeros_like(donor)), dim=-1),)
def make_adapters(config, ranks, shared):
rope = config['rope_parameters']
adapters = {i: LearnableSharingAttention(config['hidden_size'], config['num_attention_heads'],
config['num_key_value_heads'], ranks[i], rope['rope_theta'], rope['partial_rotary_factor'],
bias=config.get('attention_bias', False)) for i in SITES}
if not shared:
for adapter in adapters.values():
adapter.fuse.register_forward_pre_hook(local_scores_only)
return adapters
def score_gold_answers(outputs, sequences, starts, embedding):
gold = [ids[first:] for ids, first in zip(sequences, starts)]
targets = torch.tensor([token for answer in gold for token in answer])
sizes = [len(answer) for answer in gold]
vectors = torch.cat([out[i, first-1:len(ids)-1] for out in outputs.values()
for i, (ids, first) in enumerate(zip(sequences, starts))])
_, nll = vocabulary_scores(vectors, targets.repeat(len(outputs)), embedding)
if not torch.isfinite(nll).all():
raise FloatingPointError('Invalid full-vocabulary diagnostic score')
scores = [{} for _ in gold]
for label, values in zip(outputs, nll.split(len(targets))):
for row, part in zip(scores, values.split(sizes)):
row[label] = (-part).tolist()
return gold, scores
@torch.no_grad()
def diagnostic_log_probs(model, tok, weights, questions, path):
"""Teacher-force gold answers; all restorations share the same frozen stem."""
if fingerprint(weights) != ADAPTER_SHA:
raise ValueError('Unexpected diagnostic checkpoint')
adapters = make_adapters(model.config, dict.fromkeys(SITES, 40), True)
tail = TorchTail(model, SITES[0], adapters)
tail.adapters.load_state_dict(torch.load(weights, weights_only=True, map_location='cpu'))
native = FitCapture(model, 0)
native.sites = SITES
rows = json.loads(path.read_text()) if path.exists() else []
if [r['id'] for r in rows] != [q['id'] for q in questions[:len(rows)]]:
raise ValueError('Unexpected gold-score prefix')
for start in range(len(rows), len(questions), 2):
batch = questions[start:start+2]
sequences, starts = [], []
for item in batch:
text = prompt(item['question'])
base = tok.encode(text, add_special_tokens=False).ids
ids = tok.encode(text + str(item['answer']) + STOP_TEXT[0], add_special_tokens=False).ids
if ids[:len(base)] != base or len(ids) <= len(base):
raise ValueError('Gold answer is not an extension of its prompt')
sequences.append(ids)
starts.append(len(base))
lengths = torch.tensor([len(ids)-1 for ids in sequences])
width = int(lengths.max())
padded = torch.tensor([ids[:-1] + [0]*(width-len(ids)+1) for ids in sequences])
h = torch.from_numpy(model.embedding(padded.numpy()))
original, maps = native(h, None, lengths, 'native', ())
outputs = {'native':original}
for restored in (None, *SITES):
sites = tuple(i for i in SITES if i != restored)
label = 'baseline' if restored is None else f'restore-{restored}'
outputs[label], _ = tail(native.residual, maps[SITES[0]-4][0], lengths, 'lisa', sites)
gold_tokens, log_probs = score_gold_answers(outputs, sequences, starts,
model.tensors[PREFIX+'embed_tokens.weight'])
results = [{'id': item['id'], 'gold': item['answer'], 'tokens': gold, 'log_probs': scores}
for item, gold, scores in zip(batch, gold_tokens, log_probs)]
rows.extend(results)
write_json(path, rows)
print('diagnostic gold sequence', len(rows), '/', len(questions), flush=True)
def main():
p = argparse.ArgumentParser(description=__doc__)
for name in ('source','prior','out'):
p.add_argument('--'+name, type=Path, required=True)
args = p.parse_args()
torch.set_num_threads(1)
protocol_file = args.out/'protocol.json'
if fingerprint(protocol_file) != '6858dbc64db0b989e8112e9dbea70662a2a05f66f11b180e8f2c668c74c43aef':
raise ValueError('Protocol mismatch')
protocol = json.loads(protocol_file.read_text())
scores, ranks = assignments(protocol,args.out)
_, prior = load_locked(args.source,args.prior)
source = args.prior/'final'
captures = source/'fit-capture'
fit = [r for r in prior['problems']['fit'] if r['task']=='lookup']
verified_fit_captures(source, fit)
config = json.loads((args.source/'model_config.json').read_text())
tok = Tokenizer.from_file(str(args.source/'tokenizer.json'))
diagnostic_model = StreamingLM(args.source/'weights', config, seconds=172800, process_swap_limit_kib=None)
diagnostic_log_probs(diagnostic_model, tok, source/'lisa.pt', protocol['splits']['diagnostic'],
args.out/'diagnostic-gold-log-probs.json')
del diagnostic_model
arms = [('allocated',True),('uniform',True),('reversed',True),
('uniform',False),('allocated',False)]
for allocation, shared in arms:
label = ('shared-' if shared else 'local-')+allocation
out = args.out/label
out.mkdir(exist_ok=True)
torch.manual_seed(621011)
model = StreamingLM(args.source/'weights',config,seconds=172800,process_swap_limit_kib=None)
model.sites = SITES
adapters = make_adapters(model.config, ranks[allocation], shared)
count = sum(p.numel() for adapter in adapters.values() for p in adapter.parameters())
spec = {'diagnostic_correct':scores,'ranks':{str(k):v for k,v in ranks[allocation].items()},
'shared':shared,'parameters':count,'seed':621011,'epochs':2}
path = out/'config.json'
if count != 2476032 or (path.exists() and json.loads(path.read_text()) != spec):
raise ValueError('Unmatched rank budget or run configuration')
write_json(path,spec)
if not (out/'lisa.pt').exists():
train(model,tok,out,protocol['splits'],2,40,adapters=adapters,captures=captures)
print(label,'finished',flush=True)
if __name__=='__main__':
main()
+200
View File
@@ -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()
+190
View File
@@ -0,0 +1,190 @@
"""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, positions=None):
d = int(x.shape[-1] * fraction)
inv = theta ** (-torch.arange(0, d, 2, dtype=x.dtype, device=x.device) / d)
if positions is None:
positions = torch.arange(x.shape[1], dtype=x.dtype, device=x.device)[None, :]
phase = positions[..., None] * inv
angle = torch.cat((phase, phase), dim=-1).unsqueeze(-2)
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_chunk(q, k, v, g, beta, state=None):
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()
if state is None:
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), state
def gated_delta(q, k, v, g, beta):
return gated_delta_chunk(q, k, v, g, beta)[0]
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):
return self.linear_attention_chunk(x, layer)[0]
def linear_attention_chunk(self, x, layer, previous=None):
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')
history = kernel.shape[-1] - 1
if previous is None:
projected = F.pad(projected, (history, 0))
state = None
else:
prefix, state = previous
projected = torch.cat((prefix, projected), dim=-1)
convolved = F.conv1d(projected, kernel, groups=projected.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, state = gated_delta_chunk(q, k, v, g, beta, state)
output = self.linear((self.norm(out, p+'norm', centered=False)*F.silu(gate)).flatten(-2),
p+'out_proj')
return output, (projected[..., projected.shape[-1]-history:].clone(), state)
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
+126
View File
@@ -0,0 +1,126 @@
"""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,
completion_starts=None):
"""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]
if completion_starts is not None:
valid = valid & (positions[None, :] + 1 >= completion_starts[:, 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)
+183
View File
@@ -0,0 +1,183 @@
"""Distill next-token distributions along LiSA's current greedy trajectories."""
import argparse
import json
from pathlib import Path
import numpy as np
import torch
from tokenizers import Tokenizer
from crossqkv.lisa_combination_screen import ADAPTER_SHA, SITES
from crossqkv.lisa_full_answer import STOP_TEXT, evaluate, fingerprint, prompt
from crossqkv.lisa_full_answer_train import FitCapture, checkpoint, load_locked, verified_fit_captures
from crossqkv.lisa_full_answer_verify import verify
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 reverse_kl(student, teacher, chunks):
"""Exact reverse KL and its first derivative for a streamed, frozen head."""
with torch.no_grad():
# Both models use the same frozen output weights. Read each block once
# for the two projections, then revisit it only for the student gradient.
student_logits = []
teacher_logits = []
for w in chunks():
student_logits.append(student @ w.T)
teacher_logits.append(teacher @ w.T)
logp = torch.cat(student_logits, dim=-1).log_softmax(-1)
del student_logits
logq = torch.cat(teacher_logits, dim=-1).log_softmax(-1)
del teacher_logits
diff = logp - logq
prob = logp.exp()
kl = (prob * diff).sum(-1, keepdim=True)
dlogits = prob * (diff - kl) / len(student)
grad = torch.zeros_like(student)
start = 0
for w in chunks():
grad.addmm_(dlogits[:, start:start+len(w)], w)
start += len(w)
return kl.mean() + ((student - student.detach()) * grad).sum()
@torch.no_grad()
def full_teacher_inputs(model, teacher, ids, lengths):
hidden = torch.from_numpy(model.embedding(ids.numpy()))
target, maps = teacher(hidden, None, lengths, 'native', ())
return target, teacher.residual, maps[SITES[0]-4][0]
@torch.no_grad()
def replay_teacher_inputs(tail, path, ids, start, lengths):
with np.load(path, allow_pickle=False) as saved:
if int(saved['start'].item()) != start or not np.array_equal(saved['ids'], ids.numpy()):
raise ValueError('Cached sequence does not match this gold answer and prompt')
residual = torch.from_numpy(saved['residual'])
donor = torch.from_numpy(saved['donor'])
target, _ = tail(residual, donor, lengths, 'native', ())
return target, residual, donor
def validate_checkpoint(model, tokenizer, adapters, questions, decode_spec, path):
label = path.stem
rows = json.loads(path.read_text()) if path.exists() else []
if rows:
verify(tokenizer, decode_spec, questions, rows, (label,), allow_prefix=True)
for start in range(len(rows), len(questions), 2):
batch = questions[start:start+2]
outputs = evaluate(model, tokenizer, batch, {label: SITES}, adapters)
verify(tokenizer, decode_spec, batch, outputs, (label,))
rows.extend(outputs)
write_json(path, rows)
correct = sum(row['arms'][label]['correct'] for row in rows)
print(label, 'validation correct', correct, '/', len(rows), flush=True)
def main():
p = argparse.ArgumentParser(description=__doc__)
for name in ('source', 'prior', 'out'):
p.add_argument('--'+name, required=True, type=Path)
p.add_argument('--prefix', choices=('student', 'reference'), required=True)
args = p.parse_args()
torch.set_num_threads(1)
torch.manual_seed(72504)
_, prior = load_locked(args.source, args.prior)
tasks = [x for x in prior['problems']['fit'] if x['task']=='lookup']
protocol = args.out/'protocol.json'
if fingerprint(protocol) != '6858dbc64db0b989e8112e9dbea70662a2a05f66f11b180e8f2c668c74c43aef':
raise ValueError('Unknown combination study protocol')
validation = json.loads(protocol.read_text())['splits']['validation']
old = args.prior/'final/lisa.pt'
if fingerprint(old) != ADAPTER_SHA:
raise ValueError('Unknown baseline checkpoint')
directory = args.out/('trajectory-'+args.prefix)
directory.mkdir(exist_ok=True)
config = json.loads((args.source/'model_config.json').read_text())
model = StreamingLM(args.source/'weights', config, seconds=172800, process_swap_limit_kib=None)
c = model.config
rope = c['rope_parameters']
adapters = {i: LearnableSharingAttention(c['hidden_size'], c['num_attention_heads'],
c['num_key_value_heads'], 40, rope['rope_theta'], rope['partial_rotary_factor'],
bias=c.get('attention_bias', False)) for i in SITES}
tail = TorchTail(model, SITES[0], adapters)
tail.adapters.load_state_dict(torch.load(old, weights_only=True))
teacher = FitCapture(model, 0)
teacher.sites = SITES
opt = torch.optim.AdamW(tail.parameters(), lr=0.0001, weight_decay=0.1)
tok = Tokenizer.from_file(str(args.source/'tokenizer.json'))
if args.prefix == 'student':
validate_checkpoint(model, tok, adapters, validation, prior['protocol'],
args.out/'validation-prior-lisa.json')
statefile = directory/'resume.pt'
rows = []
if statefile.exists():
state = torch.load(statefile, weights_only=True)
rows = state['rows']
tail.adapters.load_state_dict(state['weights'])
opt.load_state_dict(state['optimizer'])
if [r['id'] for r in rows] != [x['id'] for x in tasks[:len(rows)]]:
raise ValueError('Training prefix mismatch')
embedding = model.tensors[PREFIX+'embed_tokens.weight']
def chunks():
yield from weight_chunks(embedding, 0, embedding.shape[0], rows=1024)
captures = {}
final = args.prior/'final'
if args.prefix == 'reference' and (final/'verified-fit-capture.json').is_file():
try:
captures = verified_fit_captures(final, tasks)
except (OSError, ValueError, KeyError) as exc:
print('Using full native forward for reference prefixes:', exc, flush=True)
for offset, item in enumerate(tasks[len(rows):]):
text = prompt(item['question'])
base = tok.encode(text, add_special_tokens=False).ids
if args.prefix == 'student':
rollout = evaluate(model, tok, [item], {'student': SITES}, adapters)[0]['arms']['student']
sampled = rollout['tokens']
else:
complete = tok.encode(text+str(item['answer'])+STOP_TEXT[0], add_special_tokens=False).ids
assert complete[:len(base)] == base
sampled = complete[len(base):]
ids = torch.tensor([base+sampled])
lengths = torch.tensor([ids.shape[1]])
if captures:
try:
cached = replay_teacher_inputs(tail, captures[item['id']], ids, len(base), lengths)
except (OSError, ValueError, KeyError) as exc:
print('Using full native forward for reference prefixes:', exc, flush=True)
captures = {}
if not captures or offset == 0:
inputs = full_teacher_inputs(model, teacher, ids, lengths)
if captures:
if all(torch.equal(a, b) for a, b in zip(inputs, cached)):
print('Reference cache matches full native target, residual and donor', flush=True)
else:
print('Reference cache differs. Using full native forward', flush=True)
captures = {}
else:
inputs = cached
target, residual, donor = inputs
opt.zero_grad(set_to_none=True)
student, _ = tail(residual, donor, lengths, 'lisa', SITES)
span = slice(len(base)-1, -1)
loss = reverse_kl(student[0, span], target[0, span], chunks)
loss.backward()
if not torch.isfinite(loss) or any(p.grad is None or not torch.isfinite(p.grad).all() for p in tail.parameters()):
raise FloatingPointError('Invalid reverse KL update')
opt.step()
rows.append({'id': item['id'], 'tokens': sampled, 'reverse_kl':float(loss.detach())})
checkpoint(statefile, {'rows':rows,'weights':tail.adapters.state_dict(),'optimizer':opt.state_dict()})
print(args.prefix, len(rows), '/', len(tasks), flush=True)
checkpoint(directory/'adapter.pt', tail.adapters.state_dict())
write_json(directory/'trace.json', rows)
validate_checkpoint(model, tok, adapters, validation, prior['protocol'],
directory/('validation-'+args.prefix+'.json'))
if __name__ == '__main__':
main()
+57
View File
@@ -0,0 +1,57 @@
# 研究图册:Qwen3.5-2B 参数几何与头贡献
这份图册与原始PNG/PDF/SVG一同保存在Git中。头贡献基线图片已随PR #6合并到main;其固定提交链接不依赖聊天附件或本机路径。后续实验分别列于下方,可通过图册所在的Git提交查看对应版本。
原始结果提交:`098ea8650c7d0e06339c66e3a0509e38b85b3d7d`;模型revision:`15852e8c16360a2fea060d615a32b45270f8a8fc`。
| 基线指标(逐观测中位数) | QKV复合变化 | √JS检索距离 |
|---|---:|---:|
| 有效头数÷总头数 | 76.0% | 55.8% |
| 最强25%头的影响份额 | 44.6% | 56.5% |
| 最弱25%头的影响份额 | 10.6% | 6.8% |
**√JS有效头数:8.931822/16;P10=5.784081,P90=11.672658。** 这是消融影响的集中程度,不是注意力概率质量。原基线为4条文本各32 token,普通注意力接收层的query7–31。
## 连续分布与尺度敏感性
![连续分布与尺度敏感性](../results/head-dominance/figures/retrieval_scale_sensitivity.png)
[PNG固定提交副本](https://gitea.entroia.com/Zayden-Jung/exp-model-parameter-similarity/raw/commit/098ea8650c7d0e06339c66e3a0509e38b85b3d7d/results/head-dominance/figures/retrieval_scale_sensitivity.png)
[PDF固定提交副本](https://gitea.entroia.com/Zayden-Jung/exp-model-parameter-similarity/raw/commit/098ea8650c7d0e06339c66e3a0509e38b85b3d7d/results/head-dominance/figures/retrieval_scale_sensitivity.pdf)
[SVG固定提交副本](https://gitea.entroia.com/Zayden-Jung/exp-model-parameter-similarity/raw/commit/098ea8650c7d0e06339c66e3a0509e38b85b3d7d/results/head-dominance/figures/retrieval_scale_sensitivity.svg)
## 联合强弱头消融
![联合强弱头消融](../results/head-dominance/figures/joint_removal_effects.png)
[PNG固定提交副本](https://gitea.entroia.com/Zayden-Jung/exp-model-parameter-similarity/raw/commit/098ea8650c7d0e06339c66e3a0509e38b85b3d7d/results/head-dominance/figures/joint_removal_effects.png)
[PDF固定提交副本](https://gitea.entroia.com/Zayden-Jung/exp-model-parameter-similarity/raw/commit/098ea8650c7d0e06339c66e3a0509e38b85b3d7d/results/head-dominance/figures/joint_removal_effects.pdf)
[SVG固定提交副本](https://gitea.entroia.com/Zayden-Jung/exp-model-parameter-similarity/raw/commit/098ea8650c7d0e06339c66e3a0509e38b85b3d7d/results/head-dominance/figures/joint_removal_effects.svg)
[完整基线报告](../results/head-dominance/REPORT.md) · [全部图表目录](../results/head-dominance/figures) · [图册SHA清单](figure-gallery-manifest.json)
使用√JS距离进行微调前后配对比较;保留JS散度作为尺度敏感性参考,避免混淆平方尺度与距离尺度。
## GSM8K微调前后配对图
[配对报告](../results/finetune-comparison/REPORT.md) · [CDF](../results/finetune-comparison/figures/paired_effective_heads_cdf.png) · [逐层分布](../results/finetune-comparison/figures/paired_effective_heads_by_layer.png) · [配对变化](../results/finetune-comparison/figures/paired_effective_heads_delta.png)
同目录保留PDF/SVG。图表随代码、原始数据和SHA清单一同提交,不依赖聊天附件。
## 高维壳与稀疏性对照
![稀疏球壳对照](../results/sparse-shell/sparse_shell_controls.png)
[条件定理、反例与数据说明](../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/interior_reference_sensitivity.png)
![径向分布的内外两尾](../results/model-shell/figures/radial_shape_two_tails.png)
![固定角色的径向CDF示例](../results/model-shell/figures/fixed_role_radial_cdfs.png)
[微调前后配对图](../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。
+42
View File
@@ -0,0 +1,42 @@
# 三层跨层注意力共享的两种改进实验
复用 Qwen3.5-2B 中层号为 15、19、23 的三个全注意力接收层(按整个模型从零编号),在新的查表任务上评估完整整数答案。上一轮第二个训练轮次的 LiSA 检查点作为轨迹蒸馏的起点,适配器 SHA-256 为 `c82db5af7fa42cf58a349f3e53961da2360b211a7ed606f53a728860c64f6f29`。
论文库中的三个条目是 LiSA(2197656)、AdaRank(2204577)和 MiniLLM(2176556)。LiSA 提供跨层共享与低秩修正。AdaRank 用模型分歧估计各模块所需的相对秩,本实验改用逐层恢复对完整答案的影响估计秩。MiniLLM 用学生轨迹和逆 KL 做蒸馏,本实验使用贪心轨迹。 [LiSA 原文](https://aclanthology.org/2026.tacl-1.30/) · [AdaRank 原文](https://arxiv.org/abs/2408.09015) · [MiniLLM 原文](https://arxiv.org/abs/2306.08543)
## 题集与验证
8 对诊断题用于为三个层分配秩,8 对验证题用于在两个分秩训练轮次之间选检查点,32 对新留出题用于最后的配对比较。每对保持键、查询和表格顺序一致,交换目标键和一个干扰键的值。训练使用上一轮的 24 道拟合题。生成上限为 24 个 token,判分要求正常结束并能提取完整整数。主指标是完整答案准确率,次指标是同一对的两个答案都正确的比例。准确率差的 bootstrap 以题对为重采样单位。
## 层敏感度与秩分配
依次用原生 Q/K 恢复单个接收层,其余层使用上一轮训练的 LiSA。在诊断集上恢复正确答案净增最多的层取秩 48,其次取 40,最后取 32。同分时层号小者优先。恢复分数并列时会弱化对敏感度排序的解释。对照包括均匀秩和反向分配,以及关闭跨层分数输入后的均匀秩和敏感度分配。关闭共享输入时在融合网络前将供给层的分数通道置零。每组名义参数量一致,置零通道对应的权重不会获得有效训练信号。
另在相同的 16 道诊断题上,分别为原模型、已有 LiSA 和三个逐层恢复条件计算标准答案各 token 的全词表对数概率,包含结束符。按题保存结果,用于观察恢复一层后,模型是否给正确答案分配了更大的概率。分秩仍按预先冻结的完整答案正确数与同分规则执行。
分秩实验沿用上一轮教师分数与训练题的缓存。五组从固定种子初始化,各做两轮、每轮 24 步。按验证正确数选择检查点,同分取较早轮次。四组交互项为共享时分秩相对均匀秩的增益,减去关闭共享输入时的同一增益。反向分配用于检验高秩是否确实给对了层。
留出答卷还会列出每项两组比较中从错变对、从对变错的题号。对跨层共享与分秩的组合,单列两个单项均答错而组合答对的题,以及两单项均答对而组合答错的题,同时附上关闭共享且使用均匀秩时的结果。这些题号解释净正确数的来源,四组交互项衡量两种改动的增益是否相互影响。
## 学生轨迹蒸馏
在同一批 8 对验证题上,分别生成起始检查点、学生前缀组和标准答案前缀组三种完整答卷,并用冻结的分词器从 token 重算判分。三个检查点预先指定。验证答卷可用于在留出评估之前判断轨迹训练是否值得进一步研究。
两组均从上一轮 LiSA 权重开始,依次在相同 24 道训练题上各更新一次。学生轨迹组每步先用更新前的学生生成完整的贪心回答,在这些前缀上最小化学生对原模型的全词表逆 KL。参考轨迹组使用标准答案前缀,学习率、优化器和题序相同。两组均使用最后一步权重。生成路径固定时反向传播下一 token 分布的梯度。这是借鉴 MiniLLM 的简化方法。两组的训练步数相等,生成与训练 token 数和实际训练开销可不同。
学生前缀随更新变化,当前学生组以提交 `2338679` 的蒸馏代码逐题运行原生教师。标准答案前缀固定,参考组可以复用上一轮保存的第 15 层输入及第 11 层供给分数。先核验缓存回执、24 个文件的摘要、题序,再逐题核对完整 token 序列与答案起点。每次启动或续跑时,首道待训题同时走完整前向和缓存路径,逐元素核对教师最终隐状态、接收层输入和供给分数。三者完全相等后,后续题才使用缓存。缓存缺失或核对不符时,以完整教师前向继续。分秩组使用同一份缓存回执。参考组实际采用的路径由训练日志记录,解释训练耗时需考虑这项缓存复用。
## 复跑顺序
使用上一轮远程 CPU Python 环境和完整仓库依赖。所有命令共用 `--source`(冻结模型目录)、`--prior`(上一轮包含 frozen.json 和 final 子目录的作业目录)、`--out`(本轮独立目录)。按顺序运行以下 Python 模块。
1. `crossqkv.lisa_combination_screen` 冻结清单并生成四种诊断条件。
2. `crossqkv.lisa_trajectory_train --prefix student` 和 `crossqkv.lisa_trajectory_train --prefix reference` 训练两个轨迹条件。
3. `crossqkv.lisa_rank_compare` 根据诊断分数分配秩,训练五个条件。
4. `crossqkv.lisa_combination_eval` 生成十组留出答卷,逐题校验并写入 holdout/audit.json。
冻结清单 SHA-256 为 `6858dbc64db0b989e8112e9dbea70662a2a05f66f11b180e8f2c668c74c43aef`。秩分配与轨迹方法分别和各自匹配的对照比较。跨路线的总训练预算不同。
留出评估按每批两题记录生成耗时,从提示词编码前计时到回答解析结束,同时汇总生成 token 数。远程 CPU 在多个作业间共享,这些运行记录用于解释实际开销。要验证部署加速,还需要在受控负载下重复测量。
已记录远程部署的 13 个实现与测试文件摘要。部署目录中的 `crossqkv/lisa_full_answer.py` 来自提交 `c53d78b`。它与本轮主线版本的差异限于该模块自身的筛选命令行入口,本轮调用的 `evaluate`、`prompt`、`grade` 等函数一致。 [远程代码摘要](../results/lisa-combinations/execution.sha256)
+20
View File
@@ -0,0 +1,20 @@
# 三层 LiSA 共享的诊断与分秩
在 Qwen3.5-2B 的 8 对查表题上,单独恢复第 19 层的原生 Q/K,16 道完整答案全部正确。恢复第 15 层答对 15 道,恢复第 23 层答对 1 道。其余两个接收层继续使用同一份 LiSA 权重,每次恢复都会影响下游计算。层号按整个模型从零开始。 [冻结协议](LISA_COMBINATIONS_PROTOCOL.md)
| 条件 | 完整答案正确 | 同一对交换前后均正确 |
|---|---:|---:|
| 原 LiSA | 0/16 | 0/8 |
| 恢复第 15 层 | 15/16 | 7/8 |
| 恢复第 19 层 | 16/16 | 8/8 |
| 恢复第 23 层 | 1/16 | 0/8 |
四组共 64 次生成均得到完整整数。逐题复核使用冻结分词器重新解码 token,检查正常结束或长度上限、题目 ID、标准答案及记分。复核回执保存了原始答卷、题集、分词器及起始适配器的 SHA-256。 [逐题答卷及复核回执](../results/lisa-combinations/diagnostic/)
这组题可以区分模型是否跟随目标值变化,以及变化后是否答对。原 LiSA 在 8 对题上全都重复了交换前的数字,尽管每对的正确答案都变了。16 个错误答案中,12 个是该题表内其他键的值,4 个是表外数字。恢复第 15 层后,8 对的回答都随交换变化,7 对两次都正确。恢复第 19 层后,8 对两次都正确。恢复第 23 层后,4 对的回答发生变化,但没有一对两次都正确。这些计数来自同一诊断集,用于解释按层分秩的依据。 [成对题目](../results/lisa-combinations/protocol.json) · [四组原始回答](../results/lisa-combinations/diagnostic/)
第 15 层和第 19 层的正确性只在一题上有差异。目标键位于第 9 项,值为 39,恢复第 15 层生成第 8 项的 98,恢复第 19 层生成 39。交换表项后,两种恢复条件都正确生成 77。每次去掉一对题重新排序,第 23 层在 8 次中均居末位。去掉上述题对时,第 15 层和第 19 层打平,预定的同分规则将第 15 层排在前面。其他 7 次均为第 19 层领先。 [配对复核](../results/lisa-combinations/diagnostic/verified.json)
按全部诊断题,敏感度分配给第 15、19、23 层的秩依次为 **40、48、32**。均匀对照为 40、40、40,反向对照为 40、32、48。上述结果衡量恢复原生 Q/K 的效果。增加低秩参数能救回多少答案,以及学生轨迹蒸馏能否改善生成,需在训练后用 32 对新留出题检验。
五个分秩条件各有 2,476,032 个适配器参数。关闭共享时,三个接收层各有 8 个供给分数通道被置零,每个通道连接到 256 个融合单元。因此共有 6,144 个权重(占 0.248%)的输入恒为零,其余 2,469,888 个权重保留连接。分别在开启和关闭共享的条件内比较分秩与均匀秩,两侧的连接数各自相等。
+165
View File
@@ -0,0 +1,165 @@
# 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. Each epoch of the trainable variants sees
1,874 next-token targets drawn from those same 12 prompts. 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)
Qwen's text decoder has six full-attention layers and 18 linear-attention
layers. The chained configuration modifies two of the six full-attention
layers and two of the 24 decoder layers overall. Layer numbers are zero-based.
The source record in `results/lisa-effect-reproduction/runtime.json` pins
the original model revision, the checkpoint shard and its download-manifest hash.
## 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.
The answer is one token per prompt. In the fit set, it accounts for about
0.64% of the unweighted CE target mass and about 9.35% with the 16-fold answer
weight. The objective applies the same 0.75 coefficient to the resulting
mean CE in both trainable variants.
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.
+49
View File
@@ -0,0 +1,49 @@
# Qwen3.5-2B 双层 LiSA 复现实验
在冻结的 32 道查找题上,原模型、直接共享、线性修正和两版 LiSA 的四选一准确率均为 32/32。全词表首 token 命中率从双层直接共享的 27/32 升到两版 LiSA 的 32/32。五道变化题都涉及首 token 从 `<think>` 变成正确选项。两个接收层各自的 K/V 缓存减少 42.2%。耗时随权重是否驻留及测量阶段而异。
## 四选一任务表现
开发筛选中,原模型和单层直接共享各答对 8/8,双层直接共享答对 7/8。以此冻结 16 条目查找任务,测试使用独立题目。共享链为 15→19→23,层号从 0 起算。第 19、23 层占 6 个全注意力层的三分之一,占 24 个解码层的十二分之一。
| 方法 | 留出正确数 | 四选一答案 NLL ↓ |
| --- | ---: | ---: |
| 原模型 | 32/32 | 0.1341 |
| 双层直接共享 | 32/32 | 0.0728 |
| 双层线性修正 | 32/32 | 0.0720 |
| 双层 LiSA | 32/32 | 0.1846 |
| 双层 LiSA,答案损失加权 | 32/32 | 0.1260 |
直接共享在留出集上丢失 0 道原模型答对的题,因此无法估计 LiSA 对这类错题的恢复率。答案加权把 LiSA 的四选一 NLL 降低了 0.0586,仍高于直接共享。相比直接共享,原版 LiSA 的 NLL 增加 0.1118,按题配对 bootstrap 95% 区间为 [0.0968, 0.1282]。答案加权 LiSA 的差为 0.0532,区间为 [0.0327, 0.0749]。三种训练方法各用 12 道拟合题跑两轮,并由另外 12 道验证题选择检查点。所选检查点都是第 2 轮。
## 全词表首 token
| 方法 | 正确选项为首 token | 全词表答案 NLL ↓ |
| --- | ---: | ---: |
| 原模型 | 27/32 | 0.5633 |
| 单层直接共享,第 23 层 | 32/32 | 0.3124 |
| 单层 LiSA,第 23 层,使用双层训练的适配器 | 32/32 | 0.2554 |
| 双层直接共享 | 27/32 | 0.5579 |
| 双层线性修正 | 27/32 | 0.5574 |
| 双层 LiSA | 32/32 | 0.4706 |
| 双层 LiSA,答案损失加权 | 32/32 | 0.1545 |
两版 LiSA 对双层直接共享的首 token 净改善均为 5/32,另有 0 道从正确变成错误,McNemar 精确双侧 p = 0.0625。双层直接共享比单层直接共享少答对的五道,恰好也是原模型和线性修正先输出 `<think>` 的五道。它们的正确选项都是 `4`,四选一口径在全部方法上均答对。输出符合格式是这里观察到的改善,后续生成内容没有记录。
原版 LiSA 相对双层直接共享的全词表 NLL 差为 −0.0872,按题配对 bootstrap 95% 区间为 [−0.1498, −0.0305]。答案加权版的差为 −0.4033,区间为 [−0.4796, −0.3344]。原版和加权版的首 token 命中数一致,加权版的平均答案 NLL 更低。由于五道变化集中于同一选项和同一个替代 token,推广到其它任务或输出格式还需要独立证据。
## CPU 计时和缓存
| 测量范围 | 原模型 | LiSA |
| --- | ---: | ---: |
| 缓存前缀后的尾部预填充,157 tokens | 12.37 s | 16.31 s |
| 第 19 层单步,流式读取权重 | 136.15 ms | 96.32 ms |
| 第 23 层单步,流式读取权重 | 136.39 ms | 138.80 ms |
| 第 19 层单步,投影权重常驻 | 42.57 ms | 32.09 ms |
| 第 23 层单步,投影权重常驻 | 44.80 ms | 22.79 ms |
每个接收层的 FP32 K/V 实际分配从 643,072 降到 371,776 字节,下降 42.2%。计入该层所用的 5,024 字节上游分数行后,单层合计下降 41.4%。V 缓存为 321,536 字节。解码计时的单位是单个接收层的一步,计时范围从接收现成分数行开始,至该层注意力输出结束。预填充用 3 次计时的中位数,单层解码每个配置用 9 步计时的中位数。
论文表 2 的 96.44% 衡量 LLaMA2-13B 在共享 22 层时多个基准上的平均性能保留率。这里每轮只有 1,874 个训练目标 token,测到的是单一查找任务的表现和 CPU 组件耗时。 [论文表 2、表 3 和附录 C.1](https://aclanthology.org/2026.tacl-1.30.pdf)
训练轨迹、两种答案口径的逐题记录、配对统计、缓存和时延原始结果均在 [实验结果目录](../results/lisa-effect-reproduction/)。[复跑协议](LISA_EFFECT_PROTOCOL.md)
+42
View File
@@ -0,0 +1,42 @@
# 完整答案评估下的 LiSA 共享实验
本轮在同一 Qwen3.5-2B 检查点上比较 3、4、5 个全注意力层接收共享分数的效果。上一轮发现首 token 命中的变化集中在 `<think>` 和同一个选项。本轮要求模型从全词表生成完整的多 token 数值答案,逐题复核答案的数值。
## 开发筛选与冻结
从 0 开始编号。接收层分别为 `[15, 19, 23]`、`[11, 15, 19, 23]` 和 `[7, 11, 15, 19, 23]`。每个接收层使用本次前向中前一全注意力层实际输出的分数。接收端保留自身的 V、门控和输出投影。原模型与三个直接共享配置配对生成。
候选任务为表中数值查找、重复键最后值查找、两位数加法、重复项计数。固定生成器在运行筛选之前写出每类任务 8 道开发题、24 道训练题、8 道验证题和 32 道留出测试题。同一数值题跨数据划分去重,加法按交换律规范操作数。每个候选都要满足原模型至少答对 6/8 且至少 2 道原模型答对的题在直接共享下生成了错误整数。选择时依次比较数字错误数、原模型正确数和接收层数,仍并列时取字典序最大的任务标识。完成了生成却没有可提取答案的情况单独记数。
使用检查点发布的单轮聊天模板和关闭 thinking 的生成前缀。所有配置从全词表逐 token 贪心生成,遇到回合结束或文本结束 token 停止,最多生成 24 tokens。主要指标要求已生成停止 token,并从整条答复提取完整整数。接受纯整数或明确的最终答案行,可去掉开头完整的 thinking 区块。原始 token、文本、停止原因和提取值都随结果存档。 [检查点聊天模板](https://huggingface.co/Qwen/Qwen3.5-2B/blob/15852e8c16360a2fea060d615a32b45270f8a8fc/chat_template.jinja)
## LiSA 训练与测试
开发筛选完成后用固定哈希验证题集、共享配置、原模型和筛选数据。仅在存在达标配置时启动训练。冻结原模型,只训练两个线性层组成的注意力头融合和 rank 40 的低秩 Q/K。用原模型在同一训练序列上的遮罩前注意力分数作为教师。损失为 0.25 倍 Huber 距离加 0.75 倍全词表交叉熵。Huber 覆盖实际序列长度内的所有查询和键,注意力前向应用因果遮罩。交叉熵覆盖参考答案的所有 token 和结束 token。每个训练样本更新后保存优化器和模型状态。验证集上生成完整答案,按正确数选择两轮中的最佳检查点,同分选较早者。
最终对同一批留出题的原模型、直接共享、训练后的 LiSA 分别生成并保存完整回答。报告准确率、直接共享造成的数值错误、其中被 LiSA 恢复的题、新增错误和缺少可提取答案的情况。准确率差按题配对估计,另报告 McNemar 精确双侧检验。
## 运行命令
在已确认的远程 CPU 环境中,从源代码目录运行,使用独立输出目录。模型源目录需要包含上一轮实验使用的权重、配置、下载清单和 tokenizer。
```sh
export OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1
PYTHON=venv/bin/python
SOURCE=runs/cpu-qwen35-2b
SCREEN=runs/NEW_FULL_ANSWER_SCREEN
RESULT=runs/NEW_FULL_ANSWER_RESULT
"$PYTHON" -B -m crossqkv.lisa_full_answer --source "$SOURCE" --out "$SCREEN" --batch-prompts 1 --preflight
"$PYTHON" -B -m crossqkv.lisa_full_answer --source "$SOURCE" --out "$SCREEN" --batch-prompts 1
"$PYTHON" -B -m crossqkv.lisa_full_answer_train --source "$SOURCE" --screen "$SCREEN" --out "$RESULT"
"$PYTHON" -B -m crossqkv.lisa_full_answer_verify --tokenizer "$SOURCE/tokenizer.json" \
--frozen "$SCREEN/frozen.json" --selection "$SCREEN/selection.json" \
--rows "$RESULT/test-items.json" --out "$RESULT/verified-test.json"
```
使用原目录运行相同命令即可续跑。筛选和测试将按已保存的题号继续。训练使用已保存的优化器和训练步。
筛选续跑可加 `--execution-batch-prompts 2`。它会重跑已完成的前两题,要求所有配置的 token 序列、停止原因与判分逐项一致,才继续处理剩余题目,并把回放凭证写入 `execution-batch-replay.json`。冻结的 `--batch-prompts 1` 参数仍用于校验原实验。双题模式超出资源限制或未通过回放时,可用原单题命令从已保存的行继续。本次在第五题写盘后交接,前两题的四个配置均通过了完整回放核对。
服务器约有 1.7 GiB 内存。前五题采用单题批量,从第六题起采用通过回放的双题批量。每道题的四个配置共享权重读取。前两次预检和一次生成在服务器仍有约 1 GiB 可用内存时触发进程独立换页上限。当前作业沿用原冻结题集,并在每层结束时释放空闲内存。可用内存、进程 RSS、低可用内存下的持续换页压力和运行时间均由原检查器监控。
+46
View File
@@ -0,0 +1,46 @@
# 完整答案下的 3–5 层共享实验
开发集筛选选定表中数值查找和三个接收层 `[15, 19, 23]`,层号从 0 起算。原模型在查表组答对 8/8,3 层直接共享在这八题上都生成了用结束 token 收尾的错误整数。该条件用于后续 LiSA 训练和独立留出评估。
## 开发集筛选
每个任务各有八题。共享列依次列出正确数、原模型答对却在直接共享后得到错误整数的题数,以及未提取到答案的题数。
| 任务 | 原模型正确 | 3 层共享 | 4 层共享 | 5 层共享 |
| --- | ---: | ---: | ---: | ---: |
| 查表 | 8 | 0 / 8 / 0 | 0 / 4 / 4 | 0 / 0 / 8 |
| 重复键最后值 | 6 | 0 / 6 / 0 | 0 / 3 / 4 | 0 / 0 / 8 |
| 加法 | 7 | 0 / 7 / 0 | 0 / 1 / 7 | 0 / 0 / 8 |
| 重复项计数 | 1 | 1 / 1 / 0 | 0 / 1 / 0 | 0 / 0 / 8 |
5 层配置的 32 道生成均达到 24-token 上限。3 层对查表、重复键和加法均达到筛选门槛,查表中从正确变成错误整数的题数最多。筛选结果用于选择条件。留出集将另行估计准确率差、恢复题和新增错误。
独立复核用原分词器重新解析 32 道题的全部四组 token 序列,核对终止原因和正确性。冻结清单、逐题生成、组内汇总、选择记录和训练配置均已归档。 [实验协议](LISA_FULL_ANSWER_PROTOCOL.md) · [原始数据](../results/lisa-full-answer-reproduction/)
## 训练与独立留出评估
三个接收层各训练 825,344 个参数,总计 2,476,032 个。完成了 24 道冻结拟合题的教师分数采集,复核按题检查输入 token、教师张量形状与有限值,并保存各采集文件的 SHA-256。
两轮各完成 24 次更新。用冻结分词器重新解码两轮各 8 道验证题的生成结果,首轮答对 1 道,第二轮答对 2 道。按预先固定的验证正确数选用第二轮检查点。两轮逐步损失、验证题原始输出及检查点选择见训练记录。 [训练记录](../results/lisa-full-answer-reproduction/trace.json)
### 留出集结果
在 32 道独立查表题上,三组共 96 条回答全部生成了正常的结束 token,并能提取完整整数。原模型全对。三层直接共享让 32 道题都答成了错误整数,LiSA 救回其中 3 道,另外 29 道仍答错。
| 配置 | 正确数 | 准确率 |
| --- | ---: | ---: |
| 原模型 | 32/32 | 100% |
| 三层直接共享 | 0/32 | 0% |
| 三层 LiSA | 3/32 | 9.38% |
| 恢复题 | 原模型及标准答案 | 直接共享 | LiSA |
| --- | ---: | ---: | ---: |
| `test-lookup-014` | 71 | 47 | 71 |
| `test-lookup-020` | 94 | 5 | 94 |
| `test-lookup-021` | 44 | 10 | 44 |
相对直接共享,LiSA 准确率提高 9.38 个百分点,按题配对 bootstrap 95% 区间为 0 至 21.88 个百分点。McNemar 精确双侧检验的 p 值为 0.25。逐题变化方向是 3 道从错变对、0 道从对变错。直接共享全错,因此这个留出集无法估计 LiSA 保留直接共享已有正确答案的能力。
结果确认了三个真实数值错误的恢复案例。样本上的准确率提升仍有较大不确定性。结论限于这一个 Qwen3.5-2B 检查点、查表任务和三个接收层,训练用 24 道合成题。四层和五层共享只做了开发筛选,其 LiSA 恢复效果仍待测。
远程实验和独立复核均以退出码 0 完成。复核从保存的 token 重新解析并重算三组分数,结果与训练进程生成的汇总一致。摘要记录的是远程原件路径,选中的适配器保存在该远程运行目录。 [逐题输出](../results/lisa-full-answer-reproduction/test-items.json) · [配对统计](../results/lisa-full-answer-reproduction/test-audit.json) · [复核回执](../results/lisa-full-answer-reproduction/verified-test.json) · [文件摘要](../results/lisa-full-answer-reproduction/result.sha256)
+50
View File
@@ -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%。这说明两尾同时增加是普遍现象,比“所有向量整体更靠内”更符合这些数据。
![最大半径与RMS尺度下的固定角色示例](../results/model-shell/figures/fixed_role_radial_cdfs.png)
这三组示例按模块角色固定: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及对照摘要、实测范数一同保存。结论为描述性统计:视图相关且重叠,没有将其当作独立重复实验进行显著性检验。
+48
View File
@@ -0,0 +1,48 @@
{
"source_commit": "098ea8650c7d0e06339c66e3a0509e38b85b3d7d",
"base_model_revision": "15852e8c16360a2fea060d615a32b45270f8a8fc",
"sqrt_js_effective_heads": {
"median": 8.93182211792415,
"p10": 5.7840811612328125,
"p90": 11.67265834734814,
"donor_heads": 16
},
"files": [
{
"path": "results/head-dominance/figures/retrieval_scale_sensitivity.png",
"sha256": "4f2dac5fdb5506ee5282d459dcb86cc6b58fac05d494d6409c29ea6924365add",
"immutable_url": "https://gitea.entroia.com/Zayden-Jung/exp-model-parameter-similarity/raw/commit/098ea8650c7d0e06339c66e3a0509e38b85b3d7d/results/head-dominance/figures/retrieval_scale_sensitivity.png",
"http_status": 200,
"remote_sha_verified": true,
"content_type": "image/png"
},
{
"path": "results/head-dominance/figures/retrieval_scale_sensitivity.pdf",
"sha256": "56a2f5655196018f4310dbccb29cb55c314111007598491496c9a36256958525",
"immutable_url": "https://gitea.entroia.com/Zayden-Jung/exp-model-parameter-similarity/raw/commit/098ea8650c7d0e06339c66e3a0509e38b85b3d7d/results/head-dominance/figures/retrieval_scale_sensitivity.pdf"
},
{
"path": "results/head-dominance/figures/retrieval_scale_sensitivity.svg",
"sha256": "f51803e68df40df6dda91bce7236c999f405ccf30be56e7819242147a5e9a5b8",
"immutable_url": "https://gitea.entroia.com/Zayden-Jung/exp-model-parameter-similarity/raw/commit/098ea8650c7d0e06339c66e3a0509e38b85b3d7d/results/head-dominance/figures/retrieval_scale_sensitivity.svg"
},
{
"path": "results/head-dominance/figures/joint_removal_effects.png",
"sha256": "7dc26da9fda80e62c6445c5dee29fe52c06146dea0cd65d444755cf0eb5bb729",
"immutable_url": "https://gitea.entroia.com/Zayden-Jung/exp-model-parameter-similarity/raw/commit/098ea8650c7d0e06339c66e3a0509e38b85b3d7d/results/head-dominance/figures/joint_removal_effects.png",
"http_status": 200,
"remote_sha_verified": true,
"content_type": "image/png"
},
{
"path": "results/head-dominance/figures/joint_removal_effects.pdf",
"sha256": "b35132d3e1cf3d202bc6695e64f64c9e495196bc6c9a92659ccf65aceb566040",
"immutable_url": "https://gitea.entroia.com/Zayden-Jung/exp-model-parameter-similarity/raw/commit/098ea8650c7d0e06339c66e3a0509e38b85b3d7d/results/head-dominance/figures/joint_removal_effects.pdf"
},
{
"path": "results/head-dominance/figures/joint_removal_effects.svg",
"sha256": "03e6b299c1dbfa703ac72cbc7e9749e3173b649a22d829316dd5b5dccbe8728d",
"immutable_url": "https://gitea.entroia.com/Zayden-Jung/exp-model-parameter-similarity/raw/commit/098ea8650c7d0e06339c66e3a0509e38b85b3d7d/results/head-dominance/figures/joint_removal_effects.svg"
}
]
}
+76
View File
@@ -0,0 +1,76 @@
# Head influence concentration: measurement protocol
Target: quantify the statistical distribution of large and small upstream head
influences on the next layer's Q/K/V; identity of dominant heads may vary at each
sample, query token and recipient head. No training, GPU, deletion or model edits.
Scope: all 23 adjacent layer transitions of the retained Qwen3.5-2B text model,
including 16-head linear attention and 8-head full attention. Measure effective
Q/K/V, and retrieval probability changes where the recipient uses full attention.
The intervening source-layer residual/MLP and recipient input normalization must
be recomputed after interventions. Residual stream is preserved: removing an
attention head is not removing all information reaching the recipient.
For each observation, remove one upstream attention head's projected contribution
at a time. Record nonnegative influence magnitude d_i and its absolute scale.
When sum(d_i)>0, p_i=d_i/sum(d_i) is normalized intervention influence, NOT an
additive causal attribution or a native attention probability over upstream heads.
All-zero influence has undefined concentration and must be flagged, not assigned
uniform or concentrated values. Record small total influences explicitly.
Primary continuous measures:
- Effective head count: N_eff=1/sum(p_i^2), range [1,H].
- Effective head fraction: N_eff/H, supports different H.
- Normalized concentration: C=(sum(p_i^2)-1/H)/(1-1/H), range [0,1].
These are related summaries, not independent evidence. Report distributions over
texts/tokens/recipient heads/layers, not only concentration of globally averaged
influences. Primary query positions 7 onward avoid trivial short-prefix attention.
Secondary intuitive measures: top1/top25%/top50% influence share, bottom25%
share, and number of heads reaching 90% influence. Preserve raw influence tables.
No RMS activity threshold is used to define influence concentration.
Joint interventions are required: per observation's weak-head set and strong-head
set must be removed together and measured, because individual ablations are not
additive and may conceal cancellation or synergy. Rankings may be input-specific;
these experiments cannot imply a universally removable fixed head set. Distinguish
local next-layer QKV/probability effects from unmeasured final LM quality.
CPU measurements, scientific plots, tests and audits execute on the previously
authorized server 8.211.154.134. All weights and existing caches remain retained.
## Fixed execution details (before real-model measurements)
Four texts are reused from crossqkv/fresh_samples.json (two Chinese/two English),
32 tokens each; no independent generalization claim. All tokens are computed,
queries7..31 are primary statistical observations. The observer caches source
residual inputs and exact per-head projected output components; their sum is
checked against the native branch output. First text's full forward is checked
against the canonical streaming forward, and every transition has a null-mask
control. No cached tensor is deleted.
For each query/recipient query-head, individual influence is the L2 change divided
by that same baseline vector's L2 (floor1e-12). Q,K,V are analyzed separately.
A declared balanced score sqrt((relative_Q^2+relative_K^2+relative_V^2)/3) is also
analyzed; it does not treat their different physical scales as directly additive.
Full attention: Q/K are measured after learned norm/partial RoPE, V before output
mixing, and actual softmax retrieval JS is measured. Linear attention: Q/K/V are
after causal convolution+SiLU; Q/K include the delta-rule L2 normalization and Q
scale. It has no ordinary softmax retrieval distribution. Full-attention GQA K/V
are repeated to query-head slots for aligned joint tests; these slots are not
independent KV heads, and statistical observations are not independent samples.
Joint weak-half/strong-half/random-half/all-head removal uses a separate coherent
sequence for each recipient query-head. At each source token, choose the donor
half by that recipient query-head's QKV influence ranking at the same token.
Recompute full recipient sequence; convolution and QK retrieval can therefore
propagate changes between positions. Only the intended recipient head is scored
for each scenario. This is an input-adaptive diagnostic, not a computationally
free head-selection policy. Random uses fixed seed31000+sample_index*100+layer.
Compare joint effects to sums of corresponding single effects but do not assume
additivity. For JS use the same joint sets (selected by QKV, not by JS).
No success criterion assumes that dominance exists. Report effective-head and
absolute-effect distributions even if contributions are diffuse. No final-LM
NLL or deployable pruning quality claim. Scientific output includes all raw
single/joint effects and deletion masks; large baseline caches remain external.
+75
View File
@@ -0,0 +1,75 @@
# Statistical head influence dominance (CPU)
This study answers how concentrated the **distribution of measured upstream-head
influences** is, without assuming that dominant head identities are fixed across
texts, positions or recipient heads. Read [registered protocol](PROTOCOL.md).
- `core.py`: normalized effective Q/K/V extraction for both attention types,
source projected head decomposition, exact nonlinear downstream recomputation,
coherent masks, continuous concentration and JS.
- `run.py`: four fixed prior texts, all23 adjacent connections, single-head and
weak/strong/random-half/all-head interventions, per-transition checkpointing,
canonical-forward/null controls, preserved baseline caches.
- `report.py`: full saved-data distributions, per-transition CSV, continuous
effective head plots, influence rank curves, joint tests and Chinese report.
- `audit.py`: independently recomputes concentration/masks from raw effects,
validates scope/null/head sums, and hashes retained caches, source and results.
- `tests/test_dominance.py`: continuous limiting cases, undefined zero-total,
token-dependent masks, JS identity, both canonical mixed-layer paths, and joint
interventions on a small checkpoint with known arrays.
Influence for Q/K/V is relative L2 change after deleting one whole donor attention
head (at all sequence positions), preserving the prior residual and recomputing
source MLP + recipient normalization. Source **output/value heads** are the units:
16 for linear attention,8 for full attention. These are not arbitrary individual
Q/K/V weight blocks. For a recipient query-head at one token, normalize donor
influences to p. Primary continuous summary is N_eff=1/sum(p²), and N_eff/H.
C=(sum(p²)-1/H)/(1-1/H) is a related0..1 concentration score. These are not
independent confirmations. No RMS near-zero threshold or R fitting is used.
Q/K/V are separate primary scales; balanced QKV score is RMS of their three
relative changes. It is a declared summary, not a norm in a single physical space.
Zero total implies undefined concentration, not a uniform distribution. Single-head relative effects before head-share normalization and true joint
effects are retained as well as shares. The saved metric named max_absolute is
the largest unsigned relative-L2 effect, not an unnormalized hidden-space norm.
The total field sums individual relative effects; it is not the measured joint
effect of removing the whole attention branch.
Full-attention recipients additionally have real token-key probability JS changes;
linear attention does not have an ordinary softmax attention probability matrix.
Full-attention K/V repeat their GQA groups to query-head slots for aligned joint
experiments, not as extra independent KV observations. Every headline statistic
is descriptive: query/token/head observations are dependent, and four short prior
texts do not establish universal dominance or independent generalization.
Joint masks vary per source token and recipient head. Recompute a coherent full
sequence for each recipient head, scoring that intended head afterward. Rank by
single QKV influence, remove weakest half/strongest half/a fixed-seed random half,
or all attention heads. This investigates interactions and cross-token effects;
it is not a validated free selector, fixed removable head subset or LM pruning.
Only run model work and scientific plotting on the authorized CPU server:
```
OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 venv/bin/python -B -m unittest tests.test_dominance -v
OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 venv/bin/python -B -m dominance.run --source runs/cpu-qwen35-2b --out runs/NEW_DOMINANCE_DIR --seconds 7200
venv/bin/python -B -m dominance.report runs/NEW_DOMINANCE_DIR
venv/bin/python -B -m dominance.audit runs/NEW_DOMINANCE_DIR runs/cpu-qwen35-2b
```
No training, GPU, new model download or automatic deletion. Raw intervention
arrays and masks are delivered to Git; large baseline caches stay on the server
with path/size/SHA metadata. Existing checkpoints/caches are never removed.
The saved sum of selected individual effects is only a query-wise mask-weighted
reference: individual ablations remove a head at all positions, whereas joint
masks can vary across positions. Their difference cannot isolate pure nonlinear
interaction, since temporal intervention supports also differ. Use the measured
weak/strong/random joint effects directly; do not call this reference an additive
causal decomposition or a Shapley attribution.
Scale sensitivity: after reviewing the first complete summaries, add sqrt(JS)
(Jensen–Shannon distance) alongside primary JS divergence. Divergence is roughly
quadratic for small changes, so shares and effective head counts depend on this
scale. All original primary statistics and raw interventions remain unchanged;
primary-analysis-summary.json preserves the pre-sensitivity aggregate for exact
audit comparison. Retrieval-scale plots and source tables show both definitions.
View File
+90
View File
@@ -0,0 +1,90 @@
"""Recompute saved concentration, masks, scale and scope checks; preserve caches."""
import json,hashlib,csv,sys
from pathlib import Path
import numpy as np
from .core import concentration
def main(root,source):
root=Path(root);source=Path(source);status=json.loads((root/'status.json').read_text());assert status['state']=='completed'
samples=json.loads((root/'samples.json').read_text());assert len(samples)==4 and all(len(s['token_ids'])==32 for s in samples)
expected={(s['id'],i) for s in samples for i in range(23)};actual={(x['sample'],x['source']) for x in status['completed_links']};assert actual==expected and len(status['completed_links'])==92
cfg=json.loads((source/'model_config.json').read_text())['text_config'];obs=dict(np.load(root/'observations.npz'));lookup=sorted(s['id'] for s in samples);counts={};undefined={};full_js_links=0;joint_values={}
for sample,layer in sorted(actual):
f=root/'raw'/f'{sample}-link-{layer:02d}.npz';d=dict(np.load(f));hs=8 if cfg['layer_types'][layer]=='full_attention' else 16;hr=8 if cfg['layer_types'][layer+1]=='full_attention' else 16
if hr==8:
full_js_links+=1;d['single_sqrtJS']=np.sqrt(d['single_JS'])
for label in ('weak_half','strong_half','random_half','all_heads'):
d['joint_'+label+'_sqrtJS']=np.sqrt(d['joint_'+label+'_JS'])
mask=d.get('mask_'+label,np.ones((hr,32,hs),dtype=np.float32))
d['individual_sum_'+label+'_sqrtJS']=np.sum(d['single_sqrtJS'].transpose(2,1,0)*mask,-1).T
d['null_sqrtJS']=np.sqrt(d['null_JS'])
masks={label:d['mask_'+label] for label in ('weak_half','strong_half','random_half')}
for label,m in masks.items():
assert m.shape==(hr,32,hs);assert np.isin(m,[0,1]).all();np.testing.assert_array_equal(m.sum(-1),hs//2)
np.testing.assert_array_equal(masks['weak_half']+masks['strong_half'],1)
ranked=np.argsort(d['single_QKV'].transpose(2,1,0),axis=-1,kind='stable')
np.testing.assert_array_equal(np.take_along_axis(masks['weak_half'],ranked[...,:hs//2],-1),1)
for key in ('Q','K','V','QKV')+(('JS','sqrtJS') if hr==8 else ()):
single=d['single_'+key];assert single.shape==(hs,32,hr) and np.isfinite(single).all() and np.min(single)>=0
effect=single[:,7:,:].transpose(1,2,0);stats=concentration(effect);counts[key]=counts.get(key,0)+effect.shape[0]*hr;undefined[key]=undefined.get(key,0)+int((~stats['valid']).sum())
choose=(obs[key+'_source']==layer)&(obs[key+'_sample_index']==lookup.index(sample))
assert int(choose.sum())==25*hr
for metric,values in stats.items():
if metric=='valid':continue
np.testing.assert_allclose(obs[key+'_'+metric][choose],values.ravel(),rtol=1e-6,atol=1e-7,equal_nan=True)
for label in ('weak_half','strong_half','random_half','all_heads'):
mask=masks.get(label,np.ones((hr,32,hs),dtype=np.float32));expected_sum=np.sum(single.transpose(2,1,0)*mask,-1).T
np.testing.assert_allclose(d['individual_sum_'+label+'_'+key],expected_sum,rtol=1e-6,atol=1e-8)
assert d['joint_'+label+'_'+key].shape==(32,hr) and np.isfinite(d['joint_'+label+'_'+key]).all()
joint_values.setdefault((key,label),[]).extend(d['joint_'+label+'_'+key][7:].ravel())
assert float(np.max(d['null_'+key]))<=2e-5
assert full_js_links==24
summary=json.loads((root/'analysis-summary.json').read_text())
def check_stats(values,record):
v=np.asarray(values,dtype=np.float64);v=v[np.isfinite(v)];assert len(v)==record['count']
if len(v):
for name,x in zip(['p10','median','p90','mean'],[*np.quantile(v,[.1,.5,.9]),v.mean()]):np.testing.assert_allclose(record[name],x,rtol=2e-6,atol=1e-8)
for key in counts:
for metric,record in summary['concentration'][key].items():check_stats(obs[key+'_'+metric],record)
primary=json.loads((root/'primary-analysis-summary.json').read_text())
for section in ('concentration','joint','paired_joint','by_recipient_type'):
for key,value in primary[section].items():assert summary[section][key]==value,(section,key)
full_sources=sorted({x['source'] for x in status['completed_links'] if x['full_attention_recipient']})
assert summary['full_attention_source_indices']==full_sources
for key,groups in summary['by_recipient_type'].items():
src=obs[key+'_source']
for label,metrics in groups.items():
choose=np.isin(src,full_sources) if label=='full_attention' else ~np.isin(src,full_sources)
for metric,record in metrics.items():check_stats(obs[key+'_'+metric][choose],record)
for (key,label),values in joint_values.items():check_stats(values,summary['joint'][key][label])
for key in counts:
weak=np.asarray(joint_values[(key,'weak_half')]);strong=np.asarray(joint_values[(key,'strong_half')]);random=np.asarray(joint_values[(key,'random_half')]);valid=weak>0;record=summary['paired_joint'][key]
assert record['zero_weak_effect_count']==int((~valid).sum())
np.testing.assert_allclose(record['weak_less_than_strong_fraction'],np.mean(weak<strong))
np.testing.assert_allclose(record['weak_less_than_random_fraction'],np.mean(weak<random))
check_stats(strong[valid]/weak[valid],record['strong_over_weak']);check_stats(random[valid]/weak[valid],record['random_over_weak'])
controls=json.loads((root/'head-sum-controls.json').read_text());assert len(controls)==96 and max(x['relative_l2'] for x in controls)<2e-5
assert status['canonical_forward_relative_error']<2e-5
caches=[]
for f in sorted((root/'cache').rglob('*')):
if f.is_file():caches.append({'path':str(f.resolve()),'bytes':f.stat().st_size,'sha256':hashlib.sha256(f.read_bytes()).hexdigest()})
weights=list((source/'weights').rglob('*.safetensors'));assert weights and sum(f.stat().st_size for f in weights)==4548221488
manifest=json.loads((source/'manifest.json').read_text());weight_records=[]
for f in weights:
with f.open('rb') as stream:sha=hashlib.file_digest(stream,'sha256').hexdigest()
expected=next(x['upstream_sha256'] for x in manifest['files'] if x['name']==f.name);assert sha==expected
weight_records.append({'path':str(f.resolve()),'bytes':f.stat().st_size,'sha256':sha,'matches_upstream':True})
external={'host':'8.211.154.134','checkpoint_directory':str((source/'weights').resolve()),'checkpoint_bytes':sum(f.stat().st_size for f in weights),'checkpoint_files':weight_records,'revision':'15852e8c16360a2fea060d615a32b45270f8a8fc','baseline_caches':caches,'automatic_deletion':False,'prior_caches_untouched':True}
(root/'external-caches.json').write_text(json.dumps(external,indent=2)+'\n')
reference=json.loads((source/'reference-check.json').read_text())
assert reference['passed'] and all(x['passed'] for x in reference['tests'])
assert hashlib.sha256(Path('functional/model.py').read_bytes()).hexdigest()==reference['implementation_sha256']
(root/'prior-official-reference-check.json').write_bytes((source/'reference-check.json').read_bytes())
files=list(Path('dominance').glob('*.py'))+[Path('dominance/PROTOCOL.md'),Path('dominance/README.md'),Path('tests/test_dominance.py'),Path('functional/model.py'),Path('crossqkv/fresh_samples.json')]
(root/'source-hashes.json').write_text(json.dumps({str(f):hashlib.sha256(f.read_bytes()).hexdigest() for f in files if not f.name.startswith('._')},indent=2)+'\n')
audit={'passed':True,'transitions':23,'texts':4,'link_observations':92,'primary_observations_per_metric':counts,'undefined_zero_total_per_metric':undefined,'full_attention_js_links':full_js_links,'head_sum_controls':96,'canonical_forward_relative_error':status['canonical_forward_relative_error'],'all_raw_concentration_and_masks_recomputed':True,'pooled_concentration_and_joint_summary_recomputed':True,'original_primary_summaries_unchanged':True,'sqrt_JS_scale_sensitivity_recomputed':True,'retained_baseline_cache_files':len(caches),'checkpoint_sha_matches_upstream':True,'prior_official_reference_check_passed_same_implementation':True,'prior_official_reference_tests':len(reference['tests'])}
(root/'audit.json').write_text(json.dumps(audit,indent=2)+'\n');print(json.dumps(audit,indent=2),flush=True)
included=[f for f in root.rglob('*') if f.is_file() and 'cache' not in f.relative_to(root).parts and f.name!='checksums.json']
(root/'checksums.json').write_text(json.dumps({str(f.relative_to(root)):hashlib.sha256(f.read_bytes()).hexdigest() for f in sorted(included)},indent=2)+'\n')
if __name__=='__main__':main(sys.argv[1],sys.argv[2])
+85
View File
@@ -0,0 +1,85 @@
"""Frozen-model head interventions and continuous influence concentration."""
import numpy as np
from functional.model import StreamingLM,PREFIX,rope,causal_conv,attention
def concentration(d):
"""Last axis donor head; zero total is undefined, represented by NaNs."""
d=np.asarray(d,dtype=np.float64)
if not np.isfinite(d).all() or np.any(d<0):raise ValueError('Finite nonnegative influences required')
h=d.shape[-1];total=d.sum(-1);valid=total>0
p=np.divide(d,total[...,None],out=np.zeros_like(d),where=valid[...,None]);square=np.sum(p*p,-1)
neff=np.divide(1,square,out=np.full_like(total,np.nan),where=valid)
ordered=np.sort(p,axis=-1)[...,::-1]
return {'total':total,'max_absolute':d.max(-1),'valid':valid,'effective_heads':neff,'effective_fraction':neff/h,
'concentration':np.where(valid,(square-1/h)/(1-1/h),np.nan),
'top1':np.where(valid,ordered[...,0],np.nan),'top25':np.where(valid,ordered[...,:max(1,h//4)].sum(-1),np.nan),
'top50':np.where(valid,ordered[...,:max(1,h//2)].sum(-1),np.nan),
'bottom25':np.where(valid,ordered[...,-max(1,h//4):].sum(-1),np.nan),
'heads90':np.where(valid,1+np.sum(np.cumsum(ordered,axis=-1)<.9,axis=-1),np.nan)}
def masks_from_influences(d,weak=True):
"""d [donor,T,recipient]; output masks [recipient,T,donor]."""
ranked=np.argsort(d.transpose(2,1,0),axis=-1,kind='stable');n=d.shape[0]//2
selected=ranked[...,:n] if weak else ranked[...,-n:]
mask=np.zeros_like(ranked,dtype=np.float32);np.put_along_axis(mask,selected,1,axis=-1)
return mask
def js_rows(a,b):
a=np.asarray(a,dtype=np.float64);b=np.asarray(b,dtype=np.float64);m=(a+b)/2
def term(x):return np.where(x>0,x*np.log(np.maximum(x,1e-300)/np.maximum(m,1e-300)),0)
return np.maximum(0,.5*np.sum(term(a)+term(b),axis=-1))
class InfluenceLM(StreamingLM):
capturing=False
def linear(self,x,name,rows=256):
y=super().linear(x,name,rows)
if self.capturing and (name.endswith('self_attn.o_proj') or name.endswith('linear_attn.out_proj')):
layer=int(name.split('.')[1]);nh=self.config['num_attention_heads'] if 'self_attn' in name else self.config['linear_num_value_heads']
xx=x.reshape(*x.shape[:2],nh,-1);dim=xx.shape[-1];t=self.tensors[PREFIX+name+'.weight'];od,idim=t.shape
out=np.empty((*x.shape[:2],nh,od),dtype=np.float32)
for start in range(0,od,256):
self.guard();stop=min(od,start+256);w=t.read(slice(start*idim,stop*idim)).reshape(stop-start,idim)
for head in range(nh):out[:,:,head,start:stop]=xx[:,:,head]@w[:,head*dim:(head+1)*dim].T
del w;t.evict()
err=float(np.linalg.norm(out.sum(2).astype(np.float64)-y)/max(np.linalg.norm(y.astype(np.float64)),1e-30))
if err>2e-5:raise AssertionError(('head sum mismatch',layer,err))
self.head_outputs=out;self.head_sum_errors.append({'layer':layer,'relative_l2':err})
return y
def baseline(self,ids,root):
h=self.embedding(ids);self.head_sum_errors=[]
for layer,kind in enumerate(self.config['layer_types']):
raw=h.copy();n=self.normalization(h,f'layers.{layer}.input_layernorm');self.capturing=True
out,_=self.full_attention(n,layer) if kind=='full_attention' else (self.linear_attention(n,layer),None)
self.capturing=False;heads=self.head_outputs;self.head_outputs=None
mid=raw+out;h=mid+self.mlp(self.normalization(mid,f'layers.{layer}.post_attention_layernorm'),layer)
np.savez(root/f'layer-{layer}.npz',raw=raw,out=out,heads=heads,next_raw=h)
print('baseline layer',layer,flush=True)
return h
def recipient(self,raw,layer):
h=self.normalization(raw,f'layers.{layer}.input_layernorm');c=self.config;b,t=h.shape[:2]
if c['layer_types'][layer]=='full_attention':
p=f'layers.{layer}.self_attn.';nh=c['num_attention_heads'];nk=c['num_key_value_heads'];d=c['head_dim']
q=self.linear(h,p+'q_proj').reshape(b,t,nh,2*d)[...,:d];k=self.linear(h,p+'k_proj').reshape(b,t,nk,d);v=self.linear(h,p+'v_proj').reshape(b,t,nk,d)
q=self.normalization(q,p+'q_norm');k=self.normalization(k,p+'k_norm');r=c['rope_parameters'];q,k=(rope(z,r['rope_theta'],r['partial_rotary_factor']) for z in (q,k))
k=np.repeat(k,nh//nk,axis=2);v=np.repeat(v,nh//nk,axis=2)
_,prob=attention(q,k,v)
return {'Q':q,'K':k,'V':v,'P':prob}
p=f'layers.{layer}.linear_attn.';kh=c['linear_num_key_heads'];vh=c['linear_num_value_heads'];kd=c['linear_key_head_dim'];vd=c['linear_value_head_dim']
x=causal_conv(self.linear(h,p+'in_proj_qkv'),self.small(p+'conv1d.weight')[:,0,:]);q,k,v=np.split(x,[kh*kd,2*kh*kd],axis=-1)
q=q.reshape(b,t,kh,kd);k=k.reshape(b,t,kh,kd);v=v.reshape(b,t,vh,vd)
if vh!=kh:q,k=np.repeat(q,vh//kh,axis=2),np.repeat(k,vh//kh,axis=2)
q=q/np.sqrt(np.sum(q*q,axis=-1,keepdims=True)+1e-6)/np.float32(np.sqrt(kd));k=k/np.sqrt(np.sum(k*k,axis=-1,keepdims=True)+1e-6)
return {'Q':q,'K':k,'V':v}
def intervene(self,cache,layer,masks):
# Each scenario has a full coherent token-dependent deletion mask.
removed=np.einsum('bth,thd->btd',masks,cache['heads'][0],optimize=True)
mid=cache['raw']+cache['out']-removed
nxt=mid+self.mlp(self.normalization(mid,f'layers.{layer}.post_attention_layernorm'),layer)
return self.recipient(nxt,layer+1)
+140
View File
@@ -0,0 +1,140 @@
"""Saved-data scientific analysis; no model invocation or fitting."""
import csv,json
from pathlib import Path
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from .core import concentration
def stats(x):
x=np.asarray(x,dtype=np.float64);valid=x[np.isfinite(x)]
if not valid.size:return {'count':0,'p10':None,'median':None,'p90':None,'mean':None}
q=np.quantile(valid,[.1,.5,.9]);return {'count':int(valid.size),'p10':float(q[0]),'median':float(q[1]),'p90':float(q[2]),'mean':float(valid.mean())}
def csvwrite(p,rows):
with p.open('w') as f:
w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)
def main(root):
root=Path(root);figdir=root/'figures';figdir.mkdir(exist_ok=True);status=json.loads((root/'status.json').read_text());assert status['state']=='completed'
rows=[];joint_rows=[];pool={};curves={};joint_pool={};obs={};winner=[];joint_by_layer={}
for entry in status['completed_links']:
sample=entry['sample'];source=entry['source'];data=dict(np.load(root/'raw'/f'{sample}-link-{source:02d}.npz'))
if 'single_JS' in data:
data['single_sqrtJS']=np.sqrt(data['single_JS'])
for label in ('weak_half','strong_half','random_half','all_heads'):
data['joint_'+label+'_sqrtJS']=np.sqrt(data['joint_'+label+'_JS'])
masks=data.get('mask_'+label,np.ones_like(data['mask_weak_half']))
data['individual_sum_'+label+'_sqrtJS']=np.sum(data['single_sqrtJS'].transpose(2,1,0)*masks,-1).T
for key in ('Q','K','V','QKV','JS','sqrtJS'):
if 'single_'+key not in data:continue
d=data['single_'+key][:,7:,:].transpose(1,2,0);c=concentration(d);valid=c['valid'];h=d.shape[-1]
metric={k:v.reshape(-1) for k,v in c.items() if k!='valid'}
row={'sample':sample,'source':source,'recipient':source+1,'metric':key,'source_heads':h,'recipient_attention_type':'full_attention' if entry['full_attention_recipient'] else 'linear_attention','observations':d.shape[0]*d.shape[1],'undefined_zero_total':int((~valid).sum())}
for k,v in metric.items():
pool.setdefault(key,{}).setdefault(k,[]).extend(v)
for s,z in stats(v).items():row[k+'_'+s]=z
rows.append(row)
# Raw per-observation statistics for independently reproducing figures.
for k,v in metric.items():obs.setdefault(key+'_'+k,[]).append(v.astype(np.float32))
n=d.shape[0]*d.shape[1]
for k,v in [('source',np.full(n,source)),('sample_index',np.full(n,sorted({e['sample'] for e in status['completed_links']}).index(sample))),('token',np.repeat(np.arange(7,32),d.shape[1])),('recipient_head',np.tile(np.arange(d.shape[1]),25))]:obs.setdefault(key+'_'+k,[]).append(v.astype(np.int16))
p=np.divide(d,d.sum(-1,keepdims=True),out=np.zeros_like(d),where=d.sum(-1,keepdims=True)>0);cum=np.concatenate([np.zeros((*d.shape[:2],1)),np.cumsum(np.sort(p,-1)[...,::-1],-1)],-1)
grid=np.linspace(0,1,101);cc=np.array([np.interp(grid,np.linspace(0,1,h+1),v) for v in cum[valid]])
curves.setdefault(key,[]).extend(cc)
win=np.argmax(d,-1);counts=np.bincount(win[valid],minlength=h)
winner.append({'sample':sample,'source':source,'metric':key,'most_frequent_winner_fraction':float(counts.max()/max(counts.sum(),1)),'distinct_winning_heads':int((counts>0).sum()),'head_counts':json.dumps(counts.tolist())})
for label in ('weak_half','strong_half','random_half','all_heads'):
values=data['joint_'+label+'_'+key][7:];summed=data['individual_sum_'+label+'_'+key][7:]
jr={'sample':sample,'source':source,'recipient':source+1,'metric':key,'removed':label}
for k,x in [('joint_effect',values),('sum_individual',summed)]:
for s,z in stats(x).items():jr[k+'_'+s]=z
joint_rows.append(jr);joint_pool.setdefault(key,{}).setdefault(label,[]).extend(values.ravel());joint_by_layer.setdefault((key,label,source),[]).extend(values.ravel())
csvwrite(root/'concentration-by-link.csv',rows);csvwrite(root/'joint-by-link.csv',joint_rows);csvwrite(root/'winner-identities.csv',winner)
np.savez_compressed(root/'observations.npz',**{k:np.concatenate(v) for k,v in obs.items()})
pooled={k:{m:stats(v) for m,v in metrics.items()} for k,metrics in pool.items()};joint_stats={k:{m:stats(v) for m,v in metrics.items()} for k,metrics in joint_pool.items()}
paired={}
for key,labels in joint_pool.items():
weak=np.asarray(labels['weak_half']);strong=np.asarray(labels['strong_half']);random=np.asarray(labels['random_half']);valid=weak>0
paired[key]={'weak_less_than_strong_fraction':float(np.mean(weak<strong)),'weak_less_than_random_fraction':float(np.mean(weak<random)),'zero_weak_effect_count':int((~valid).sum()),'strong_over_weak':stats(strong[valid]/weak[valid]),'random_over_weak':stats(random[valid]/weak[valid])}
full_sources=sorted({x['source'] for x in status['completed_links'] if x['full_attention_recipient']})
by_type={}
for key in pool:
src=np.concatenate(obs[key+'_source']);by_type[key]={}
for label,choose in [('full_attention',np.isin(src,full_sources)),('linear_attention',~np.isin(src,full_sources))]:
if not choose.any():continue
by_type[key][label]={m:stats(np.concatenate(obs[key+'_'+m])[choose]) for m in pool[key]}
summary={'scale_sensitivity':'sqrt(JS) added after reviewing completed primary summaries; primary JS and all raw interventions unchanged; squared divergences cannot be equated to probability mass or linear-scale effects','by_recipient_type':by_type,'full_attention_source_indices':full_sources,'paired_joint':paired,'pooling':'query7..31, per text/token/recipient-query-head; descriptive dependent observations, not independent samples','concentration':pooled,'joint':joint_stats,'counts':{'links':len(status['completed_links']),'texts':len(json.loads((root/'samples.json').read_text())),'layer_transitions':23},'sample_index_key':sorted({e['sample'] for e in status['completed_links']}),'winner_identity_file':'winner-identities.csv'}
(root/'analysis-summary.json').write_text(json.dumps(summary,indent=2,allow_nan=False)+'\n')
def save(fig,name):
for ext in ('png','pdf','svg'):fig.savefig(figdir/(name+'.'+ext),dpi=180)
plt.close(fig)
fig,axs=plt.subplots(1,2,figsize=(14,4.8),layout='constrained')
colors={'Q':'C0','K':'C1','V':'C2','QKV':'C3'}
for key in colors:
for ax,metric in zip(axs,['effective_fraction','top1']):
med=[];lo=[];hi=[]
source= np.concatenate(obs[key+'_source']);vals=np.concatenate(obs[key+'_'+metric])
for layer in range(23):
z=stats(vals[source==layer]);lo.append(z['p10']);med.append(z['median']);hi.append(z['p90'])
ax.plot(range(1,24),med,label=key,color=colors[key]);ax.fill_between(range(1,24),lo,hi,color=colors[key],alpha=.10)
axs[0].set(title='Continuous effective-head fraction (median, p10–p90)',ylabel='N_eff / number of donor heads')
axs[1].set(title='Largest donor-head influence share',ylabel='Top-1 normalized ablation effect')
for ax in axs:
for j,source in enumerate(full_sources):ax.axvspan(source+.6,source+1.4,color='gray',alpha=.08,label='Full-attention receiver' if j==0 else None)
ax.set(xlabel='Recipient layer index',ylim=(0,1.02));ax.legend();ax.grid(alpha=.2)
fig.suptitle('All 23 adjacent transitions; four texts, query positions 7–31; no training')
save(fig,'continuous_dominance')
fig,axs=plt.subplots(1,2,figsize=(13,4.8),layout='constrained');curve_rows=[]
for key in colors:
a=np.asarray(curves[key]);lo,med,hi=np.quantile(a,[.1,.5,.9],axis=0);x=np.linspace(0,1,101)
axs[0].plot(x,med,label=key,color=colors[key]);axs[0].fill_between(x,lo,hi,color=colors[key],alpha=.1)
for j,xx in enumerate(x):curve_rows.append({'metric':key,'fraction_ranked_heads':xx,'p10':lo[j],'median':med[j],'p90':hi[j]})
v=np.sort(np.asarray(pool[key]['effective_fraction']));axs[1].plot(v,np.arange(1,len(v)+1)/len(v),label=key,color=colors[key])
axs[0].plot([0,1],[0,1],':',color='gray',label='Uniform');axs[0].set(title='Influence concentration curve',xlabel='Fraction of donor heads, largest first',ylabel='Cumulative normalized single-head effects')
axs[1].set(title='Continuous effective-head fraction: empirical CDF',xlabel='N_eff / donor heads',ylabel='Fraction of observed cases')
for ax in axs:ax.set(xlim=(0,1),ylim=(0,1.02));ax.legend();ax.grid(alpha=.2)
fig.suptitle('Observation-wise ranking; dominant identities can differ; shaded p10–p90')
csvwrite(root/'concentration-curve.csv',curve_rows);save(fig,'ranked_influence_distribution')
fig,axs=plt.subplots(1,2,figsize=(14,4.8),layout='constrained')
for label,color in zip(['weak_half','strong_half','random_half','all_heads'],['C0','C3','C1','gray']):
for ax,key in zip(axs,['QKV','JS']):
selected=[r for r in joint_rows if r['metric']==key and r['removed']==label]
xs=sorted(set(r['recipient'] for r in selected));ys=[np.median(joint_by_layer[(key,label,x-1)]) for x in xs]
ax.plot(xs,np.maximum(ys,1e-12),'o-',label=label,color=color,markersize=4)
axs[0].set(title='Joint removal: balanced QKV relative effect',ylabel='Median token/head relative L2 score')
axs[1].set(title='Full-attention recipients: retrieval change',ylabel='Median token/head JS divergence (nats)')
for ax in axs:ax.set(xlabel='Recipient layer index',yscale='log');ax.legend();ax.grid(alpha=.2)
fig.suptitle('Equal-count weak/strong/random removal; token-wise masks; log display floor 1e-12')
save(fig,'joint_removal_effects')
fig,axs=plt.subplots(1,2,figsize=(13,4.8),layout='constrained')
for key,label,color in [('JS','JS divergence (squared scale)','C4'),('sqrtJS','sqrt(JS) distance','C5')]:
a=np.asarray(curves[key]);lo,med,hi=np.quantile(a,[.1,.5,.9],axis=0);x=np.linspace(0,1,101)
axs[0].plot(x,med,label=label,color=color);axs[0].fill_between(x,lo,hi,color=color,alpha=.12)
for j,xx in enumerate(x):curve_rows.append({'metric':key,'fraction_ranked_heads':xx,'p10':lo[j],'median':med[j],'p90':hi[j]})
v=np.sort(np.asarray(pool[key]['effective_fraction']));axs[1].plot(v,np.arange(1,len(v)+1)/len(v),label=label,color=color)
axs[0].plot([0,1],[0,1],':',color='gray',label='Uniform');axs[0].set(title='Retrieval influence rank curve',xlabel='Fraction of donor heads, largest first',ylabel='Cumulative normalized intervention effects')
axs[1].set(title='Sensitivity to divergence versus distance scale',xlabel='Effective donor-head fraction',ylabel='Fraction of observations')
for ax in axs:ax.set(xlim=(0,1),ylim=(0,1.02));ax.legend();ax.grid(alpha=.2)
fig.suptitle('Full-attention recipients; sqrt(JS) is post-summary scale sensitivity, not a new model run')
csvwrite(root/'concentration-curve.csv',curve_rows);save(fig,'retrieval_scale_sensitivity')
lines=['# 上游注意力头对下一层 Q/K/V 的影响集中度','', '实测全部23个相邻层连接、4条既有中英文文本各32 token。主统计取query7–31,按文本/token/接收query头分别计算,再汇总。不是独立样本的显著性检验。','', '影响是移除上游一个头后,下一层Q/K/V向量的相对L2变化;重新计算中间MLP/残差/归一化。各头影响归一化仅构成消融影响分布,不是天然可相加的贡献概率。','', '| 对象 | 有效头比例中位数 [P10,P90] | 最大头份额中位数 | 前25%头份额中位数 | 最小25%头份额中位数 | 90%影响所需头数中位数 |','|---|---:|---:|---:|---:|---:|']
for k in ('Q','K','V','QKV','JS','sqrtJS'):
if k not in pooled:continue
z=pooled[k];a=z['effective_fraction'];lines.append(f"| {k} | {a['median']:.3f} [{a['p10']:.3f},{a['p90']:.3f}] | {z['top1']['median']:.1%} | {z['top25']['median']:.1%} | {z['bottom25']['median']:.1%} | {z['heads90']['median']:.1f} |")
lines+=['','sqrtJS为JS距离尺度敏感性分析:在初次完整汇总后增加,原始消融和原JS主结果不变。JS散度近似平方尺度,归一化后会放大强弱差距;JS影响份额不是注意力概率质量份额。','', '按接收层类型分层(避免总体分布混合不同机制):','', '| 接收层类型 | Q有效头比例中位数 | K | V | QKV |','|---|---:|---:|---:|---:|']
for label in ('linear_attention','full_attention'):
lines.append('| '+label+' | '+' | '.join(format(by_type[k][label]['effective_fraction']['median'],'.3f') for k in ('Q','K','V','QKV'))+' |')
lines+=['','QKV是三个相对变化平方的均值再开根号,避免混加不同Q/K/V尺度;JS仅普通注意力接收层有。普通注意力GQA的K/V复制到query头索引用于配对,不是额外独立KV头。','', '| 联合移除 | QKV相对影响中位数 [P10,P90] | 检索JS中位数 [P10,P90] |','|---|---:|---:|']
for label in ('weak_half','strong_half','random_half','all_heads'):
a=joint_stats['QKV'][label];b=joint_stats['JS'][label];lines.append(f"| {label} | {a['median']:.5f} [{a['p10']:.5f},{a['p90']:.5f}] | {b['median']:.6f} [{b['p10']:.6f},{b['p90']:.6f}] |")
lines+=['', '配对观测:QKV弱半数的实际联合影响小于强半数的比例为'+format(paired['QKV']['weak_less_than_strong_fraction'],'.1%')+';强/弱影响比中位数为'+format(paired['QKV']['strong_over_weak']['median'],'.3f')+'。这是逐观测比值的中位数,不是两个总体中位数之比。弱效应为零的观测另计,不做除法。', '', '联合实验的弱/强/随机半数头,在各token、各接收头上分别选择,形成完整序列再重算。排名依据单头QKV影响,同样用于JS;它是输入自适应诊断,不是免费可用的剪枝策略。线性注意力的卷积和普通注意力的QK可能传播跨token影响。所有上游头移除仍保留残差背景,不能把它称为删除全部上游信息。', '', '连续指标:N_eff=1/Σp²;有效头比例=N_eff/H;C=(Σp²−1/H)/(1−1/H)。全零总影响时集中度未定义,原始数组保留NaN并在统计时排除、另计数量。单头相对L2影响在做头间占比归一化之前的总和及最大值均保留,避免把微小效应中的集中误认作重要。字段max_absolute指最大无符号相对效应,并非隐藏坐标中的未归一化L2;total是单头效应之和,真正全头联合效果另测。', '', '联合实验中保存的单头影响之和仅为按query掩码加权的参考。单头消融移除整段序列的一个头,联合掩码则可跨位置变化;二者的差不能单独解释成纯非线性交互,因为时间支持也不同。应直接比较实际弱/强/随机联合效果。', '', '## 文件与限制','', '`raw/*.npz`保留每次单头影响、联合影响、相应单头影响之和、删除掩码及空操作对照;`observations.npz`保留逐观测连续指标及索引;CSV和JSON为全部图表源表。原模型权重和大基线缓存继续保留在服务器。','', '只测短文本上的局部下一层作用;不代表全LM质量、可直接删头、所有输入普遍集中,或相似头可互相替代。所有头贡献可能是广泛分布的;报告不以发现稀疏为成功条件。','',f"CPU测量耗时{status['elapsed_seconds']:.1f}秒,峰值RSS{status['peak_rss_kib']/1024:.1f} MiB;无训练、GPU或清理。"]
(root/'REPORT.md').write_text('\n'.join(lines)+'\n')
print((root/'REPORT.md').read_text())
if __name__=='__main__':
import sys
main(sys.argv[1])
+84
View File
@@ -0,0 +1,84 @@
"""All adjacent layers, input-dependent influence distributions; CPU only."""
import argparse,json,time,resource,hashlib,traceback
from pathlib import Path
import numpy as np
from tokenizers import Tokenizer
from functional.model import StreamingLM
from .core import InfluenceLM,concentration,masks_from_influences,js_rows
def dump(path,data):path.write_text(json.dumps(data,indent=2,allow_nan=False)+'\n')
def distances(base,changed):
out={}
for key in ('Q','K','V'):
a=base[key].astype(np.float64);b=changed[key].astype(np.float64)
out[key]=np.linalg.norm(b-a,axis=-1)/np.maximum(np.linalg.norm(a,axis=-1),1e-12)
out['QKV']=np.sqrt(sum(out[k]**2 for k in ('Q','K','V'))/3)
if 'P' in base:out['JS']=js_rows(base['P'],changed['P']).transpose(0,2,1)
return out
def link(lm,cache,layer,path,seed):
started=time.monotonic();base=lm.recipient(cache['next_raw'],layer+1);hs=cache['heads'].shape[2];t=cache['raw'].shape[1];hr=base['Q'].shape[2]
# Whole donor head across the full sequence is the single-ablation intervention.
singles={k:[] for k in ('Q','K','V','QKV')+ (('JS',) if 'P' in base else ())}
for start in range(0,hs,4):
index=list(range(start,min(start+4,hs)));masks=np.zeros((len(index),t,hs),dtype=np.float32)
for n,h in enumerate(index):masks[n,:,h]=1
scores=distances(base,lm.intervene(cache,layer,masks))
for k,v in scores.items():singles[k].extend(v)
singles={k:np.asarray(v,dtype=np.float32) for k,v in singles.items()}
# Identical cardinality weak/strong/random removals, ranking by balanced QKV influence.
# One coherent full-sequence mask per recipient head; only that head's output scored.
rank=singles['QKV'];rng=np.random.default_rng(seed)
weak=masks_from_influences(rank,True);strong=masks_from_influences(rank,False)
random=np.zeros_like(weak)
for r in range(hr):
for q in range(t):random[r,q,rng.choice(hs,hs//2,replace=False)]=1
joint={};sum_individual={}
for label,masks in [('weak_half',weak),('strong_half',strong),('random_half',random),('all_heads',np.ones_like(weak))]:
values={k:[] for k in singles}
for start in range(0,hr,4):
stop=min(start+4,hr);scores=distances(base,lm.intervene(cache,layer,masks[start:stop]))
for k,v in scores.items():
for n,r in enumerate(range(start,stop)):values[k].append(v[n,:,r])
for k,v in values.items():
joint[label+'_'+k]=np.asarray(v,dtype=np.float32).T
sum_individual[label+'_'+k]=np.sum(singles[k].transpose(2,1,0)*masks,axis=-1).T
null=distances(base,lm.intervene(cache,layer,np.zeros((1,t,hs),dtype=np.float32)))
if max(float(np.max(v)) for v in null.values())>2e-5:raise AssertionError('Null intervention changed recipient')
payload={'single_'+k:v for k,v in singles.items()};payload.update({'joint_'+k:v for k,v in joint.items()});payload.update({'individual_sum_'+k:v for k,v in sum_individual.items()})
payload.update({'mask_weak_half':weak,'mask_strong_half':strong,'mask_random_half':random})
payload.update({'null_'+k:v for k,v in null.items()})
np.savez_compressed(path,**payload)
return {'source':layer,'recipient':layer+1,'source_heads':hs,'recipient_query_heads':hr,'full_attention_recipient':'P' in base,'elapsed_seconds':time.monotonic()-started,'null_max':max(float(np.max(v)) for v in null.values())}
def main():
p=argparse.ArgumentParser();p.add_argument('--source',type=Path,required=True);p.add_argument('--out',type=Path,required=True);p.add_argument('--seconds',type=int,default=7200);a=p.parse_args()
a.out.mkdir(parents=True,exist_ok=False);(a.out/'cache').mkdir();(a.out/'raw').mkdir();started=time.monotonic()
protocol={'scope':'all 23 adjacent layer transitions; source attention head contribution to next effective Q/K/V','samples':'4 previously authored zh/en texts, first32 tokens, descriptive','primary_queries':list(range(7,32)), 'influence':'L2 change / baseline token recipient-head L2; QKV score sqrt(mean of three squared relative changes))','linear_QK':'after causal convolution/SiLU and delta-rule L2 normalization; Q additionally divided by sqrt(key dim)','full_QK':'QK norm and partial RoPE applied; K/V repeated to query heads for indexing (not independent KV observations)','single_ablation':'remove complete source head projected output at all tokens; recompute source postattention normalization, MLP, residual and next input normalization','joint_ablation':'weak/strong/random half and all attention heads; one coherent token-varying removal mask for each recipient query head; ranking uses QKV single effects; no fitting','continuous':'effective heads=1/sum(p^2); fraction=effective/H; concentration=(sum(p^2)-1/H)/(1-1/H)','zero_total':'undefined concentration (NaN arrays), count explicitly','cost_budget_seconds':a.seconds,'no_training':True,'keep_all_weights_and_caches':True,'limitations':['not final LM quality or pruning proof','individual effects not additive; normalized scores not true contribution probabilities','token-varying masks are input-specific diagnostic and not a deployable fixed head subset','linear attention does not have an ordinary softmax probability matrix','Q/K/V scales handled separately; combined QKV is a declared balanced relative-effect score']}
dump(a.out/'protocol.json',protocol);status={'state':'running','completed_links':[]};dump(a.out/'status.json',status)
try:
lm=InfluenceLM(a.source/'weights',json.loads((a.source/'model_config.json').read_text()),seconds=a.seconds)
samples=json.loads(Path('crossqkv/fresh_samples.json').read_text())['samples'];tok=Tokenizer.from_file(str(a.source/'tokenizer.json'));controls=[]
for si,s in enumerate(samples):
lm.guard();s['token_ids']=tok.encode(s['text']).ids[:32];ids=np.array([s['token_ids']],dtype=np.int64);cache=a.out/'cache'/s['id'];cache.mkdir()
final=lm.baseline(ids,cache);np.save(cache/'final.npy',final)
for x in lm.head_sum_errors:controls.append({'sample':s['id'],**x})
if si==0:
reference,_=StreamingLM.forward(lm,ids);normalized=lm.normalization(final,'norm');err=float(np.linalg.norm(normalized-reference)/max(np.linalg.norm(reference),1e-30));assert err<2e-5;status['canonical_forward_relative_error']=err
dump(a.out/'head-sum-controls.json',controls);dump(a.out/'samples.json',samples)
for layer in range(23):
target=a.out/'raw'/f'{s["id"]}-link-{layer:02d}.npz'
with np.load(cache/f'layer-{layer}.npz') as data:loaded={k:data[k] for k in data.files}
info=link(lm,loaded,layer,target,31000+si*100+layer)
del loaded
status['completed_links'].append({'sample':s['id'],**info});status['elapsed_seconds']=time.monotonic()-started;dump(a.out/'status.json',status)
print('completed',s['id'],layer,'seconds',round(info['elapsed_seconds'],2),flush=True)
status.update(state='completed',elapsed_seconds=time.monotonic()-started,peak_rss_kib=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss);dump(a.out/'status.json',status)
except BaseException as e:
status.update(state='failed',error=repr(e),elapsed_seconds=time.monotonic()-started);dump(a.out/'status.json',status);raise
if __name__=='__main__':main()
+42
View File
@@ -0,0 +1,42 @@
# Paired task-finetuning comparison (registered before reading finetuned effects)
Primary checkpoint: Avifenesh/gdn-beta-gate-qwen3.5-2b-grpo,
HF revision038d8be9bd0edd3883fa019651b02bdf65609468, pure lora/seed0,
step150 after shared40-step warmup. GSM8K GRPO, not SFT. Selected by smallest
seed index before observing concentration, not by benchmark score or our metric.
No gate01/gate02 arm or architecture changes. Exact base revision matches retained
Qwen/Qwen3.5-2B15852e8c16360a2fea060d615a32b45270f8a8fc.
Download existing18.9MB F32 LoRA tensors, verify official file SHA. All144 tensors
must form72 A/B pairs on the4 declared GDN projections of18 linear-attention
layers, rank16 alpha32. Apply FP32 effective W +2BA in streamed row chunks, also
when decomposing source output heads. Do not quantize merged weights, mutate or
save over base weights, execute foreign .pt files, train or use GPU. Validate
against separate base-output +2B(Ax) forward and check head sums/null masks.
Primary comparison exactly matches the reported8.931822/16 statistic: all six
ordinary attention receivers3/7/11/15/19/23, previous-layer16 donor output heads,
all32 tokens computed, query7..31, original4 plain-text inputs and same token IDs.
Reuse corresponding immutable base single-ablation arrays, recompute FT baselines
and all16 single donor removals, source MLP/residual/recipient normalization exact.
Use the same sqrt(JS) distance influence, normalized shares and N_eff=1/sum(p²).
Preserve JS divergence as a sensitivity row; no change of ranking or threshold.
All4800 per-token/query-head observations are paired. No new joint-mask search:
the requested statistic depends on single removals, not the previous joint tests.
Secondary task-conditioned comparison: first4 original GSM8K test questions with
at least32 base-tokenizer tokens (length selection only, before model effects),
question-only plain text, first32 tokens. Freeze original author repository commit,
JSONL SHA, item indices, question hashes and exact token IDs. No answers, generation,
chat-template change or accuracy claim. Compute both base and FT on these same
questions; never compare old general-text base to new GSM8K FT as if paired.
Report overall median/P10/P90, paired differences, per receiver layer and per text,
strong/weak-quartile shares, and dominant donor identity agreement. No iid-token
p-values, no claim over training seeds (one fixed trained seed), no proof of
GSM8K accuracy improvement or long-context behavior. Positive, negative and near
zero changes all count as results. Source cohort remains4+4 short texts.
All model work/tests/plots on authorized CPU server8.211.154.134, bounded7200s.
Preserve all base/FT weights, adapters and caches; no automatic cleanup. Save raw
arrays, source provenance, SHA manifests, fixed chart gallery and reviewable PR.
+61
View File
@@ -0,0 +1,61 @@
# Existing GSM8K fine-tune: paired head-concentration comparison
First restore the original charts through [the fixed figure gallery](../docs/FIGURE_GALLERY.md).
The original 8.931822/16, P10=5.784081 and P90=11.672658 refer to sqrt(JS)
influences of all16 prior-layer heads on the six full-attention receivers.
Selected release: [Avifenesh/gdn-beta-gate-qwen3.5-2b-grpo](https://huggingface.co/Avifenesh/gdn-beta-gate-qwen3.5-2b-grpo),
pinned038d8be9bd0edd3883fa019651b02bdf65609468, pure lora/seed0. The publisher
records GSM8K GRPO from a shared warmup, rank16 alpha32, exact same original
Qwen3.5-2B revision. This is extra RL fine-tuning of the post-trained release,
not pretraining-to-SFT, and not a beta-gate architecture modification. Our seed
choice is fixed before seeing effects; no new training is performed.
`lora.py` validates all144 tensors/72 pairs, maps only declared GDN projections,
and provides read-only FP32 effective row chunks W+2BA. Source head decomposition
uses the same effective weights. `ExplicitLoRA` adds2B(Ax) independently to the
base projection as a numerical reference. No BF16 re-rounding is introduced:
the author's training code also warns that rounding merged increments can erase
small LoRA changes. Author configuration commit/SHA and public HF metadata are
saved alongside the protocol; foreign training code and pickle checkpoints are
not executed.
`run.py` reuses the exact original single-ablation arrays for the original cohort,
then computes matched finetuned states; it computes both models on4 question-only
GSM8K test prefixes as a separate cohort. Every input has32 tokens. All16 donor
heads, six receiver layers andquery7..31 remain identical to the original metric.
The task corpus is the canonical author's test JSONL at a fixed Git commit, and
selection uses only the first4 items with at least32 tokenizer tokens. All item
indices, question hashes and token IDs are recorded; answers are not model inputs.
`report.py` generates paired CDFs, per-layer medians/quantiles, paired change
histograms, raw observations and tables. `audit.py` independently reconstructs
effective-head counts via(sum d)^2/sum(d^2), checks pairing, exact old baselines,
head sums, null masks, adapter/dataset/base SHA and retained external caches.
`tests/test_finetune_compare.py` checks streamed row arithmetic, an independent
low-rank forward and head decomposition, plus exact zero-scale restoration.
No iid-token p-values, training-seed generalization, GSM8K accuracy result,
long-context claim, pruning recommendation or functional-duplicate claim.
The paired delta median is distinguished from the difference of pooled medians.
All weights, adapters and caches remain on the authorized CPU server until user
explicit deletion. Git stores all raw influence arrays, not the model/adapter.
Remote workflow on8.211.154.134:
```
OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 venv/bin/python -B -m unittest tests.test_finetune_compare -v
OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 venv/bin/python -B -m finetune_compare.run --source runs/cpu-qwen35-2b --parent runs/head-dominance --assets runs/finetune-head-comparison --out runs/finetune-head-comparison/NEW_EXPERIMENT
venv/bin/python -B -m finetune_compare.report runs/finetune-head-comparison/NEW_EXPERIMENT
venv/bin/python -B -m finetune_compare.audit runs/finetune-head-comparison/NEW_EXPERIMENT runs/head-dominance runs/finetune-head-comparison runs/cpu-qwen35-2b
```
The supplemental QKV field is measured only on the same six full-attention
receivers, so its baseline must not be confused with the older76.0% pooled
QKV effective-head fraction across all23 adjacent transitions. The gallery
preserves that original table separately; the requested8.931822 metric uses
exactly the matching six receivers in both studies.
The audit also records all72 low-rank update Frobenius norms (via small Gram
matrices) and final pre-normalization residual changes per text. These separate
a stable concentration statistic from an accidentally inactive adapter. Residual
changes are not logit distributions, accuracy differences or capability scores.
View File
+74
View File
@@ -0,0 +1,74 @@
"""Independent paired effective-head, source, preservation and delivery checks."""
import json,hashlib,sys
from pathlib import Path
import numpy as np
def sha(path):
with Path(path).open('rb') as f:return hashlib.file_digest(f,'sha256').hexdigest()
def main(root,parent,assets,source):
root,parent,assets,source=map(Path,[root,parent,assets,source]);status=json.loads((root/'status.json').read_text());assert status['state']=='completed' and len(status['links'])==96
samples=json.loads((root/'samples.json').read_text());assert set(samples)=={'legacy','gsm8k'} and all(len(v)==4 for v in samples.values());assert all(len(s['token_ids'])==32 for ss in samples.values() for s in ss)
assert status['explicit_lora_forward_relative_error']<1e-4;rawstats={};expected=set();obs=dict(np.load(root/'observations.npz'));summary=json.loads((root/'summary.json').read_text())
def check(x,record):
x=np.asarray(x,dtype=np.float64);x=x[np.isfinite(x)];assert record['count']==len(x)
for name,value in zip(('p10','median','p90','mean'),[*np.quantile(x,[.1,.5,.9]),x.mean()]):np.testing.assert_allclose(record[name],value,atol=1e-8,rtol=1e-6)
for cohort,ss in samples.items():
for role in ('base','finetuned'):
for sample in ss:
for layer in (2,6,10,14,18,22):
name=f'{cohort}-{role}-{sample["id"]}-{layer:02d}.npz';expected.add(name);d=dict(np.load(root/'raw'/name))
for key in ('Q','K','V','QKV','JS'):
assert d['single_'+key].shape==(16,32,8) and np.isfinite(d['single_'+key]).all() and np.min(d['single_'+key])>=0
assert np.max(d['null_'+key])<2e-5
if cohort=='legacy' and role=='base':
with np.load(parent/'raw'/f'{sample["id"]}-link-{layer:02d}.npz') as original:
for key in d:np.testing.assert_array_equal(d[key],original[key])
for metric,impacts in [('distance',np.sqrt(d['single_JS'])),('divergence',d['single_JS']),('QKV',d['single_QKV'])]:
x=impacts[:,7:,:].transpose(1,2,0).astype(np.float64);total=x.sum(-1);den=np.sum(x*x,-1);assert np.all(den>0)
neff=total*total/den
rawstats.setdefault((cohort,role,metric),[]).append(neff.ravel())
assert expected=={f.name for f in (root/'raw').glob('*.npz')}
for cohort in samples:
for metric in ('distance','divergence','QKV'):
for role in ('base','finetuned'):
x=np.concatenate(rawstats[(cohort,role,metric)]);assert len(x)==4800
np.testing.assert_allclose(obs['__'.join((cohort,role,metric,'effective_heads'))],x,rtol=1e-8,atol=1e-8)
check(x,summary[cohort][metric][role]['effective_heads'])
before=np.concatenate(rawstats[(cohort,'base',metric)]);after=np.concatenate(rawstats[(cohort,'finetuned',metric)]);check(after-before,summary[cohort][metric]['paired']['effective_heads_delta'])
base=summary['legacy']['distance']['base']['effective_heads'];np.testing.assert_allclose([base[x] for x in ('median','p10','p90')],[8.93182211792415,5.7840811612328125,11.67265834734814],rtol=1e-10)
controls=json.loads((root/'head-sum-controls.json').read_text());assert len(controls)==288 and all(c['relative_l2']<2e-5 for c in controls)
refs=json.loads((root/'baseline-references.json').read_text());assert len(refs)==24 and all(sha(v['source'])==v['sha256'] for v in refs)
assert sha(assets/'adapter.safetensors')=='93a3f43a4356f84da0d13ecc622fee13e41ba15d237cdaad6094f243899c62d6'
dataset=json.loads((root/'gsm8k-source.json').read_text());assert sha(assets/'gsm8k-test.jsonl')==dataset['sha256']
oldweights=list((source/'weights').glob('*.safetensors'));assert len(oldweights)==1
base_sha=sha(oldweights[0]);assert base_sha=='aa33250c4fc64891ddfaba3a314fd9542ea371843c387178b425fbcc5ed680b1'
from pilot.tensors import load_tensors
import re
tensors=load_tensors(assets);pairs={}
for name,t in tensors.items():
stem,which=name.split('.lora_');pairs.setdefault(stem,{})[which[0]]=t.read().reshape(t.shape).copy();t.evict()
updates=[]
for name,pair in pairs.items():
a=pair['A'].astype(np.float64);b=pair['B'].astype(np.float64)
norm2=4*float(np.sum((b.T@b)*(a@a.T).T))
updates.append({'module':name,'delta_frobenius':float(np.sqrt(max(norm2,0))),'A_nonzero':int(np.count_nonzero(a)),'B_nonzero':int(np.count_nonzero(b))})
assert len(updates)==72 and any(x['delta_frobenius']>0 for x in updates)
(root/'weight-update-summary.json').write_text(json.dumps({'scale':2,'modules':updates,'nonzero_update_modules':sum(x['delta_frobenius']>0 for x in updates),'norm_identity':'||2BA||_F^2 = 4 trace((B^T B)(A A^T))'},indent=2)+'\n')
changes=[]
for cohort,ss in samples.items():
for sample in ss:
basefile=parent/'cache'/sample['id']/'final.npy' if cohort=='legacy' else root/'cache'/f"{cohort}-base-{sample['id']}"/'final.npy'
ftfile=root/'cache'/f"{cohort}-finetuned-{sample['id']}"/'final.npy'
before=np.load(basefile).astype(np.float64);after=np.load(ftfile).astype(np.float64)
changes.append({'cohort':cohort,'sample':sample['id'],'final_pre_norm_residual_relative_l2':float(np.linalg.norm(after-before)/np.linalg.norm(before))})
assert any(x['final_pre_norm_residual_relative_l2']>0 for x in changes)
(root/'hidden-state-changes.json').write_text(json.dumps({'definition':'final residual before final RMSNorm, not logits, accuracy or LM quality','changes':changes},indent=2)+'\n')
caches=[{'path':str(p.resolve()),'bytes':p.stat().st_size,'sha256':sha(p)} for p in sorted((root/'cache').rglob('*')) if p.is_file()]
assert len(caches)==300
(root/'external-caches.json').write_text(json.dumps({'host':'8.211.154.134','base_weights':str(oldweights[0].resolve()),'base_sha256':base_sha,'adapter_path':str((assets/'adapter.safetensors').resolve()),'adapter_sha256':sha(assets/'adapter.safetensors'),'caches':caches,'automatic_deletion':False},indent=2)+'\n')
files=list(Path('finetune_compare').glob('*.py'))+[Path('finetune_compare/PROTOCOL.md'),Path('tests/test_finetune_compare.py'),Path('dominance/core.py'),Path('dominance/run.py'),Path('functional/model.py')]
(root/'source-hashes.json').write_text(json.dumps({str(f):sha(f) for f in files},indent=2)+'\n')
proof={'passed':True,'links':96,'paired_observations_per_cohort_metric':4800,'legacy_baseline_exact':True,'effective_head_formula_independently_recomputed':True,'head_sum_checks':288,'explicit_lora_forward_relative_error':status['explicit_lora_forward_relative_error'],'adapter_sha_verified':True,'base_sha_verified':True,'dataset_sha_verified':True,'retained_cache_files':len(caches),'nonzero_update_modules':sum(x['delta_frobenius']>0 for x in updates),'nonzero_hidden_state_changes_verified':True}
(root/'audit.json').write_text(json.dumps(proof,indent=2)+'\n');print(json.dumps(proof,indent=2),flush=True)
included=[p for p in root.rglob('*') if p.is_file() and 'cache' not in p.relative_to(root).parts and p.name!='checksums.json'];(root/'checksums.json').write_text(json.dumps({str(p.relative_to(root)):sha(p) for p in sorted(included)},indent=2)+'\n')
if __name__=='__main__':main(*sys.argv[1:])
@@ -0,0 +1,12 @@
{
"source_repository": "https://github.com/avifenesh/gdn-beta-gate",
"source_revision": "f12f61f24ebe5997aac58667f413dcd1dcd96f54",
"lora_configuration_path": "src/gdn_gate/broad/arms.py",
"lora_configuration_sha256": "fc5b8de096eaa259ab166b8083bb774f9e14859d566ce82ea15986cc8d6eb5b5",
"verified_fields": [
"LoraConfig r=rank",
"lora_alpha=2*rank",
"use_rslora not enabled"
],
"effective_scale": 2
}
+38
View File
@@ -0,0 +1,38 @@
93a3f43a4356f84da0d13ecc622fee13e41ba15d237cdaad6094f243899c62d6 lora/seed0/adapter.safetensors
b8d4737a5b940bcdfed72258600227a89f883dc863e9724bf84e457b46a53703 lora/seed0/adapter_meta.json
63d54e1c2f6bf7d07ca0f6e83a3299bd4b6d00740919bc7cae0b422af05a828e lora/seed1/adapter.safetensors
f8be6c4218876b7b12a47945cafe18fcc27d59ff06447db6d3e5b21f0bb9fc29 lora/seed1/adapter_meta.json
702b764e2c39b3529914dac1547148ef2f462d9ee04e256201e79f00b20ccc62 lora/seed2/adapter.safetensors
9acee331b9383f49a81cfc057163e034f06ea1ba4b8167fea441f0fbfd490f94 lora/seed2/adapter_meta.json
7dbf35899fe1186453e599ad8c7a85c56b7fad3d630e371ca026a1e95da2c5a7 lora/seed3/adapter.safetensors
b5bfbefa8ce6b428feea761c39a148f003bf02396ca6e01b68abfba2ab3f71af lora/seed3/adapter_meta.json
a5cb1e7fa74dff467bd7f163e1db23d30ef8b1a1c935cfa55dcc8cd1b39082a7 lora/seed4/adapter.safetensors
23a6c3f198978e79014361a326af20ec364ea266cf9b5e9ced4c9da06feab30e lora/seed4/adapter_meta.json
d513d499dfd409da88b3db7da025ba9872fb48ec92d6b29bc2ce7a092a69745d lora/seed5/adapter.safetensors
9384d0b4ce4cec6b3dc15756fb4d46c5625a4dacd3805af728fc37b89627d0ed lora/seed5/adapter_meta.json
fda9b4c15d283ef8ee778c4416d69b12e1922527ea330bfc67bab5cde1b6741a gate01/seed0/adapter.safetensors
131e60bc768412f4d344e5b17cbc811f35d149aad0c328bc6503646513bbd8fc gate01/seed0/adapter_meta.json
6ada79d07414641bed58d74fd23090937abcf52337e75e8f06483d502fa64c57 gate01/seed1/adapter.safetensors
0350240ed838a93a26f406ef0d63f29ced21ea2284c9430d07aefccd30f8d924 gate01/seed1/adapter_meta.json
a9359e3f3be68468604f9bf93f20f4b65114084f3fc6a3c13363e7062c4cf547 gate01/seed2/adapter.safetensors
17fa2e876770ec636f8a0a0eb0b3f7b58c91a5f6f9910c09c38c593d856b035f gate01/seed2/adapter_meta.json
a2d0c27fee0263c9a8152e0849975edefedc9d10061bbf789a3ead223db8703c gate01/seed3/adapter.safetensors
4da32ea52fe6e7c2a0a8858e4d3255540fcc7adf18a7ab2ce9fd3164e4bb0a05 gate01/seed3/adapter_meta.json
810b8f8d6147af3620cf08d2cf575c0eb2b0134ae0253a93ceeae5be9dca8695 gate01/seed4/adapter.safetensors
f943fc6874af4e4b24763ee6e0cf6e737bc62720045190441d0b33dd561a439f gate01/seed4/adapter_meta.json
b34e8d999612415c7395f341633ff3d2365a020b9e27b7e371c5f80f0105a486 gate01/seed5/adapter.safetensors
98983ecbf303bf1b10e11c816f850db13af8a0ca5ff2e4efd121f7fd70262918 gate01/seed5/adapter_meta.json
1fc5a4a4392c35820c26e24d0075824b3426c4a77f3119713b4a1e577d31df5b gate02/seed0/adapter.safetensors
0a17ea0542fb52751d0e628985f8d07240a3ccc4b44a7e2c970e7029c00f6c3f gate02/seed0/adapter_meta.json
b742f4ffed0e293f27e4646c364a85ae359a3eae1690d3840e531dca7fba9cd8 gate02/seed1/adapter.safetensors
4b6c7bf77edf3049ca904863d59d4d3bfdbe1d0b1b3f563b7fd3bea7f179f97c gate02/seed1/adapter_meta.json
dc36c27a98379535007f2df798953624b6a67f0677bd41dec42349f8ce868afa gate02/seed2/adapter.safetensors
20009502b1bd6aa9c67b509b77eac0aa0d367af7f347caf4d05c7a51367b8f61 gate02/seed2/adapter_meta.json
1dcb6132afeec8101daf9a3fd73d42141fb871bff11fff28069f238dcff6afd0 gate02/seed3/adapter.safetensors
518289370e0eb9fc064c3226c2b3811f94cec180a9ae366a026f30cf1d3a3131 gate02/seed3/adapter_meta.json
5b97b0601585925c19bf849ecb11ad68597d1b0d55551b917ec0f5091f85c2ff gate02/seed4/adapter.safetensors
8419e8e22aa583f97e570950baf37e7c6370856b7cacefaf9c5ebeb0ea4f731c gate02/seed4/adapter_meta.json
3f944a6d210958de5840e5b76e263f2105b9f49d15b9ab505950c2b29a5343af gate02/seed5/adapter.safetensors
94d9c1e202f7962da61fa060d27941bbef7ff3d23ca5548f5d73fb6f5ac39aac gate02/seed5/adapter_meta.json
9108bce2acfcc3ccd38d0dfae67ac33253b95bdc94133bd25deb4daa45d41700 warmup/seed0/adapter.safetensors
d2d4346179104830410be9d2776d79983481503daeb5c8383e2a062de43714ef warmup/seed0/adapter_meta.json
+379
View File
@@ -0,0 +1,379 @@
{
"_id": "6accb5a881b0c228f413b5e5",
"id": "Avifenesh/gdn-beta-gate-qwen3.5-2b-grpo",
"private": false,
"pipeline_tag": "text-generation",
"library_name": "pytorch",
"tags": [
"pytorch",
"lora",
"gated-deltanet",
"qwen3.5",
"beta-gate",
"grpo",
"reasoning",
"math",
"safetensors",
"research",
"text-generation",
"en",
"dataset:openai/gsm8k",
"base_model:Qwen/Qwen3.5-2B",
"base_model:adapter:Qwen/Qwen3.5-2B",
"license:apache-2.0",
"region:us"
],
"downloads": 0,
"likes": 2,
"modelId": "Avifenesh/gdn-beta-gate-qwen3.5-2b-grpo",
"author": "Avifenesh",
"sha": "038d8be9bd0edd3883fa019651b02bdf65609468",
"lastModified": "2026-11-09T19:45:55.000Z",
"gated": false,
"disabled": false,
"widgetData": [
{
"text": "Hi, what can you help me with?"
},
{
"text": "What is 84 * 3 / 2?"
},
{
"text": "Tell me an interesting fact about the universe!"
},
{
"text": "Explain quantum computing in simple terms."
}
],
"model-index": null,
"config": {},
"cardData": {
"license": "apache-2.0",
"base_model": "Qwen/Qwen3.5-2B",
"base_model_relation": "adapter",
"library_name": "pytorch",
"pipeline_tag": "text-generation",
"language": [
"en"
],
"datasets": [
"openai/gsm8k"
],
"tags": [
"lora",
"gated-deltanet",
"qwen3.5",
"beta-gate",
"grpo",
"reasoning",
"math",
"safetensors",
"research"
]
},
"siblings": [
{
"rfilename": ".gitattributes",
"blobId": "a6344aac8c09253b3b630fb776ae94478aa0275b",
"size": 1519
},
{
"rfilename": "README.md",
"blobId": "916419ce9530318d51d71325023fb2a5024475f0",
"size": 6527
},
{
"rfilename": "SHA256SUMS",
"blobId": "cc8927482e300cb79fed740be333a8ac5639386c",
"size": 3700
},
{
"rfilename": "gate01/seed0/adapter.safetensors",
"blobId": "86a05f3f118a88940a9122fab59a8e7db73d4b4f",
"size": 21293968,
"lfs": {
"sha256": "fda9b4c15d283ef8ee778c4416d69b12e1922527ea330bfc67bab5cde1b6741a",
"size": 21293968,
"pointerSize": 133
}
},
{
"rfilename": "gate01/seed0/adapter_meta.json",
"blobId": "0652fd0ab9647ed184e2c65a670da74de1a24a4e",
"size": 661
},
{
"rfilename": "gate01/seed1/adapter.safetensors",
"blobId": "596ed265e665aea6f674b81eecfdaaada202be45",
"size": 21293968,
"lfs": {
"sha256": "6ada79d07414641bed58d74fd23090937abcf52337e75e8f06483d502fa64c57",
"size": 21293968,
"pointerSize": 133
}
},
{
"rfilename": "gate01/seed1/adapter_meta.json",
"blobId": "934875448487af7efe63e3eae775b24d2d388964",
"size": 661
},
{
"rfilename": "gate01/seed2/adapter.safetensors",
"blobId": "6413c056f06232ad2ca3d513fa44cd01a90d251b",
"size": 21293968,
"lfs": {
"sha256": "a9359e3f3be68468604f9bf93f20f4b65114084f3fc6a3c13363e7062c4cf547",
"size": 21293968,
"pointerSize": 133
}
},
{
"rfilename": "gate01/seed2/adapter_meta.json",
"blobId": "abc653d6a65aa8b3b1f2a18aaf12dc1260409573",
"size": 661
},
{
"rfilename": "gate01/seed3/adapter.safetensors",
"blobId": "f17c2715463cadb293f36a0fc2c15fb0542990a6",
"size": 21293968,
"lfs": {
"sha256": "a2d0c27fee0263c9a8152e0849975edefedc9d10061bbf789a3ead223db8703c",
"size": 21293968,
"pointerSize": 133
}
},
{
"rfilename": "gate01/seed3/adapter_meta.json",
"blobId": "f511293207bf322ce11a4c26dc83cc57b20edf52",
"size": 661
},
{
"rfilename": "gate01/seed4/adapter.safetensors",
"blobId": "32503f87fd062bf0631c8eac7d8dbba09ef0e6cb",
"size": 21293968,
"lfs": {
"sha256": "810b8f8d6147af3620cf08d2cf575c0eb2b0134ae0253a93ceeae5be9dca8695",
"size": 21293968,
"pointerSize": 133
}
},
{
"rfilename": "gate01/seed4/adapter_meta.json",
"blobId": "3fef81591cd7a41c636c39e72e22d5b3394dc6a5",
"size": 661
},
{
"rfilename": "gate01/seed5/adapter.safetensors",
"blobId": "63b9a6dd509a288e6095ed9531fe76a055e2e5b4",
"size": 21293968,
"lfs": {
"sha256": "b34e8d999612415c7395f341633ff3d2365a020b9e27b7e371c5f80f0105a486",
"size": 21293968,
"pointerSize": 133
}
},
{
"rfilename": "gate01/seed5/adapter_meta.json",
"blobId": "d0daa05e6348923237cdac83935118e4f020e9f7",
"size": 661
},
{
"rfilename": "gate02/seed0/adapter.safetensors",
"blobId": "d566d86611edc89edb7cac62dc73d72619df55bd",
"size": 21293968,
"lfs": {
"sha256": "1fc5a4a4392c35820c26e24d0075824b3426c4a77f3119713b4a1e577d31df5b",
"size": 21293968,
"pointerSize": 133
}
},
{
"rfilename": "gate02/seed0/adapter_meta.json",
"blobId": "36173814d1d838077da330e92fa5f0b1b222ba17",
"size": 660
},
{
"rfilename": "gate02/seed1/adapter.safetensors",
"blobId": "cba04a7ef1bcb48952a723b6aa80d1b6847ef8dc",
"size": 21293968,
"lfs": {
"sha256": "b742f4ffed0e293f27e4646c364a85ae359a3eae1690d3840e531dca7fba9cd8",
"size": 21293968,
"pointerSize": 133
}
},
{
"rfilename": "gate02/seed1/adapter_meta.json",
"blobId": "3c7751cefbe375871d0b99bfda0b3ba1e6ca896c",
"size": 660
},
{
"rfilename": "gate02/seed2/adapter.safetensors",
"blobId": "af547c0fcaa9e69024e14818eb82c46f155dfa59",
"size": 21293968,
"lfs": {
"sha256": "dc36c27a98379535007f2df798953624b6a67f0677bd41dec42349f8ce868afa",
"size": 21293968,
"pointerSize": 133
}
},
{
"rfilename": "gate02/seed2/adapter_meta.json",
"blobId": "baaefc1b64b0dce0c87bbc2a7c4342f87111aba6",
"size": 660
},
{
"rfilename": "gate02/seed3/adapter.safetensors",
"blobId": "21066e00dfc55fc619ca74202ff8ad8dd6017d4e",
"size": 21293968,
"lfs": {
"sha256": "1dcb6132afeec8101daf9a3fd73d42141fb871bff11fff28069f238dcff6afd0",
"size": 21293968,
"pointerSize": 133
}
},
{
"rfilename": "gate02/seed3/adapter_meta.json",
"blobId": "f675496569bbec647fcb31784c4a6d9d83872ee0",
"size": 660
},
{
"rfilename": "gate02/seed4/adapter.safetensors",
"blobId": "bec0713c08368303a25e2ccef690d37a8cf2d54b",
"size": 21293968,
"lfs": {
"sha256": "5b97b0601585925c19bf849ecb11ad68597d1b0d55551b917ec0f5091f85c2ff",
"size": 21293968,
"pointerSize": 133
}
},
{
"rfilename": "gate02/seed4/adapter_meta.json",
"blobId": "8535e4793f089b37fa8bf5724cf49ac24fd2750c",
"size": 660
},
{
"rfilename": "gate02/seed5/adapter.safetensors",
"blobId": "128821f8b3b0591990a3b18c70ca66a16d69aff3",
"size": 21293968,
"lfs": {
"sha256": "3f944a6d210958de5840e5b76e263f2105b9f49d15b9ab505950c2b29a5343af",
"size": 21293968,
"pointerSize": 133
}
},
{
"rfilename": "gate02/seed5/adapter_meta.json",
"blobId": "ae2076c513dc6898a8e30f2cf0fafc4486d8f7c3",
"size": 660
},
{
"rfilename": "lora/seed0/adapter.safetensors",
"blobId": "c3d80937be6f8262769b08a53f5e19548c516420",
"size": 18932336,
"lfs": {
"sha256": "93a3f43a4356f84da0d13ecc622fee13e41ba15d237cdaad6094f243899c62d6",
"size": 18932336,
"pointerSize": 133
}
},
{
"rfilename": "lora/seed0/adapter_meta.json",
"blobId": "c67a9c7f3db4db8f73cc71d27d4a8a664967b624",
"size": 573
},
{
"rfilename": "lora/seed1/adapter.safetensors",
"blobId": "5f0b88be4fa8d1a7fd586ecc640b7ac73fb8a68d",
"size": 18932336,
"lfs": {
"sha256": "63d54e1c2f6bf7d07ca0f6e83a3299bd4b6d00740919bc7cae0b422af05a828e",
"size": 18932336,
"pointerSize": 133
}
},
{
"rfilename": "lora/seed1/adapter_meta.json",
"blobId": "2f1ebca329c8579362d80f0e9e731b832a139349",
"size": 573
},
{
"rfilename": "lora/seed2/adapter.safetensors",
"blobId": "d66df32e3e1e67c4c6b3eccf6229f223fa61a5f8",
"size": 18932336,
"lfs": {
"sha256": "702b764e2c39b3529914dac1547148ef2f462d9ee04e256201e79f00b20ccc62",
"size": 18932336,
"pointerSize": 133
}
},
{
"rfilename": "lora/seed2/adapter_meta.json",
"blobId": "7e4737b99685c9f9542f7d15ad4efebc45fc26f3",
"size": 573
},
{
"rfilename": "lora/seed3/adapter.safetensors",
"blobId": "abb761e518f2bcd7285c7c2cb11579943b942d55",
"size": 18932336,
"lfs": {
"sha256": "7dbf35899fe1186453e599ad8c7a85c56b7fad3d630e371ca026a1e95da2c5a7",
"size": 18932336,
"pointerSize": 133
}
},
{
"rfilename": "lora/seed3/adapter_meta.json",
"blobId": "655fd5600b67568bc9da02e4480a14483e0a1067",
"size": 573
},
{
"rfilename": "lora/seed4/adapter.safetensors",
"blobId": "8bd506ae2220c7d0b025d69a4fbeb9ddaf37198d",
"size": 18932336,
"lfs": {
"sha256": "a5cb1e7fa74dff467bd7f163e1db23d30ef8b1a1c935cfa55dcc8cd1b39082a7",
"size": 18932336,
"pointerSize": 133
}
},
{
"rfilename": "lora/seed4/adapter_meta.json",
"blobId": "d8d7b0df8c3d7d1e2f5ef2f2f6e02e22478e2055",
"size": 573
},
{
"rfilename": "lora/seed5/adapter.safetensors",
"blobId": "487c771e11d8e7ca1fa5bd2670d060e8f77fbaee",
"size": 18932336,
"lfs": {
"sha256": "d513d499dfd409da88b3db7da025ba9872fb48ec92d6b29bc2ce7a092a69745d",
"size": 18932336,
"pointerSize": 133
}
},
{
"rfilename": "lora/seed5/adapter_meta.json",
"blobId": "26fc54919eeaffc92a453ddd31cec660c2ab7f0b",
"size": 573
},
{
"rfilename": "warmup/seed0/adapter.safetensors",
"blobId": "378bc7e4f70afb2e947fc6f53ae822dc4bc422d2",
"size": 18932344,
"lfs": {
"sha256": "9108bce2acfcc3ccd38d0dfae67ac33253b95bdc94133bd25deb4daa45d41700",
"size": 18932344,
"pointerSize": 133
}
},
{
"rfilename": "warmup/seed0/adapter_meta.json",
"blobId": "20989af8c7f2ff5959625878167aca5e0fc7203a",
"size": 576
}
],
"spaces": [],
"createdAt": "2026-10-12T10:25:44.000Z",
"usedStorage": 388053976
}
@@ -0,0 +1,22 @@
{
"record": "qwen3.5-2b-grpo",
"arm": "lora",
"receipt_arm": "ctrl",
"seed": 0,
"step": 150,
"base_model": "Qwen/Qwen3.5-2B",
"base_revision": "15852e8c16360a2fea060d615a32b45270f8a8fc",
"recipe": "GRPO, correctness-gated length penalty alpha 0.2, 150 steps from the shared warm-up (paper Section 4)",
"lora_rank": 16,
"lora_alpha": 32,
"lora_targets": [
"in_proj_qkv",
"in_proj_a",
"in_proj_b",
"out_proj"
],
"gate": null,
"n_tensors": 144,
"n_params": 4727808,
"source_sha256": "de2794c085f5096fea53374ba1cea31075071bb6de3f227bb3350b3035970447"
}
+47
View File
@@ -0,0 +1,47 @@
"""Read-only FP32 effective weights for an existing pure-LoRA checkpoint."""
import re
import numpy as np
from functional.model import PREFIX,StreamingLM
from pilot.tensors import load_tensors
BASE_REVISION='15852e8c16360a2fea060d615a32b45270f8a8fc'
TARGETS={'in_proj_qkv','in_proj_a','in_proj_b','out_proj'}
class EffectiveWeight:
def __init__(self,base,a,b,scale):
assert a.ndim==b.ndim==2 and (b.shape[0],a.shape[1])==base.shape and a.shape[0]==b.shape[1]
self.base,self.a,self.b,self.scale=base,a,b,scale
self.shape,self.numel,self.dtype=base.shape,base.numel,'F32'
def read(self,selector=slice(None)):
if not isinstance(selector,slice):raise ValueError('Only contiguous row chunks supported')
start,stop,step=selector.indices(self.numel);dim=self.shape[1]
if step!=1 or start%dim or stop%dim:raise ValueError('Row aligned chunks required')
w=self.base.read(slice(start,stop)).reshape(-1,dim)
return (w+self.scale*(self.b[start//dim:stop//dim]@self.a)).astype(np.float32).reshape(-1)
def evict(self):self.base.evict()
def install(lm,directory,meta,multiplier=1.):
assert meta['base_model']=='Qwen/Qwen3.5-2B' and meta['base_revision']==BASE_REVISION and meta['gate'] is None and meta['arm']=='lora'
tensors=load_tensors(directory);pairs={};pattern=re.compile(r'^base_model\.model\.model\.(layers\.(\d+)\.linear_attn\.(in_proj_qkv|in_proj_a|in_proj_b|out_proj))\.lora_([AB])\.default\.weight$')
for name,tensor in tensors.items():
match=pattern.fullmatch(name)
if not match:raise ValueError('Unexpected trainable tensor: '+name)
target=PREFIX+match[1]+'.weight';assert lm.config['layer_types'][int(match[2])]=='linear_attention'
assert target in lm.tensors
value=tensor.read().reshape(tensor.shape).copy();tensor.evict();assert np.isfinite(value).all()
pairs.setdefault(target,{})[match[4]]=value
expected={PREFIX+f'layers.{layer}.linear_attn.{role}.weight' for layer,kind in enumerate(lm.config['layer_types']) if kind=='linear_attention' for role in TARGETS}
assert set(pairs)==expected and len(tensors)==meta['n_tensors']
scale=meta['lora_alpha']/meta['lora_rank']*multiplier
for target,pair in pairs.items():
assert set(pair)=={'A','B'} and pair['A'].shape[0]==meta['lora_rank']
lm.tensors[target]=EffectiveWeight(lm.tensors[target],pair['A'],pair['B'],scale)
return pairs,scale
class ExplicitLoRA(StreamingLM):
"""Independent reference: base projection + scaled low-rank output, no W merge."""
def linear(self,x,name,rows=256):
y=super().linear(x,name,rows);pair=self.pairs.get(PREFIX+name+'.weight')
if pair is not None:y=y+self.scale*((x@pair['A'].T)@pair['B'].T)
return y.astype(np.float32)
+73
View File
@@ -0,0 +1,73 @@
"""Paired concentration changes from saved immutable intervention arrays."""
import csv,json,sys
from pathlib import Path
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from dominance.core import concentration
def stats(x):
x=np.asarray(x,dtype=np.float64);v=x[np.isfinite(x)];q=np.quantile(v,[.1,.5,.9])
return {'count':int(v.size),'p10':float(q[0]),'median':float(q[1]),'p90':float(q[2]),'mean':float(v.mean())}
def csvwrite(path,rows):
with path.open('w') as f:w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)
def main(root):
root=Path(root);status=json.loads((root/'status.json').read_text());assert status['state']=='completed';samples=json.loads((root/'samples.json').read_text());pool={};observations={};summary={};rows=[];layer_rows=[]
for cohort in ('legacy','gsm8k'):
for role in ('base','finetuned'):
for sample in samples[cohort]:
for source in (2,6,10,14,18,22):
data=np.load(root/'raw'/f'{cohort}-{role}-{sample["id"]}-{source:02d}.npz')
for metric,key,transform in [('distance','JS',np.sqrt),('divergence','JS',lambda x:x),('QKV','QKV',lambda x:x)]:
impacts=transform(data['single_'+key])[:,7:,:].transpose(1,2,0);c=concentration(impacts)
record={'cohort':cohort,'role':role,'sample':sample['id'],'recipient':source+1,'metric':metric}
for name,x in c.items():
observations.setdefault((cohort,role,metric,name),[]).append(x.reshape(-1))
if name!='valid':
for stat,value in stats(x).items():record[name+'_'+stat]=value
pool.setdefault((cohort,role,metric,'recipient'),[]).append(np.full(200,source+1))
pool.setdefault((cohort,role,metric,'sample'),[]).append(np.full(200,sample['id']))
observations.setdefault((cohort,role,metric,'winner'),[]).append(np.argmax(impacts,-1).reshape(-1))
rows.append(record)
arrays={k:np.concatenate(v) for k,v in observations.items()};np.savez_compressed(root/'observations.npz',**{'__'.join(k):v for k,v in arrays.items()})
for cohort in ('legacy','gsm8k'):
summary[cohort]={}
for metric in ('distance','divergence','QKV'):
item={role:{name:stats(arrays[(cohort,role,metric,name)]) for name in ('effective_heads','effective_fraction','concentration','top1','top25','bottom25','heads90','total')} for role in ('base','finetuned')}
before=arrays[(cohort,'base',metric,'effective_heads')];after=arrays[(cohort,'finetuned',metric,'effective_heads')];delta=after-before
item['paired']={'effective_heads_delta':stats(delta),'increased_fraction':float(np.mean(delta>0)),'decreased_fraction':float(np.mean(delta<0)),'winner_agreement':float(np.mean(arrays[(cohort,'base',metric,'winner')]==arrays[(cohort,'finetuned',metric,'winner')]))}
summary[cohort][metric]=item
recipients=np.concatenate(pool[(cohort,'base',metric,'recipient')]);names=np.concatenate(pool[(cohort,'base',metric,'sample')])
for layer in (3,7,11,15,19,23):
which=recipients==layer;a=stats(before[which]);b=stats(after[which]);d=stats(delta[which]);layer_rows.append({'cohort':cohort,'metric':metric,'recipient':layer,'base_median':a['median'],'base_p10':a['p10'],'base_p90':a['p90'],'finetuned_median':b['median'],'finetuned_p10':b['p10'],'finetuned_p90':b['p90'],'paired_delta_median':d['median']})
for sample in samples[cohort]:
which=names==sample['id'];item.setdefault('per_text',{})[sample['id']]={'base':stats(before[which]),'finetuned':stats(after[which]),'paired_delta':stats(delta[which])}
expected=(8.93182211792415,5.7840811612328125,11.67265834734814);b=summary['legacy']['distance']['base']['effective_heads'];np.testing.assert_allclose([b[k] for k in ['median','p10','p90']],expected,rtol=1e-10)
(root/'summary.json').write_text(json.dumps(summary,indent=2)+'\n');csvwrite(root/'per-text-layer.csv',rows);csvwrite(root/'per-layer.csv',layer_rows)
figs=root/'figures';figs.mkdir(exist_ok=True)
def save(fig,name):
for ext in ('png','pdf','svg'):fig.savefig(figs/(name+'.'+ext),dpi=180)
plt.close(fig)
fig,axs=plt.subplots(1,2,figsize=(13,4.8),layout='constrained')
for ax,cohort in zip(axs,['legacy','gsm8k']):
for role,label,color in [('base','Original release','C0'),('finetuned','GSM8K GRPO LoRA seed0','C1')]:
x=np.sort(arrays[(cohort,role,'distance','effective_heads')]);ax.plot(x,np.arange(1,len(x)+1)/len(x),label=label,color=color)
ax.set(title='Original four texts' if cohort=='legacy' else 'Four GSM8K held-out question prefixes',xlabel='Effective donor heads: sqrt(JS) influence',ylabel='Empirical CDF',xlim=(1,16),ylim=(0,1));ax.grid(alpha=.2);ax.legend()
fig.suptitle('Same inputs before/after existing task fine-tuning; 32 tokens; one training seed; no training here');save(fig,'paired_effective_heads_cdf')
fig,axs=plt.subplots(1,2,figsize=(13,4.8),layout='constrained')
for ax,cohort in zip(axs,['legacy','gsm8k']):
for role,prefix,color in [('base','base','C0'),('finetuned','finetuned','C1')]:
rr=[r for r in layer_rows if r['cohort']==cohort and r['metric']=='distance'];x=[r['recipient'] for r in rr];med=[r[prefix+'_median'] for r in rr];lo=[r[prefix+'_p10'] for r in rr];hi=[r[prefix+'_p90'] for r in rr];ax.plot(x,med,'o-',color=color,label=role);ax.fill_between(x,lo,hi,color=color,alpha=.12)
ax.set(title=cohort,xlabel='Full-attention recipient layer index',ylabel='Effective donor heads: median / P10–P90',ylim=(1,16));ax.legend();ax.grid(alpha=.2)
fig.suptitle('All six full-attention receivers, sixteen donor heads each; descriptive dependent observations');save(fig,'paired_effective_heads_by_layer')
fig,axs=plt.subplots(1,2,figsize=(13,4.8),layout='constrained')
for ax,cohort in zip(axs,['legacy','gsm8k']):
delta=arrays[(cohort,'finetuned','distance','effective_heads')]-arrays[(cohort,'base','distance','effective_heads')];ax.hist(delta,bins=60,density=True,alpha=.7);ax.axvline(0,color='black',linestyle='--');ax.axvline(np.median(delta),color='C3',label='Paired median');ax.set(title=cohort,xlabel='Finetuned minus original effective head count',ylabel='Density');ax.legend()
fig.suptitle('Paired changes; positive = more distributed, negative = more concentrated');save(fig,'paired_effective_heads_delta')
lines=['# GSM8K任务微调前后的有效头数','', '比较原Qwen3.5-2B发布权重与同一revision上的纯LoRA seed0(额外GSM8K GRPO,非SFT)。没有训练新模型。主指标为√JS距离消融影响的N_eff;正变化表示更分散,负变化表示更集中。','', '| 输入组 | 原权重中位数 [P10,P90] | 微调后中位数 [P10,P90] | 配对变化中位数 | 增加的观测比例 |','|---|---:|---:|---:|---:|']
for cohort,label in [('legacy','原四条文本'),('gsm8k','GSM8K测试题前缀')]:
item=summary[cohort]['distance'];a=item['base']['effective_heads'];b=item['finetuned']['effective_heads'];d=item['paired']['effective_heads_delta'];lines.append(f"| {label} | {a['median']:.6f} [{a['p10']:.6f},{a['p90']:.6f}] | {b['median']:.6f} [{b['p10']:.6f},{b['p90']:.6f}] | {d['median']:+.6f} | {item['paired']['increased_fraction']:.1%} |")
lines+=['', '每组4条输入×6个接收层×25个query位置×8个接收query头=4800个配对观测;它们不是4800个独立文本样本。前后使用同一原模型tokenizer、完全相同token IDs。原四条输入的基线8.931822/16已精确复现。','', 'GSM8K输入取原作者固定版本test split中前4道至少32token的题目,仅用题目前32token,不含答案,不套不同聊天模板。另算了同组GSM8K输入的原权重基线;没有把旧通用文本与新任务文本混作配对。','', '## 方法与限定','', '所有6个普通注意力接收层和16个上游输出头均保留;每次移除一个上游头在全序列的投影输出,重算中间MLP/残差/归一化和检索分布。微调只改变18个GDN层的指定投影,普通注意力权重不变;隐藏状态和上游贡献仍会变化。','', '采用read-only FP32有效权重W+2BA,未把增量舍入为BF16、未修改底座;另用base projection+2B(Ax)独立前向校验。头输出求和、空消融和源数组复用校验均记录。JS散度及QKV复合相对变化也保留,避免只展示有利度量。这里QKV补充指标仅覆盖相同六个普通注意力接收层,其原基线不能与旧研究全部23连接的76.0%混作同一统计量。','', '单个发布者训练seed、4条短文本/组,仅支持这些输入上的描述性变化;不推广为所有微调都会如此,不报告GSM8K准确率,不据此推断删头可用或最终LM能力。配对变化中位数与两个总体中位数之差不是同一个统计量。','', '[公开微调权重与训练说明](https://huggingface.co/Avifenesh/gdn-beta-gate-qwen3.5-2b-grpo);固定版本、参数SHA、dataset版本和题目索引见protocol.json/gsm8k-source.json/samples.json。所有权重、适配器和缓存继续保留。']
(root/'REPORT.md').write_text('\n'.join(lines)+'\n');print((root/'REPORT.md').read_text(),end='')
if __name__=='__main__':main(sys.argv[1])
+72
View File
@@ -0,0 +1,72 @@
"""Paired CPU-only existing-adapter comparison for the published sqrt(JS) metric."""
import argparse,json,hashlib,time,resource,gc
from pathlib import Path
import numpy as np
from tokenizers import Tokenizer
from dominance.core import InfluenceLM,concentration
from dominance.run import distances
from .lora import install,ExplicitLoRA,BASE_REVISION
SOURCES=(2,6,10,14,18,22)
def dump(p,d):p.write_text(json.dumps(d,indent=2,allow_nan=False)+'\n')
def single(lm,cache,layer,path):
base=lm.recipient(cache['next_raw'],layer+1);hs=cache['heads'].shape[2];t=cache['raw'].shape[1];assert hs==16
scores={k:[] for k in ('Q','K','V','QKV','JS')}
for start in range(0,hs,4):
masks=np.zeros((4,t,hs),dtype=np.float32)
for n in range(4):masks[n,:,start+n]=1
effects=distances(base,lm.intervene(cache,layer,masks))
for k,v in effects.items():scores[k].extend(v)
null=distances(base,lm.intervene(cache,layer,np.zeros((1,t,hs),dtype=np.float32)))
assert max(float(np.max(v)) for v in null.values())<2e-5
payload={'single_'+k:np.asarray(v,dtype=np.float32) for k,v in scores.items()};payload.update({'null_'+k:v for k,v in null.items()});np.savez_compressed(path,**payload)
def main():
p=argparse.ArgumentParser();p.add_argument('--source',type=Path,required=True);p.add_argument('--parent',type=Path,required=True);p.add_argument('--assets',type=Path,required=True);p.add_argument('--out',type=Path,required=True);a=p.parse_args();a.out.mkdir(parents=True,exist_ok=False);(a.out/'cache').mkdir();(a.out/'raw').mkdir()
started=time.monotonic();meta=json.loads((a.assets/'adapter_meta.json').read_text());assert meta['base_revision']==BASE_REVISION
adapter_sha=hashlib.sha256((a.assets/'adapter.safetensors').read_bytes()).hexdigest();assert adapter_sha=='93a3f43a4356f84da0d13ecc622fee13e41ba15d237cdaad6094f243899c62d6'
tok=Tokenizer.from_file(str(a.source/'tokenizer.json'));legacy=json.loads((a.parent/'samples.json').read_text());gsm=[]
for s in legacy:assert s['token_ids']==tok.encode(s['text']).ids[:32]
for index,line in enumerate((a.assets/'gsm8k-test.jsonl').read_text().splitlines()):
q=json.loads(line)['question'];ids=tok.encode(q).ids
if len(ids)<32:continue
gsm.append({'id':f'gsm8k-test-{index:04d}','row_index':index,'text':q,'question_sha256':hashlib.sha256(q.encode()).hexdigest(),'token_ids':ids[:32]})
if len(gsm)==4:break
assert len(gsm)==4
cohorts={'legacy':legacy,'gsm8k':gsm};dump(a.out/'samples.json',cohorts);dump(a.out/'adapter_meta.json',meta);dump(a.out/'gsm8k-source.json',json.loads((a.assets/'gsm8k-source.json').read_text()))
protocol={'primary':'same six full-attention receivers and original4x32 token cohort as published8.931822/16','adapter_repo':'Avifenesh/gdn-beta-gate-qwen3.5-2b-grpo','adapter_revision':'038d8be9bd0edd3883fa019651b02bdf65609468','adapter_file':'lora/seed0/adapter.safetensors','adapter_sha256':adapter_sha,'base_revision':BASE_REVISION,'scale':2,'rank':16,'arm':'pure LoRA','training':'publisher-reported GSM8K GRPO; we do no training','sample_choice':'four original texts; first4 canonical GSM8K test questions with >=32tokens, length selection only, first32tokens; question only','source_layers':SOURCES,'primary_queries':list(range(7,32)),'main_metric':'concentration(sqrt(single_JS)); same FP32 tensors and sequence-wide donor-head deletion as prior run','cohort_pairing':'each comparison uses same question/tokenIDs before and after; base legacy arrays reused with elementwise checks','runtime':'read-only FP32 effective W+2BA; no BF16 re-rounding or quantization','controls':'head sum, null mask, explicit low-rank versus effective-weight full forward relL2<1e-4','budget_seconds':7200,'keep_all_weights_and_caches':True,'limitations':['one existing training seed','4 texts per cohort, 32 tokens each','dependent query/head observations, not iid textual samples','no generation or accuracy measurement','GDN targets only; ordinary attention weights stay unchanged','no pruning or functional interchangeability claim']}
dump(a.out/'protocol.json',protocol);status={'state':'running','links':[]};dump(a.out/'status.json',status);cfg=json.loads((a.source/'model_config.json').read_text());controls=[];references=[]
try:
for cohort,samples in cohorts.items():
for role in ('base','finetuned'):
reuse=cohort=='legacy' and role=='base';lm=None
if not reuse:
lm=InfluenceLM(a.source/'weights',cfg,seconds=max(1,7200-(time.monotonic()-started)))
if role=='finetuned':pairs,scale=install(lm,a.assets,meta)
for si,s in enumerate(samples):
if time.monotonic()-started>7200:raise TimeoutError('Paired CPU budget')
if not reuse:
cache=a.out/'cache'/f'{cohort}-{role}-{s["id"]}';cache.mkdir();ids=np.array([s['token_ids']],dtype=np.int64);final=lm.baseline(ids,cache);np.save(cache/'final.npy',final)
controls.extend({'cohort':cohort,'role':role,'sample':s['id'],**v} for v in lm.head_sum_errors)
if cohort=='legacy' and role=='finetuned' and si==0:
ref=ExplicitLoRA(a.source/'weights',cfg,seconds=max(1,7200-(time.monotonic()-started)));ref.pairs,ref.scale=pairs,scale;expected,_=ref.forward(ids);actual=lm.normalization(final,'norm');error=float(np.linalg.norm(actual.astype(np.float64)-expected)/np.linalg.norm(expected.astype(np.float64)));assert error<1e-4
status['explicit_lora_forward_relative_error']=error;del ref;gc.collect()
for layer in SOURCES:
out=a.out/'raw'/f'{cohort}-{role}-{s["id"]}-{layer:02d}.npz'
if reuse:
old=a.parent/'raw'/f'{s["id"]}-link-{layer:02d}.npz'
with np.load(old) as d:payload={prefix+k:d[prefix+k] for prefix in ('single_','null_') for k in ('Q','K','V','QKV','JS')}
np.savez_compressed(out,**payload)
with np.load(out) as d:
for k,v in payload.items():np.testing.assert_array_equal(d[k],v)
references.append({'source':str(old.resolve()),'sha256':hashlib.sha256(old.read_bytes()).hexdigest(),'derived':out.name})
else:
with np.load(cache/f'layer-{layer}.npz') as d:loaded={k:d[k] for k in d.files}
single(lm,loaded,layer,out);del loaded
status['links'].append({'cohort':cohort,'role':role,'sample':s['id'],'source':layer,'path':str(out.relative_to(a.out))});status['elapsed_seconds']=time.monotonic()-started;dump(a.out/'status.json',status);print('completed',cohort,role,s['id'],layer,flush=True)
dump(a.out/'head-sum-controls.json',controls);dump(a.out/'baseline-references.json',references)
if lm is not None:del lm;gc.collect()
status.update(state='completed',elapsed_seconds=time.monotonic()-started,peak_rss_kib=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss);dump(a.out/'status.json',status)
except BaseException as e:
status.update(state='failed',error=repr(e),elapsed_seconds=time.monotonic()-started);dump(a.out/'status.json',status);raise
if __name__=='__main__':main()
+6 -2
View File
@@ -77,11 +77,13 @@ def attention(q, k, v):
class StreamingLM:
def __init__(self, weights, config, seconds=7200, enforce_memory=True):
def __init__(self, weights, config, seconds=7200, enforce_memory=True,
process_swap_limit_kib=128*1024):
self.tensors = load_tensors(Path(weights))
self.config = config.get('text_config', config)
self.deadline = time.monotonic() + seconds
self.enforce_memory = enforce_memory
self.process_swap_limit_kib = process_swap_limit_kib
self.eps = self.config['rms_norm_eps']
self.norm_replacement = None
self.capture_qk = False
@@ -107,7 +109,9 @@ class StreamingLM:
rate = (count-self.swap_observation[1])*4096/elapsed
self.swap_pressure_windows = self.swap_pressure_windows+1 if rate > 4*1024**2 else 0
own_swap_kib = int(status.get('VmSwap', '0 kB').split()[0])
if self.swap_pressure_windows >= 3 and (available < 384*1024 or own_swap_kib > 128*1024):
over_process_limit = (self.process_swap_limit_kib is not None
and own_swap_kib > self.process_swap_limit_kib)
if self.swap_pressure_windows >= 3 and (available < 384*1024 or over_process_limit):
raise MemoryError(f'Sustained host swap pressure plus constrained memory: available={available} KiB, process_swap={own_swap_kib} KiB')
self.swap_observation = (now,count)
if rss_kib > 512*1024 or available < 256*1024:
+83
View File
@@ -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.
+42
View File
@@ -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.
+124
View File
@@ -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()
+29
View File
@@ -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
+176
View File
@@ -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()
+49
View File
@@ -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()
+25
View File
@@ -0,0 +1,25 @@
# 实测激活率:SiLU 门控模型
覆盖24层、4条中英文文本,每条32 token;所有投影输出及 MLP 门控中间量,按64/128输出通道分块。
| 输出 | 精确零比例均值 | 0.01 RMS以下均值 | 0.1 RMS以下均值 | 32 token内曾活跃通道比例均值 | 90%能量所需通道比例均值 |
|---|---:|---:|---:|---:|---:|
| mlp.gate_proj.output | 0.0000% | 0.7811% | 7.8005% | 100.0000% | 63.3063% |
| mlp.silu_gate | 0.0000% | 0.5031% | 5.1789% | 100.0000% | 70.1228% |
| mlp.gated_product | 0.0000% | 3.1636% | 21.0460% | 100.0000% | 54.8421% |
| self_attn.q_proj.output | 0.0000% | 1.2760% | 12.4831% | 100.0000% | 44.0277% |
| self_attn.k_proj.output | 0.0000% | 1.2245% | 12.0834% | 100.0000% | 53.4587% |
| self_attn.v_proj.output | 0.0000% | 1.3741% | 13.4814% | 100.0000% | 59.9447% |
128通道块×文本观测共27600条,整个32 token窗口全为精确零的块观测数为0。
表中是整模块逐文本统计再取均值;每个分块的独立统计见 metrics.csv。阈值是各自RMS的比例;阈值下激活率=1−近零比例。能量集中不等于可删除或可替换。
仅测该模型、四条短文本;不推断所有语言/长上下文。SiLU不把负值整体截零,负数不等于静默。未执行删块/跳算的质量验证。权重和既有缓存全部保留。
CPU测量耗时268.6秒,峰值RSS151.6 MiB。
mlp.gated_product: 128通道块在0.1 RMS阈值上的激活率范围 10.47%–89.04%。
self_attn.q_proj.output: 128通道块在0.1 RMS阈值上的激活率范围 75.49%–100.00%。
self_attn.k_proj.output: 128通道块在0.1 RMS阈值上的激活率范围 81.20%–93.95%。
self_attn.v_proj.output: 128通道块在0.1 RMS阈值上的激活率范围 76.66%–91.89%。
+200
View File
@@ -0,0 +1,200 @@
{
"mlp.gate_proj.output": {
"observations": 96,
"zero_rate": {
"min": 0.0,
"mean": 0.0,
"max": 0.0
},
"negative_rate": {
"min": 0.6825663248697916,
"mean": 0.8063652250501846,
"max": 0.9117279052734375
},
"near_001_rms": {
"min": 0.005289713541666667,
"mean": 0.007811493343777125,
"max": 0.010442097981770834
},
"near_01_rms": {
"min": 0.053070068359375,
"mean": 0.07800536685519749,
"max": 0.10291544596354167
},
"ever_active_001": {
"min": 1.0,
"mean": 1.0,
"max": 1.0
},
"energy90_channel_fraction": {
"min": 0.5314127604166666,
"mean": 0.6330634223090278,
"max": 0.78955078125
}
},
"mlp.silu_gate": {
"observations": 96,
"zero_rate": {
"min": 0.0,
"mean": 0.0,
"max": 0.0
},
"negative_rate": {
"min": 0.6825663248697916,
"mean": 0.8063652250501846,
"max": 0.9117279052734375
},
"near_001_rms": {
"min": 0.0018768310546875,
"mean": 0.0050310028923882385,
"max": 0.0082244873046875
},
"near_01_rms": {
"min": 0.020375569661458332,
"mean": 0.05178917778862848,
"max": 0.09897359212239583
},
"ever_active_001": {
"min": 1.0,
"mean": 1.0,
"max": 1.0
},
"energy90_channel_fraction": {
"min": 0.04736328125,
"mean": 0.7012278238932291,
"max": 0.8186848958333334
}
},
"mlp.gated_product": {
"observations": 96,
"zero_rate": {
"min": 0.0,
"mean": 0.0,
"max": 0.0
},
"negative_rate": {
"min": 0.4942118326822917,
"mean": 0.5002292527092828,
"max": 0.5078125
},
"near_001_rms": {
"min": 0.020960489908854168,
"mean": 0.03163560231526693,
"max": 0.07338460286458333
},
"near_01_rms": {
"min": 0.16080220540364584,
"mean": 0.21046002705891928,
"max": 0.4075215657552083
},
"ever_active_001": {
"min": 1.0,
"mean": 1.0,
"max": 1.0
},
"energy90_channel_fraction": {
"min": 0.06380208333333333,
"mean": 0.5484212239583334,
"max": 0.7263997395833334
}
},
"self_attn.q_proj.output": {
"observations": 24,
"zero_rate": {
"min": 0.0,
"mean": 0.0,
"max": 0.0
},
"negative_rate": {
"min": 0.6834945678710938,
"mean": 0.7360480626424154,
"max": 0.7523574829101562
},
"near_001_rms": {
"min": 0.01090240478515625,
"mean": 0.012759526570638021,
"max": 0.01556396484375
},
"near_01_rms": {
"min": 0.106048583984375,
"mean": 0.1248311996459961,
"max": 0.148590087890625
},
"ever_active_001": {
"min": 1.0,
"mean": 1.0,
"max": 1.0
},
"energy90_channel_fraction": {
"min": 0.413330078125,
"mean": 0.440277099609375,
"max": 0.4931640625
}
},
"self_attn.k_proj.output": {
"observations": 24,
"zero_rate": {
"min": 0.0,
"mean": 0.0,
"max": 0.0
},
"negative_rate": {
"min": 0.47601318359375,
"mean": 0.49783579508463544,
"max": 0.52325439453125
},
"near_001_rms": {
"min": 0.00909423828125,
"mean": 0.01224517822265625,
"max": 0.01629638671875
},
"near_01_rms": {
"min": 0.095458984375,
"mean": 0.1208343505859375,
"max": 0.15106201171875
},
"ever_active_001": {
"min": 1.0,
"mean": 1.0,
"max": 1.0
},
"energy90_channel_fraction": {
"min": 0.41015625,
"mean": 0.5345865885416666,
"max": 0.65234375
}
},
"self_attn.v_proj.output": {
"observations": 24,
"zero_rate": {
"min": 0.0,
"mean": 0.0,
"max": 0.0
},
"negative_rate": {
"min": 0.49267578125,
"mean": 0.5059967041015625,
"max": 0.51666259765625
},
"near_001_rms": {
"min": 0.0084228515625,
"mean": 0.01374053955078125,
"max": 0.02447509765625
},
"near_01_rms": {
"min": 0.087890625,
"mean": 0.1348139444986979,
"max": 0.22296142578125
},
"ever_active_001": {
"min": 1.0,
"mean": 1.0,
"max": 1.0
},
"energy90_channel_fraction": {
"min": 0.291015625,
"mean": 0.5994466145833334,
"max": 0.732421875
}
}
}
+7
View File
@@ -0,0 +1,7 @@
{
"passed": true,
"rows": 83616,
"layers": 24,
"samples": 4,
"all_zero_128_blocks": 0
}
+18
View File
@@ -0,0 +1,18 @@
{
"REPORT.md": "f7f05bdbf9c9d096fe685ebb49ee15ff9866a99071302f9d7710b99b1a2e7db4",
"aggregates.json": "57dfef79b14e73dafd39840661abacd8b44447884e640bb40b86f90ec441ee4d",
"audit.json": "2a67fde20f6765d0dbfa783ff31c548f8135af5d74b6fc0e27a3e71c9cbdffb1",
"figures/block_activity.pdf": "354cbc89dfc6da6d6611c6effc9dfefc6762e3da1d52bfba89cc11be8c8a9247",
"figures/block_activity.png": "ddcfa1f0de30f4f8bdece16b3451ca1b5bf419fac5a5bb9bb944301983efaeec",
"figures/block_activity.svg": "da85920dd0fc32ba439b650c8b695757d42eb72768b4017a78109cb8a2f24216",
"figures/mlp_activation.pdf": "6eef102d1ecc7c21206da862f79d4edaed77a695f7c46d53550c3dc6f9087ee5",
"figures/mlp_activation.png": "0e1a01ea5b21274eaa757c1c9cd493524003220eadcf7aa378e0eb39a37a7c40",
"figures/mlp_activation.svg": "d7b0a67d2d1d501e6fa70aa4a38010bead93a450423e5cd6b3b1284794353c8f",
"final-tests.txt": "7b52cfeffca483471297e30aa9658bc2c5c6585b682f5ee5fbbcc2e1b2b8abe4",
"first-attempt.txt": "7a1f686db3b7412b681d516bdd83bb8ed7ab2a758a44a2d84c4c7968017d9c91",
"full-tests.txt": "55fe658a01d15ed380f2b5cd01058f2374997ffde945025262e92fd966f0dc3b",
"metrics.csv": "8f6205e7f446f83567485275f57f63ce64233eee711a4be89c30b37182772e4d",
"run.txt": "9fe01020a3ac92db51a17042eef6af73f854dd2e81220d7a04cd5a843c6ff9ba",
"source-hashes.json": "34d1c164e787ec6ec5b77d4bc056da2e72365e1cd4b5089741f2b979a3c8beb3",
"summary.json": "1e7c3bace11673d10cb927d689348bf00790a9b074ccafed6ce44d898410ef98"
}
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 163 KiB

File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 76 KiB

+7
View File
@@ -0,0 +1,7 @@
test_known_activity (tests.test_activation.ActivationTests.test_known_activity) ... ok
test_zero_and_scale (tests.test_activation.ActivationTests.test_zero_and_scale) ... ok
----------------------------------------------------------------------
Ran 2 tests in 0.002s
OK
@@ -0,0 +1,24 @@
completed fresh-zh-1 20904
completed fresh-zh-2 41808
completed fresh-en-1 62712
Traceback (most recent call last):
File "/opt/exp-model-parameter-similarity/activation_probe.py", line 44, in <module>
if __name__=='__main__':main()
~~~~^^
File "/opt/exp-model-parameter-similarity/activation_probe.py", line 39, in main
lm.forward(np.array([ids],dtype=np.int64)); print('completed',s['id'],len(lm.rows),flush=True)
~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/exp-model-parameter-similarity/functional/model.py", line 220, in forward
h = h + self.mlp(n,donor)
~~~~~~~~^^^^^^^^^
File "/opt/exp-model-parameter-similarity/activation_probe.py", line 30, in mlp
return self.linear(g*u,p+'down_proj')
~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^
File "/opt/exp-model-parameter-similarity/activation_probe.py", line 22, in linear
y=super().linear(x,name,rows); self.record(y,name+'.output')
File "/opt/exp-model-parameter-similarity/functional/model.py", line 130, in linear
self.guard()
~~~~~~~~~~^^
File "/opt/exp-model-parameter-similarity/functional/model.py", line 111, in guard
raise MemoryError(f'Sustained host swap pressure plus constrained memory: available={available} KiB, process_swap={own_swap_kib} KiB')
MemoryError: Sustained host swap pressure plus constrained memory: available=989040 KiB, process_swap=132360 KiB
+33
View File
@@ -0,0 +1,33 @@
test_known_activity (test_activation.ActivationTests.test_known_activity) ... ok
test_zero_and_scale (test_activation.ActivationTests.test_zero_and_scale) ... ok
test_assignment_against_exhaustive_and_inverse (test_crossqkv.CrossQKVTests.test_assignment_against_exhaustive_and_inverse) ... ok
test_cached_mode_rejects_future_state_reuse (test_crossqkv.CrossQKVTests.test_cached_mode_rejects_future_state_reuse) ... ok
test_controls_cover_multiple_projection_layers (test_crossqkv.CrossQKVTests.test_controls_cover_multiple_projection_layers) ... ok
test_head_matrix_metrics_and_gram_are_diagnostic (test_crossqkv.CrossQKVTests.test_head_matrix_metrics_and_gram_are_diagnostic) ... ok
test_probability_identity_and_nontrivial_queries (test_crossqkv.CrossQKVTests.test_probability_identity_and_nontrivial_queries) ... ok
test_profile_matches_canonical_and_head_sum (test_crossqkv.CrossQKVTests.test_profile_matches_canonical_and_head_sum) ... ok
test_recipient_value_gate_output_and_gqa_group_stay_fixed (test_crossqkv.CrossQKVTests.test_recipient_value_gate_output_and_gqa_group_stay_fixed) ... ok
test_topk_tail_rank_can_change_with_tiny_probability_difference (test_crossqkv.CrossQKVTests.test_topk_tail_rank_can_change_with_tiny_probability_difference) ... ok
test_causal_convolution_and_norm_boundary (test_functional.FunctionalTests.test_causal_convolution_and_norm_boundary) ... ok
test_causality_and_identical_function_metrics (test_functional.FunctionalTests.test_causality_and_identical_function_metrics) ... ok
test_neuron_function_metrics_and_targeted_replacement (test_functional.FunctionalTests.test_neuron_function_metrics_and_targeted_replacement) ... ok
test_nonrotary_gain_identity_and_rotary_negative_control (test_functional.FunctionalTests.test_nonrotary_gain_identity_and_rotary_negative_control) ... ok
test_streamed_projection_embedding_and_output_head (test_functional.FunctionalTests.test_streamed_projection_embedding_and_output_head) ... ok
test_uniform_rmsnorm_function_bound_is_tight (test_functional.FunctionalTests.test_uniform_rmsnorm_function_bound_is_tight) ... ok
test_3d_reader_and_exact_block (test_pilot.PilotTests.test_3d_reader_and_exact_block) ... ok
test_bfloat16 (test_pilot.PilotTests.test_bfloat16) ... ok
test_directional_replacement_error_and_scaling (test_pilot.PilotTests.test_directional_replacement_error_and_scaling) ... ok
test_end_to_end_synthetic_groups_and_savings (test_pilot.PilotTests.test_end_to_end_synthetic_groups_and_savings) ... Inventory: 4 tensors, 33792 bytes
tensor: sampling 4 objects
block: sampling 22 objects
block: verified 100/109
{"model": "synthetic", "revision": "test", "tensor_count": 4, "parameter_count": 8448, "model_weight_bytes": 33792, "ndim_counts": {"2": 2, "3": 2}, "elapsed_seconds": 0.3087193910032511, "analysis_budget_seconds": 60, "peak_rss_kib": 57700, "python": "3.14.4", "numpy": "2.5.4", "seed": 20261109, "limitations": ["No inference or functional equivalence measured", "No exhaustive pair search", "Block search uses per-role/shape/scale reservoirs of 256", "Different block scales overlap; savings must not be added", "Block savings count only verified disjoint sampled blocks, no extrapolation", "Spectral probes use aligned bounded subvolumes, not whole tensors", "Shared encoding is theoretical, not a runnable compressed checkpoint", "No cross-role grouping, neuron permutation alignment, or training"], "completed": true}
ok
test_no_transitive_chaining (test_pilot.PilotTests.test_no_transitive_chaining) ... ok
test_ranged_download_preserves_prefix (test_pilot.PilotTests.test_ranged_download_preserves_prefix) ... Weight download 36/36 bytes (100.0%)
ok
----------------------------------------------------------------------
Ran 22 tests in 33.253s
OK
File diff suppressed because it is too large Load Diff
+4
View File
@@ -0,0 +1,4 @@
completed fresh-zh-1 20904
completed fresh-zh-2 20904
completed fresh-en-1 20904
completed fresh-en-2 20904
@@ -0,0 +1,8 @@
{
"activation/report.py": "e67bfa4af69e43cdceb803b77fe6a6dcc151163e72b3ff2bb7e6b69e7c6fa1fc",
"activation/audit.py": "7dc8af7c31de379a50bdcbd3c41243eb190e6a50e8ec00a30182e82a34e73627",
"activation/run.py": "cba62a2d8b6344625f233309b166b091028154890d93e48278eb338cbcd19b18",
"activation/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"tests/test_activation.py": "dee1756b63cd03c2051cdc92d678d2e27aff639fbfd3d3cb3169140760da4c68",
"functional/model.py": "48a2a97d0445dc6e08ac7f27a935637a7553417d0982eb94122d6cb02bbb499c"
}
+180
View File
@@ -0,0 +1,180 @@
{
"completed": true,
"elapsed_seconds": 268.55615069903433,
"peak_rss_kib": 155288,
"config_activation": "silu",
"layer_count": 24,
"samples": [
{
"id": "fresh-zh-1",
"language": "zh",
"text": "\u690d\u7269\u5b66\u5bb6\u5728\u4e0d\u540c\u6d77\u62d4\u91c7\u96c6\u4e86\u53f6\u7247\u6837\u672c\uff0c\u5e76\u4e3a\u6bcf\u4e00\u4efd\u6807\u672c\u8bb0\u5f55\u6e29\u5ea6\u3001\u5149\u7167\u548c\u571f\u58e4\u6e7f\u5ea6\u3002\u56de\u5230\u5b9e\u9a8c\u5ba4\u540e\uff0c\u5979\u6309\u5730\u70b9\u6574\u7406\u6807\u7b7e\uff0c\u5148\u6838\u5bf9\u7f3a\u5931\u8bb0\u5f55\uff0c\u518d\u6bd4\u8f83\u4e0d\u540c\u73af\u5883\u4e2d\u7684\u53f6\u7247\u5f62\u72b6\u3002",
"token_ids": [
99951,
101071,
115802,
111685,
102099,
95759,
111583,
109928,
3709,
115026,
134176,
116599,
98151,
99472,
5205,
114180,
95793,
104074,
102454,
1710,
103744,
103911,
95946,
3709,
96343,
96656,
100560,
99946,
101659,
3709,
96218,
113089
]
},
{
"id": "fresh-zh-2",
"language": "zh",
"text": "\u5982\u679c\u4e00\u4e2a\u76d2\u5b50\u91cc\u6709\u5341\u4e8c\u679a\u84dd\u8272\u68cb\u5b50\u548c\u516b\u679a\u767d\u8272\u68cb\u5b50\uff0c\u968f\u673a\u53d6\u51fa\u4e00\u679a\u540e\u4e0d\u653e\u56de\uff0c\u7b2c\u4e8c\u6b21\u53d6\u5230\u84dd\u8272\u7684\u6982\u7387\u9700\u8981\u6839\u636e\u7b2c\u4e00\u6b21\u7684\u7ed3\u679c\u5206\u522b\u8ba1\u7b97\u3002\u8bf7\u5148\u5217\u51fa\u5404\u4e2a\u4e8b\u4ef6\uff0c\u518d\u68c0\u67e5\u5b83\u4eec\u7684\u6982\u7387\u4e4b\u548c\u3002",
"token_ids": [
127356,
98996,
98970,
95762,
98175,
101184,
104145,
99357,
111324,
96702,
101184,
103828,
129730,
3709,
102038,
96284,
98938,
101184,
95946,
122271,
96120,
3709,
109387,
96284,
95839,
116981,
104514,
122501,
103720,
109146,
99446,
97792
]
},
{
"id": "fresh-en-1",
"language": "en",
"text": "A technician recorded the vibration of a small motor before and after replacing its bearings. She used the same mounting position and sampling interval for both measurements. The final notebook included the raw traces, instrument settings, and a brief explanation of unusual observations.",
"token_ids": [
32,
51715,
12076,
279,
46219,
314,
264,
2526,
8604,
1518,
321,
1238,
24101,
1141,
33309,
13,
2838,
1429,
279,
1788,
32525,
2234,
321,
24102,
9581,
364,
2107,
20934,
13,
561,
1534,
35935
]
},
{
"id": "fresh-en-2",
"language": "en",
"text": "The function walks through a list of integers and stores each running total in a new list. An empty input should return an empty result. Before changing the implementation, compare a short example by hand and make sure negative numbers preserve the intended behavior.",
"token_ids": [
760,
709,
21780,
1472,
264,
1103,
314,
24959,
321,
10220,
1754,
4162,
2702,
303,
264,
491,
1103,
13,
1473,
4147,
1879,
1220,
460,
449,
4147,
1067,
13,
12851,
9722,
279,
7873,
11
]
}
],
"rows": 83616,
"block_widths": [
64,
128
],
"threshold_reference": "RMS within each sample/module/block, thresholds 0.01 and 0.1; exact zero measured separately",
"training": false,
"weights_deleted": false,
"limits": [
"4 short texts, 32 tokens each, descriptive only",
"Block is contiguous output channels, not Transformer block",
"Small output does not prove removable computation or parameter interchangeability",
"All samples previously used; no generalization claim",
"Relative threshold differs between blocks; width=0 is whole module reference"
]
}
+22
View File
@@ -0,0 +1,22 @@
# GSM8K任务微调前后的有效头数
比较原Qwen3.5-2B发布权重与同一revision上的纯LoRA seed0(额外GSM8K GRPO,非SFT)。没有训练新模型。主指标为√JS距离消融影响的N_eff;正变化表示更分散,负变化表示更集中。
| 输入组 | 原权重中位数 [P10,P90] | 微调后中位数 [P10,P90] | 配对变化中位数 | 增加的观测比例 |
|---|---:|---:|---:|---:|
| 原四条文本 | 8.931822 [5.784081,11.672658] | 8.918301 [5.776576,11.683940] | -0.007827 | 45.6% |
| GSM8K测试题前缀 | 8.906046 [6.013504,11.801882] | 8.904117 [5.982593,11.818115] | -0.006747 | 47.2% |
每组4条输入×6个接收层×25个query位置×8个接收query头=4800个配对观测;它们不是4800个独立文本样本。前后使用同一原模型tokenizer、完全相同token IDs。原四条输入的基线8.931822/16已精确复现。
GSM8K输入取原作者固定版本test split中前4道至少32token的题目,仅用题目前32token,不含答案,不套不同聊天模板。另算了同组GSM8K输入的原权重基线;没有把旧通用文本与新任务文本混作配对。
## 方法与限定
所有6个普通注意力接收层和16个上游输出头均保留;每次移除一个上游头在全序列的投影输出,重算中间MLP/残差/归一化和检索分布。微调只改变18个GDN层的指定投影,普通注意力权重不变;隐藏状态和上游贡献仍会变化。
采用read-only FP32有效权重W+2BA,未把增量舍入为BF16、未修改底座;另用base projection+2B(Ax)独立前向校验。头输出求和、空消融和源数组复用校验均记录。JS散度及QKV复合相对变化也保留,避免只展示有利度量。这里QKV补充指标仅覆盖相同六个普通注意力接收层,其原基线不能与旧研究全部23连接的76.0%混作同一统计量。
单个发布者训练seed、4条短文本/组,仅支持这些输入上的描述性变化;不推广为所有微调都会如此,不报告GSM8K准确率,不据此推断删头可用或最终LM能力。配对变化中位数与两个总体中位数之差不是同一个统计量。
[公开微调权重与训练说明](https://huggingface.co/Avifenesh/gdn-beta-gate-qwen3.5-2b-grpo);固定版本、参数SHA、dataset版本和题目索引见protocol.json/gsm8k-source.json/samples.json。所有权重、适配器和缓存继续保留。
@@ -0,0 +1,22 @@
{
"record": "qwen3.5-2b-grpo",
"arm": "lora",
"receipt_arm": "ctrl",
"seed": 0,
"step": 150,
"base_model": "Qwen/Qwen3.5-2B",
"base_revision": "15852e8c16360a2fea060d615a32b45270f8a8fc",
"recipe": "GRPO, correctness-gated length penalty alpha 0.2, 150 steps from the shared warm-up (paper Section 4)",
"lora_rank": 16,
"lora_alpha": 32,
"lora_targets": [
"in_proj_qkv",
"in_proj_a",
"in_proj_b",
"out_proj"
],
"gate": null,
"n_tensors": 144,
"n_params": 4727808,
"source_sha256": "de2794c085f5096fea53374ba1cea31075071bb6de3f227bb3350b3035970447"
}
@@ -0,0 +1,15 @@
{
"passed": true,
"links": 96,
"paired_observations_per_cohort_metric": 4800,
"legacy_baseline_exact": true,
"effective_head_formula_independently_recomputed": true,
"head_sum_checks": 288,
"explicit_lora_forward_relative_error": 8.33777860933606e-07,
"adapter_sha_verified": true,
"base_sha_verified": true,
"dataset_sha_verified": true,
"retained_cache_files": 300,
"nonzero_update_modules": 72,
"nonzero_hidden_state_changes_verified": true
}
+15
View File
@@ -0,0 +1,15 @@
{
"passed": true,
"links": 96,
"paired_observations_per_cohort_metric": 4800,
"legacy_baseline_exact": true,
"effective_head_formula_independently_recomputed": true,
"head_sum_checks": 288,
"explicit_lora_forward_relative_error": 8.33777860933606e-07,
"adapter_sha_verified": true,
"base_sha_verified": true,
"dataset_sha_verified": true,
"retained_cache_files": 300,
"nonzero_update_modules": 72,
"nonzero_hidden_state_changes_verified": true
}
@@ -0,0 +1,122 @@
[
{
"source": "/opt/exp-model-parameter-similarity/runs/head-dominance/raw/fresh-zh-1-link-02.npz",
"sha256": "7f3662c3f9badc8d7cd7d7bb312afbc8b7e0e3a3890c64b503040d0d9c11025a",
"derived": "legacy-base-fresh-zh-1-02.npz"
},
{
"source": "/opt/exp-model-parameter-similarity/runs/head-dominance/raw/fresh-zh-1-link-06.npz",
"sha256": "c196a05605c73ad28a1eb18299743e5c2ab9b5edacb31d8bb1afbb5addd90b5a",
"derived": "legacy-base-fresh-zh-1-06.npz"
},
{
"source": "/opt/exp-model-parameter-similarity/runs/head-dominance/raw/fresh-zh-1-link-10.npz",
"sha256": "5f8e151ce7656350b6e1505356e22fe7fc91a543e19a4315b1be0730e9504c74",
"derived": "legacy-base-fresh-zh-1-10.npz"
},
{
"source": "/opt/exp-model-parameter-similarity/runs/head-dominance/raw/fresh-zh-1-link-14.npz",
"sha256": "bedeb732de606f62e6af6bbc85d90146b0ae0bd0b97889d67e026f7374e89212",
"derived": "legacy-base-fresh-zh-1-14.npz"
},
{
"source": "/opt/exp-model-parameter-similarity/runs/head-dominance/raw/fresh-zh-1-link-18.npz",
"sha256": "1cffd0b08074027d75997f602e3f42440bc5d2126618da7e74c28a13a34f3bd6",
"derived": "legacy-base-fresh-zh-1-18.npz"
},
{
"source": "/opt/exp-model-parameter-similarity/runs/head-dominance/raw/fresh-zh-1-link-22.npz",
"sha256": "62326fccae8a66a39ba5cd076464ff4e29d0c0f13492fa588a692d2e8dd8f313",
"derived": "legacy-base-fresh-zh-1-22.npz"
},
{
"source": "/opt/exp-model-parameter-similarity/runs/head-dominance/raw/fresh-zh-2-link-02.npz",
"sha256": "f479c9681dea7c9a20937964eddda0f44fb6c7d896258e8d0be0da897fe4b0f1",
"derived": "legacy-base-fresh-zh-2-02.npz"
},
{
"source": "/opt/exp-model-parameter-similarity/runs/head-dominance/raw/fresh-zh-2-link-06.npz",
"sha256": "9bc654f5eb7c8d9ee55afcbc0d2afad1fc2f0472101abadc3c2859d14532c72a",
"derived": "legacy-base-fresh-zh-2-06.npz"
},
{
"source": "/opt/exp-model-parameter-similarity/runs/head-dominance/raw/fresh-zh-2-link-10.npz",
"sha256": "0253a2fe6dc2a429e79bbc42ee8ae36605577df417e84154c6accd2ea674ea37",
"derived": "legacy-base-fresh-zh-2-10.npz"
},
{
"source": "/opt/exp-model-parameter-similarity/runs/head-dominance/raw/fresh-zh-2-link-14.npz",
"sha256": "be9496bbe6fc6628e89e712d3196faff89560769fd42956aa147f78f265019b9",
"derived": "legacy-base-fresh-zh-2-14.npz"
},
{
"source": "/opt/exp-model-parameter-similarity/runs/head-dominance/raw/fresh-zh-2-link-18.npz",
"sha256": "59027a05d715123275ce00e5a999df58cda31807e4b329d91a3f5698c7f2cee6",
"derived": "legacy-base-fresh-zh-2-18.npz"
},
{
"source": "/opt/exp-model-parameter-similarity/runs/head-dominance/raw/fresh-zh-2-link-22.npz",
"sha256": "d8ad49c825823916d7208672ab86e002e32b0f2b49e2ecbf6238b8244a8487fb",
"derived": "legacy-base-fresh-zh-2-22.npz"
},
{
"source": "/opt/exp-model-parameter-similarity/runs/head-dominance/raw/fresh-en-1-link-02.npz",
"sha256": "ffb16b2e53428a6cd7dd60c08424f519cae1ce9a1ef0e0de8314d62217cbdda7",
"derived": "legacy-base-fresh-en-1-02.npz"
},
{
"source": "/opt/exp-model-parameter-similarity/runs/head-dominance/raw/fresh-en-1-link-06.npz",
"sha256": "a936f7fd99905cd1a93a646e267d7204581ff2ddfd88da700261dbcc6af1e6e7",
"derived": "legacy-base-fresh-en-1-06.npz"
},
{
"source": "/opt/exp-model-parameter-similarity/runs/head-dominance/raw/fresh-en-1-link-10.npz",
"sha256": "33b76293fe9cea3c198408b77981f88c866271ae6d4396c1269de402ff02f124",
"derived": "legacy-base-fresh-en-1-10.npz"
},
{
"source": "/opt/exp-model-parameter-similarity/runs/head-dominance/raw/fresh-en-1-link-14.npz",
"sha256": "e2a7fcafc95e6ee1caab2cce5b089a73d9b51aad3fb3ad6dcb898d1932ca874c",
"derived": "legacy-base-fresh-en-1-14.npz"
},
{
"source": "/opt/exp-model-parameter-similarity/runs/head-dominance/raw/fresh-en-1-link-18.npz",
"sha256": "87577b06589afcbc0c51663ef82d3be2a53730b91834b748e1e08c9e60093153",
"derived": "legacy-base-fresh-en-1-18.npz"
},
{
"source": "/opt/exp-model-parameter-similarity/runs/head-dominance/raw/fresh-en-1-link-22.npz",
"sha256": "5decb8e48cc8399c671e39f98418f8920a89259ada3b339bb85d165b6736c747",
"derived": "legacy-base-fresh-en-1-22.npz"
},
{
"source": "/opt/exp-model-parameter-similarity/runs/head-dominance/raw/fresh-en-2-link-02.npz",
"sha256": "d21f11c5ab5d554ddbb06d6b937281bc9474f0f45e27ddc83f9c3447b2242e10",
"derived": "legacy-base-fresh-en-2-02.npz"
},
{
"source": "/opt/exp-model-parameter-similarity/runs/head-dominance/raw/fresh-en-2-link-06.npz",
"sha256": "003fb8c74875cff6def86871280218dd6166b8d248da0f4a2f68beacee2ba2fe",
"derived": "legacy-base-fresh-en-2-06.npz"
},
{
"source": "/opt/exp-model-parameter-similarity/runs/head-dominance/raw/fresh-en-2-link-10.npz",
"sha256": "7d69b262b259562f02517f3c57b978d0cf8f85d93e257f6cb8514847b01924c5",
"derived": "legacy-base-fresh-en-2-10.npz"
},
{
"source": "/opt/exp-model-parameter-similarity/runs/head-dominance/raw/fresh-en-2-link-14.npz",
"sha256": "c2fe9b11d500af37dbf2dd86c2cf0fb4a30dc4e9d45a1f3c2db7ad898f4c51f2",
"derived": "legacy-base-fresh-en-2-14.npz"
},
{
"source": "/opt/exp-model-parameter-similarity/runs/head-dominance/raw/fresh-en-2-link-18.npz",
"sha256": "d3b5ce2c4dbadfb8864c698b67fbf8561e01536d03befbd9a80bb3bf9d0341bf",
"derived": "legacy-base-fresh-en-2-18.npz"
},
{
"source": "/opt/exp-model-parameter-similarity/runs/head-dominance/raw/fresh-en-2-link-22.npz",
"sha256": "bb71e2d13fbff283728037ecff93d87e2475e182fde385216c6d59ab68113f0f",
"derived": "legacy-base-fresh-en-2-22.npz"
}
]
+128
View File
@@ -0,0 +1,128 @@
{
"REPORT.md": "5d9a955c2e47539aa4d6b3946d2695307793a4ac908781c18378aecbdbb96a64",
"adapter_meta.json": "c1262193a71bdca14ed9b762842adb34521c0a4abcdd4944606d28fbf37491c4",
"audit-output.txt": "43eadee842fd6aa6830b91f8490442f83f8127c30bff6bdbadc012800e7adc7e",
"audit.json": "43eadee842fd6aa6830b91f8490442f83f8127c30bff6bdbadc012800e7adc7e",
"baseline-references.json": "08d55f493049fe590039250d187977f7af88c32f9342f4631bc360b2b5a33cf6",
"external-caches.json": "3fcc5f222bddaea60df8241c104c092d2e807a1899f9aaa2889db28186737a05",
"figures/paired_effective_heads_by_layer.pdf": "1606898509bcd023e8dbb925cff35b798efb00046179e2182f291cd590cd6b44",
"figures/paired_effective_heads_by_layer.png": "5dc16dacbab27f2d96c95f744a72124e8eba25d398f434b666639fc3765ef82c",
"figures/paired_effective_heads_by_layer.svg": "29557150e6b9da53f3d4b792c709cbc9d929248c1e8cc2f4a7174282b091c7cd",
"figures/paired_effective_heads_cdf.pdf": "1c7e0203218dcf1dc04461c2df17a8d771a0c5f142155f0ecc2d9912eac569c2",
"figures/paired_effective_heads_cdf.png": "31ecf93a05585d2729a3426a5ceaaedb9f3d43a89fc114f12edc7d6764a898c5",
"figures/paired_effective_heads_cdf.svg": "fcfe932c82423ba4fea6f8488a5031d008b2f5484383f40e883c2e566361b107",
"figures/paired_effective_heads_delta.pdf": "35c574848fbbabc5d5952f11e73164a5be1417fbc7c670e0560e8d33451010e1",
"figures/paired_effective_heads_delta.png": "ed9232e86e945737389d5b0b00a3f32f62f49a92499fc8748dd1b0bbcd97df16",
"figures/paired_effective_heads_delta.svg": "ed5e254afa515d11935b32586ca8f530e59321ab4eb2b449a3996a7a7985a1d6",
"final-tests.txt": "d162aad1f7a8b8ad78e4e465a5618f0f201cb41701ec21acf29ba44774e77185",
"gsm8k-source.json": "1aa995a8e41c299d61749f95a6cda0478e6947c2d104d88ee2c88ac5b9cf2ae1",
"head-sum-controls.json": "13ccab8e890ae6c9898355ea93b9bfdc131974b124152050628ab5a10a61bfeb",
"hidden-state-changes.json": "9c3132ab5d71a03962d056bd11c36930fcd5dcc66fa12f747f539bbfff9e65ce",
"observations.npz": "48c33b8e1eaf3eb722f83b34507c1d4138d78b706b4cff673945c8c2f8f11a67",
"per-layer.csv": "b98afe569ca48b310f8b54af05556e06c6d9a08de2f6d6318f519d6cc1b059fd",
"per-text-layer.csv": "52b13443f17662167476fe7657c543397a549c49f767192faf8f59470a9c41d5",
"protocol.json": "70f107499364a1c43d85d4f8a0014a96fdf2eec533613cbfc9cb940887474439",
"raw/gsm8k-base-gsm8k-test-0000-02.npz": "ecfc2fe3fe70281feca0667e1f26d8a69a6106a36073ef584cbbdda66010b373",
"raw/gsm8k-base-gsm8k-test-0000-06.npz": "e7e4a7cffd8916aefb03e8aa25729e012b6f67d6bf6fc96e18885adb3e1fe566",
"raw/gsm8k-base-gsm8k-test-0000-10.npz": "135aa65770cc8d561d134051ce995758fd326a4e077369f567c2328701e5f3fa",
"raw/gsm8k-base-gsm8k-test-0000-14.npz": "6af0f8858693eca8ccaf409e62de26b1df00185dc2416b019090b267377150fc",
"raw/gsm8k-base-gsm8k-test-0000-18.npz": "33ea81625978e5e616bc51ebef4115a2c6e1cde70010448bde7810bb58200a7f",
"raw/gsm8k-base-gsm8k-test-0000-22.npz": "029854a53076fd7583a854ce74b23ab9a68779e3876b77b2a7c54093a2e30686",
"raw/gsm8k-base-gsm8k-test-0002-02.npz": "9d435e4a3d4096799727ebaf9df544c7b31cd044836bc60711f085d3f574aa07",
"raw/gsm8k-base-gsm8k-test-0002-06.npz": "47c165bedb771582c4718c5d25cec3c790b0c9e26b420f0f391e04d2c6c90220",
"raw/gsm8k-base-gsm8k-test-0002-10.npz": "bcaf0686fc04515330ad234776df491d59acaa2568ff84dcbf3c0c61522d83fb",
"raw/gsm8k-base-gsm8k-test-0002-14.npz": "d1f17789ef5e7d63390da5ff9baeaf81fa1647b54ea700794b38315486636b3e",
"raw/gsm8k-base-gsm8k-test-0002-18.npz": "458fc2ce51fc2c4bd52fbbc2490654ad08ffe708fd30e40cb3af27141e0a787c",
"raw/gsm8k-base-gsm8k-test-0002-22.npz": "040004d851fc6ea916054307e9cb1be6e98a8393865be1a55d0fe69f1fe2a843",
"raw/gsm8k-base-gsm8k-test-0003-02.npz": "7bb4247e7a0b1db976bbeb3e67f54ab3dec94ae7e399a32a34dd3f81c5b7001f",
"raw/gsm8k-base-gsm8k-test-0003-06.npz": "962976972eb64108068262a349aba53b7c81c6f7753ce5f9cf2c16c50e3f7df3",
"raw/gsm8k-base-gsm8k-test-0003-10.npz": "e6a554f3477c373a0d662c8e7469099fcd0f3b0647b203ceaa5cb2c7fdcdc39b",
"raw/gsm8k-base-gsm8k-test-0003-14.npz": "898f490b0989e5967d56e760fa9f8f6fff2b39449d5528ae461710e8e1fefa84",
"raw/gsm8k-base-gsm8k-test-0003-18.npz": "91197613bf169d3f45381e8660811f4eedf4883d7e744c11be8f18035efaa606",
"raw/gsm8k-base-gsm8k-test-0003-22.npz": "b9f0c1a7f9a3c0ecb77443c6ffa2d8a4f8addc75b5acf5a65a48d7e493bbaa62",
"raw/gsm8k-base-gsm8k-test-0004-02.npz": "4bd803b726afe24f486b8f6795c576b82cbf66216f081c4377f3148cc945f064",
"raw/gsm8k-base-gsm8k-test-0004-06.npz": "b2480beb27a7097e1ffc9ffccf36607bdb466a693bf681743d6dc27bd6b8ef25",
"raw/gsm8k-base-gsm8k-test-0004-10.npz": "d97ec969621c07cf415c32894bd1d58d0ceaaafa09d52e794ab64fc4f77743a9",
"raw/gsm8k-base-gsm8k-test-0004-14.npz": "5202e7e67545d28c098b8a69c64df7df9ce0cee14159b3c63b242ec413962845",
"raw/gsm8k-base-gsm8k-test-0004-18.npz": "3967869d031d0dfc369843b17598a8ed974eef29a92a67ca3039e5f8d54756fc",
"raw/gsm8k-base-gsm8k-test-0004-22.npz": "65fc463f1a0c2ab6f8ee43a1b5b7550c237ce68439139bff68f8fcb6929774bd",
"raw/gsm8k-finetuned-gsm8k-test-0000-02.npz": "70ca3d17ab016639e7b82e0a86ff7ac8010e010568a3d557314af81c8ae56f02",
"raw/gsm8k-finetuned-gsm8k-test-0000-06.npz": "c3dd0bfa9c2aadcad83406740a7cb26103f36869e86e8dde54bc444f20486f88",
"raw/gsm8k-finetuned-gsm8k-test-0000-10.npz": "dd4dc2adf0f138748734269e5c567c1ecd1409f613227de4fce4c6b0e496959c",
"raw/gsm8k-finetuned-gsm8k-test-0000-14.npz": "444db92129fcf1361563bc694413772eeae5cd4a8468bbd5c8f20a5c8f84c581",
"raw/gsm8k-finetuned-gsm8k-test-0000-18.npz": "d329c4e1f66ac7faba575af3c79159b661ecb9a0a0b8774fe261b29c46d596b3",
"raw/gsm8k-finetuned-gsm8k-test-0000-22.npz": "8822354b5cb72d519d1999f4572d6dd01e73c3b8ab9d9c42c149d8a3c67ded9f",
"raw/gsm8k-finetuned-gsm8k-test-0002-02.npz": "6382a19dbb82da1550b276fca614a49aa4eb2ff9432b661ee24a70583f10444c",
"raw/gsm8k-finetuned-gsm8k-test-0002-06.npz": "7b3eabeed7793fc1c30ef04be2f5e94b73b6aafe635601cc543b2713b986b50a",
"raw/gsm8k-finetuned-gsm8k-test-0002-10.npz": "1296bd5ef6bfc564cfe3d641fae2bcfc605ab1c8965e7f983e0e6332208ac956",
"raw/gsm8k-finetuned-gsm8k-test-0002-14.npz": "31e344565c5e3935693ae72f488d7bad994f7a45b750b31b645642367dbdf945",
"raw/gsm8k-finetuned-gsm8k-test-0002-18.npz": "b1b8c224355373caccaf3fa0d5542e9a39b726904ab154c67e36d46be2f5f6c4",
"raw/gsm8k-finetuned-gsm8k-test-0002-22.npz": "d8b00f473c025ed6f55e72385b2e6e34ab4e3557af5e743d799834e2e3abf7f6",
"raw/gsm8k-finetuned-gsm8k-test-0003-02.npz": "bbaa5a3f1a6978a8f1b0f2ae136986b2e6aa19cc37179c4490f273d8a1bd742b",
"raw/gsm8k-finetuned-gsm8k-test-0003-06.npz": "48a1417b11e1188fd9b2262d283d366ea158ef6152e3ed38bacda61b44b88230",
"raw/gsm8k-finetuned-gsm8k-test-0003-10.npz": "d57ac5c308fd2d7c8c47c9d9f8306c36e8502592adc535f48306a69f406b2e83",
"raw/gsm8k-finetuned-gsm8k-test-0003-14.npz": "acee7b009e3ae76760a382c37c7bcde01aec93f5f18eec5df3bd63e5d40f7a46",
"raw/gsm8k-finetuned-gsm8k-test-0003-18.npz": "21507efdf6cd88164a39a010a1d7892273ea30844af876ee1d0a8e458fce1b3a",
"raw/gsm8k-finetuned-gsm8k-test-0003-22.npz": "9bf79f32a875142ccaff29f1a7f158281e4577c367899eaeea4dc3963d54dbcc",
"raw/gsm8k-finetuned-gsm8k-test-0004-02.npz": "85e6678bf76d36936601b59d9974642eef6c56991dc73f81d3e50631d945b84a",
"raw/gsm8k-finetuned-gsm8k-test-0004-06.npz": "c38802c693d40e9974e63b85625e7e4976859514e5c44b56fa037cde49fd6fcb",
"raw/gsm8k-finetuned-gsm8k-test-0004-10.npz": "217d547f807bd056f5fa407d192aa4ccaae3c5e1ff11fbe77d8cf8a16a971021",
"raw/gsm8k-finetuned-gsm8k-test-0004-14.npz": "7b93542d836bcc1c5e6053a4b447997e2f5afafc2dbee1834b0bf31f9da246a4",
"raw/gsm8k-finetuned-gsm8k-test-0004-18.npz": "457a03603055b4ad7da5c4b347370e070904b4996a1fe508651e56043a323c20",
"raw/gsm8k-finetuned-gsm8k-test-0004-22.npz": "580db43631651cb501f9a34051e0bbf4a875cd3f8e25b1ed1c79026dc1f2ce7c",
"raw/legacy-base-fresh-en-1-02.npz": "02d39a0c9063d9b49026098e1026d9e8ed6658a52eea00a117cf8868fbe5a9c5",
"raw/legacy-base-fresh-en-1-06.npz": "d9d37a188840807d1e8e3c68826e49054b2ac90c445f73022a5290f4160a7716",
"raw/legacy-base-fresh-en-1-10.npz": "39d50060988427a999b9b7fee1a340cffa3d1b27e55e96b38f980ba4b6ca182c",
"raw/legacy-base-fresh-en-1-14.npz": "985c54ad7e4d96fcd53ff1f1b290c5a5018ec7e4218b16b1104866745ba83719",
"raw/legacy-base-fresh-en-1-18.npz": "a8ed3dd62428dca4b3fdad9bdb159609e0d2fe38657681d7acca42d79c2bb876",
"raw/legacy-base-fresh-en-1-22.npz": "da1a5799d789e8561935448e2eb49a2427865ce26602b26f3df2c19fa8f061b9",
"raw/legacy-base-fresh-en-2-02.npz": "918fb1ed19925ec01f60d02ac2edd813de6638c1b6dba8e2ccc16b2921d06a41",
"raw/legacy-base-fresh-en-2-06.npz": "84447aec23901d8430b38a69a2601c48f7e57aa7224ab740362b7c36dc0300e7",
"raw/legacy-base-fresh-en-2-10.npz": "6c89f1f7b87fd28ca9d3292b043280bfd1841ee38d8f077ece52d17d5aa9428b",
"raw/legacy-base-fresh-en-2-14.npz": "20140c00b5df0750cb5929fa20ddd39f935ff536d6b0ad019abe5b75dfaa626f",
"raw/legacy-base-fresh-en-2-18.npz": "eac15b1f5c19baecff37ae792195c69e978cd1d592090e28e580e8114a491c62",
"raw/legacy-base-fresh-en-2-22.npz": "3e089d27887946450b5961f8bfe99d4725ff59872de86ef547a5512fcfc5f622",
"raw/legacy-base-fresh-zh-1-02.npz": "3459f24661cdd9b58fa8aaed0081db19400ebd758d4ace7112df926f5c11baad",
"raw/legacy-base-fresh-zh-1-06.npz": "502aa9cd493c863abddaa44c1b530d94703b2fbe0b04489d7638457576770291",
"raw/legacy-base-fresh-zh-1-10.npz": "6ebc0d130320a1bc9037dbb17c258e2f8501af4f1dc7dbc750caac6ef38a4f39",
"raw/legacy-base-fresh-zh-1-14.npz": "45f10901f3f1bfd9d069bf7c92ae9c6807b3ae1220bbbfe0a1d61a3cb3a1b5c5",
"raw/legacy-base-fresh-zh-1-18.npz": "199ccf41bc26a03fafd69d3890b1f389a2152f1afaefcd972eff15f36f36b780",
"raw/legacy-base-fresh-zh-1-22.npz": "2551355956dfdf20ff381e150eb1f618d134913403a30eda6e02270742b2e31a",
"raw/legacy-base-fresh-zh-2-02.npz": "db0e721058e7149766328c2a2b17b55f02daff750daf732a061fa54248186a8f",
"raw/legacy-base-fresh-zh-2-06.npz": "acc584949dea7baaefdf8f8a7e95ea0be812bbb364335df97274ea316181c309",
"raw/legacy-base-fresh-zh-2-10.npz": "a54b0133e538d96c469e63ef5b33590a9c0895837bd53aef758377b7584d51e6",
"raw/legacy-base-fresh-zh-2-14.npz": "8d58f0672075f97009009508978216bc131d8a69754046cfc619f7d5ed83aec0",
"raw/legacy-base-fresh-zh-2-18.npz": "5503272cf1787c1c87f1502621bea2f18801a14d8424554736ea9640c778a2a8",
"raw/legacy-base-fresh-zh-2-22.npz": "7daa469f1c68756cf3078ad691a35c2eb26cc78d420d79cd16cc03512df907d3",
"raw/legacy-finetuned-fresh-en-1-02.npz": "dacb43fbde5b7cd0ae011141818832545a29d0e0ece532ad7f076ac1770d576e",
"raw/legacy-finetuned-fresh-en-1-06.npz": "1adb8642c4c2767c99301a7f92107d98426636456d70bd3e69868df3332997f0",
"raw/legacy-finetuned-fresh-en-1-10.npz": "4540b80c2c630c293841278066a4a17f36c9fe3fa2a1fae9ed0c7ba4d7b70c55",
"raw/legacy-finetuned-fresh-en-1-14.npz": "1928fb89a08af6b843ffcb6ff58ab4d0ac5b0848d9e35a04a91884c1a929b893",
"raw/legacy-finetuned-fresh-en-1-18.npz": "7348f577974ce49f0d618b78ea99f32c6e7ea66265ba048d688e1faccb1c4743",
"raw/legacy-finetuned-fresh-en-1-22.npz": "aced3a86e6dec59d49a42f24d142b2bf62c93fbc31441395a42bcc46d786f749",
"raw/legacy-finetuned-fresh-en-2-02.npz": "e3689374812d9fb4bc00827fd9e6b082ba73d8546e9ec9f7c5ef692c6946dafb",
"raw/legacy-finetuned-fresh-en-2-06.npz": "ac9fcc744476e47494d3d60922573e90af8de4a45a5b426931386b8f0adb16cb",
"raw/legacy-finetuned-fresh-en-2-10.npz": "d5ca98484ca83735319218b58c9a11146a9d884976034a839adb7036fec295e0",
"raw/legacy-finetuned-fresh-en-2-14.npz": "b89dd50f99ebe5eccb99e153585566fab5f40178394e3992e1f7d12ff11089fe",
"raw/legacy-finetuned-fresh-en-2-18.npz": "0f0ddd848aa51d98ba8c4a288ea93d6304c578bbf3a563e88a3028dce52ad9d9",
"raw/legacy-finetuned-fresh-en-2-22.npz": "670883b063d993ac96ceb7e258d4de2a03bd7fbb8639aca24fc49602a6ba6d6a",
"raw/legacy-finetuned-fresh-zh-1-02.npz": "f2bef255988bd0d947c65c06808c7d0caceab30d832015b55bcd8342d9bf28b9",
"raw/legacy-finetuned-fresh-zh-1-06.npz": "c2d886c833ca4e51d53d57a2b076ea915c0d517ef26ed5b1d143b9224829922b",
"raw/legacy-finetuned-fresh-zh-1-10.npz": "c20f2d166d175fbec7e236d6b95da6dd61865c7ab4cc17433a46647a0d511a11",
"raw/legacy-finetuned-fresh-zh-1-14.npz": "c005ec04e8c439543cc5b3a9643f267d414c2757c43d1706f493f937d4f6ffc4",
"raw/legacy-finetuned-fresh-zh-1-18.npz": "d01520126987ace2f73f3eaef5e560326158c16cf66c659626ab933e17622b1d",
"raw/legacy-finetuned-fresh-zh-1-22.npz": "40933610f61bbb4d9c29c278b7fa1a188d4f8813fb827515a01dce90aa827feb",
"raw/legacy-finetuned-fresh-zh-2-02.npz": "7d2828387978b21801a87d924e8e254c39c599c5781b82a7a5d05ecb9d239f27",
"raw/legacy-finetuned-fresh-zh-2-06.npz": "a82b7ad2e05cd6019a05ae4bc2184171c5493cc26577bd347e5cc9176d8e28d1",
"raw/legacy-finetuned-fresh-zh-2-10.npz": "49d0311d99960838036083e8d866ba418146538bae6b098f84d6a45824dc5dda",
"raw/legacy-finetuned-fresh-zh-2-14.npz": "729cea1ba6f3f4d694552002900085256f4ffdf2dc06c0d5ae6d6829be3f1749",
"raw/legacy-finetuned-fresh-zh-2-18.npz": "0a13c6bd541c3afe521de2fcc51bbcaf2ec180ffb8adfd98eb179171e2e80b20",
"raw/legacy-finetuned-fresh-zh-2-22.npz": "2dbcd8ea5d4dc09bf160462ba0fc1f7cfd52ca1b1f9e4914227aa2b746ed3c35",
"report-output.txt": "5d9a955c2e47539aa4d6b3946d2695307793a4ac908781c18378aecbdbb96a64",
"run-log.txt": "afe8f52f7bf8694b088c15f610915fd91b77236d6b90282fd11d6164d229ae9e",
"samples.json": "d5d5d707ba9365a0ad43e2a03d4c4659ddc4e6b1fc665ed14f9fceb1757f4d28",
"source-hashes.json": "410aa0685f26e65311589abafc9661eb1054b5ab8e6beac5e85adbbd4c7396d5",
"status.json": "41afcb194af4ed23fb1f80bee803e135059e06c403d9ab9b936d39be0ad3f4f9",
"summary.json": "fa0df1bb7f7b7174885e7c9b37da0e05e46acc3932830c8f4f2476f23fa54b38",
"weight-update-summary.json": "cb22c0e21a60c9d36ea2e7827b8b4b54b127e10e6e7aa47869d936f7e78e2013"
}
File diff suppressed because it is too large Load Diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 185 KiB

File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 144 KiB

File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 142 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 72 KiB

@@ -0,0 +1,49 @@
test_3d_reader_and_exact_block (tests.test_pilot.PilotTests.test_3d_reader_and_exact_block) ... ok
test_bfloat16 (tests.test_pilot.PilotTests.test_bfloat16) ... ok
test_directional_replacement_error_and_scaling (tests.test_pilot.PilotTests.test_directional_replacement_error_and_scaling) ... ok
test_end_to_end_synthetic_groups_and_savings (tests.test_pilot.PilotTests.test_end_to_end_synthetic_groups_and_savings) ... Inventory: 4 tensors, 33792 bytes
tensor: sampling 4 objects
block: sampling 22 objects
block: verified 100/109
{"model": "synthetic", "revision": "test", "tensor_count": 4, "parameter_count": 8448, "model_weight_bytes": 33792, "ndim_counts": {"2": 2, "3": 2}, "elapsed_seconds": 0.09112083166837692, "analysis_budget_seconds": 60, "peak_rss_kib": 55772, "python": "3.14.4", "numpy": "2.5.4", "seed": 20261109, "limitations": ["No inference or functional equivalence measured", "No exhaustive pair search", "Block search uses per-role/shape/scale reservoirs of 256", "Different block scales overlap; savings must not be added", "Block savings count only verified disjoint sampled blocks, no extrapolation", "Spectral probes use aligned bounded subvolumes, not whole tensors", "Shared encoding is theoretical, not a runnable compressed checkpoint", "No cross-role grouping, neuron permutation alignment, or training"], "completed": true}
ok
test_no_transitive_chaining (tests.test_pilot.PilotTests.test_no_transitive_chaining) ... ok
test_ranged_download_preserves_prefix (tests.test_pilot.PilotTests.test_ranged_download_preserves_prefix) ... Weight download 36/36 bytes (100.0%)
ok
test_causal_convolution_and_norm_boundary (tests.test_functional.FunctionalTests.test_causal_convolution_and_norm_boundary) ... ok
test_causality_and_identical_function_metrics (tests.test_functional.FunctionalTests.test_causality_and_identical_function_metrics) ... ok
test_neuron_function_metrics_and_targeted_replacement (tests.test_functional.FunctionalTests.test_neuron_function_metrics_and_targeted_replacement) ... ok
test_nonrotary_gain_identity_and_rotary_negative_control (tests.test_functional.FunctionalTests.test_nonrotary_gain_identity_and_rotary_negative_control) ... ok
test_streamed_projection_embedding_and_output_head (tests.test_functional.FunctionalTests.test_streamed_projection_embedding_and_output_head) ... ok
test_uniform_rmsnorm_function_bound_is_tight (tests.test_functional.FunctionalTests.test_uniform_rmsnorm_function_bound_is_tight) ... ok
test_assignment_against_exhaustive_and_inverse (tests.test_crossqkv.CrossQKVTests.test_assignment_against_exhaustive_and_inverse) ... ok
test_cached_mode_rejects_future_state_reuse (tests.test_crossqkv.CrossQKVTests.test_cached_mode_rejects_future_state_reuse) ... ok
test_controls_cover_multiple_projection_layers (tests.test_crossqkv.CrossQKVTests.test_controls_cover_multiple_projection_layers) ... ok
test_head_matrix_metrics_and_gram_are_diagnostic (tests.test_crossqkv.CrossQKVTests.test_head_matrix_metrics_and_gram_are_diagnostic) ... ok
test_probability_identity_and_nontrivial_queries (tests.test_crossqkv.CrossQKVTests.test_probability_identity_and_nontrivial_queries) ... ok
test_profile_matches_canonical_and_head_sum (tests.test_crossqkv.CrossQKVTests.test_profile_matches_canonical_and_head_sum) ... ok
test_recipient_value_gate_output_and_gqa_group_stay_fixed (tests.test_crossqkv.CrossQKVTests.test_recipient_value_gate_output_and_gqa_group_stay_fixed) ... ok
test_topk_tail_rank_can_change_with_tiny_probability_difference (tests.test_crossqkv.CrossQKVTests.test_topk_tail_rank_can_change_with_tiny_probability_difference) ... ok
test_known_activity (tests.test_activation.ActivationTests.test_known_activity) ... ok
test_zero_and_scale (tests.test_activation.ActivationTests.test_zero_and_scale) ... ok
test_continuous_limits_and_undefined_zero (tests.test_dominance.DominanceTests.test_continuous_limits_and_undefined_zero) ... ok
test_joint_recomputation_null_and_saved_raw (tests.test_dominance.DominanceTests.test_joint_recomputation_null_and_saved_raw) ... baseline layer 0
baseline layer 1
ok
test_js_identity_and_disjoint (tests.test_dominance.DominanceTests.test_js_identity_and_disjoint) ... ok
test_mask_ranks_vary_by_token_and_recipient (tests.test_dominance.DominanceTests.test_mask_ranks_vary_by_token_and_recipient) ... ok
test_mixed_layer_forward_and_effective_qkv (tests.test_dominance.DominanceTests.test_mixed_layer_forward_and_effective_qkv) ... baseline layer 0
baseline layer 1
baseline layer 0
baseline layer 1
ok
test_effective_rows_equal_explicit_low_rank_output (tests.test_finetune_compare.FineTuneTests.test_effective_rows_equal_explicit_low_rank_output) ... ok
test_forward_and_head_decomposition_match_independent_overlay (tests.test_finetune_compare.FineTuneTests.test_forward_and_head_decomposition_match_independent_overlay) ... baseline layer 0
baseline layer 1
ok
test_zero_scale_preserves_original_and_bad_metadata_rejected (tests.test_finetune_compare.FineTuneTests.test_zero_scale_preserves_original_and_bad_metadata_rejected) ... ok
----------------------------------------------------------------------
Ran 30 tests in 23.124s
OK
@@ -0,0 +1,9 @@
{
"repository": "https://github.com/openai/grade-school-math",
"revision": "3101c7d5072418e28b9008a6636bde82a006892c",
"url": "https://raw.githubusercontent.com/openai/grade-school-math/3101c7d5072418e28b9008a6636bde82a006892c/grade_school_math/data/test.jsonl",
"sha256": "3730d312f6e3440559ace48831e51066acaca737f6eabec99bccb9e4b3c39d14",
"split": "test",
"format": "original author JSONL",
"rows": 1319
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,45 @@
{
"definition": "final residual before final RMSNorm, not logits, accuracy or LM quality",
"changes": [
{
"cohort": "legacy",
"sample": "fresh-zh-1",
"final_pre_norm_residual_relative_l2": 0.021898728857078685
},
{
"cohort": "legacy",
"sample": "fresh-zh-2",
"final_pre_norm_residual_relative_l2": 0.03829561458389978
},
{
"cohort": "legacy",
"sample": "fresh-en-1",
"final_pre_norm_residual_relative_l2": 0.02432907925877068
},
{
"cohort": "legacy",
"sample": "fresh-en-2",
"final_pre_norm_residual_relative_l2": 0.034934933219615986
},
{
"cohort": "gsm8k",
"sample": "gsm8k-test-0000",
"final_pre_norm_residual_relative_l2": 0.03901556767460501
},
{
"cohort": "gsm8k",
"sample": "gsm8k-test-0002",
"final_pre_norm_residual_relative_l2": 0.04043223109300957
},
{
"cohort": "gsm8k",
"sample": "gsm8k-test-0003",
"final_pre_norm_residual_relative_l2": 0.045740534396548564
},
{
"cohort": "gsm8k",
"sample": "gsm8k-test-0004",
"final_pre_norm_residual_relative_l2": 0.04190792993325029
}
]
}
Binary file not shown.

Some files were not shown because too many files have changed in this diff Show More