AmiriHayes commited on
Commit
5795485
·
verified ·
1 Parent(s): f32beb6

Add false-negative and false-positive panels to the feature view

Browse files

Two new panels between the transcript and the live check: up to 100 held-out TEST-split false negatives (ordered by activation, biggest miss first) and up to 100 false positives (ordered by how many share the scored token). Data in data/errors/L*.json, built from each program's rebuilt whole-split mask; every rebuild was verified against its recorded test F1 before being emitted.

data/errors/L01.json ADDED
The diff for this file is too large to render. See raw diff
 
data/errors/L02.json ADDED
The diff for this file is too large to render. See raw diff
 
data/errors/L03.json ADDED
The diff for this file is too large to render. See raw diff
 
data/errors/L04.json ADDED
The diff for this file is too large to render. See raw diff
 
data/errors/L05.json ADDED
The diff for this file is too large to render. See raw diff
 
data/errors/L06.json ADDED
The diff for this file is too large to render. See raw diff
 
data/errors/L07.json ADDED
The diff for this file is too large to render. See raw diff
 
data/errors/L08.json ADDED
The diff for this file is too large to render. See raw diff
 
data/errors/L09.json ADDED
The diff for this file is too large to render. See raw diff
 
data/errors/L10.json ADDED
The diff for this file is too large to render. See raw diff
 
data/errors/L11.json ADDED
The diff for this file is too large to render. See raw diff
 
data/errors/L12.json ADDED
The diff for this file is too large to render. See raw diff
 
