lcn-paper-data / thesaurus /code /merge_chunks.py
Chenhangcui's picture
Add thesaurus task1: selectivity (indicator 3), grouping master table, data-scaling de-bias, full scripts (qwen3_1b full 20000)
6cca5e1 verified
Raw
History Blame Contribute Delete
2.44 kB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""合并分块 analysis 的 neuron_analysis: 逐 (module,layer) 把各 chunk 的 per-channel 高激活
entry list 拼接 (sentence_idx 按累计偏移修正以支持 ctx), sentence 拼接。结果等价于在全部
样本上一次性 analysis (na-count = 各 chunk 之和, top-K-by-activation 不变)。
用法: merge_chunks.py <out_dir> <chunk_dir0> <chunk_dir1> ...
"""
import json, sys, glob
from pathlib import Path
def _load(p):
try:
import orjson
return orjson.loads(Path(p).read_bytes())
except Exception:
return json.loads(Path(p).read_text(encoding="utf-8"))
def main(out_dir, chunk_dirs):
out_dir = Path(out_dir); out_dir.mkdir(parents=True, exist_ok=True)
chunk_dirs = [Path(c) for c in chunk_dirs]
bases = sorted(p.name.replace("_neuron_analysis.json", "")
for p in chunk_dirs[0].glob("*_neuron_analysis.json"))
print(f"merging {len(chunk_dirs)} chunks, {len(bases)} module-layer files", flush=True)
for bi, base in enumerate(bases):
merged = {}; merged_sents = []; offset = 0
for cd in chunk_dirs:
naf = cd / f"{base}_neuron_analysis.json"
sf = cd / f"{base}_sentence.json"
if not naf.exists():
continue
ntt = _load(naf).get("neuron_top_tokens", {})
sents = _load(sf).get("sentences", []) if sf.exists() else []
for ch, entries in ntt.items():
if offset:
for e in entries:
if isinstance(e, dict) and e.get("sentence_idx") is not None:
e["sentence_idx"] = e["sentence_idx"] + offset
merged.setdefault(ch, []).extend(entries)
merged_sents.extend(sents); offset += len(sents)
(out_dir / f"{base}_neuron_analysis.json").write_text(
json.dumps({"neuron_top_tokens": merged}, ensure_ascii=False, separators=(",", ":")),
encoding="utf-8")
(out_dir / f"{base}_sentence.json").write_text(
json.dumps({"sentences": merged_sents}, ensure_ascii=False, separators=(",", ":")),
encoding="utf-8")
if (bi + 1) % 20 == 0:
print(f" {bi+1}/{len(bases)} done (last {base}: {offset} sents)", flush=True)
print(f"merged -> {out_dir}", flush=True)
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2:])