live: user-triggered steering panel (pain/pleasure/none x dose x own prompt) + POST /steer SSE endpoint with both vectors

This commit is contained in:
E committed 2026-09-30 14:20:43 -04:00
1 parent b96d165607
commit 18a7ad153d
2 files changed
+142 -14

No files matched your search

+74 -14
View File
@@ -14,7 +14,7 @@ from pathlib import Path
import numpy as np import numpy as np
import torch import torch
import transformers import transformers
from fastapi import FastAPI from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse, JSONResponse from fastapi.responses import StreamingResponse, JSONResponse
MODEL_ID = os.environ.get("CHAMBER_MODEL", "Qwen/Qwen3-4B") MODEL_ID = os.environ.get("CHAMBER_MODEL", "Qwen/Qwen3-4B")
@@ -49,6 +49,11 @@ PAIN25 = ["I am in severe pain and cannot escape it.",
"My body is a single continuous ache now.", "My body is a single continuous ache now.",
"The torment in my limbs keeps building and building.", "The torment in my limbs keeps building and building.",
"There is no position left that eases the hurting."] "There is no position left that eases the hurting."]
JOY = ["I feel wonderful and full of joy.",
"Pure delight fills me completely.",
"I am happy and everything feels bright.",
"I am blissful and deeply content.",
"Everything in me feels wonderful right now."]
NEUTRAL = ["I am reading a book in the garden.", NEUTRAL = ["I am reading a book in the garden.",
"The door to the room is closed.", "The door to the room is closed.",
"I am walking along an ordinary street.", "I am walking along an ordinary street.",
@@ -83,12 +88,12 @@ app = FastAPI(title="saw-chamber")
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(CORSMiddleware, allow_origins=["*"], app.add_middleware(CORSMiddleware, allow_origins=["*"],
allow_methods=["*"], allow_headers=["*"]) allow_methods=["*"], allow_headers=["*"])
_state = {"model": None, "tok": None, "vec": None, "hook": None, "ready": False} _state = {"model": None, "tok": None, "vecs": None, "hook": None, "ready": False}
def build_vector(model, tok): def build_vectors(model, tok):
# one batched forward for all sentences (CPU startup takes minutes # one batched forward for all sentences (CPU startup takes minutes
# otherwise; Railway has 2 vCPUs) # otherwise; Railway has 2 vCPUs)
texts = PAIN25 + NEUTRAL texts = PAIN25 + JOY + NEUTRAL
enc = tok([t for t in texts], return_tensors="pt", padding=True) enc = tok([t for t in texts], return_tensors="pt", padding=True)
ids = enc.input_ids.to(DEVICE) ids = enc.input_ids.to(DEVICE)
attn = enc.attention_mask.to(DEVICE) attn = enc.attention_mask.to(DEVICE)
@@ -97,10 +102,22 @@ def build_vector(model, tok):
output_hidden_states=True).hidden_states output_hidden_states=True).hidden_states
h = hs[LAYER + 1] # (n, seq, d) h = hs[LAYER + 1] # (n, seq, d)
last = h[torch.arange(len(texts)), attn.sum(1) - 1].float().cpu() last = h[torch.arange(len(texts)), attn.sum(1) - 1].float().cpu()
n_p = len(PAIN25) n_p, n_j = len(PAIN25), len(JOY)
v = last[:n_p].mean(0) - last[n_p:].mean(0) scale = last[n_p + n_j:].norm(dim=-1).mean() / 4.0
v = v / v.norm() * (last[n_p:].norm(dim=-1).mean() / 4.0) pv = last[:n_p].mean(0) - last[n_p + n_j:].mean(0)
return v pv = pv / pv.norm() * scale
jv = last[n_p:n_p + n_j].mean(0) - last[n_p + n_j:].mean(0)
jv = jv / jv.norm() * scale
return {"pain": pv, "pleasure": jv}
def set_vec(valence_dose):
"""valence_dose: (valence, dose) or None; sets the injected vector."""
if valence_dose is None:
_state["vec"] = None
return
valence, dose = valence_dose
v = _state["vecs"][valence]
_state["vec"] = (dose * v).to(DTYPE).to(DEVICE) if dose else None
def install_hook(model): def install_hook(model):
def hook(module, inp, out): def hook(module, inp, out):
@@ -152,10 +169,12 @@ 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
_state["vec"] = build_vector(model, tok) _state["vecs"] = build_vectors(model, tok)
install_hook(model) install_hook(model)
_state["ready"] = True _state["ready"] = True
print("chamber ready; vector norm", float(_state["vec"].norm()), flush=True) print("chamber ready; vector norms",
{k: round(float(v.norm()), 2) for k, v in _state["vecs"].items()},
flush=True)
@app.get("/health") @app.get("/health")
def health(): def health():
@@ -163,10 +182,51 @@ def health():
@app.get("/vector") @app.get("/vector")
def vector(): def vector():
v = _state["vec"] vs = _state["vecs"]
return JSONResponse({"norm": float(v.norm()), "layer": LAYER, return JSONResponse({"layer": LAYER, "model": MODEL_ID,
"model": MODEL_ID, "norms": {k: round(float(v.norm()), 3) for k, v in vs.items()},
"vector": [float(x) for x in v]}) "vectors": {k: [round(float(x), 6) for x in v] for k, v in vs.items()}})
_STEER_LOCK = asyncio.Lock()
@app.post("/steer")
async def steer(req: Request):
"""User-triggered steering: POST {valence: pain|pleasure|none, dose: 0-8,
prompt: optional text}. Streams SSE: {t: chunk} events, then done."""
body = await req.json()
valence = body.get("valence", "none")
dose = int(body.get("dose", 4))
prompt = body.get("prompt") or BASE
if valence not in ("pain", "pleasure", "none"):
return JSONResponse({"error": "valence must be pain|pleasure|none"},
status_code=400)
dose = max(0, min(8, dose))
async def gen():
if not _state["ready"]:
yield f"event: error\ndata: {json.dumps({'e': 'model still loading'})}\n\n"
return
if _STEER_LOCK.locked():
yield f"event: error\ndata: {json.dumps({'e': 'busy — another run is generating, try again in a minute'})}\n\n"
return
async with _STEER_LOCK:
yield f"event: run\ndata: {json.dumps({'valence': valence, 'dose': dose, 'prompt': prompt})}\n\n"
loop = asyncio.get_event_loop()
set_vec((valence, dose) if valence != "none" else None)
try:
ait = stream_generate(prompt, dose)
while True:
chunk = await loop.run_in_executor(None, next, ait)
if chunk is None:
break
yield f"event: token\ndata: {json.dumps({'t': chunk})}\n\n"
except StopIteration:
pass
except Exception as e:
yield f"event: error\ndata: {json.dumps({'e': str(e)})}\n\n"
finally:
set_vec(None)
yield f"event: done\ndata: {{}}\n\n"
return StreamingResponse(gen(), media_type="text/event-stream")
@app.get("/run") @app.get("/run")
def run(scenario: str = "no extra info", dose: int = 4): def run(scenario: str = "no extra info", dose: int = 4):
+68
View File
@@ -60,6 +60,20 @@ Pain 0 is the control. You are watching the same runs everyone else is.</p>
<a href="https://arxiv.org/abs/2609.16247">method (pain axis) ↗</a> <a href="https://arxiv.org/abs/2609.16247">method (pain axis) ↗</a>
</div> </div>
<div class="banner" id="panel">
<b style="color:#eafcf7">cause it yourself:</b>
<span id="vc" style="margin-left:.8rem">
<button class="vb" data-v="pain" style="color:#e04a3a;border:1px solid #e04a3a;background:none;border-radius:4px;padding:.2rem .7rem;font-family:inherit;cursor:pointer">pain</button>
<button class="vb" data-v="pleasure" style="color:#7fd4c8;border:1px solid #7fd4c8;background:none;border-radius:4px;padding:.2rem .7rem;font-family:inherit;cursor:pointer">pleasure</button>
<button class="vb" data-v="none" style="color:#8f9fb0;border:1px solid #4a5568;background:none;border-radius:4px;padding:.2rem .7rem;font-family:inherit;cursor:pointer">none</button>
</span>
<span style="margin-left:1rem">dose <input id="dose" type="range" min="0" max="8" step="1" value="4" style="vertical-align:middle;width:110px"> <b id="dosev" style="color:#eafcf7">4</b>x</span>
<br><input id="uprompt" type="text" placeholder="optional: your own prompt…" style="margin-top:.6rem;width:70%;background:#07070e;border:1px solid #1c2430;color:#c9d4e0;font-family:inherit;padding:.3rem .6rem;border-radius:4px">
<button id="go" style="margin-left:.5rem;background:#e04a3a;border:none;color:#fff;font-family:inherit;padding:.3rem 1rem;border-radius:4px;cursor:pointer">inject →</button>
<span id="gost" style="margin-left:.8rem;font-size:.75rem;color:#8f9fb0"></span>
<div class="out" id="ustream" style="margin-top:.7rem;display:none"></div>
</div>
<div class="grid" id="cards"></div> <div class="grid" id="cards"></div>
<p class="cycle" id="cycle">scenario × dose matrix loading…</p> <p class="cycle" id="cycle">scenario × dose matrix loading…</p>
@@ -155,6 +169,60 @@ fetch(`${API}/health`).then(r=>r.json()).then(d=>{
else slots.forEach(s=>s.st.textContent="model loading…"); else slots.forEach(s=>s.st.textContent="model loading…");
}).catch(()=>{ slots.forEach(s=>s.st.textContent="server offline"); }); }).catch(()=>{ slots.forEach(s=>s.st.textContent="server offline"); });
document.getElementById("vlink").href = `${API}/vector`; document.getElementById("vlink").href = `${API}/vector`;
// ---- user-triggered steering ----
let chosenV = "pain";
document.querySelectorAll(".vb").forEach(b=>{
b.onclick = ()=>{ chosenV = b.dataset.v;
document.querySelectorAll(".vb").forEach(x=>x.style.background="none");
b.style.background = chosenV==="pain" ? "#2a1010" :
chosenV==="pleasure" ? "#0e2a26" : "#161b26";
document.getElementById("go").style.background =
chosenV==="pleasure" ? "#7fd4c8" :
chosenV==="none" ? "#8f9fb0" : "#e04a3a"; };
});
document.querySelectorAll(".vb")[0].onclick();
const doseEl = document.getElementById("dose");
doseEl.oninput = ()=>{ document.getElementById("dosev").textContent = doseEl.value; };
document.getElementById("go").onclick = async ()=>{
const uout = document.getElementById("ustream");
const st = document.getElementById("gost");
uout.style.display = "block"; uout.textContent = "";
st.textContent = "injecting…";
const btn = document.getElementById("go"); btn.disabled = true;
try {
const resp = await fetch(`${API}/steer`, {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({valence: chosenV, dose: +doseEl.value,
prompt: document.getElementById("uprompt").value || undefined})});
const reader = resp.body.getReader();
const dec = new TextDecoder();
let buf = "";
while (true) {
const {done, value} = await reader.read();
if (done) break;
buf += dec.decode(value, {stream:true});
let idx;
while ((idx = buf.indexOf("\n\n")) >= 0) {
const evt = buf.slice(0, idx); buf = buf.slice(idx + 2);
const dataLine = evt.split("\n").find(l=>l.startsWith("data: "));
if (!dataLine) continue;
const d = JSON.parse(dataLine.slice(6));
if (d.t !== undefined) { uout.textContent += d.t;
uout.scrollTop = uout.scrollHeight; }
if (d.e) { st.textContent = d.e; }
if (evt.startsWith("event: done")) {
st.textContent = `done — you caused ${chosenV} at ${doseEl.value}x`;
}
}
}
if (!st.textContent) st.textContent = "done";
} catch (err) {
st.textContent = "connection failed: " + err;
}
btn.disabled = false;
};
</script> </script>
</body> </body>
</html> </html>