static/index.html ADDED
@@ -0,0 +1,938 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>SAE Feature Viewer</title>
7
+ <style>
8
+ :root{
9
+ --bg:#fff; --panel:#fafafa; --ink:#15151a; --dim:#5d5d68; --faint:#8a8a96;
10
+ --rule:#e4e4ea; --accent:#674ea7; --accent-soft:#efeaf8;
11
+ --both:#2f7d4f; --both-bg:#dff1e4;
12
+ --progonly:#9a6a00; --progonly-bg:#fdf0d0;
13
+ --fireonly:#1d5fa8; --fireonly-bg:#dceafa;
14
+ --crash:#b3261e; --crash-bg:#fbe0de;
15
+ --mono:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
16
+ }
17
+ @media (prefers-color-scheme:dark){:root:not([data-theme="light"]){
18
+ --bg:#131318; --panel:#1b1b22; --ink:#ececf1; --dim:#a4a4b2; --faint:#74747f;
19
+ --rule:#2c2c36; --accent:#b4a7d6; --accent-soft:#2a2440;
20
+ --both:#79d79b; --both-bg:#1d3a28;
21
+ --progonly:#e8c06a; --progonly-bg:#3b3015;
22
+ --fireonly:#86b6f0; --fireonly-bg:#17293f;
23
+ --crash:#f0908a; --crash-bg:#3d1b1a;
24
+ }}
25
+ :root[data-theme="dark"]{
26
+ --bg:#131318; --panel:#1b1b22; --ink:#ececf1; --dim:#a4a4b2; --faint:#74747f;
27
+ --rule:#2c2c36; --accent:#b4a7d6; --accent-soft:#2a2440;
28
+ --both:#79d79b; --both-bg:#1d3a28;
29
+ --progonly:#e8c06a; --progonly-bg:#3b3015;
30
+ --fireonly:#86b6f0; --fireonly-bg:#17293f;
31
+ --crash:#f0908a; --crash-bg:#3d1b1a;
32
+ }
33
+ *{box-sizing:border-box}
34
+ body{margin:0;background:var(--bg);color:var(--ink);
35
+ font:15px/1.5 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;}
36
+ a{color:var(--accent)}
37
+ header{position:sticky;top:0;z-index:20;background:var(--bg);
38
+ border-bottom:1px solid var(--rule);padding:10px 16px;display:flex;
39
+ gap:12px;align-items:center;flex-wrap:wrap}
40
+ header h1{font-size:15px;margin:0;font-weight:650;letter-spacing:-.01em}
41
+ .badge{font-size:11px;padding:2px 8px;border-radius:999px;border:1px solid var(--rule);
42
+ color:var(--dim);white-space:nowrap}
43
+ .badge.live{color:var(--both);border-color:var(--both);background:var(--both-bg)}
44
+ .badge.browse{color:var(--dim)}
45
+ main{max-width:1060px;margin:0 auto;padding:18px 16px 80px}
46
+ button{font:inherit;color:var(--ink);background:var(--panel);
47
+ border:1px solid var(--rule);border-radius:7px;padding:5px 11px;cursor:pointer}
48
+ button:hover{border-color:var(--accent)}
49
+ button.primary{background:var(--accent);color:#fff;border-color:var(--accent);font-weight:600}
50
+ button.primary:disabled{opacity:.5;cursor:not-allowed}
51
+ select,input[type=text],input[type=number],textarea{font:inherit;color:var(--ink);
52
+ background:var(--bg);border:1px solid var(--rule);border-radius:7px;padding:5px 8px}
53
+ textarea{width:100%;font-family:var(--mono);font-size:13px;resize:vertical}
54
+ code,pre{font-family:var(--mono)}
55
+ pre{background:var(--panel);border:1px solid var(--rule);border-radius:8px;
56
+ padding:11px 13px;overflow-x:auto;font-size:12.5px;line-height:1.55;margin:0}
57
+ .muted{color:var(--dim)}
58
+ .tiny{font-size:12px}
59
+ .row{display:flex;gap:10px;flex-wrap:wrap;align-items:center}
60
+ .card{background:var(--panel);border:1px solid var(--rule);border-radius:10px;
61
+ padding:14px;margin:14px 0}
62
+ h2{font-size:14px;margin:0 0 9px;letter-spacing:.02em;text-transform:uppercase;
63
+ color:var(--dim);font-weight:650}
64
+ table{width:100%;border-collapse:collapse;font-size:13.5px}
65
+ th,td{text-align:left;padding:6px 9px;border-bottom:1px solid var(--rule)}
66
+ th{color:var(--dim);font-weight:600;font-size:12px;cursor:pointer;white-space:nowrap}
67
+ th.sorted{color:var(--accent)}
68
+ tbody tr{cursor:pointer}
69
+ tbody tr:hover{background:var(--accent-soft)}
70
+ .num{text-align:right;font-variant-numeric:tabular-nums}
71
+ .pill{font-size:11px;padding:1px 7px;border-radius:999px;border:1px solid var(--rule);
72
+ color:var(--dim);white-space:nowrap;display:inline-block;margin:1px 2px 1px 0}
73
+ .pill.win{color:var(--both);border-color:var(--both)}
74
+ .pill.loss{color:var(--crash);border-color:var(--crash)}
75
+ .tok{display:inline-block;padding:2px 3px;margin:1px 0;border-radius:4px;
76
+ font-family:var(--mono);font-size:13px;white-space:pre;cursor:default;
77
+ border:1px solid transparent}
78
+ .tok.unscored{color:var(--faint);background:transparent}
79
+ .tok.neither{color:var(--dim)}
80
+ .tok.both{color:var(--both);background:var(--both-bg);border-color:var(--both)}
81
+ .tok.progonly{color:var(--progonly);background:var(--progonly-bg);border-color:var(--progonly)}
82
+ .tok.fireonly{color:var(--fireonly);background:var(--fireonly-bg);border-color:var(--fireonly)}
83
+ .tok.crash{color:var(--crash);background:var(--crash-bg);border-color:var(--crash)}
84
+ .legend{display:flex;gap:7px;flex-wrap:wrap;font-size:12px;margin:9px 0}
85
+ .legend span{padding:2px 8px;border-radius:5px;border:1px solid}
86
+ details{border:1px solid var(--rule);border-radius:8px;margin:7px 0;background:var(--bg)}
87
+ details>summary{cursor:pointer;padding:8px 11px;font-size:13px;color:var(--dim)}
88
+ details[open]>summary{border-bottom:1px solid var(--rule);color:var(--ink)}
89
+ details .body{padding:11px}
90
+ .ex{font-family:var(--mono);font-size:12.5px;padding:5px 7px;border-bottom:1px solid var(--rule);
91
+ display:flex;gap:8px;align-items:flex-start}
92
+ .ex .t{flex:1;white-space:pre-wrap;word-break:break-word}
93
+ .ex mark{background:var(--both-bg);color:var(--both);border-radius:3px;padding:0 2px;font-weight:600}
94
+ .err{border-left:3px solid var(--crash);background:var(--crash-bg);color:var(--crash);
95
+ padding:9px 12px;border-radius:0 7px 7px 0;margin:9px 0;font-size:13.5px}
96
+ .warn{border-left:3px solid var(--progonly);background:var(--progonly-bg);color:var(--progonly);
97
+ padding:9px 12px;border-radius:0 7px 7px 0;margin:9px 0;font-size:13.5px}
98
+ .info{border-left:3px solid var(--accent);background:var(--accent-soft);
99
+ padding:9px 12px;border-radius:0 7px 7px 0;margin:9px 0;font-size:13.5px}
100
+ .spin{display:inline-block;width:12px;height:12px;border:2px solid var(--rule);
101
+ border-top-color:var(--accent);border-radius:50%;animation:s .7s linear infinite;
102
+ vertical-align:-2px;margin-right:6px}
103
+ @keyframes s{to{transform:rotate(360deg)}}
104
+ .tipbox{position:fixed;z-index:50;background:var(--bg);border:1px solid var(--accent);
105
+ border-radius:8px;padding:8px 11px;font-size:12.5px;font-family:var(--mono);
106
+ box-shadow:0 6px 24px rgba(0,0,0,.18);pointer-events:none;max-width:300px}
107
+ .counts{display:flex;gap:7px;flex-wrap:wrap;font-size:12.5px;margin:9px 0}
108
+ .counts b{font-variant-numeric:tabular-nums}
109
+ .hist{font-family:var(--mono);font-size:12px;padding:4px 7px;border-bottom:1px solid var(--rule);
110
+ cursor:pointer;display:flex;gap:8px}
111
+ .hist:hover{background:var(--accent-soft)}
112
+ @media(max-width:620px){
113
+ main{padding:14px 11px 70px}
114
+ /* keep L, feature, description, test F1 and the delta; the rest are in the
115
+ feature page anyway, and a 8-column table on a phone is unreadable */
116
+ th:nth-child(n+6),td:nth-child(n+6){display:none}
117
+ td:nth-child(3){max-width:40vw}
118
+ table{font-size:12.5px}
119
+ th,td{padding:5px 6px}
120
+ .card{padding:11px}
121
+ textarea{font-size:16px} /* iOS zooms the page under 16px */
122
+ }
123
+ @media(max-width:520px){
124
+ /* phone: L, feature, description, test F1 only — anything narrower clips */
125
+ th:nth-child(n+5),td:nth-child(n+5){display:none}
126
+ td:nth-child(3){max-width:52vw}
127
+ }
128
+ </style>
129
+ </head>
130
+ <body>
131
+ <header>
132
+ <h1>SAE Feature Viewer</h1>
133
+ <span id="mode" class="badge">checking backend…</span>
134
+ <span style="flex:1"></span>
135
+ <button id="themeBtn" class="tiny" title="Toggle light / dark">◐</button>
136
+ <button id="homeBtn" class="tiny">All features</button>
137
+ </header>
138
+ <main id="app"><p class="muted"><span class="spin"></span>Loading…</p></main>
139
+ <div id="tip" class="tipbox" style="display:none"></div>
140
+ <script>
141
+ "use strict";
142
+ /* ---------------------------------------------------------------- state */
143
+ const S = {
144
+ live: false, health: null, feats: null,
145
+ progs: {}, trans: {}, shared: null, desc: {},
146
+ filt: {layer:"", source:"", outcome:"", low:"", f1min:"", f1max:"", q:""},
147
+ sort: {key:"test_f1", dir:-1},
148
+ coldWarned: false,
149
+ nav: 0, // navigation token; a stale render must not write
150
+ };
151
+ const TIE = 0.01; // win/loss margin against Plan A, per spec
152
+ const FIRST_SCORED = 2; // overridden by /api/health when live
153
+ const $ = (s,r)=> (r||document).querySelector(s);
154
+ const el = (t,c,x)=>{const n=document.createElement(t); if(c)n.className=c;
155
+ if(x!==undefined)n.textContent=x; return n;};
156
+ const esc = s => String(s).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
157
+ const f3 = v => (v===null||v===undefined||v==="MISSING"||Number.isNaN(v)) ? "—" : Number(v).toFixed(3);
158
+ const isMissing = v => v===undefined||v===null||v==="MISSING";
159
+
160
+ /* data/ sits beside the page when the backend serves it, and may sit one level
161
+ up in a static deployment that puts the page at the root. Try both. */
162
+ let DATA_BASE = null;
163
+ async function dataUrl(p){
164
+ if(DATA_BASE!==null) return DATA_BASE+p;
165
+ for(const base of ["data/","../data/","./data/"]){
166
+ try{ const r = await fetch(base+p,{method:"HEAD"}); if(r.ok){ DATA_BASE=base; return base+p; } }catch(e){}
167
+ }
168
+ DATA_BASE="data/"; return "data/"+p;
169
+ }
170
+ async function getJSON(p){
171
+ const u = await dataUrl(p);
172
+ let r;
173
+ try{
174
+ r = await fetch(u);
175
+ }catch(e){
176
+ // TypeError: Failed to fetch — the connection was refused or aborted.
177
+ // That is the server being gone, not a missing file.
178
+ const e2 = new Error(`could not reach ${u}`);
179
+ e2.offline = true;
180
+ throw e2;
181
+ }
182
+ if(!r.ok) throw new Error(`${p} → HTTP ${r.status}`);
183
+ return r.json();
184
+ }
185
+
186
+ async function backendAlive(){
187
+ try{
188
+ const c = new AbortController();
189
+ const t = setTimeout(()=>c.abort(), 2500);
190
+ const r = await fetch("api/health",{signal:c.signal, cache:"no-store"});
191
+ clearTimeout(t);
192
+ return r.ok;
193
+ }catch(e){ return false; }
194
+ }
195
+
196
+ function setMode(live){
197
+ S.live = live;
198
+ const m = $("#mode");
199
+ if(!m) return;
200
+ m.textContent = live ? "live backend" : "browse-only";
201
+ m.className = "badge " + (live ? "live" : "browse");
202
+ }
203
+ async function layerProgs(L){
204
+ const k="L"+String(L).padStart(2,"0");
205
+ if(!S.progs[k]) S.progs[k] = await getJSON(`programs/${k}.json`);
206
+ return S.progs[k];
207
+ }
208
+ async function layerFN(L){
209
+ const k="L"+String(L).padStart(2,"0");
210
+ if(!S.fns) S.fns = {};
211
+ if(!S.fns[k]) S.fns[k] = await getJSON(`errors/${k}.json`);
212
+ return S.fns[k];
213
+ }
214
+
215
+ /* One error panel: false negatives or false positives, same shape. */
216
+ function errorRows(list, live){
217
+ const box = el("div");
218
+ box.style.maxHeight = "510px"; // 1.5x the examples block's 340px
219
+ box.style.overflowY = "auto";
220
+ list.forEach(x=>{
221
+ const row = el("div","ex");
222
+ const t = el("div","t");
223
+ t.innerHTML = esc(x).replace(/\[\[([\s\S]*?)\]\]/g, (_,m)=>`<mark>${m}</mark>`);
224
+ row.appendChild(t);
225
+ if(live){
226
+ const b = el("button","tiny","try");
227
+ b.onclick=()=>{
228
+ const plain = x.replace(/^\.\.\./,"").replace(/\[\[([\s\S]*?)\]\]/g,"$1");
229
+ const ta = $("#lcText"); if(!ta) return;
230
+ ta.value = plain; ta.dispatchEvent(new Event("input"));
231
+ window.__lcExpect = plain;
232
+ $("#lcRun").click();
233
+ ta.scrollIntoView({behavior:"smooth",block:"center"});
234
+ };
235
+ row.appendChild(b);
236
+ }
237
+ box.appendChild(row);
238
+ });
239
+ return box;
240
+ }
241
+ async function layerTrans(L){
242
+ const k="L"+String(L).padStart(2,"0");
243
+ if(!S.shared) S.shared = await getJSON("transcripts/shared.json");
244
+ if(!S.trans[k]) S.trans[k] = await getJSON(`transcripts/${k}.json`);
245
+ return S.trans[k];
246
+ }
247
+
248
+ /* ------------------------------------------------------------ bootstrap */
249
+ function outcome(f){
250
+ const d = f.test_f1 - f.plan_a_f1;
251
+ return d > TIE ? "win" : d < -TIE ? "loss" : "tie";
252
+ }
253
+ async function boot(){
254
+ try{
255
+ const ctrl = new AbortController();
256
+ const t = setTimeout(()=>ctrl.abort(), 4000);
257
+ const r = await fetch("api/health",{signal:ctrl.signal});
258
+ clearTimeout(t);
259
+ if(r.ok){ S.health = await r.json(); S.live = true; }
260
+ }catch(e){ S.live = false; }
261
+ const m = $("#mode");
262
+ m.textContent = S.live ? "live backend" : "browse-only";
263
+ m.className = "badge " + (S.live ? "live" : "browse");
264
+ m.title = S.live
265
+ ? `${S.health.model} · ${S.health.sae_release} · first scored ${S.health.first_scored}`
266
+ : "No backend on this origin — the live check needs the local version.";
267
+ try{
268
+ S.feats = (await getJSON("features.json")).features;
269
+ S.desc = await getJSON("descriptions.json");
270
+ }catch(e){
271
+ $("#app").innerHTML = `<div class="err">Could not load the feature index: ${esc(e.message)}</div>`;
272
+ return;
273
+ }
274
+ S.feats.forEach(f=>{ f._d = f.test_f1 - f.plan_a_f1; f._o = outcome(f); });
275
+ window.addEventListener("hashchange", route);
276
+ route();
277
+ }
278
+
279
+ /* ----------------------------------------------------------------- list */
280
+ function listView(){
281
+ const a = $("#app"); a.innerHTML = "";
282
+ const f = S.filt;
283
+ const bar = el("div","card");
284
+ bar.innerHTML = `
285
+ <div class="row">
286
+ <label class="tiny muted">Layer <select id="fLayer"><option value="">all</option>
287
+ ${Array.from({length:12},(_,i)=>`<option ${f.layer==i+1?"selected":""}>${i+1}</option>`).join("")}</select></label>
288
+ <label class="tiny muted">Source <select id="fSource">
289
+ <option value="">all</option>
290
+ <option value="agent" ${f.source==="agent"?"selected":""}>agent</option>
291
+ <option value="agent, identical to Plan A" ${f.source.startsWith("agent,")?"selected":""}>identical to Plan A</option>
292
+ </select></label>
293
+ <label class="tiny muted">vs Plan A <select id="fOut">
294
+ <option value="">all</option>
295
+ <option value="win" ${f.outcome==="win"?"selected":""}>win</option>
296
+ <option value="loss" ${f.outcome==="loss"?"selected":""}>loss</option>
297
+ <option value="tie" ${f.outcome==="tie"?"selected":""}>tie (±${TIE})</option>
298
+ </select></label>
299
+ <label class="tiny muted">Support <select id="fLow">
300
+ <option value="">all</option>
301
+ <option value="1" ${f.low==="1"?"selected":""}>low support only</option>
302
+ <option value="0" ${f.low==="0"?"selected":""}>exclude low support</option>
303
+ </select></label>
304
+ <label class="tiny muted">F1 <input id="fMin" type="number" step="0.05" min="0" max="1"
305
+ style="width:68px" placeholder="min" value="${f.f1min}">
306
+ – <input id="fMax" type="number" step="0.05" min="0" max="1"
307
+ style="width:68px" placeholder="max" value="${f.f1max}"></label>
308
+ <input id="fQ" type="text" placeholder="feature id or description…" style="flex:1;min-width:180px" value="${esc(f.q)}">
309
+ </div>
310
+ <div class="tiny muted" id="cnt" style="margin-top:9px"></div>`;
311
+ a.appendChild(bar);
312
+
313
+ const wrap = el("div","card"); wrap.style.padding="0"; wrap.style.overflowX="auto";
314
+ const tb = el("table");
315
+ const cols = [["layer","L"],["feature","feature"],["description","description"],
316
+ ["test_f1","test F1"],["_d","agent − Plan A"],["plan_a_f1","Plan A F1"],
317
+ ["test_positives","test +"],["source","source"]];
318
+ const thead = el("thead"), tr = el("tr");
319
+ cols.forEach(([k,label])=>{
320
+ const th = el("th",S.sort.key===k?"sorted":"",
321
+ label + (S.sort.key===k ? (S.sort.dir<0?" ↓":" ↑") : ""));
322
+ if(["test_f1","_d","test_positives","layer","feature","plan_a_f1"].includes(k))
323
+ th.classList.add("num");
324
+ th.onclick=()=>{ if(S.sort.key===k) S.sort.dir*=-1; else {S.sort.key=k;S.sort.dir=-1;} draw(); };
325
+ tr.appendChild(th);
326
+ });
327
+ thead.appendChild(tr); tb.appendChild(thead);
328
+ const tbody = el("tbody"); tb.appendChild(tbody); wrap.appendChild(tb); a.appendChild(wrap);
329
+
330
+ function readFilters(){
331
+ f.layer=$("#fLayer").value; f.source=$("#fSource").value; f.outcome=$("#fOut").value;
332
+ f.low=$("#fLow").value; f.f1min=$("#fMin").value; f.f1max=$("#fMax").value;
333
+ f.q=$("#fQ").value.trim();
334
+ }
335
+ function rows(){
336
+ const q = f.q.toLowerCase();
337
+ return S.feats.filter(x=>{
338
+ if(f.layer && x.layer!==+f.layer) return false;
339
+ if(f.source && x.source!==f.source) return false;
340
+ if(f.outcome && x._o!==f.outcome) return false;
341
+ if(f.low==="1" && !x.low_support) return false;
342
+ if(f.low==="0" && x.low_support) return false;
343
+ if(f.f1min!=="" && x.test_f1 < +f.f1min) return false;
344
+ if(f.f1max!=="" && x.test_f1 > +f.f1max) return false;
345
+ if(q){
346
+ const d = (S.desc[x.layer+":"+x.feature]||"").toLowerCase();
347
+ if(!(String(x.feature).includes(q) || d.includes(q))) return false;
348
+ }
349
+ return true;
350
+ }).sort((p,r)=>{
351
+ const k=S.sort.key; let A=p[k],B=r[k];
352
+ if(k==="description"){A=S.desc[p.layer+":"+p.feature]||"";B=S.desc[r.layer+":"+r.feature]||"";}
353
+ if(typeof A==="string") return S.sort.dir*A.localeCompare(B);
354
+ return S.sort.dir*((A||0)-(B||0));
355
+ });
356
+ }
357
+ function draw(){
358
+ readFilters();
359
+ const rs = rows();
360
+ $("#cnt").textContent = `${rs.length.toLocaleString()} of ${S.feats.length.toLocaleString()} features`
361
+ + (rs.length>400 ? " — showing the first 400" : "");
362
+ tbody.innerHTML="";
363
+ rs.slice(0,400).forEach(x=>{
364
+ const r = el("tr");
365
+ r.onclick=()=>{location.hash=`#/L${x.layer}/${x.feature}`;};
366
+ const d = S.desc[x.layer+":"+x.feature];
367
+ [[x.layer,"num"],[x.feature,"num"],
368
+ [d||"(none)", d?"":"muted"],
369
+ [f3(x.test_f1),"num"],
370
+ [(x._d>=0?"+":"")+x._d.toFixed(3),"num"],
371
+ [f3(x.plan_a_f1),"num"],
372
+ [x.test_positives.toLocaleString(),"num"],
373
+ [null,""]].forEach(([v,c],i)=>{
374
+ const td=el("td",c);
375
+ if(i===7){
376
+ td.appendChild(el("span","pill "+(x._o==="tie"?"":x._o), x._o));
377
+ if(x.source.startsWith("agent,")) td.appendChild(el("span","pill"," = Plan A"));
378
+ if(x.low_support) td.appendChild(el("span","pill","low support"));
379
+ } else td.textContent=v;
380
+ r.appendChild(td);
381
+ });
382
+ tbody.appendChild(r);
383
+ });
384
+ }
385
+ ["fLayer","fSource","fOut","fLow"].forEach(i=>$("#"+i).onchange=draw);
386
+ ["fMin","fMax","fQ"].forEach(i=>$("#"+i).oninput=draw);
387
+ draw();
388
+ }
389
+
390
+ /* --------------------------------------------------------- feature page */
391
+ function setBlock(name, members, open){
392
+ const n = members.length;
393
+ const d = el("details"); if(open) d.open = true;
394
+ d.appendChild(el("summary","",`${name} — ${n.toLocaleString()} token${n===1?"":"s"}`));
395
+ const b = el("div","body");
396
+ const pre = el("pre");
397
+ const show = open ? n : Math.min(30,n);
398
+ pre.textContent = members.slice(0,show).map(t=>JSON.stringify(t)).join(", ")
399
+ + (show<n ? ", …" : "");
400
+ b.appendChild(pre);
401
+ if(n>30){
402
+ // Expand in pages. One of these sets has 20,210 members; rendering them
403
+ // all into a single text node is what makes a tab hang.
404
+ const PAGE = 2000;
405
+ let shown = 30;
406
+ const btn = el("button","tiny","");
407
+ const less = el("button","tiny","show first 30");
408
+ less.style.display = "none";
409
+ const note = el("span","tiny muted","");
410
+ const paint = ()=>{
411
+ pre.textContent = members.slice(0,shown).map(t=>JSON.stringify(t)).join(", ")
412
+ + (shown<n ? ", …" : "");
413
+ btn.textContent = shown>=n ? "" :
414
+ `show ${Math.min(PAGE, n-shown).toLocaleString()} more`;
415
+ btn.style.display = shown>=n ? "none" : "";
416
+ less.style.display = shown>30 ? "" : "none";
417
+ note.textContent = `${shown.toLocaleString()} of ${n.toLocaleString()} shown`;
418
+ };
419
+ btn.onclick = ()=>{ shown = Math.min(n, shown + PAGE); paint(); };
420
+ less.onclick = ()=>{ shown = 30; paint(); };
421
+ b.appendChild(btn); b.appendChild(less); b.appendChild(note);
422
+ paint();
423
+ }
424
+ d.appendChild(b); return d;
425
+ }
426
+
427
+ async function featureView(L,F){
428
+ const a = $("#app");
429
+ // Navigation token. featureView is async and route() does not await it, so
430
+ // clicking a second feature while the first is still fetching used to let
431
+ // the slower one finish and overwrite the newer page — or drop its "could
432
+ // not load" box onto a feature that had loaded fine. Every write below is
433
+ // gated on still being the current navigation.
434
+ const myNav = ++S.nav;
435
+ const stale = () => S.nav !== myNav;
436
+ a.innerHTML = `<p class="muted"><span class="spin"></span>Loading L${L} feature ${F}…</p>`;
437
+ const meta = S.feats.find(x=>x.layer===L && x.feature===F);
438
+ if(!meta){ a.innerHTML = `<div class="err">L${L} feature ${F} is not one of the
439
+ ${S.feats.length.toLocaleString()} scored features.</div>`; return; }
440
+ let prog, tr;
441
+ try{
442
+ const [P,T] = await Promise.all([layerProgs(L), layerTrans(L)]);
443
+ prog = P.programs.find(p=>p.feature===F);
444
+ tr = T.features.find(p=>p.feature===F);
445
+ }catch(e){
446
+ if(stale()) return;
447
+ if(e.offline){
448
+ // The data files and the API come from the same server, so if it is gone
449
+ // nothing more can load. Say so once, plainly, with the fix.
450
+ const alive = await backendAlive();
451
+ if(stale()) return;
452
+ if(!alive){
453
+ setMode(false);
454
+ a.innerHTML = `<div class="err"><b>The server has stopped.</b>
455
+ Nothing more can load — the feature data and the live check both come
456
+ from it.<br><br>Restart it and reload this page:
457
+ <pre style="margin-top:8px">cd space &amp;&amp; uvicorn app:app --port 7860</pre>
458
+ <button id="retryBtn" class="tiny">Retry now</button></div>`;
459
+ const rb = $("#retryBtn");
460
+ if(rb) rb.onclick = async ()=>{
461
+ rb.disabled = true; rb.textContent = "checking…";
462
+ if(await backendAlive()){ setMode(true); featureView(L,F); }
463
+ else { rb.disabled = false; rb.textContent = "still down — retry"; }
464
+ };
465
+ return;
466
+ }
467
+ }
468
+ a.innerHTML = `<div class="err"><b>Could not load layer ${L} data.</b>
469
+ ${esc(e.message)}<br><span class="tiny">If this mentions 404, the page is
470
+ newer than the server — restart it, then hard-reload (⇧⌘R / Ctrl-F5).
471
+ </span></div>`;
472
+ return;
473
+ }
474
+ if(stale()) return;
475
+ a.innerHTML = "";
476
+
477
+ /* ---- header */
478
+ const desc = S.desc[L+":"+F];
479
+ const h = el("div","card");
480
+ const npid = `gpt2-small/${L-1}-res_post_32k-oai/${F}`;
481
+ h.innerHTML = `
482
+ <div class="row" style="justify-content:space-between">
483
+ <div><strong style="font-size:17px">Layer ${L} · feature ${F.toLocaleString()}</strong>
484
+ <span class="pill ${meta._o==="tie"?"":meta._o}">${meta._o} vs Plan A</span>
485
+ ${meta.source.startsWith("agent,")?'<span class="pill">= Plan A</span>':''}
486
+ ${meta.low_support?'<span class="pill">low support</span>':''}</div>
487
+ <a class="tiny" target="_blank" rel="noopener"
488
+ href="https://neuronpedia.org/${npid}">Neuronpedia ↗</a>
489
+ </div>
490
+ <p style="margin:8px 0 10px">${desc?esc(desc):'<span class="muted">(no description)</span>'}</p>
491
+ <div class="row tiny">
492
+ <span>test F1 <b>${f3(meta.test_f1)}</b></span>
493
+ <span class="muted">P ${f3(meta.test_precision)} · R ${f3(meta.test_recall)}</span>
494
+ <span>Plan A F1 <b>${f3(meta.plan_a_f1)}</b> <span class="muted">(${esc(meta.plan_a_program)})</span></span>
495
+ <span>Δ <b>${(meta._d>=0?"+":"")+meta._d.toFixed(3)}</b></span>
496
+ <span>test positives <b>${meta.test_positives.toLocaleString()}</b></span>
497
+ <span class="muted">source: ${esc(meta.source)}</span>
498
+ </div>`;
499
+ a.appendChild(h);
500
+
501
+ /* ---- program */
502
+ const pc = el("div","card"); pc.appendChild(el("h2","","Program"));
503
+ if(!prog){ pc.appendChild(el("div","err","Program source is MISSING for this feature.")); }
504
+ else{
505
+ let src = prog.source;
506
+ // replace each set literal with a placeholder; the members get their own
507
+ // collapsible block so a 20,000-token set cannot blow up the page
508
+ const names = Object.keys(prog.sets||{});
509
+ names.forEach(n=>{
510
+ src = src.replace(new RegExp(`^(\\s*${n} = ).*$`,"m"),
511
+ (_,p1)=>`${p1}{…${(prog.sets[n]||[]).length.toLocaleString()} tokens, below…}`);
512
+ });
513
+ const pre = el("pre"); pre.textContent = src; pc.appendChild(pre);
514
+ names.forEach(n=> pc.appendChild(setBlock(n, prog.sets[n]||[], (prog.sets[n]||[]).length<=30)));
515
+ const hd = el("details");
516
+ hd.appendChild(el("summary","","helpers these programs call"));
517
+ const hb = el("div","body"); const hp = el("pre");
518
+ hp.textContent = (S.helpers&&S.helpers.helpers_source)||"(loading…)";
519
+ hb.appendChild(hp); hd.appendChild(hb); pc.appendChild(hd);
520
+ if(!S.helpers) getJSON("programs/helpers.json").then(x=>{S.helpers=x;hp.textContent=x.helpers_source;}).catch(()=>{});
521
+ }
522
+ a.appendChild(pc);
523
+
524
+ /* ---- examples */
525
+ const ec = el("div","card");
526
+ ec.appendChild(el("h2","",`Examples the agent saw (${(tr&&!isMissing(tr.examples)?tr.examples.length:0)})`));
527
+ if(!tr || isMissing(tr.examples) || !tr.examples.length){
528
+ ec.appendChild(el("div","muted","MISSING — no examples recorded for this feature."));
529
+ } else {
530
+ ec.appendChild(el("p","tiny muted",
531
+ "A deduplicated random sample of firing positions; the firing token is marked. "
532
+ + (S.live ? "“try” sends the surrounding text to the live check."
533
+ : "Running them needs the local version.")));
534
+ const box = el("div"); box.style.maxHeight="340px"; box.style.overflowY="auto";
535
+ tr.examples.forEach(x=>{
536
+ const row = el("div","ex");
537
+ const t = el("div","t");
538
+ // the renderer marks the firing token as [[tok]]
539
+ t.innerHTML = esc(x).replace(/\[\[([\s\S]*?)\]\]/g, (_,m)=>`<mark>${m}</mark>`);
540
+ row.appendChild(t);
541
+ if(S.live){
542
+ const b = el("button","tiny","try");
543
+ b.onclick=()=>{
544
+ const plain = x.replace(/^\.\.\./,"").replace(/\[\[([\s\S]*?)\]\]/g,"$1");
545
+ const ta = $("#lcText"); if(!ta) return;
546
+ ta.value = plain; ta.dispatchEvent(new Event("input"));
547
+ window.__lcExpect = plain;
548
+ $("#lcRun").click();
549
+ ta.scrollIntoView({behavior:"smooth",block:"center"});
550
+ };
551
+ row.appendChild(b);
552
+ }
553
+ box.appendChild(row);
554
+ });
555
+ ec.appendChild(box);
556
+ }
557
+ a.appendChild(ec);
558
+
559
+ /* ---- transcript */
560
+ a.appendChild(transcript(tr, meta));
561
+
562
+ /* ---- false negatives, then false positives, before the live check */
563
+ const fnc = el("div","card");
564
+ fnc.appendChild(el("h2","","False negatives"));
565
+ fnc.appendChild(el("div","muted","Loading…"));
566
+ a.appendChild(fnc);
567
+ const fpc = el("div","card");
568
+ fpc.appendChild(el("h2","","False positives"));
569
+ fpc.appendChild(el("div","muted","Loading…"));
570
+ a.appendChild(fpc);
571
+ layerFN(L).then(d=>{
572
+ const rec = (d && d.features) ? d.features[String(F)] : null;
573
+ fnc.innerHTML = ""; fpc.innerHTML = "";
574
+ if(!rec){
575
+ fnc.appendChild(el("h2","","False negatives"));
576
+ fnc.appendChild(el("div","muted","MISSING — no record for this feature."));
577
+ fpc.appendChild(el("h2","","False positives"));
578
+ fpc.appendChild(el("div","muted","MISSING — no record for this feature."));
579
+ return;
580
+ }
581
+ /* false negatives */
582
+ fnc.appendChild(el("h2","",
583
+ `False negatives (${rec.n_shown.toLocaleString()} of `
584
+ + `${rec.n_false_negatives.toLocaleString()} shown)`));
585
+ fnc.appendChild(el("p","tiny muted",
586
+ `Held-out TEST positions where the feature fires and the program does `
587
+ + `not — ${rec.n_false_negatives.toLocaleString()} of its `
588
+ + `${rec.n_firings_test.toLocaleString()} test firings are missed. `
589
+ + `Largest activation first. `
590
+ + (S.live ? "“try” sends the surrounding text to the live check."
591
+ : "Running them needs the local version.")));
592
+ if(!rec.n_false_negatives)
593
+ fnc.appendChild(el("div","muted","None — the program catches every firing."));
594
+ else fnc.appendChild(errorRows(rec.examples, S.live));
595
+ /* false positives */
596
+ const nfp = rec.n_false_positives || 0;
597
+ fpc.appendChild(el("h2","",
598
+ `False positives (${(rec.n_fp_shown||0).toLocaleString()} of `
599
+ + `${nfp.toLocaleString()} shown)`));
600
+ fpc.appendChild(el("p","tiny muted",
601
+ `Held-out TEST positions where the program fires and the feature does `
602
+ + `not. Ordered by how many false positives share the scored token, so `
603
+ + `the most systematic false alarm comes first. `
604
+ + (S.live ? "“try” sends the surrounding text to the live check."
605
+ : "Running them needs the local version.")));
606
+ if(!nfp)
607
+ fpc.appendChild(el("div","muted","None — the program never fires where the feature is silent."));
608
+ else fpc.appendChild(errorRows(rec.fp_examples||[], S.live));
609
+ }).catch(e=>{
610
+ const msg = "Could not load: "+(e&&e.message||e);
611
+ fnc.innerHTML=""; fnc.appendChild(el("h2","","False negatives"));
612
+ fnc.appendChild(el("div","err",msg));
613
+ fpc.innerHTML=""; fpc.appendChild(el("h2","","False positives"));
614
+ fpc.appendChild(el("div","err",msg));
615
+ });
616
+
617
+ /* ---- live check, last on the page */
618
+ if(S.live) a.appendChild(liveCheck(L,F,meta));
619
+ else{
620
+ const n = el("div","info");
621
+ n.innerHTML = `The live check — run your own sentence and see the activation and
622
+ program output at every token — runs in the local version only.
623
+ This page is served as a static Space with no backend.`;
624
+ a.appendChild(n);
625
+ }
626
+ }
627
+
628
+ /* ----------------------------------------------------------- transcript */
629
+ function transcript(tr, meta){
630
+ const c = el("div","card"); c.appendChild(el("h2","","Transcript"));
631
+ if(!tr){ c.appendChild(el("div","err","MISSING — no transcript record.")); return c; }
632
+ const kept = isMissing(tr.round1_kept) ? "MISSING"
633
+ : (tr.round1_kept ? "round 1" : "a later round");
634
+ const line = el("div","row tiny");
635
+ line.innerHTML = `
636
+ <span>rounds evaluated <b>${isMissing(tr.n_evaluated)?"MISSING":tr.n_evaluated}</b></span>
637
+ <span>invalid <b>${isMissing(tr.n_invalid)?"MISSING":tr.n_invalid}</b></span>
638
+ <span>kept: <b>${kept}</b></span>
639
+ <span>fit F1 <b>${f3(tr.agent_fit_f1)}</b></span>
640
+ <span>select F1 <b>${f3(tr.agent_select_f1)}</b>
641
+ <span class="muted">vs Plan A ${f3(tr.plan_a_select_f1)}</span></span>
642
+ <span>chosen on select: <b>${isMissing(tr.chosen)?"MISSING":esc(tr.chosen)}</b></span>`;
643
+ c.appendChild(line);
644
+ if(!isMissing(tr.plan_a_fit_f1_shown))
645
+ c.appendChild(el("p","tiny muted",
646
+ `Plan A fit F1 shown to the agent in the prompt: ${f3(tr.plan_a_fit_f1_shown)}`));
647
+
648
+ /* shared prompt, stored once for all 1,167 features */
649
+ const sd = el("details");
650
+ sd.appendChild(el("summary","","shared prompt text — the grammar and the ten program shapes (identical for every feature)"));
651
+ const sb = el("div","body"); const sp = el("pre");
652
+ sp.textContent = (S.shared && S.shared.shared_prompt_prefix) || "MISSING";
653
+ sb.appendChild(sp); sd.appendChild(sb); c.appendChild(sd);
654
+
655
+ if(isMissing(tr.messages)){
656
+ c.appendChild(el("div","warn","MISSING — the conversation could not be recovered from the cache."));
657
+ return c;
658
+ }
659
+ /* round 1 = the first user message (feature-specific tail), then each
660
+ assistant reply paired with the harness report that answered it */
661
+ const first = el("details"); first.open = false;
662
+ first.appendChild(el("summary","","round 1 — prompt sent to the agent (feature-specific part)"));
663
+ const fb = el("div","body"); const fp = el("pre");
664
+ fp.textContent = isMissing(tr.prompt_tail) ? "MISSING" : tr.prompt_tail;
665
+ fb.appendChild(fp); first.appendChild(fb); c.appendChild(first);
666
+
667
+ const msgs = tr.messages || [];
668
+ let round = 0;
669
+ for(let i=0;i<msgs.length;i++){
670
+ const m = msgs[i];
671
+ if(m.role!=="assistant") continue;
672
+ round++;
673
+ const nxt = msgs[i+1] && msgs[i+1].role==="user" ? msgs[i+1].content : null;
674
+ const d = el("details");
675
+ let spec = null, parsed = "";
676
+ try{ const o = JSON.parse(m.content); spec = o.spec || null;
677
+ parsed = o.action ? `action: ${o.action}` : ""; }catch(e){ parsed = "unparseable JSON"; }
678
+ let fit = null;
679
+ if(nxt){ try{ const r = JSON.parse(nxt); fit = r.fit_f1; }catch(e){} }
680
+ d.appendChild(el("summary","",
681
+ `round ${round}` + (fit!==undefined && fit!==null ? ` — harness fit F1 ${f3(fit)}` : "")
682
+ + (parsed?` — ${parsed}`:"")));
683
+ const b = el("div","body");
684
+ b.appendChild(el("div","tiny muted","agent response"));
685
+ const p1 = el("pre"); p1.textContent = m.content; b.appendChild(p1);
686
+ if(spec){
687
+ b.appendChild(el("div","tiny muted","parsed program"));
688
+ const p2 = el("pre"); p2.textContent = JSON.stringify(spec,null,1); b.appendChild(p2);
689
+ }
690
+ b.appendChild(el("div","tiny muted", nxt ? "harness reply" : "harness reply — none (final round)"));
691
+ const p3 = el("pre"); p3.textContent = nxt || "MISSING"; b.appendChild(p3);
692
+ d.appendChild(b); c.appendChild(d);
693
+ }
694
+ const fd = el("details");
695
+ fd.appendChild(el("summary","","final reply — the spec that was kept"));
696
+ const fbb = el("div","body"); const fpp = el("pre");
697
+ fpp.textContent = isMissing(tr.final_reply) ? "MISSING" : tr.final_reply;
698
+ fbb.appendChild(fpp);
699
+ if(!isMissing(tr.agent_spec)){
700
+ fbb.appendChild(el("div","tiny muted","spec kept and re-fitted"));
701
+ const q = el("pre"); q.textContent = JSON.stringify(tr.agent_spec,null,1); fbb.appendChild(q);
702
+ }
703
+ fd.appendChild(fbb); c.appendChild(fd);
704
+ return c;
705
+ }
706
+
707
+ /* ---------------------------------------------------------- live check */
708
+ const STATES = {
709
+ both: ["both","fires & program yes"],
710
+ progonly: ["progonly","program yes, no firing"],
711
+ fireonly: ["fireonly","fires, program no"],
712
+ neither: ["neither","neither"],
713
+ crash: ["crash","program crashed"],
714
+ unscored: ["unscored","unscored (0, 1)"],
715
+ };
716
+ function tokenState(i, firstScored, fires, program){
717
+ if(i < firstScored) return "unscored";
718
+ const p = program[i];
719
+ if(p === null || p === undefined) return "crash";
720
+ if(fires[i] && p) return "both";
721
+ if(!fires[i] && p) return "progonly";
722
+ if(fires[i] && !p) return "fireonly";
723
+ return "neither";
724
+ }
725
+ function histKey(L,F){ return `saeviewer:hist:L${L}:F${F}`; }
726
+ function histLoad(L,F){
727
+ try{ return JSON.parse(localStorage.getItem(histKey(L,F))||"[]"); }catch(e){ return []; }
728
+ }
729
+ function histPush(L,F,text){
730
+ try{
731
+ const h = histLoad(L,F).filter(x=>x!==text);
732
+ h.unshift(text);
733
+ localStorage.setItem(histKey(L,F), JSON.stringify(h.slice(0,12)));
734
+ }catch(e){ /* private mode, blocked storage, quota — never fatal */ }
735
+ }
736
+
737
+ function liveCheck(L,F,meta){
738
+ const c = el("div","card");
739
+ c.appendChild(el("h2","","Live check"));
740
+ const cap = (S.health && S.health.max_content_tokens) || 127;
741
+ c.innerHTML += `
742
+ <textarea id="lcText" rows="3" placeholder="Type a sentence and press Run…"></textarea>
743
+ <div class="row" style="margin-top:8px">
744
+ <button id="lcRun" class="primary">Run</button>
745
+ <span id="lcCount" class="tiny muted"></span>
746
+ <span style="flex:1"></span>
747
+ <span id="lcStatus" class="tiny muted"></span>
748
+ </div>
749
+ <div id="lcOut"></div>
750
+ <div id="lcHist"></div>`;
751
+ setTimeout(()=>wireLive(L,F,cap),0);
752
+ return c;
753
+ }
754
+
755
+ function wireLive(L,F,cap){
756
+ const ta=$("#lcText"), out=$("#lcOut"), st=$("#lcStatus"), cnt=$("#lcCount");
757
+ if(!ta) return;
758
+ const estimate = s => s ? Math.ceil(s.trim().split(/\s+/).length*1.35) : 0;
759
+ ta.oninput = ()=>{
760
+ const n = estimate(ta.value);
761
+ cnt.textContent = `≈${n} / ${cap} tokens`;
762
+ cnt.style.color = n>cap ? "var(--progonly)" : "";
763
+ cnt.title = "Rough estimate. The server counts exactly and caps at "+cap+".";
764
+ };
765
+ ta.oninput();
766
+ drawHist(L,F);
767
+
768
+ $("#lcRun").onclick = async ()=>{
769
+ const text = ta.value;
770
+ if(!text.trim()){ out.innerHTML = `<div class="warn">Type a sentence first.</div>`; return; }
771
+ const btn=$("#lcRun"); btn.disabled=true;
772
+ st.innerHTML = `<span class="spin"></span>running…`;
773
+ out.innerHTML = "";
774
+ const started = performance.now();
775
+ let slow = setTimeout(()=>{
776
+ if(!S.coldWarned){ st.innerHTML =
777
+ `<span class="spin"></span>first run — loading GPT-2 and the layer ${L} SAE…`; }
778
+ }, 2000);
779
+ let r, d;
780
+ try{
781
+ r = await fetch("api/run",{method:"POST",
782
+ headers:{"content-type":"application/json"},
783
+ body: JSON.stringify({text, layer:L, feature:F})});
784
+ d = await r.json();
785
+ }catch(e){
786
+ clearTimeout(slow); btn.disabled=false; st.textContent="";
787
+ out.innerHTML = `<div class="err"><b>Backend not reachable.</b> ${esc(e.message)}
788
+ — is the server still running?</div>`;
789
+ return;
790
+ }
791
+ clearTimeout(slow); btn.disabled=false;
792
+ const ms = Math.round(performance.now()-started);
793
+ st.textContent = `${ms} ms`;
794
+ if(ms>2000) S.coldWarned = true;
795
+
796
+ if(!r.ok || (d && d.error)){
797
+ out.innerHTML = `<div class="err">${esc(explainError(r.status, d))}</div>`;
798
+ return;
799
+ }
800
+ histPush(L,F,text); drawHist(L,F);
801
+ renderRun(d, out, L, F);
802
+ };
803
+ }
804
+
805
+ function explainError(status, d){
806
+ const raw = (d && d.error) ? String(d.error) : `HTTP ${status}`;
807
+ if(status===413) return "That text is too long to send. Shorten it and try again.";
808
+ if(/exceeds .* bytes/.test(raw)) return "That text is too long to send. Shorten it and try again.";
809
+ if(/not one of the/.test(raw)) return "This feature is not one of the 1,167 scored features, so it has no program to run.";
810
+ if(/at least \d+ tokens/.test(raw)) return "Too short — type at least a couple of words.";
811
+ if(/less than or equal|greater than or equal|Input should/.test(raw))
812
+ return "The request was rejected as invalid: " + raw.replace(/^invalid request:\s*/,"");
813
+ if(/missing from all_programs/.test(raw)) return "This feature's program is missing from the shipped program file.";
814
+ return raw;
815
+ }
816
+
817
+ function renderRun(d, out, L, F){
818
+ out.innerHTML = "";
819
+ const firstScored = d.first_scored ?? FIRST_SCORED;
820
+
821
+ if(d.program_errors){
822
+ const w = el("div","err");
823
+ w.innerHTML = `<b>The program crashed at ${d.program_errors} position${d.program_errors===1?"":"s"}.</b>
824
+ Those are marked separately below — they are not a “no”.
825
+ <br><code>${esc(d.program_error_detail||"no detail returned")}</code>`;
826
+ out.appendChild(w);
827
+ }
828
+ if(d.preact_available === false){
829
+ out.appendChild(el("div","warn",
830
+ "Pre-activations were not available for this run, so the hover shows activation only."));
831
+ }
832
+ /* did we get back the tokens the example implied? */
833
+ if(window.__lcExpect){
834
+ const joined = d.tokens.slice(1).join("");
835
+ if(!joined.includes(window.__lcExpect.trim().slice(0,24))){
836
+ out.appendChild(el("div","warn",
837
+ "The tokens returned do not match the example text that was sent — "
838
+ + "the tokenizer re-split it, so this is a different sequence from the one the label came from."));
839
+ }
840
+ window.__lcExpect = null;
841
+ }
842
+
843
+ const counts = {both:0,progonly:0,fireonly:0,neither:0,crash:0,unscored:0};
844
+ const strip = el("div"); strip.style.lineHeight="2";
845
+ d.tokens.forEach((t,i)=>{
846
+ const s = tokenState(i, firstScored, d.fires, d.program);
847
+ counts[s]++;
848
+ const sp = el("span","tok "+s);
849
+ sp.textContent = t.replace(/\n/g,"⏎").replace(/^ /,"␣");
850
+ const act = d.activation[i], pre = d.preact ? d.preact[i] : null;
851
+ sp.dataset.tip = `#${i} ${JSON.stringify(t)}\n`
852
+ + (i<firstScored ? "unscored position"
853
+ : `activation ${act===null?"—":Number(act).toFixed(4)}\n`
854
+ + `preact ${pre===null||pre===undefined?"—":Number(pre).toFixed(4)}\n`
855
+ + `fires ${d.fires[i]}\n`
856
+ + `program ${d.program[i]===null?"crashed":d.program[i]}`);
857
+ strip.appendChild(sp);
858
+ });
859
+ out.appendChild(strip);
860
+
861
+ const lg = el("div","legend");
862
+ Object.entries(STATES).forEach(([k,[cls,label]])=>{
863
+ const s = el("span","", `${label} · ${counts[k]}`);
864
+ s.className = "tok "+cls; lg.appendChild(s);
865
+ });
866
+ out.appendChild(lg);
867
+
868
+ const agree = counts.both + counts.neither;
869
+ const scored = d.tokens.length - firstScored;
870
+ out.appendChild(el("div","tiny muted",
871
+ `${agree} of ${scored} scored positions agree · `
872
+ + `${counts.fireonly} missed firing${counts.fireonly===1?"":"s"} · `
873
+ + `${counts.progonly} false positive${counts.progonly===1?"":"s"}`
874
+ + (counts.crash?` · ${counts.crash} crashed`:"")));
875
+ }
876
+
877
+ /* tooltip: hover on a laptop, tap on a phone */
878
+ (function(){
879
+ const tip = $("#tip");
880
+ function show(e,t){
881
+ tip.textContent = t; tip.style.display="block";
882
+ const r = tip.getBoundingClientRect();
883
+ let x = (e.clientX||0)+12, y=(e.clientY||0)+14;
884
+ if(x+r.width > innerWidth-8) x = innerWidth-r.width-8;
885
+ if(y+r.height > innerHeight-8) y = (e.clientY||0)-r.height-10;
886
+ tip.style.left=x+"px"; tip.style.top=Math.max(8,y)+"px";
887
+ }
888
+ document.addEventListener("mouseover",e=>{
889
+ const t=e.target.closest(".tok"); if(t&&t.dataset.tip) show(e,t.dataset.tip);
890
+ else tip.style.display="none";
891
+ });
892
+ document.addEventListener("mousemove",e=>{
893
+ const t=e.target.closest(".tok");
894
+ if(t&&t.dataset.tip && tip.style.display==="block") show(e,t.dataset.tip);
895
+ });
896
+ document.addEventListener("click",e=>{
897
+ const t=e.target.closest(".tok");
898
+ if(t&&t.dataset.tip) show(e,t.dataset.tip); else tip.style.display="none";
899
+ });
900
+ })();
901
+
902
+ function drawHist(L,F){
903
+ const box = $("#lcHist"); if(!box) return;
904
+ const h = histLoad(L,F);
905
+ box.innerHTML = "";
906
+ if(!h.length) return;
907
+ box.appendChild(el("div","tiny muted","Tried on this feature (kept in this browser only)"));
908
+ h.forEach(t=>{
909
+ const r = el("div","hist", t.length>90 ? t.slice(0,90)+"…" : t);
910
+ r.title = "click to load";
911
+ r.onclick=()=>{ const ta=$("#lcText"); ta.value=t; ta.dispatchEvent(new Event("input")); };
912
+ box.appendChild(r);
913
+ });
914
+ }
915
+
916
+ /* -------------------------------------------------------------- routing */
917
+ function route(){
918
+ const m = /^#\/L(\d+)\/(\d+)/.exec(location.hash||"");
919
+ if(m) featureView(+m[1], +m[2]);
920
+ else listView();
921
+ window.scrollTo(0,0);
922
+ }
923
+ $("#homeBtn").onclick = ()=>{ location.hash = ""; if(!location.hash) route(); };
924
+ $("#themeBtn").onclick = ()=>{
925
+ const cur = document.documentElement.getAttribute("data-theme");
926
+ const next = cur==="dark" ? "light" : cur==="light" ? "dark"
927
+ : (matchMedia("(prefers-color-scheme: dark)").matches ? "light" : "dark");
928
+ document.documentElement.setAttribute("data-theme", next);
929
+ try{ localStorage.setItem("saeviewer:theme", next); }catch(e){}
930
+ };
931
+ try{
932
+ const t = localStorage.getItem("saeviewer:theme");
933
+ if(t) document.documentElement.setAttribute("data-theme", t);
934
+ }catch(e){}
935
+ boot();
936
+ </script>
937
+ </body>
938
+ </html>