Download exp/analyze_behavior.py from yaro1214/daim: direct link, hf CLI and curl.
- Browser
- Download file 10.8 kB
-
https://huggingface.co/yaro1214/daim/resolve/main/exp/analyze_behavior.py
- Command line
-
hf download hf://yaro1214/daim/exp/analyze_behavior.py
-
curl -L -o analyze_behavior.py https://huggingface.co/yaro1214/daim/resolve/main/exp/analyze_behavior.py
10.8 kB
| """Behavior-level analysis of all-mask vs soft-mask traces. | |
| Answers: | |
| A. overall acceptance length per mode (sanity) | |
| B. per-slot acceptance P(accept slot k | slots 1..k-1 accepted), per mode | |
| -> does soft help, and at which slot offsets ("injection positions") | |
| C. same, split by whether slot k itself carried a delta | |
| -> "让自己更好" | |
| D. same for PLAIN-mask slots inside soft-mode iterations (k > num_reuse) | |
| vs all-mask mode -> "让后续更好" (block-level spillover) | |
| E. stale-signal quality: is the injected belief right, does the draft copy | |
| it or refine it ("细化 vs 复制") | |
| F. confidence geometry: entropy / margin / P_draft(target token) at reached | |
| slots, per mode | |
| G. num_reuse distribution and acceptance vs num_reuse | |
| Reads exp/traces/<dataset>/*.pt, writes exp/analysis/<dataset>_behavior.json | |
| and exp/figs/*.png. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| from pathlib import Path | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| import torch | |
| BLOCK = 16 | |
| def iter_slot_records(trace: dict) -> list[dict]: | |
| """Flatten a prompt trace into per-slot records with stale/true joins.""" | |
| output_ids = trace["output_ids"] | |
| traces = trace["traces"] | |
| records = [] | |
| for ti, rec in enumerate(traces): | |
| start = rec["start"] | |
| accepted = rec["accepted"] | |
| prev = traces[ti - 1] if ti > 0 else None | |
| for k in range(1, BLOCK): | |
| x = start + k # absolute position this slot predicts... slot holds draft for x | |
| slot = { | |
| "iter": ti, | |
| "k": k, | |
| "reached": accepted >= k - 1, # prefix up to k-1 accepted | |
| "accepted": accepted >= k, | |
| "has_soft": bool(rec["has_soft"][k - 1]), | |
| "num_reuse": rec["num_reuse"], | |
| "draft_top1_prob": float(rec["draft_top1_prob"][k - 1]), | |
| "draft_entropy": float(rec["draft_entropy"][k - 1]), | |
| "draft_margin": float(rec["draft_margin"][k - 1]), | |
| "draft_post_prob": float(rec["draft_post_prob"][k - 1]), | |
| "kl": float(rec["kl_draft_target"][k - 1]), | |
| "target_top1_prob": float(rec["target_top1_prob"][k - 1]), | |
| "delta_norm": float(rec["delta_norm"][k - 1]), | |
| } | |
| # stale join: delta at this slot came from verifier hidden at | |
| # soft_src_pos = x-1, computed in the previous iteration's block. | |
| src = int(rec["soft_src_pos"][k - 1]) | |
| if src >= 0 and prev is not None and prev["start"] <= src < prev["start"] + BLOCK: | |
| slot["stale_tok"] = int(prev["posterior"][src - prev["start"]]) | |
| if x < output_ids.shape[0]: | |
| slot["true_tok"] = int(output_ids[x]) | |
| slot["draft_tok"] = int(rec["draft_ids"][k - 1]) | |
| records.append(slot) | |
| return records | |
| def cond_accept(records: list[dict], k: int, **filt) -> tuple[float, int]: | |
| """P(accepted at k | reached k, filters).""" | |
| sel = [ | |
| r for r in records | |
| if r["k"] == k and r["reached"] and all(r.get(key) == v for key, v in filt.items()) | |
| ] | |
| if not sel: | |
| return float("nan"), 0 | |
| return sum(r["accepted"] for r in sel) / len(sel), len(sel) | |
| def mean_field(records: list[dict], field: str, k: int, **filt) -> tuple[float, int]: | |
| sel = [ | |
| r for r in records | |
| if r["k"] == k and r["reached"] and all(r.get(key) == v for key, v in filt.items()) | |
| ] | |
| if not sel: | |
| return float("nan"), 0 | |
| return sum(r[field] for r in sel) / len(sel), len(sel) | |
| def analyze_dataset(ds: str, traces_dir: Path, out_dir: Path, fig_dir: Path) -> dict: | |
| by_mode: dict[str, list[dict]] = {"allmask": [], "soft": []} | |
| acc_by_mode: dict[str, list[int]] = {"allmask": [], "soft": []} | |
| for path in sorted(traces_dir.glob("*.pt")): | |
| mode = path.stem.split("_")[-1] | |
| trace = torch.load(path, weights_only=False, map_location="cpu") | |
| by_mode[mode].extend(iter_slot_records(trace)) | |
| acc_by_mode[mode].extend(t["accepted"] + 1 for t in trace["traces"]) | |
| summary: dict = {"dataset": ds} | |
| for mode in ("allmask", "soft"): | |
| summary[f"mean_accept_{mode}"] = float(np.mean(acc_by_mode[mode])) | |
| summary[f"iters_{mode}"] = len(acc_by_mode[mode]) | |
| # ---- B/C/D: per-slot acceptance ---- | |
| ks = list(range(1, BLOCK)) | |
| curves = {} | |
| for label, mode, filt in ( | |
| ("allmask", "allmask", {}), | |
| ("soft_all", "soft", {}), | |
| ("soft_injected", "soft", {"has_soft": True}), | |
| ("soft_plain", "soft", {"has_soft": False}), | |
| ): | |
| pts = [cond_accept(by_mode[mode], k, **filt) for k in ks] | |
| curves[label] = {"p": [p for p, _ in pts], "n": [n for _, n in pts]} | |
| summary["per_slot_accept"] = curves | |
| fig, ax = plt.subplots(figsize=(7, 4)) | |
| for label, style in ( | |
| ("allmask", "k--"), | |
| ("soft_all", "r-"), | |
| ("soft_injected", "b-"), | |
| ("soft_plain", "g-"), | |
| ): | |
| ax.plot(ks, curves[label]["p"], style, marker="o", ms=3, label=label) | |
| ax.set_xlabel("slot offset k in block (draft position)") | |
| ax.set_ylabel("P(accept k | 1..k-1 accepted)") | |
| ax.set_title(f"{ds}: per-slot conditional acceptance") | |
| ax.legend() | |
| ax.grid(alpha=0.3) | |
| fig.tight_layout() | |
| fig.savefig(fig_dir / f"{ds}_per_slot_accept.png", dpi=150) | |
| plt.close(fig) | |
| # ---- E: stale signal quality (soft mode, reached slots with a stale join) ---- | |
| soft = by_mode["soft"] | |
| stale = [r for r in soft if r.get("stale_tok") is not None and r.get("true_tok") is not None and r["reached"]] | |
| n_st = len(stale) | |
| stale_stats = {"n": n_st} | |
| if n_st: | |
| stale_stats["p_stale_correct"] = sum(r["stale_tok"] == r["true_tok"] for r in stale) / n_st | |
| stale_stats["p_draft_eq_stale"] = sum(r["draft_tok"] == r["stale_tok"] for r in stale) / n_st | |
| sc = [r for r in stale if r["stale_tok"] == r["true_tok"]] | |
| sw = [r for r in stale if r["stale_tok"] != r["true_tok"]] | |
| stale_stats["p_draft_correct_given_stale_correct"] = ( | |
| sum(r["draft_tok"] == r["true_tok"] for r in sc) / len(sc) if sc else float("nan") | |
| ) | |
| stale_stats["p_draft_correct_given_stale_wrong"] = ( | |
| sum(r["draft_tok"] == r["true_tok"] for r in sw) / len(sw) if sw else float("nan") | |
| ) | |
| stale_stats["n_stale_correct"] = len(sc) | |
| stale_stats["n_stale_wrong"] = len(sw) | |
| # baseline: plain-mask slots in all-mask mode, draft vs true | |
| base = [ | |
| r for r in by_mode["allmask"] | |
| if r.get("true_tok") is not None and r["reached"] | |
| ] | |
| # allmask records lack true_tok join (no soft_src); rebuild below | |
| summary["stale"] = stale_stats | |
| # draft-vs-true accuracy at reached slots (all modes, for comparison with | |
| # the stale-conditional numbers above) | |
| true_acc = {} | |
| for label, mode, filt in ( | |
| ("allmask", "allmask", {}), | |
| ("soft_injected", "soft", {"has_soft": True}), | |
| ("soft_plain", "soft", {"has_soft": False}), | |
| ): | |
| sel = [ | |
| r for r in by_mode[mode] | |
| if r.get("true_tok") is not None and r["reached"] | |
| and all(r.get(key) == v for key, v in filt.items()) | |
| ] | |
| true_acc[label] = ( | |
| sum(r["draft_tok"] == r["true_tok"] for r in sel) / len(sel) if sel else float("nan"), | |
| len(sel), | |
| ) | |
| summary["draft_true_acc"] = true_acc | |
| # ---- F: confidence geometry at reached slots ---- | |
| conf = {} | |
| fields = ("draft_entropy", "draft_margin", "draft_post_prob", "kl") | |
| for label, mode, filt in ( | |
| ("allmask", "allmask", {}), | |
| ("soft_injected", "soft", {"has_soft": True}), | |
| ("soft_plain", "soft", {"has_soft": False}), | |
| ): | |
| conf[label] = { | |
| fi: [mean_field(by_mode[mode], fi, k, **filt)[0] for k in ks] | |
| for fi in fields | |
| } | |
| fig, axes = plt.subplots(1, 3, figsize=(15, 4)) | |
| for ax, fi, name in zip( | |
| axes, ("draft_entropy", "draft_margin", "draft_post_prob"), | |
| ("draft entropy", "draft top1-top2 margin", "P_draft(target token)"), | |
| ): | |
| for label, style in (("allmask", "k--"), ("soft_injected", "b-"), ("soft_plain", "g-")): | |
| ax.plot(ks, conf[label][fi], style, marker="o", ms=3, label=label) | |
| ax.set_xlabel("slot offset k") | |
| ax.set_title(f"{ds}: {name} (reached slots)") | |
| ax.grid(alpha=0.3) | |
| axes[0].legend() | |
| fig.tight_layout() | |
| fig.savefig(fig_dir / f"{ds}_confidence.png", dpi=150) | |
| plt.close(fig) | |
| summary["confidence"] = conf | |
| # ---- G: num_reuse ---- | |
| reuse = [r["num_reuse"] for r in soft if r["k"] == 1] | |
| summary["num_reuse_mean"] = float(np.mean(reuse)) if reuse else 0.0 | |
| summary["num_reuse_hist"] = np.bincount(reuse, minlength=BLOCK).tolist() | |
| # acceptance of the whole block vs num_reuse (iteration level) | |
| iter_lvl = {} | |
| for path in sorted(traces_dir.glob("*_soft.pt")): | |
| trace = torch.load(path, weights_only=False, map_location="cpu") | |
| for t in trace["traces"]: | |
| iter_lvl.setdefault(t["num_reuse"], []).append(t["accepted"] + 1) | |
| summary["accept_vs_num_reuse"] = { | |
| str(nr): (float(np.mean(v)), len(v)) for nr, v in sorted(iter_lvl.items()) | |
| } | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| with open(out_dir / f"{ds}_behavior.json", "w") as f: | |
| json.dump(summary, f, indent=2) | |
| return summary | |
| def main() -> None: | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--traces-dir", default=str(Path(__file__).parent / "traces")) | |
| ap.add_argument("--out-dir", default=str(Path(__file__).parent / "analysis")) | |
| ap.add_argument("--fig-dir", default=str(Path(__file__).parent / "figs")) | |
| args = ap.parse_args() | |
| traces_dir = Path(args.traces_dir) | |
| fig_dir = Path(args.fig_dir) | |
| fig_dir.mkdir(parents=True, exist_ok=True) | |
| for ds in sorted(p.name for p in traces_dir.iterdir() if p.is_dir()): | |
| s = analyze_dataset(ds, traces_dir / ds, Path(args.out_dir), fig_dir) | |
| print(f"== {ds}: allmask={s['mean_accept_allmask']:.3f} soft={s['mean_accept_soft']:.3f} " | |
| f"({s['iters_allmask']}/{s['iters_soft']} iters), num_reuse_mean={s['num_reuse_mean']:.2f}") | |
| st = s.get("stale", {}) | |
| if st.get("n"): | |
| print(f" stale: P(stale correct)={st['p_stale_correct']:.3f} " | |
| f"P(draft=stale)={st['p_draft_eq_stale']:.3f} " | |
| f"P(draft ok|stale ok)={st['p_draft_correct_given_stale_correct']:.3f} " | |
| f"P(draft ok|stale wrong)={st['p_draft_correct_given_stale_wrong']:.3f}") | |
| if __name__ == "__main__": | |
| main() | |