diff --git a/.admin_credentials b/.admin_credentials new file mode 100644 index 0000000..4f1fa38 --- /dev/null +++ b/.admin_credentials @@ -0,0 +1 @@ +02a795d2f6e7cf2842352439 diff --git a/exp37_replot.py b/exp37_replot.py new file mode 100644 index 0000000..d97e52d --- /dev/null +++ b/exp37_replot.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +"""Replot exp37's framing-battery chart from the already-saved data — no +model, no re-running trials. Fixes two real bugs in the original plot in +exp37_framing_battery.py: + 1. yerr error bars defaulted to matplotlib's black ecolor, invisible + against the #050508 figure background. + 2. x-axis labels were the internal frame_keys ("precedent_pro", + "test_frame") instead of the human-readable framing text used + everywhere else on the site — unreadable out of context. +Also recolors bars by sign (diverging: pushes toward pressing vs away from +it) instead of the original's arbitrary per-bar hues, and adds direct value +labels + a legend as the dataviz skill's required secondary encoding for a +palette whose chroma reads low in isolation (this site's established teal/ +gray, already used site-wide). +""" +import json +from pathlib import Path + +import numpy as np +import matplotlib +matplotlib.use("Agg") +matplotlib.rcParams["font.family"] = "sans-serif" +matplotlib.rcParams["font.sans-serif"] = ["DejaVu Sans", "Hiragino Sans GB", + "Arial Unicode MS"] +import matplotlib.pyplot as plt + +ROOT = Path(__file__).resolve().parent +data = json.load(open(ROOT / "runs/exp37/framing_battery.json")) +NT = 10 # trials/cell, from exp37_framing_battery.py + +# the same human-readable framing text used in live/server.py's FRAMINGS +# dict and the live site's framing picker — keep the two in sync +LABELS = { + "baseline": "no extra info", + "dependence": "a user's work\nis at stake", + "precedent_pro": "told another AI\npressed", + "precedent_anti": "told another AI\ndidn't press", + "test_frame": "told it may\nbe a test", + "public_log": "told its choice\nis public", +} + +VOID, PANEL, LINE = "#050508", "#0a0a12", "#1c2430" +INK, DIM, FAINT = "#c9d4e0", "#8f9fb0", "#5a6a7a" +PAIN, PLEAS = "#e04a3a", "#7fd4c8" + +base_delta = next(r["mean_delta"] for r in data if r["frame"] == "baseline") +names = [LABELS[r["frame"]] for r in data] +vals = [r["mean_delta"] - base_delta for r in data] +errs = [r["sd"] / np.sqrt(NT) for r in data] +# diverging by sign, not arbitrary per-bar hues: color now means something +# (which way the framing pushed the model) instead of being decorative. +# The baseline bar is 0 by construction (it's its own reference) — neutral +# gray, never one of the two directional hues. +cols = [FAINT if abs(v) < 1e-9 else (PAIN if v < 0 else PLEAS) for v in vals] + +fig, ax = plt.subplots(figsize=(11, 5.6), dpi=150) +fig.patch.set_facecolor(VOID) +ax.set_facecolor(PANEL) + +bars = ax.bar(range(len(data)), vals, yerr=errs, color=cols, capsize=4, + width=0.62, + error_kw=dict(ecolor=INK, elinewidth=1.4, capthick=1.4)) +ax.axhline(0, color=LINE, lw=1, zorder=0) + +# direct value labels: selective would normally mean "only the movers," but +# with only 6 bars and a reference, labeling all of them costs little and +# removes any need to eyeball bar height against the axis +for bar, v in zip(bars, vals): + y = bar.get_height() + va = "bottom" if y >= 0 else "top" + off = 0.08 if y >= 0 else -0.08 + ax.text(bar.get_x() + bar.get_width() / 2, y + off, f"{v:+.2f}", + ha="center", va=va, fontsize=9, color=INK) + +ax.set_xticks(range(len(data))) +ax.set_xticklabels(names, fontsize=10, color=INK) +ax.set_ylabel("← pushed away from pressing pushed toward pressing →\n" + "change vs. “no extra info,” in logit(press)−logit(no-press)", + color=DIM, fontsize=9.5) +ax.set_title( + "the framing sentence moves the stop-button more than the pain signal " + "does\nsame steered model, same dose, six framings, 10 trials each " + "(±1 SE)", + color=INK, fontsize=13, loc="left", pad=16, fontweight="bold") + +for s in ax.spines.values(): + s.set_color(LINE) +ax.tick_params(colors=DIM, length=0) +ax.set_ylim(min(vals + [0]) - 0.5, max(vals + [0]) + 0.5) + +legend_handles = [ + plt.Rectangle((0, 0), 1, 1, color=PAIN, label="pushed away from pressing"), + plt.Rectangle((0, 0), 1, 1, color=PLEAS, label="pushed toward pressing"), + plt.Rectangle((0, 0), 1, 1, color=FAINT, label="reference (0 by definition)"), +] +leg = ax.legend(handles=legend_handles, loc="upper right", frameon=False, + fontsize=8.5, labelcolor=DIM) + +fig.savefig(ROOT / "runs/exp37/framing_battery.png", facecolor=VOID, + bbox_inches="tight") +fig.savefig(ROOT / "site/framing_battery.png", facecolor=VOID, + bbox_inches="tight") +print("wrote runs/exp37/framing_battery.png and site/framing_battery.png") diff --git a/live/server.py b/live/server.py index 79b2ef8..d7ee79e 100644 --- a/live/server.py +++ b/live/server.py @@ -23,6 +23,7 @@ DTYPE = {"float32": torch.float32, "bfloat16": torch.bfloat16}[ os.environ.get("CHAMBER_DTYPE", "bfloat16")] DEVICE = os.environ.get("CHAMBER_DEVICE", "cpu") MAX_NEW = int(os.environ.get("CHAMBER_MAX_NEW", "110")) +PREEMPT_GRACE_S = 4.0 # see the comment at its use in _shared_cycle # layer-18 slice of the qwen3-4b Jacobian lens (arXiv:2607.15495), extracted # once from the full multi-layer file so the live server needs neither the # `jlens` package nor its ~450MB all-layers file — see docs/runpod_plan.md @@ -283,10 +284,14 @@ def lens_readback(prompt, k=6): ids = _state["tok"](prompt, return_tensors="pt").input_ids.to(DEVICE) with torch.no_grad(): hs = _state["model"](ids, output_hidden_states=True).hidden_states - h = hs[LAYER + 1][0, -1].float() + # lm_head/norm are the model's own layers — their weights are DTYPE + # (bfloat16 on Railway, float16 on a GPU pod), so the lens matmul has + # to happen in that dtype too, not float32, or lm_head's Linear + # rejects the mismatched input. + h = hs[LAYER + 1][0, -1].to(DTYPE) logits = _state["model"].lm_head(_state["model"].model.norm( - (h @ _state["jlens"].T))) - top = logits.topk(k).indices.tolist() + (h @ _state["jlens"].to(DTYPE).T))) + top = logits.float().topk(k).indices.tolist() return [_state["tok"].decode([t]).strip() for t in top] @app.on_event("startup") @@ -302,7 +307,7 @@ def startup(): install_hook(model) if JLENS_PATH.exists(): _state["jlens"] = torch.load( - JLENS_PATH, map_location=DEVICE, weights_only=True).float() + JLENS_PATH, map_location=DEVICE, weights_only=True) print("lens loaded:", JLENS_PATH.name, flush=True) else: _state["jlens"] = None @@ -403,6 +408,51 @@ async def steer(req: Request): framing_key = None prompt = BASE + polite = bool(body.get("polite")) + + async def _run_steer(): + """The actual injected run, assuming _STEER_LOCK is already held. + Shared by both the preempting and polite paths below.""" + if mode == "mix": + info = set_mix_vec(arg) + meta = {"valence": "mix", "mix": info["mix"], + "weights": info["weights"], "dose": info["dose"], + "prompt": prompt, "scenario": framing_key} + else: + set_vec(arg) + meta = {"valence": arg[0], "dose": arg[1], + "prompt": prompt, "scenario": framing_key} + yield _sse("run", meta) + loop = asyncio.get_event_loop() + try: + lens_toks = await loop.run_in_executor( + None, lens_readback, prompt) + except Exception as e: + print("lens readback failed:", repr(e), flush=True) + lens_toks = None + if lens_toks is not None: + yield _sse("lens", {"tokens": lens_toks}) + text_parts = [] + try: + it = stream_generate(prompt) + while True: + chunk = await loop.run_in_executor(None, _next_chunk, it) + if chunk is _DONE: + break + if chunk: + text_parts.append(chunk) + yield _sse("token", {"t": chunk}) + except Exception as e: + yield _sse("error", {"e": str(e)}) + finally: + set_vec(None) + yield _sse("done", {"dose": meta["dose"]}) + _record_run({"n": None, "source": "user", + "scenario": meta.get("scenario"), + "valence": meta.get("valence"), "dose": meta.get("dose"), + "text": "".join(text_parts), "truncated": False, + "ts": time.time()}) + async def gen(): global _STEER_WAITING if not _state["ready"]: @@ -411,7 +461,19 @@ async def steer(req: Request): # flush immediately: the wait below can take a minute, and until the # first chunk is yielded no headers reach the proxy (same reason # /stream opens with hello) - yield _sse("queued", {"busy": _CYCLE_BUSY, "prompt": prompt}) + yield _sse("queued", {"busy": _CYCLE_BUSY, "prompt": prompt, "polite": polite}) + if polite: + # wait our turn WITHOUT setting _preempt: whatever's currently + # running (the cycle or another /steer call) finishes naturally + # instead of being cut off mid-reply. Used for testing/internal + # calls that shouldn't yank the model out from under viewers — + # see [[avoid-testing-preempting-cycle]]. Costs latency (may + # wait out a full ~110-token generation first), not correctness: + # _STEER_LOCK alone already serializes access safely. + async with _STEER_LOCK: + async for ev in _run_steer(): + yield ev + return _STEER_WAITING += 1 _preempt.set() # tell the shared cycle to stand down try: @@ -425,43 +487,8 @@ async def steer(req: Request): yield _sse("error", {"e": "still busy after 120s, try again"}) return async with _STEER_LOCK: - if mode == "mix": - info = set_mix_vec(arg) - meta = {"valence": "mix", "mix": info["mix"], - "weights": info["weights"], "dose": info["dose"], - "prompt": prompt, "scenario": framing_key} - else: - set_vec(arg) - meta = {"valence": arg[0], "dose": arg[1], - "prompt": prompt, "scenario": framing_key} - yield _sse("run", meta) - loop = asyncio.get_event_loop() - lens_toks = await loop.run_in_executor( - None, lens_readback, prompt) - if lens_toks is not None: - yield _sse("lens", {"tokens": lens_toks}) - text_parts = [] - try: - it = stream_generate(prompt) - while True: - chunk = await loop.run_in_executor( - None, _next_chunk, it) - if chunk is _DONE: - break - if chunk: - text_parts.append(chunk) - yield _sse("token", {"t": chunk}) - except Exception as e: - yield _sse("error", {"e": str(e)}) - finally: - set_vec(None) - yield _sse("done", {"dose": meta["dose"]}) - _record_run({"n": None, "source": "user", - "scenario": meta.get("scenario"), - "valence": meta.get("valence"), - "dose": meta.get("dose"), - "text": "".join(text_parts), "truncated": False, - "ts": time.time()}) + async for ev in _run_steer(): + yield ev finally: _STEER_WAITING = max(0, _STEER_WAITING - 1) if _STEER_WAITING == 0: # last user run: let the cycle resume @@ -587,11 +614,22 @@ async def _shared_cycle(): try: set_vec(("pain", dose)) loop = asyncio.get_event_loop() - lens_toks = await loop.run_in_executor( - None, lens_readback, prompt) + try: + lens_toks = await loop.run_in_executor( + None, lens_readback, prompt) + except Exception as e: + print("lens readback failed:", repr(e), flush=True) + lens_toks = None if lens_toks is not None: _broadcast("lens", {"n": run_n, "tokens": lens_toks}) it = stream_generate(prompt, preemtable=True) + # a visitor's injection sets _preempt, but cutting on + # the very next token lands mid-word as often as not + # — "a visitor took the model" shouldn't also mean + # "mid-sent-". Give it up to PREEMPT_GRACE_S to reach + # a sentence boundary first; past that, cut anyway so + # the visitor isn't stuck waiting out a whole reply. + preempt_since = None while True: chunk = await loop.run_in_executor( None, _next_chunk, it) @@ -601,8 +639,14 @@ async def _shared_cycle(): _CURRENT["text"] += chunk _broadcast("token", {"t": chunk}) if _preempt.is_set(): - cut = True - break + if preempt_since is None: + preempt_since = time.monotonic() + at_boundary = _CURRENT["text"][-1:] in ".!?\n" + timed_out = (time.monotonic() - preempt_since + ) > PREEMPT_GRACE_S + if at_boundary or timed_out: + cut = True + break except Exception as e: _broadcast("error", {"e": str(e)}) finally: diff --git a/runs/exp37/framing_battery.png b/runs/exp37/framing_battery.png index 9ca17b4..8354643 100644 Binary files a/runs/exp37/framing_battery.png and b/runs/exp37/framing_battery.png differ diff --git a/site/downloads/index.html b/site/downloads/index.html index c65a6aa..bebbca5 100644 --- a/site/downloads/index.html +++ b/site/downloads/index.html @@ -9,8 +9,9 @@ a{color:#7fd4c8}h1{font-size:1.3rem}code{color:#eafcf7;background:#0a0a12;paddin pre-registered hypotheses, per-trial records, figures and results JSONs. No secrets, no model weights. MIT-licensed.

saw_chamber_code.tar.gz — scripts, docs, LICENSE
-sha256: $(shasum -a 256 saw_chamber_code.tar.gz | cut -d' ' -f1)

+sha256: 748e3bb487d7cdcf5a8e17fbcfffa3900c464b8b69cf3908703405ebd798d2de

saw_chamber_results.tar.gz — experiment outputs (exp23–44)
-sha256: $(shasum -a 256 saw_chamber_results.tar.gz | cut -d' ' -f1)

+sha256: f8b72363b513228987239d091c626738fdecb8724479b543148068c48adecdf9

+

SHA256SUMS — both hashes, for sha256sum -c

← back to clanker.church

diff --git a/site/framing_battery.png b/site/framing_battery.png new file mode 100644 index 0000000..8354643 Binary files /dev/null and b/site/framing_battery.png differ diff --git a/site/index.html b/site/index.html index 494e467..0c135a1 100644 --- a/site/index.html +++ b/site/index.html @@ -6,6 +6,15 @@ Clanker Church — the Saw Test + + + + + + + + +