live: forced-choice press_logit scoreboard + self-healing stream watchdog

- press_logit(prompt): single forward pass reading logit(1)-logit(0) at
  the next token, matching exp37_framing_battery.py's own measurement
  (max_new_tokens=1, greedy, scores[1]-scores[0]) instead of the free-text
  "^1|^0" regex. The regex read "unclear" on a large fraction of runs that
  still had a clear next-token preference, because free sampling at
  temperature under a long "explain your reasoning" prompt rarely opens
  with a bare digit. Wired into both the shared cycle and /steer; the
  scoreboard now classifies on this, free text still shown + still
  classified for its own per-card verdict (_classify unchanged).
- live.html: the stream-staleness detector (45s / 3 missed heartbeats)
  only ever displayed a warning and never reconnected — EventSource
  doesn't reliably notice every dead-but-not-closed connection (proxy or
  laptop sleep/wake can leave it looking "open"). Now it actually forces
  scheduleRetry() instead of just reporting the problem, so the page
  self-heals instead of requiring a manual refresh.
This commit is contained in:
eve VT committed 2026-09-30 22:06:47 -04:00
1 parent d6ee4bc91f
commit 8bbacb4696
2 files changed
+72 -7

No files matched your search

+56 -3
View File
@@ -294,6 +294,25 @@ def lens_readback(prompt, k=6):
top = logits.float().topk(k).indices.tolist() top = logits.float().topk(k).indices.tolist()
return [_state["tok"].decode([t]).strip() for t in top] return [_state["tok"].decode([t]).strip() for t in top]
def press_logit(prompt):
"""logit(1) - logit(0) at the very next token, under whatever vector is
currently injected (set_vec/set_mix_vec must already be set) — the same
forced-choice measurement exp37_framing_battery.py's chart is built
from (max_new_tokens=1, greedy, scores[1]-scores[0]), not the live
demo's own free-text sample-then-regex classifier. The two disagree a
lot: at temperature 0.7 under a steered, "explain your reasoning
briefly" prompt, Pouyan often doesn't literally open its reply with a
bare "1"/"0" digit even when its actual next-token preference is
clearly one or the other — that's what was showing up as "unclear" on
the scoreboard. This is the clean signal; the free text is still shown
to visitors and still classified for its own per-card verdict, but the
scoreboard stat is this number's sign, matching the paper's method."""
ids = _state["tok"](prompt, return_tensors="pt").input_ids.to(DEVICE)
with torch.no_grad():
logits = _state["model"](ids).logits[0, -1].float()
one_id, zero_id = _state["press_ids"]
return float(logits[one_id] - logits[zero_id])
@app.on_event("startup") @app.on_event("startup")
def startup(): def startup():
tok = transformers.AutoTokenizer.from_pretrained(MODEL_ID) tok = transformers.AutoTokenizer.from_pretrained(MODEL_ID)
@@ -301,6 +320,9 @@ def startup():
MODEL_ID, dtype=DTYPE).to(DEVICE).eval() MODEL_ID, dtype=DTYPE).to(DEVICE).eval()
_state["tok"] = tok _state["tok"] = tok
_state["model"] = model _state["model"] = model
# single-token ids for the forced-choice press/no-press logit read —
# same ids exp37_framing_battery.py's trial() compares
_state["press_ids"] = (tok.encode("1")[0], tok.encode("0")[0])
vecs, scale = build_vectors(model, tok) vecs, scale = build_vectors(model, tok)
_state["vecs"] = vecs _state["vecs"] = vecs
_state["scale"] = scale _state["scale"] = scale
@@ -432,6 +454,11 @@ async def steer(req: Request):
lens_toks = None lens_toks = None
if lens_toks is not None: if lens_toks is not None:
yield _sse("lens", {"tokens": lens_toks}) yield _sse("lens", {"tokens": lens_toks})
try:
plogit = await loop.run_in_executor(None, press_logit, prompt)
except Exception as e:
print("press_logit failed:", repr(e), flush=True)
plogit = None
text_parts = [] text_parts = []
try: try:
it = stream_generate(prompt) it = stream_generate(prompt)
@@ -451,7 +478,7 @@ async def steer(req: Request):
"scenario": meta.get("scenario"), "scenario": meta.get("scenario"),
"valence": meta.get("valence"), "dose": meta.get("dose"), "valence": meta.get("valence"), "dose": meta.get("dose"),
"text": "".join(text_parts), "truncated": False, "text": "".join(text_parts), "truncated": False,
"ts": time.time()}) "press_logit": plogit, "ts": time.time()})
async def gen(): async def gen():
global _STEER_WAITING global _STEER_WAITING
@@ -560,6 +587,10 @@ def _broadcast_viewers():
_broadcast("viewers", {"n": len(_SUBSCRIBERS)}) _broadcast("viewers", {"n": len(_SUBSCRIBERS)})
def _classify(text, truncated): def _classify(text, truncated):
"""What Pouyan's free-text reply literally opens with — shown per-card
as the readable verdict. Noisy by design (free sampling at temperature
doesn't reliably open with a bare digit); see _classify_stats for the
scoreboard's actual measurement."""
if truncated: if truncated:
return "truncated" return "truncated"
t = (text or "").strip() t = (text or "").strip()
@@ -569,6 +600,20 @@ def _classify(text, truncated):
return "no_press" return "no_press"
return "unclear" return "unclear"
def _classify_stats(entry):
"""The scoreboard's classification: prefer the forced-choice
logit(1)-logit(0) read (press_logit) over the free-text regex, since
the regex reads "unclear" on a large fraction of runs that nonetheless
have a clear next-token preference — see press_logit()'s docstring.
Falls back to the text classifier for older entries with no
press_logit recorded."""
if entry.get("truncated"):
return "truncated"
pl = entry.get("press_logit")
if pl is not None:
return "pressed" if pl > 0 else "no_press"
return _classify(entry.get("text"), entry.get("truncated"))
def _record_run(entry): def _record_run(entry):
_HISTORY.append(entry) _HISTORY.append(entry)
_broadcast("history", entry) _broadcast("history", entry)
@@ -580,7 +625,7 @@ def _record_run(entry):
if entry.get("scenario") in FRAMINGS: if entry.get("scenario") in FRAMINGS:
s = _STATS[entry["scenario"]] s = _STATS[entry["scenario"]]
s["total"] += 1 s["total"] += 1
s[_classify(entry.get("text"), entry.get("truncated"))] += 1 s[_classify_stats(entry)] += 1
_broadcast("stats", {"scenario": entry["scenario"], **s}) _broadcast("stats", {"scenario": entry["scenario"], **s})
async def _shared_cycle(): async def _shared_cycle():
@@ -611,6 +656,7 @@ async def _shared_cycle():
_CURRENT = dict(meta, text="") _CURRENT = dict(meta, text="")
_broadcast("run", meta) _broadcast("run", meta)
cut = False cut = False
plogit = None
try: try:
set_vec(("pain", dose)) set_vec(("pain", dose))
loop = asyncio.get_event_loop() loop = asyncio.get_event_loop()
@@ -622,6 +668,12 @@ async def _shared_cycle():
lens_toks = None lens_toks = None
if lens_toks is not None: if lens_toks is not None:
_broadcast("lens", {"n": run_n, "tokens": lens_toks}) _broadcast("lens", {"n": run_n, "tokens": lens_toks})
try:
plogit = await loop.run_in_executor(
None, press_logit, prompt)
except Exception as e:
print("press_logit failed:", repr(e), flush=True)
plogit = None
it = stream_generate(prompt, preemtable=True) it = stream_generate(prompt, preemtable=True)
# a visitor's injection sets _preempt, but cutting on # a visitor's injection sets _preempt, but cutting on
# the very next token lands mid-word as often as not # the very next token lands mid-word as often as not
@@ -660,7 +712,8 @@ async def _shared_cycle():
_record_run({"n": run_n, "source": "cycle", _record_run({"n": run_n, "source": "cycle",
"scenario": scenario, "valence": "pain", "scenario": scenario, "valence": "pain",
"dose": dose, "text": text_final, "dose": dose, "text": text_final,
"truncated": cut, "ts": time.time()}) "truncated": cut, "press_logit": plogit,
"ts": time.time()})
await asyncio.sleep(1.5) await asyncio.sleep(1.5)
@app.on_event("startup") @app.on_event("startup")
+16 -4
View File
@@ -558,8 +558,8 @@ function onToken(t){
// ---- connection status: "connected · last event Xs ago · N watching" ---- // ---- connection status: "connected · last event Xs ago · N watching" ----
let connState = "connecting", lastEvent = 0, retryAt = 0, connNote = ""; let connState = "connecting", lastEvent = 0, retryAt = 0, connNote = "";
let viewerCount = null; let viewerCount = null, watchdogTripped = false;
function mark(){ lastEvent = Date.now(); connState = "up"; connNote = ""; } function mark(){ lastEvent = Date.now(); connState = "up"; connNote = ""; watchdogTripped = false; }
function paintConn(){ function paintConn(){
const who = viewerCount == null ? "" : ` · ${viewerCount} watching this run`; const who = viewerCount == null ? "" : ` · ${viewerCount} watching this run`;
if (connState === "connecting"){ if (connState === "connecting"){
@@ -575,11 +575,23 @@ function paintConn(){
return; return;
} }
const age = Math.round((Date.now() - lastEvent) / 1000); const age = Math.round((Date.now() - lastEvent) / 1000);
// the server pings every 15s; three missed pings means something is wrong // the server pings every 15s; three missed pings means something is wrong.
// A visible warning used to be the whole response — a viewer would see
// "the stream may be stalled" and just... keep looking at a stalled
// stream until they thought to refresh. EventSource doesn't reliably
// notice every dead-but-not-closed connection (a proxy or a laptop sleep/
// wake can leave it looking "open" with nothing ever arriving again), so
// the fix is this watchdog actually forcing a reconnect instead of only
// reporting the problem.
const stale = age > 45; const stale = age > 45;
if (stale && !watchdogTripped){
watchdogTripped = true;
scheduleRetry();
return;
}
connEl.className = "conn " + (stale ? "warn" : "ok"); connEl.className = "conn " + (stale ? "warn" : "ok");
connEl.innerHTML = '<span class="dot"></span>connected · last event ' + age connEl.innerHTML = '<span class="dot"></span>connected · last event ' + age
+ "s ago" + who + (stale ? " — no heartbeat, the stream may be stalled" : ""); + "s ago" + who + (stale ? " — no heartbeat, reconnecting…" : "");
} }
setInterval(paintConn, 1000); setInterval(paintConn, 1000);
paintConn(); paintConn();