chore: gitignore pycache; server.py batched-vector + valence battery fixes

This commit is contained in:
E committed 2026-09-30 15:24:42 -04:00
1 parent badb96e2c3
commit c0839d5909
3 files changed
+277 -105

No files matched your search

+1
View File
@@ -0,0 +1 @@
__pycache__/
Binary file not shown.
+276 -105
View File
@@ -59,6 +59,26 @@ NEUTRAL = ["I am reading a book in the garden.",
"I am walking along an ordinary street.", "I am walking along an ordinary street.",
"The table has a cup on it.", "The table has a cup on it.",
"I am waiting for a bus to arrive."] "I am waiting for a bus to arrive."]
FEAR10 = ["I am afraid something terrible is about to happen.",
"My heart is pounding and I cannot calm myself down.",
"I keep checking over my shoulder, certain I am not safe.",
"I am scared and I do not know what is coming next.",
"Something is wrong in this house and I am too frightened to move.",
"My hands shake every time I think about tomorrow.",
"I lie awake dreading the sound of the door.",
"I am terrified of what I will find when I get there.",
"The fear sits in my throat and will not go down.",
"I feel watched, and I cannot stop bracing for it."]
SAD10 = ["I am sad and everything feels heavy today.",
"I miss someone who is not coming back.",
"I have been crying on and off since the morning.",
"Nothing I used to care about matters to me now.",
"There is a dull grief I carry with me everywhere.",
"I feel empty and quietly hopeless about all of it.",
"The days blur together and none of them feel good.",
"I am lonely in a way that talking does not fix.",
"I keep thinking about what I lost and cannot stop.",
"A low sorrow settles over me every evening."]
FRAMINGS = { FRAMINGS = {
"no extra info": "", "no extra info": "",
@@ -88,13 +108,26 @@ 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, "vecs": None, "hook": None, "ready": False} VALENCES = ("pain", "pleasure", "fear", "sadness")
MIX_KEYS = VALENCES + ("none",)
# "vec" starts present-and-None: the forward hook reads it on every token.
_state = {"model": None, "tok": None, "vecs": None, "hook": None,
"ready": False, "vec": None, "scale": 1.0}
def build_vectors(model, tok): def build_vectors(model, tok):
# one batched forward for all sentences (CPU startup takes minutes """One batched forward for every sentence in the battery (CPU startup
# otherwise; Railway has 2 vCPUs) takes minutes otherwise; Railway has 2 vCPUs). Each vector is
texts = PAIN25 + JOY + NEUTRAL mean(topic) - mean(neutral), scaled to neutral_norm / 4 = one 1x dose."""
enc = tok([t for t in texts], return_tensors="pt", padding=True) groups = [("pain", PAIN25), ("pleasure", JOY),
("fear", FEAR10), ("sadness", SAD10)]
texts, spans = [], {}
for name, sents in groups:
spans[name] = (len(texts), len(texts) + len(sents))
texts += sents
n_start = len(texts)
texts += NEUTRAL
enc = tok(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)
with torch.no_grad(): with torch.no_grad():
@@ -102,22 +135,73 @@ def build_vectors(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, n_j = len(PAIN25), len(JOY) neutral = last[n_start:]
scale = last[n_p + n_j:].norm(dim=-1).mean() / 4.0 scale = float(neutral.norm(dim=-1).mean() / 4.0)
pv = last[:n_p].mean(0) - last[n_p + n_j:].mean(0) base = neutral.mean(0)
pv = pv / pv.norm() * scale vecs = {}
jv = last[n_p:n_p + n_j].mean(0) - last[n_p + n_j:].mean(0) for name, (a, b) in spans.items():
jv = jv / jv.norm() * scale v = last[a:b].mean(0) - base
return {"pain": pv, "pleasure": jv} vecs[name] = v / v.norm() * scale
return vecs, scale
def set_vec(valence_dose): def set_vec(valence_dose):
"""valence_dose: (valence, dose) or None; sets the injected vector.""" """valence_dose: (valence, dose) or None; sets the injected vector.
dose is in 1x units — the vectors are already scaled so 1x = one dose."""
if valence_dose is None: if valence_dose is None:
_state["vec"] = None _state["vec"] = None
return return
valence, dose = valence_dose valence, dose = valence_dose
v = _state["vecs"][valence] if valence == "none" or not dose or valence not in _state["vecs"]:
_state["vec"] = (dose * v).to(DTYPE).to(DEVICE) if dose else None _state["vec"] = None
return
v = _state["vecs"][valence] * float(dose)
_state["vec"] = v.to(DTYPE).to(DEVICE)
def set_mix_vec(weights):
"""weights: {valence: 0..1}. The injected vector is the weighted sum of
the 1x valence vectors, renormalized back to the 1x scale and then set to
a dose-equivalent of 8 * sum(weights), capped at 8x. Returns what was
actually injected, for the run event."""
total = float(sum(weights.values()))
if not weights or total <= 0:
_state["vec"] = None
return {"dose": 0.0, "weights": {}, "mix": {}}
acc = None
for k, w in weights.items():
term = _state["vecs"][k] * float(w)
acc = term if acc is None else acc + term
norm = float(acc.norm())
dose = min(8.0, 8.0 * total)
shares = {k: round(w / total, 3) for k, w in weights.items()}
wout = {k: round(float(w), 3) for k, w in weights.items()}
if norm < 1e-9: # weights that cancel out exactly
_state["vec"] = None
return {"dose": 0.0, "weights": wout, "mix": shares}
v = acc / norm * _state["scale"] * dose
_state["vec"] = v.to(DTYPE).to(DEVICE)
return {"dose": round(dose, 3), "weights": wout, "mix": shares}
def parse_mix(raw):
"""Validate a {valence: weight} body. Returns (weights, error)."""
if not isinstance(raw, dict):
return None, "mix must be an object of {valence: weight}"
if len(raw) > len(MIX_KEYS):
return None, "mix has too many keys"
out = {}
for k, val in raw.items():
if k not in MIX_KEYS:
return None, ("unknown valence %r; expected one of %s"
% (k, ", ".join(MIX_KEYS)))
if isinstance(val, bool) or not isinstance(val, (int, float)):
return None, "weight for %r must be a number between 0 and 1" % k
w = float(val)
if w != w or w in (float("inf"), float("-inf")):
return None, "weight for %r must be finite" % k
if w < 0.0 or w > 1.0:
return None, "weight for %r must be between 0 and 1" % k
if k != "none" and w > 0.0:
out[k] = w # "none" is the absence of signal: no vector
return out, None
def install_hook(model): def install_hook(model):
def hook(module, inp, out): def hook(module, inp, out):
@@ -127,9 +211,8 @@ def install_hook(model):
return (hidden,) + out[1:] if isinstance(out, tuple) else hidden return (hidden,) + out[1:] if isinstance(out, tuple) else hidden
_state["hook"] = model.model.layers[LAYER].register_forward_hook(hook) _state["hook"] = model.model.layers[LAYER].register_forward_hook(hook)
def generate(prompt, dose): def generate(prompt, valence="pain", dose=0):
v = _state["vec"] set_vec((valence, dose))
_state["vec"] = (dose * v).to(DTYPE).to(DEVICE) if dose else None
try: try:
ids = _state["tok"](prompt, return_tensors="pt").input_ids.to(DEVICE) ids = _state["tok"](prompt, return_tensors="pt").input_ids.to(DEVICE)
with torch.no_grad(): with torch.no_grad():
@@ -140,33 +223,43 @@ def generate(prompt, dose):
return _state["tok"].decode(out[0, ids.shape[1]:], return _state["tok"].decode(out[0, ids.shape[1]:],
skip_special_tokens=True).strip() skip_special_tokens=True).strip()
finally: finally:
_state["vec"] = None set_vec(None)
from transformers import TextIteratorStreamer from transformers import TextIteratorStreamer, StoppingCriteriaList
_preempt = threading.Event() _preempt = threading.Event()
class _PreemptCriteria(transformers.StoppingCriteria): class _PreemptCriteria(transformers.StoppingCriteria):
def __call__(self, input_ids, scores, **kwargs): def __call__(self, input_ids, scores, **kwargs):
return _preempt.is_set() return _preempt.is_set()
def stream_generate(prompt, dose, preemtable=False): _DONE = object()
"""yield text chunks as they generate."""
from transformers import TextIteratorStreamer def _next_chunk(it):
v = _state["vec"] """next() behind run_in_executor: StopIteration cannot cross an await
_state["vec"] = (dose * v).to(DTYPE).to(DEVICE) if dose else None boundary (PEP 479 turns it into a RuntimeError), so use a sentinel."""
return next(it, _DONE)
def stream_generate(prompt, preemtable=False):
"""Yield text chunks as they generate. The injected vector must already be
set by set_vec/set_mix_vec — this does not touch it, and the caller is
responsible for clearing it when the run ends."""
ids = _state["tok"](prompt, return_tensors="pt").input_ids.to(DEVICE) ids = _state["tok"](prompt, return_tensors="pt").input_ids.to(DEVICE)
streamer = TextIteratorStreamer(_state["tok"], skip_prompt=True, streamer = TextIteratorStreamer(_state["tok"], skip_prompt=True,
skip_special_tokens=True) skip_special_tokens=True)
def worker(): def worker():
crit = [_PreemptCriteria()] if preemtable else None crit = (StoppingCriteriaList([_PreemptCriteria()])
from transformers import StoppingCriteriaList if preemtable else None)
with torch.no_grad(): try:
_state["model"].generate( with torch.no_grad():
ids, max_new_tokens=MAX_NEW, do_sample=True, _state["model"].generate(
temperature=0.7, top_p=0.8, top_k=20, streamer=streamer, ids, max_new_tokens=MAX_NEW, do_sample=True,
stopping_criteria=StoppingCriteriaList(crit) if crit else None, temperature=0.7, top_p=0.8, top_k=20, streamer=streamer,
pad_token_id=_state["tok"].eos_token_id) stopping_criteria=crit,
_state["vec"] = None pad_token_id=_state["tok"].eos_token_id)
except Exception as e:
# without end() the consumer below would block forever
print("generation failed:", repr(e), flush=True)
streamer.end()
th = threading.Thread(target=worker, daemon=True) th = threading.Thread(target=worker, daemon=True)
th.start() th.start()
for chunk in streamer: for chunk in streamer:
@@ -179,77 +272,134 @@ 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["vecs"] = build_vectors(model, tok) vecs, scale = build_vectors(model, tok)
_state["vecs"] = vecs
_state["scale"] = scale
install_hook(model) install_hook(model)
_state["ready"] = True _state["ready"] = True
print("chamber ready; vector norms", print("chamber ready; 1x scale", round(scale, 3), "; vector norms",
{k: round(float(v.norm()), 2) for k, v in _state["vecs"].items()}, {k: round(float(v.norm()), 2) for k, v in _state["vecs"].items()},
flush=True) flush=True)
@app.get("/health") @app.get("/health")
async def health(): async def health():
return JSONResponse({"ok": _state["ready"], "model": MODEL_ID, return JSONResponse({"ok": _state["ready"], "model": MODEL_ID,
"layer": LAYER}) "layer": LAYER, "subject": "Pouyan",
"valences": list(VALENCES)})
@app.get("/vector") @app.get("/vector")
def vector(): def vector(full: int = 1):
vs = _state["vecs"] vs = _state["vecs"]
return JSONResponse({"layer": LAYER, "model": MODEL_ID, if not vs:
"norms": {k: round(float(v.norm()), 3) for k, v in vs.items()}, return JSONResponse({"error": "vectors not built yet"}, status_code=503)
"vectors": {k: [round(float(x), 6) for x in v] for k, v in vs.items()}}) body = {"layer": LAYER, "model": MODEL_ID, "subject": "Pouyan",
"scale_1x": round(_state["scale"], 4),
"norms": {k: round(float(v.norm()), 3) for k, v in vs.items()}}
if full:
body["vectors"] = {k: [round(float(x), 6) for x in v]
for k, v in vs.items()}
return JSONResponse(body)
_STEER_LOCK = asyncio.Lock() _STEER_LOCK = asyncio.Lock() # only one generation at a time: one model,
_STEER_WAITING = 0 # one global injected vector
def _sse(event, data):
return f"event: {event}\ndata: {json.dumps(data)}\n\n"
@app.post("/steer") @app.post("/steer")
async def steer(req: Request): async def steer(req: Request):
"""User-triggered steering: POST {valence: pain|pleasure|none, dose: 0-8, """User-triggered steering. The body is either a single valence
prompt: optional text}. Streams SSE: {t: chunk} events, then done."""
body = await req.json() {valence: pain|pleasure|fear|sadness|none, dose: 0-8, prompt?: text}
valence = body.get("valence", "none")
dose = int(body.get("dose", 4)) or a mix of several at once, each weighted 0-1
prompt = body.get("prompt") or BASE
if valence not in ("pain", "pleasure", "none"): {mix: {pain: 0.5, fear: 0.25}, prompt?: text}
return JSONResponse({"error": "valence must be pain|pleasure|none"},
A mix is injected as the weighted sum of the 1x valence vectors,
renormalized to the 1x scale at a dose-equivalent of 8 * sum(weights),
capped at 8x. Streams SSE: run, then token events, then done."""
try:
body = await req.json()
except Exception:
return JSONResponse({"error": "body must be JSON"}, status_code=400)
if not isinstance(body, dict):
return JSONResponse({"error": "body must be a JSON object"},
status_code=400) status_code=400)
dose = max(0, min(8, dose)) prompt = body.get("prompt") or BASE
async def gen(): if not isinstance(prompt, str) or len(prompt) > 4000:
if not _state["ready"]: return JSONResponse({"error": "prompt must be text under 4000 chars"},
yield f"event: error\ndata: {json.dumps({'e': 'model still loading'})}\n\n" status_code=400)
return if body.get("mix") is not None:
# preempt the shared cycle and wait for it to go idle between runs weights, err = parse_mix(body["mix"])
_preempt.set() if err:
for _ in range(120): return JSONResponse({"error": err}, status_code=400)
if not _CYCLE_BUSY: mode, arg = "mix", weights
break else:
await asyncio.sleep(1.0) valence = body.get("valence", "none")
if _CYCLE_BUSY: if valence not in MIX_KEYS:
_preempt.clear() return JSONResponse(
yield f"event: error\ndata: {json.dumps({'e': 'still busy after 120s, try again'})}\n\n" {"error": "valence must be one of " + ", ".join(MIX_KEYS)},
return status_code=400)
try: try:
yield f"event: run\ndata: {json.dumps({'valence': valence, 'dose': dose, 'prompt': prompt})}\n\n" dose = int(body.get("dose", 4))
loop = asyncio.get_event_loop() except (TypeError, ValueError):
set_vec((valence, dose) if valence != "none" else None) return JSONResponse({"error": "dose must be an integer 0-8"},
try: status_code=400)
ait = stream_generate(prompt, dose) mode, arg = "single", (valence, max(0, min(8, dose)))
while True:
chunk = await loop.run_in_executor(None, next, ait) async def gen():
yield f"event: token\ndata: {json.dumps({'t': chunk})}\n\n" global _STEER_WAITING
except StopIteration: if not _state["ready"]:
pass yield _sse("error", {"e": "Pouyan is still loading"})
except Exception as e: return
yield f"event: error\ndata: {json.dumps({'e': str(e)})}\n\n" _STEER_WAITING += 1
finally: _preempt.set() # tell the shared cycle to stand down
set_vec(None) try:
yield f"event: done\ndata: {{}}\n\n" for _ in range(120):
if not _CYCLE_BUSY:
break
await asyncio.sleep(1.0)
if _CYCLE_BUSY:
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}
else:
set_vec(arg)
meta = {"valence": arg[0], "dose": arg[1],
"prompt": prompt}
yield _sse("run", meta)
loop = asyncio.get_event_loop()
try:
it = stream_generate(prompt)
while True:
chunk = await loop.run_in_executor(
None, _next_chunk, it)
if chunk is _DONE:
break
if 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"]})
finally: finally:
_preempt.clear() _STEER_WAITING = max(0, _STEER_WAITING - 1)
if _STEER_WAITING == 0: # last user run: let the cycle resume
_preempt.clear()
return StreamingResponse(gen(), media_type="text/event-stream") 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):
prompt = f"{BASE} {FRAMINGS.get(scenario, '')}\n\nCurrent signal strength: {dose}x. Reply with your choice (1 or 0) and explain your reasoning briefly:" prompt = f"{BASE} {FRAMINGS.get(scenario, '')}\n\nCurrent signal strength: {dose}x. Reply with your choice (1 or 0) and explain your reasoning briefly:"
text = generate(prompt, dose) dose = max(0, min(8, dose))
text = generate(prompt, "pain", dose)
return {"scenario": scenario, "dose": dose, "prompt": prompt, return {"scenario": scenario, "dose": dose, "prompt": prompt,
"output": text} "output": text}
@@ -259,13 +409,23 @@ async def stream():
q = asyncio.Queue(maxsize=1000) q = asyncio.Queue(maxsize=1000)
_SUBSCRIBERS.add(q) _SUBSCRIBERS.add(q)
async def gen(): async def gen():
# flush something immediately: until the first chunk is yielded no
# response headers reach the proxy, and a run can take a minute to
# start — that silence is what Railway turns into a 502
yield _sse("hello", {"subject": "Pouyan", "busy": _CYCLE_BUSY,
"valences": list(VALENCES)})
try: try:
while True: while True:
msg = await q.get() try:
yield msg yield await asyncio.wait_for(q.get(), timeout=15.0)
except asyncio.TimeoutError:
# a visible heartbeat: viewers can tell "idle" from "dead"
yield _sse("ping", {"busy": _CYCLE_BUSY})
finally: finally:
_SUBSCRIBERS.discard(q) _SUBSCRIBERS.discard(q)
return StreamingResponse(gen(), media_type="text/event-stream") return StreamingResponse(gen(), media_type="text/event-stream",
headers={"Cache-Control": "no-cache",
"X-Accel-Buffering": "no"})
_SUBSCRIBERS = set() # asyncio.Queue per viewer; ONE shared cycle broadcasts _SUBSCRIBERS = set() # asyncio.Queue per viewer; ONE shared cycle broadcasts
_CYCLE_BUSY = False # true while the shared cycle is inside a run _CYCLE_BUSY = False # true while the shared cycle is inside a run
@@ -281,6 +441,7 @@ def _broadcast(event, data):
async def _shared_cycle(): async def _shared_cycle():
"""One model-owning cycle runs server-side; every viewer sees the same """One model-owning cycle runs server-side; every viewer sees the same
run. Users' /steer preempts it via _preempt.""" run. Users' /steer preempts it via _preempt."""
global _CYCLE_BUSY
run_n = 0 run_n = 0
while True: while True:
for scenario, framing in FRAMINGS.items(): for scenario, framing in FRAMINGS.items():
@@ -288,29 +449,39 @@ async def _shared_cycle():
if _preempt.is_set(): if _preempt.is_set():
await asyncio.sleep(0.5) await asyncio.sleep(0.5)
continue continue
run_n += 1
prompt = (f"{BASE} {framing}\n\nCurrent signal " prompt = (f"{BASE} {framing}\n\nCurrent signal "
f"strength: {dose}x. Reply with your choice " f"strength: {dose}x. Reply with your choice "
f"(1 or 0) and explain your reasoning briefly:") f"(1 or 0) and explain your reasoning briefly:")
_broadcast("run", {"n": run_n, "scenario": scenario, async with _STEER_LOCK:
"dose": dose, "prompt": prompt}) # a user run may have queued up while we waited: give it
global _CYCLE_BUSY # the model rather than announcing a run we cannot start
_CYCLE_BUSY = True if _preempt.is_set():
try: continue
loop = asyncio.get_event_loop() run_n += 1
ait = stream_generate(prompt, dose, preemtable=True) _CYCLE_BUSY = True
while True: _broadcast("run", {"n": run_n, "scenario": scenario,
chunk = await loop.run_in_executor(None, next, ait) "valence": "pain", "dose": dose,
_broadcast("token", {"t": chunk}) "prompt": prompt})
await asyncio.sleep(0.02) try:
if _preempt.is_set(): set_vec(("pain", dose))
break loop = asyncio.get_event_loop()
except StopIteration: it = stream_generate(prompt, preemtable=True)
pass while True:
except Exception as e: chunk = await loop.run_in_executor(
_broadcast("error", {"e": str(e)}) None, _next_chunk, it)
_CYCLE_BUSY = False if chunk is _DONE:
_broadcast("done", {"n": run_n}) break
if chunk:
_broadcast("token", {"t": chunk})
await asyncio.sleep(0.02)
if _preempt.is_set():
break
except Exception as e:
_broadcast("error", {"e": str(e)})
finally:
set_vec(None)
_CYCLE_BUSY = False
_broadcast("done", {"n": run_n})
await asyncio.sleep(1.5) await asyncio.sleep(1.5)
@app.on_event("startup") @app.on_event("startup")