File size: 4,526 Bytes
94da461 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 | """Render the NEW (unbundled v3) confuser trie and compare to the OLD one.
The canonical renderer (distractor_generation_2/visualize.py) builds a trie over
each row's `calls` name-sequence, colouring the real prefix BLUE and confuser
look-alikes ORANGE. We reuse it, but feed it our v3 split dataset so you can see
how unbundling reshaped the trie:
OLD: 795 confusers, each a single long mega-turn -> deep root->leaf paths.
NEW: each split confuser becomes T1 (real prefix -> confuser node F, the
preserved divergence) plus re-rooted tail turns (own short paths from
ROOT). Result: shallower, wider trie that mirrors real tau2 turn shapes.
Outputs (into this folder): trie_v3.txt, trie_v3.svg, trie_v3.png
Run: python -u temp/story_remediation/unbundle/visualize_v3.py
"""
from __future__ import annotations
import json, sys
from pathlib import Path
HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[2]
sys.path.insert(0, str(ROOT))
from models.trie import Trie # noqa: E402
from distractor_generation_2.visualize import ( # noqa: E402
_load_seqs, _load_names, _text_tree, _render_image)
N100 = ROOT / "distractor_generation_2" / "datasets" / "n100"
V3 = HERE / "out" / "trajectories_all_v3.jsonl"
REAL_APIS = ROOT / "data" / "tau-2" / "processed" / "apis.jsonl"
def seqs_from(path: Path):
out = []
for line in path.read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
e = json.loads(line)
s = [c["name"] for c in e.get("calls", []) if c.get("name")]
if s:
out.append(s)
return out
def build(seqs):
t = Trie()
for s in seqs:
t.insert(list(s))
return t
def stats(trie, classify):
lines, st, cls = _text_tree(trie.root, classify, 1)
root_branch = sum(1 for c in trie.root.children.values())
depths = []
def walk(node, d):
if not node.children:
depths.append(d); return
for c in node.children.values():
walk(c, d + 1)
walk(trie.root, 0)
return dict(nodes=st["nodes"], max_depth=st["max_depth"],
root_branch=root_branch, leaves=len(depths),
mean_leaf_depth=sum(depths) / max(len(depths), 1)), lines
def main():
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
real_names = _load_names(REAL_APIS)
conf_names = _load_names(N100 / "apis.jsonl")
def classify(name: str) -> str:
if name in conf_names:
return "confuser"
if name in real_names:
return "real"
return "?"
old_seqs = seqs_from(N100 / "trajectories.jsonl")
new_seqs = seqs_from(V3)
old_trie = build(old_seqs)
new_trie = build(new_seqs)
old_st, _ = stats(old_trie, classify)
new_st, new_lines = stats(new_trie, classify)
print("=" * 74)
print("CONFUSER TRIE — OLD (single mega-turn) vs NEW (unbundled v3)")
print("=" * 74)
print(f"{'metric':22s}{'OLD':>12s}{'NEW':>12s}")
for k in ("nodes", "max_depth", "root_branch", "leaves", "mean_leaf_depth"):
ov, nv = old_st[k], new_st[k]
of = f"{ov:.2f}" if isinstance(ov, float) else str(ov)
nf = f"{nv:.2f}" if isinstance(nv, float) else str(nv)
print(f"{k:22s}{of:>12s}{nf:>12s}")
print(f"{'trajectories(rows)':22s}{len(old_seqs):>12d}{len(new_seqs):>12d}")
header = [
"NEW UNBUNDLED CONFUSER TRIE (v3) — built over the split dataset",
"=" * 72,
f"rows: {len(new_seqs)} nodes: {new_st['nodes']} max depth: {new_st['max_depth']} "
f"root branches: {new_st['root_branch']} mean leaf depth: {new_st['mean_leaf_depth']:.2f}",
"Legend: [real] BLUE = real prefix the confuser anchors to; "
"[confuser] ORANGE = retail look-alike (the divergence node F).",
"=" * 72, "",
]
(HERE / "trie_v3.txt").write_text("\n".join(header + new_lines), encoding="utf-8")
print(f"\ntext tree -> {(HERE/'trie_v3.txt').relative_to(ROOT)} ({len(new_lines)} lines)")
png = _render_image(new_trie.root, classify, HERE / "trie_v3", 1, "png")
svg = _render_image(new_trie.root, classify, HERE / "trie_v3", 1, "svg")
if png:
print(f"PNG -> {png}")
if svg:
print(f"SVG -> {svg}")
if __name__ == "__main__":
main()
|