Measure CPU block activation sparsity and energy concentration
This commit is contained in:
@@ -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.
|
||||
@@ -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())
|
||||
@@ -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))
|
||||
@@ -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()
|
||||
Reference in New Issue
Block a user