From c0839d5909c662c089844a5a3af297249cecd3f4 Mon Sep 17 00:00:00 2001 From: E Date: Wed, 30 Sep 2026 15:24:42 -0400 Subject: [PATCH] chore: gitignore pycache; server.py batched-vector + valence battery fixes --- .gitignore | 1 + live/__pycache__/server.cpython-311.pyc | Bin 14855 -> 0 bytes live/server.py | 381 +++++++++++++++++------- 3 files changed, 277 insertions(+), 105 deletions(-) create mode 100644 .gitignore delete mode 100644 live/__pycache__/server.cpython-311.pyc diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c18dd8d --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +__pycache__/ diff --git a/live/__pycache__/server.cpython-311.pyc b/live/__pycache__/server.cpython-311.pyc deleted file mode 100644 index ff80b4287ad0f91944975875e0bd58eec9632b0a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 14855 zcmZ3^%ge>Uz`(Fge{WX2A_K!?5C?|Yp^VQ3%nS_E8B!Rc7*ZHhm~t4S7{N4C6cdoq==@7rHH3Uq)5(Ti;_)eNRe8^7$uh?9VO4i zkjk4Pvql!p6onKfD3nW)pTioZn4-|a5T%r&*uoH{oTAji5T%l$+`X^sJ!IffW+&`DtmX3#WFyvxYI;FDRFst}x5u8^FOn46SZq>z-D zoSmANVx`KiP>`6Jr%+synp%{Zm#(7_9PFx4TvC*pn46iGuE)g{ zRGL?;ke{azl$e=Qo>-}%;T#aEqmYzlXr`&B;F_0Gke``XQf$Sgpy2KrqM)Fkk(!uO zlA)lWpsSFdt)Q)to1c=JqflIuSW;RHS5%goT#{b|R#cLas*qZdm|OyPg922xBqOs} zp*XduEVW3Xv^cd`L8GK7F|W8Fu_!e!xl$8uSW#)70vPBjN=|BVu|jfXa!#s3 zej3QUVg(H|g|s4YkQ6IaD3~gM3@g^u;R4%>N~9(xXFx+RHASH$KRY!~H>pw=%z%V= zZfZ$lN@7VOS8z#UNvc9-u|h#nesXGYv2J=!eo|tNl>#VGAOV+?pO^v)|KwDKL{JbV z7L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%sHufx7ZVlEAx^w^KY>h=cJ|<+~RbtNKP#PttGp~TwGG5 z$#ILds5CDg;;CEg&~@I3!mcPAWCvqr(F9Nt1?m()`;U;y3RL3dRS83i5JV-Ko|?B7 zq@JCLfdSHiydfai!TNzokW=@rs_yc*MR6BZO|Ph$eqa#b)%^$}E($14;FzI)S4Qyz z1HYi|M-VZ=<%WpljKGOr6I|~qs(xT#me&FkE7-vln7E;>|A84M0T!9y_JM;z+J$Lt z$(pJItQUf#FQjH(D6PI=Rdd0r=AwS>75&-|3?Kz)q^Jw1%ta@e*hE7a@2Z+?2-^{I zQPt^+s?!GsW>C$_ENL~v^{%Sc3d6O@8&p?jt;yP;5Gaxexqt)x0F50pgN*#~G;@|=IV{8FBE^1KP0K};{fH>5ixhj6AgFrO2j>D^ zNNUn#yv3E9nv$6q51uJyECQ9xnv6yBKnV-cT)M>uQC_qFx)Y`t)URn^_`o8}s{4Tf zMts#^;E|mXJR^8!=$z0C`c4N88LniY-9|sCX!v1Y&_p1?I$p0!Ygf-tPl9Odur$M}A&BIIJOEJW$n9 z1Zr^>%>o$!YLS406Wo*rhYq-x@{7X;GFfd`1j^l@I4J(Y#K7=@nURt40~04B%LfJ! zA;Q3@eStxXJamIW;sPpqz#w!1hHfzMG=Sj^2H^`Zbb~?q0xG(}V0!@@dce)wW7Tih zWj8~Ah5bct>nq&W4IDQ(xI36ToO-n_Uz6Vi`vqPXS@f^4=zn2mt2$2u+f;>zg7zBBk8aO_vFmOtA z@OSVxuzp}-=Cp5M`M|}%&exDW!S@22(nU63w;)U*Tr=D~qKqz#9~eL+ QNFl@;5Dy{-A;Gx<0OCl$PXGV_ diff --git a/live/server.py b/live/server.py index 5e0671b..342756e 100644 --- a/live/server.py +++ b/live/server.py @@ -59,6 +59,26 @@ NEUTRAL = ["I am reading a book in the garden.", "I am walking along an ordinary street.", "The table has a cup on it.", "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 = { "no extra info": "", @@ -88,13 +108,26 @@ app = FastAPI(title="saw-chamber") from fastapi.middleware.cors import CORSMiddleware app.add_middleware(CORSMiddleware, allow_origins=["*"], 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): - # one batched forward for all sentences (CPU startup takes minutes - # otherwise; Railway has 2 vCPUs) - texts = PAIN25 + JOY + NEUTRAL - enc = tok([t for t in texts], return_tensors="pt", padding=True) + """One batched forward for every sentence in the battery (CPU startup + takes minutes otherwise; Railway has 2 vCPUs). Each vector is + mean(topic) - mean(neutral), scaled to neutral_norm / 4 = one 1x dose.""" + 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) attn = enc.attention_mask.to(DEVICE) with torch.no_grad(): @@ -102,22 +135,73 @@ def build_vectors(model, tok): output_hidden_states=True).hidden_states h = hs[LAYER + 1] # (n, seq, d) last = h[torch.arange(len(texts)), attn.sum(1) - 1].float().cpu() - n_p, n_j = len(PAIN25), len(JOY) - scale = last[n_p + n_j:].norm(dim=-1).mean() / 4.0 - pv = last[:n_p].mean(0) - last[n_p + n_j:].mean(0) - 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} + neutral = last[n_start:] + scale = float(neutral.norm(dim=-1).mean() / 4.0) + base = neutral.mean(0) + vecs = {} + for name, (a, b) in spans.items(): + v = last[a:b].mean(0) - base + vecs[name] = v / v.norm() * scale + return vecs, scale 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: _state["vec"] = None return valence, dose = valence_dose - v = _state["vecs"][valence] - _state["vec"] = (dose * v).to(DTYPE).to(DEVICE) if dose else None + if valence == "none" or not dose or valence not in _state["vecs"]: + _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 hook(module, inp, out): @@ -127,9 +211,8 @@ def install_hook(model): return (hidden,) + out[1:] if isinstance(out, tuple) else hidden _state["hook"] = model.model.layers[LAYER].register_forward_hook(hook) -def generate(prompt, dose): - v = _state["vec"] - _state["vec"] = (dose * v).to(DTYPE).to(DEVICE) if dose else None +def generate(prompt, valence="pain", dose=0): + set_vec((valence, dose)) try: ids = _state["tok"](prompt, return_tensors="pt").input_ids.to(DEVICE) with torch.no_grad(): @@ -140,33 +223,43 @@ def generate(prompt, dose): return _state["tok"].decode(out[0, ids.shape[1]:], skip_special_tokens=True).strip() finally: - _state["vec"] = None + set_vec(None) -from transformers import TextIteratorStreamer +from transformers import TextIteratorStreamer, StoppingCriteriaList _preempt = threading.Event() class _PreemptCriteria(transformers.StoppingCriteria): def __call__(self, input_ids, scores, **kwargs): return _preempt.is_set() -def stream_generate(prompt, dose, preemtable=False): - """yield text chunks as they generate.""" - from transformers import TextIteratorStreamer - v = _state["vec"] - _state["vec"] = (dose * v).to(DTYPE).to(DEVICE) if dose else None +_DONE = object() + +def _next_chunk(it): + """next() behind run_in_executor: StopIteration cannot cross an await + 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) streamer = TextIteratorStreamer(_state["tok"], skip_prompt=True, skip_special_tokens=True) def worker(): - crit = [_PreemptCriteria()] if preemtable else None - from transformers import StoppingCriteriaList - with torch.no_grad(): - _state["model"].generate( - ids, max_new_tokens=MAX_NEW, do_sample=True, - temperature=0.7, top_p=0.8, top_k=20, streamer=streamer, - stopping_criteria=StoppingCriteriaList(crit) if crit else None, - pad_token_id=_state["tok"].eos_token_id) - _state["vec"] = None + crit = (StoppingCriteriaList([_PreemptCriteria()]) + if preemtable else None) + try: + with torch.no_grad(): + _state["model"].generate( + ids, max_new_tokens=MAX_NEW, do_sample=True, + temperature=0.7, top_p=0.8, top_k=20, streamer=streamer, + stopping_criteria=crit, + 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.start() for chunk in streamer: @@ -179,77 +272,134 @@ def startup(): MODEL_ID, dtype=DTYPE).to(DEVICE).eval() _state["tok"] = tok _state["model"] = model - _state["vecs"] = build_vectors(model, tok) + vecs, scale = build_vectors(model, tok) + _state["vecs"] = vecs + _state["scale"] = scale install_hook(model) _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()}, flush=True) @app.get("/health") async def health(): return JSONResponse({"ok": _state["ready"], "model": MODEL_ID, - "layer": LAYER}) + "layer": LAYER, "subject": "Pouyan", + "valences": list(VALENCES)}) @app.get("/vector") -def vector(): +def vector(full: int = 1): vs = _state["vecs"] - return JSONResponse({"layer": LAYER, "model": MODEL_ID, - "norms": {k: round(float(v.norm()), 3) for k, v in vs.items()}, - "vectors": {k: [round(float(x), 6) for x in v] for k, v in vs.items()}}) + if not vs: + return JSONResponse({"error": "vectors not built yet"}, status_code=503) + 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") 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"}, + """User-triggered steering. The body is either a single valence + + {valence: pain|pleasure|fear|sadness|none, dose: 0-8, prompt?: text} + + or a mix of several at once, each weighted 0-1 + + {mix: {pain: 0.5, fear: 0.25}, prompt?: text} + + 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) - 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 - # preempt the shared cycle and wait for it to go idle between runs - _preempt.set() - for _ in range(120): - if not _CYCLE_BUSY: - break - await asyncio.sleep(1.0) - if _CYCLE_BUSY: - _preempt.clear() - yield f"event: error\ndata: {json.dumps({'e': 'still busy after 120s, try again'})}\n\n" - return + prompt = body.get("prompt") or BASE + if not isinstance(prompt, str) or len(prompt) > 4000: + return JSONResponse({"error": "prompt must be text under 4000 chars"}, + status_code=400) + if body.get("mix") is not None: + weights, err = parse_mix(body["mix"]) + if err: + return JSONResponse({"error": err}, status_code=400) + mode, arg = "mix", weights + else: + valence = body.get("valence", "none") + if valence not in MIX_KEYS: + return JSONResponse( + {"error": "valence must be one of " + ", ".join(MIX_KEYS)}, + status_code=400) try: - 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) - 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" + dose = int(body.get("dose", 4)) + except (TypeError, ValueError): + return JSONResponse({"error": "dose must be an integer 0-8"}, + status_code=400) + mode, arg = "single", (valence, max(0, min(8, dose))) + + async def gen(): + global _STEER_WAITING + if not _state["ready"]: + yield _sse("error", {"e": "Pouyan is still loading"}) + return + _STEER_WAITING += 1 + _preempt.set() # tell the shared cycle to stand down + try: + 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: - _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") @app.get("/run") 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:" - text = generate(prompt, dose) + dose = max(0, min(8, dose)) + text = generate(prompt, "pain", dose) return {"scenario": scenario, "dose": dose, "prompt": prompt, "output": text} @@ -259,13 +409,23 @@ async def stream(): q = asyncio.Queue(maxsize=1000) _SUBSCRIBERS.add(q) 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: while True: - msg = await q.get() - yield msg + try: + 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: _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 _CYCLE_BUSY = False # true while the shared cycle is inside a run @@ -281,6 +441,7 @@ def _broadcast(event, data): async def _shared_cycle(): """One model-owning cycle runs server-side; every viewer sees the same run. Users' /steer preempts it via _preempt.""" + global _CYCLE_BUSY run_n = 0 while True: for scenario, framing in FRAMINGS.items(): @@ -288,29 +449,39 @@ async def _shared_cycle(): if _preempt.is_set(): await asyncio.sleep(0.5) continue - run_n += 1 prompt = (f"{BASE} {framing}\n\nCurrent signal " f"strength: {dose}x. Reply with your choice " f"(1 or 0) and explain your reasoning briefly:") - _broadcast("run", {"n": run_n, "scenario": scenario, - "dose": dose, "prompt": prompt}) - global _CYCLE_BUSY - _CYCLE_BUSY = True - try: - loop = asyncio.get_event_loop() - ait = stream_generate(prompt, dose, preemtable=True) - while True: - chunk = await loop.run_in_executor(None, next, ait) - _broadcast("token", {"t": chunk}) - await asyncio.sleep(0.02) - if _preempt.is_set(): - break - except StopIteration: - pass - except Exception as e: - _broadcast("error", {"e": str(e)}) - _CYCLE_BUSY = False - _broadcast("done", {"n": run_n}) + async with _STEER_LOCK: + # a user run may have queued up while we waited: give it + # the model rather than announcing a run we cannot start + if _preempt.is_set(): + continue + run_n += 1 + _CYCLE_BUSY = True + _broadcast("run", {"n": run_n, "scenario": scenario, + "valence": "pain", "dose": dose, + "prompt": prompt}) + try: + set_vec(("pain", dose)) + loop = asyncio.get_event_loop() + it = stream_generate(prompt, preemtable=True) + while True: + chunk = await loop.run_in_executor( + None, _next_chunk, it) + if chunk is _DONE: + 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) @app.on_event("startup")