#!/usr/bin/env python3 # -*- coding: utf-8 -*- """最终汇总 markdown: 所有方法 × 6模型+随机 × K × 5指标 × 口径(全部/只有组) × 还原/不还原. 方法: wordnet(近义) / super(同类别) / minilm@0.4/0.45/0.5 5 指标 (全部 size>=2 口径): frac_merged / avg组词数 / max组词数 / avg组数 / max组数 口径 (外部变量, 仅对均值类 frac/avg组词/avg组数 有意义): 全部 = 所有 channel 平均 (mean_all) 只有组 = 只在'有>=1个size>=2组'的 channel 上平均 (mean_grouponly); 分子同, 分母换 n_with_group 还原/不还原 (E): ctx=碎片还原 / noctx=不还原. 默认显示 ctx (还原); 文末附 ctx vs noctx 对照说明. """ import json, io from pathlib import Path RES = Path(__file__).parent MODELS = [("llama3_8b", "Llama3-8B"), ("llama32_1b", "Llama3-1B"), ("gemma3_1b", "Gemma3-1B"), ("gemma3_4b", "Gemma3-4B"), ("qwen3_1b", "Qwen3-1.7B"), ("qwen3_8b", "Qwen3-8B")] KS = [3, 5, 10, 20, 30, 50] ENC_THS = [0.4, 0.45, 0.5] # (显示名, kind, is_frac) # kind: 'frac'/'avg_size'/'avg_n' = 均值类(有口径); 'max_size'/'max_n' = max类(无口径) METRICS = [ ("frac_merged (%)", "frac", True), ("avg组词数", "avg_size", False), ("max组词数", "max_size", False), ("avg组数", "avg_n", False), ("max组数", "max_n", False), ] HAS_SCOPE = {"frac", "avg_size", "avg_n"} def L(p): f = RES / p return json.load(io.open(f, encoding="utf-8")) if f.exists() else None def _real_block(byk, K, thresh): """返回 (mean_all_dict, mean_grouponly_dict, max_size, max_n) 或 None.""" if byk is None or str(K) not in byk: return None bk = byk[str(K)] if thresh is not None: bt = bk.get("by_thresh", {}).get(str(thresh)) if bt is None: return None return (bt.get("mean_all", {}), bt.get("mean_grouponly", {}), bt.get("max_group_size_int_all"), bt.get("max_n_multi_groups_all")) return (bk.get("mean_all", {}), bk.get("mean_grouponly", {}), bk.get("max_group_size_int_all"), bk.get("max_n_multi_groups_all")) def real_val(byk, K, kind, scope, thresh): b = _real_block(byk, K, thresh) if b is None: return None mean_all, mean_grp, mx_size, mx_n = b d = mean_grp if scope == "grouponly" else mean_all if kind == "frac": return d.get("frac_merged") if kind == "avg_size": return d.get("avg_multi_size") if kind == "avg_n": return d.get("n_multi_groups") if kind == "max_size": return mx_size if kind == "max_n": return mx_n return None def rand_val(rand, method, K, kind, scope): """旧版全局随机 (curated 词典). 保留兼容.""" if rand is None: return None e = rand.get("by_method", {}).get(method, {}).get(str(K)) if e is None: return None sfx = "_grouponly" if scope == "grouponly" else "_mean" if kind == "frac": return e.get("frac_merged" + sfx) if kind == "avg_size": return e.get("avg_multi_size" + sfx) if kind == "avg_n": return e.get("n_multi_groups" + sfx) if kind == "max_size": return e.get("max_group_size_int") if kind == "max_n": return e.get("max_n_multi_groups") return None _V2_CACHE = {} def _v2(mid): if mid not in _V2_CACHE: _V2_CACHE[mid] = L(f"random_v2_{mid}.json") return _V2_CACHE[mid] _PERM_CACHE = {} def _perm(mid): if mid not in _PERM_CACHE: _PERM_CACHE[mid] = L(f"random_perm_{mid}.json") return _PERM_CACHE[mid] def randperm_val(method, K, kind, scope): """置换/匹配 null: 用真实 channel 自己的 token multiset 抽 K, 跨 6 模型平均. 碎片率/真实词数 与真实 channel 一致 -> 这才是公平的'by chance'对照.""" vals = [] for mid, _ in MODELS: d = _perm(mid) if not d: continue e = d.get("perm", {}).get(method, {}).get(str(K)) if e is None: continue sfx = "_grouponly" if scope == "grouponly" else "_mean" if kind == "frac": v = e.get("frac_merged" + sfx) elif kind == "avg_size": v = e.get("avg_multi_size" + sfx) elif kind == "avg_n": v = e.get("n_multi_groups" + sfx) elif kind == "max_size": v = e.get("max_group_size_int") elif kind == "max_n": v = e.get("max_n_multi_groups") else: v = None if v is not None: vals.append(v) if not vals: return None if kind in ("max_size", "max_n"): return max(vals) return sum(vals) / len(vals) def randv2_val(pool, method, K, kind, scope): """v2 随机 (per-model 真实 token 池), 跨 6 模型平均. pool: 'alpaca'/'vocab'.""" vals = [] for mid, _ in MODELS: d = _v2(mid) if not d: continue e = d.get(pool, {}).get(method, {}).get(str(K)) if e is None: continue sfx = "_grouponly" if scope == "grouponly" else "_mean" if kind == "frac": v = e.get("frac_merged" + sfx) elif kind == "avg_size": v = e.get("avg_multi_size" + sfx) elif kind == "avg_n": v = e.get("n_multi_groups" + sfx) elif kind == "max_size": v = e.get("max_group_size_int") elif kind == "max_n": v = e.get("max_n_multi_groups") else: v = None if v is not None: vals.append(v) if not vals: return None # max 类取跨模型 max; 均值类取跨模型平均 if kind in ("max_size", "max_n"): return max(vals) return sum(vals) / len(vals) def fmt(v, is_frac, is_int): if v is None: return "—" if is_frac: return f"{100*v:.1f}" if is_int: return f"{int(round(v))}" return f"{v:.2f}" def method_table(title, ctx_prefix, rand_method, thresh, lines): """一个方法一个区块. 均值类指标: 每模型两行(全部/只有组)+随机两行; max类: 每模型一行.""" lines.append(f"\n### {title}\n") rand = L("random_baseline.json") for mname, kind, is_frac in METRICS: is_int = kind in ("max_size", "max_n") scoped = kind in HAS_SCOPE if scoped: lines.append(f"\n**{mname}** (上=全部channel / 下=只算有近义组的channel; 还原碎片)\n") lines.append("| 模型 | 口径 | " + " | ".join(f"K={k}" for k in KS) + " |") lines.append("|---|---|" + "|".join("---" for _ in KS) + "|") for mid, label in MODELS: d = L(f"{ctx_prefix}_{mid}.json") byk = d["by_k"] if d else None for tag, scope in (("全部", "all"), ("只有组", "grouponly")): row = [fmt(real_val(byk, k, kind, scope, thresh), is_frac, is_int) for k in KS] lab = label if tag == "全部" else "" lines.append(f"| {lab} | {tag} | " + " | ".join(row) + " |") for tag, scope in (("全部", "all"), ("只有组", "grouponly")): rp = [fmt(randperm_val(rand_method, k, kind, scope), is_frac, is_int) for k in KS] ra = [fmt(randv2_val("alpaca", rand_method, k, kind, scope), is_frac, is_int) for k in KS] rv = [fmt(randv2_val("vocab", rand_method, k, kind, scope), is_frac, is_int) for k in KS] rd = [fmt(rand_val(rand, rand_method, k, kind, scope), is_frac, is_int) for k in KS] lines.append(f"| **随机·匹配(置换)** | {tag} | " + " | ".join(rp) + " |") lines.append(f"| 随机·alpaca | {tag} | " + " | ".join(ra) + " |") lines.append(f"| 随机·vocab | {tag} | " + " | ".join(rv) + " |") lines.append(f"| 随机·词典 | {tag} | " + " | ".join(rd) + " |") else: lines.append(f"\n**{mname}** (还原碎片)\n") lines.append("| 模型 | " + " | ".join(f"K={k}" for k in KS) + " |") lines.append("|---|" + "|".join("---" for _ in KS) + "|") for mid, label in MODELS: d = L(f"{ctx_prefix}_{mid}.json") byk = d["by_k"] if d else None row = [fmt(real_val(byk, k, kind, "all", thresh), is_frac, is_int) for k in KS] lines.append(f"| {label} | " + " | ".join(row) + " |") rp = [fmt(randperm_val(rand_method, k, kind, "all"), is_frac, is_int) for k in KS] ra = [fmt(randv2_val("alpaca", rand_method, k, kind, "all"), is_frac, is_int) for k in KS] rv = [fmt(randv2_val("vocab", rand_method, k, kind, "all"), is_frac, is_int) for k in KS] rd = [fmt(rand_val(rand, rand_method, k, kind, "all"), is_frac, is_int) for k in KS] lines.append(f"| **随机·匹配(置换)** | " + " | ".join(rp) + " |") lines.append(f"| 随机·alpaca | " + " | ".join(ra) + " |") lines.append(f"| 随机·vocab | " + " | ".join(rv) + " |") lines.append(f"| 随机·词典 | " + " | ".join(rd) + " |") def ctx_compare(lines): """ctx vs noctx 对照: frac_merged @K50 全部口径, 每方法一行差值.""" lines.append("\n## 附: 还原 vs 不还原 (E) — frac_merged@K50 全部口径\n") lines.append("| 方法 | 模型 | 还原(ctx) | 不还原(noctx) | Δ |") lines.append("|---|---|---|---|---|") specs = [("近义", "sweep_expctx", "sweep_exp", None), ("同类", "sweep_superctx", "sweep_super", None)] for th in ENC_THS: specs.append((f"MiniLM@{th}", "sweep_encctx", "sweep_enc", th)) for mlabel, cp, np_, th in specs: for mid, label in MODELS: dc = L(f"{cp}_{mid}.json"); dn = L(f"{np_}_{mid}.json") vc = real_val(dc["by_k"], 50, "frac", "all", th) if dc else None vn = real_val(dn["by_k"], 50, "frac", "all", th) if dn else None if vc is None and vn is None: continue dlt = f"{100*(vc-vn):+.1f}" if (vc is not None and vn is not None) else "—" lines.append(f"| {mlabel} | {label} | {fmt(vc,True,False)} | {fmt(vn,True,False)} | {dlt} |") def _real_avg_frac(cp, K, thresh): vals = [] for mid, _ in MODELS: d = L(f"{cp}_{mid}.json") if not d: continue v = real_val(d["by_k"], K, "frac", "all", thresh) if v is not None: vals.append(v) return sum(vals) / len(vals) if vals else None def headline_compare(lines): """核心结论: 真实 channel(6模型平均) vs 置换null 的 frac_merged 差值, 全部口径.""" specs = [("WordNet-近义", "sweep_expctx", "wordnet", None), ("WordNet-同类", "sweep_superctx", "super", None), ("MiniLM@0.4", "sweep_encctx", "enc0.4", 0.4), ("MiniLM@0.45", "sweep_encctx", "enc0.45", 0.45), ("MiniLM@0.5", "sweep_encctx", "enc0.5", 0.5)] lines.append("## 核心结论 — 真实 channel vs 置换null (frac_merged%, 全部口径, 6模型平均)\n") lines.append("> **判定**: Δ = 真实 − 置换null。Δ>0 ⇒ channel 聚合超过'同 token 组成随机配对'的偶然水平 = 真在自聚合。\n") lines.append("> **结论**: 所有方法一致 — 小-中 K (3–20) Δ>0 (channel 顶部 token 真聚近义/同义), 大 K (50) Δ<0 (深入排名后取到弱激活噪声, 不再聚)。语义 encoder (MiniLM) 的正效应比 WordNet 持续到更大 K。\n") for name, cp, rm, th in specs: lines.append(f"\n**{name}**\n") lines.append("| 口径 | " + " | ".join(f"K={k}" for k in KS) + " |") lines.append("|---|" + "|".join("---" for _ in KS) + "|") r = [_real_avg_frac(cp, k, th) for k in KS] p = [randperm_val(rm, k, "frac", "all") for k in KS] lines.append("| 真实 | " + " | ".join(f"{100*x:.1f}" if x is not None else "—" for x in r) + " |") lines.append("| 置换null | " + " | ".join(f"{100*x:.1f}" if x is not None else "—" for x in p) + " |") dl = [(100*(a-b)) if (a is not None and b is not None) else None for a, b in zip(r, p)] lines.append("| **Δ(真−null)** | " + " | ".join(f"{x:+.1f}" if x is not None else "—" for x in dl) + " |") lines.append("") def selectivity_section(lines): """指标③ 数据集归一专一度 selectivity@K (real vs 纯随机 baseline).""" lines.append("\n## 指标③ — 数据集归一专一度 selectivity@K (real vs 纯随机 baseline)\n") lines.append("> **selectivity@K** = 每 channel 的 top-K *激活* token 的 `min(num/den,1)` 均值 (跨 channel+模块平均)。" "num=该 channel 高激活该 token 的次数; den=该 token 在数据集的总出现数 (tokenizer strip 计数)。\n") lines.append("> **纯随机 baseline** = 逐模块把每个 token 的总高激活数均匀随机重分配到 N 个 channel " "(保 token 总数+den 不变), 同公式算 = '若 channel 不挑 token, 纯随机会有多专一'。\n") lines.append("> **读法**: real 在小 K (3–10) 远高于 random → channel 顶部激活 token 被真正垄断(专一); " "大 K 时 random 追上 → 深层稀有词 sel≈1 是组合学必然。Δ 在 K=3 最大。\n") any_data = False for mid, label in MODELS: d = L(f"sel_sweep_{mid}.json") if not d: continue any_data = True real = [d["real"].get(str(k)) for k in KS] rand = [d["rand"].get(str(k)) for k in KS] dlt = [(a - b) if (a is not None and b is not None) else None for a, b in zip(real, rand)] f = lambda xs: " | ".join(f"{x:.3f}" if x is not None else "—" for x in xs) fd = lambda xs: " | ".join(f"{x:+.3f}" if x is not None else "—" for x in xs) lines.append(f"\n**{label}**\n") lines.append("| 量 | " + " | ".join(f"K={k}" for k in KS) + " |") lines.append("|---|" + "|".join("---" for _ in KS) + "|") lines.append("| **real** | " + f(real) + " |") lines.append("| random | " + f(rand) + " |") lines.append("| Δ(真−rand) | " + fd(dlt) + " |") if not any_data: lines.append("\n*(sel_sweep_*.json 未找到)*\n") def main(): lines = ["# Channel 自聚合 — 最终汇总表", "", "**6 模型 (llama3 1b/8b, gemma3 1b/4b, qwen3 1.7b/8b) + 纯随机 × K∈{3,5,10,20,30,50} × 5 指标 × 多方法**", "", "## 指标定义 (全部 size≥2 口径)", "- **frac_merged** = Σ(size≥2组词数) / 真实词总数 — 落在近义/同类组里的词占比", "- **avg组词数** = size≥2 组的平均词数 (avg_multi_size)", "- **max组词数** = 最大一组的词数 (跨 channel max)", "- **avg组数** = size≥2 组的平均个数 (跨 channel 平均)", "- **max组数** = 单 channel 最多几个 size≥2 组 (跨 channel max)", "", "## 外部变量", "1. **口径 (全部 / 只有组)**: 均值类指标(frac/avg组词/avg组数)两行 — *全部*=所有 channel 平均; *只有组*=只在'内部至少分出1个 size≥2 组'的 channel 上平均(无组的 channel 不进分母)。分子相同, 仅分母从 N_all 换成 N_有组。max 类指标不受口径影响。", "2. **还原 / 不还原 (E)**: 主表显示*还原*(用字符偏移+句子原文把 BPE 碎片补成完整词再分组); *不还原*(直接用碎片)对照见文末附表。", "", "## 方法", "- **WordNet-近义**: 共享 WordNet synset (扩充 similar_to+hypernym)", "- **WordNet-同类**: 共享主导 lexname — 人名/动物/食物/地点/职业/情感/动作… 各成一类 (比近义宽)", "- **MiniLM**: 句向量余弦 ≥ {0.4, 0.45, 0.5}", "", "随机基线 (n=2000 伪channel, seed=0, 走与真实 channel 相同的 clean→is_word→in_wordnet 流程):", "- **随机·匹配(置换)** ← 主对照: 用真实 channel 自己的 top-K token *multiset* (含碎片/功能词, 按出现频率) 抽 K 个。碎片率/真实词数与真实 channel 完全一致, 只打乱 channel↔token 配对 = 标准 permutation null。**真实 > 此值 才说明 channel 真在聚近义词**。", "- 随机·alpaca: 从该模型 400 句产生的 token 按频率加权抽 K 个 — 仍偏高(广撒网实词→synset 碰撞多, ~38%), 非公平对照, 仅参考。", "- 随机·vocab: 从完整 tokenizer 词表均匀抽 K 个 (多为碎片) — floor, ≈0。", "- 随机·词典: (旧) 从 77k WordNet 真实词抽 — 偏高, 仅作参考。", "", ] headline_compare(lines) method_table("方法 1: WordNet-近义 (expanded synset)", "sweep_expctx", "wordnet", None, lines) method_table("方法 2: WordNet-同类 (dominant lexname)", "sweep_superctx", "super", None, lines) for th in ENC_THS: method_table(f"方法 3: MiniLM @cos≥{th}", "sweep_encctx", f"enc{th}", th, lines) selectivity_section(lines) ctx_compare(lines) out = RES / "MASTER_TABLE.md" out.write_text("\n".join(lines), encoding="utf-8") print(f"wrote {out}") if __name__ == "__main__": main()