serverless split: worker.py (stateless GPU jobs) + cycle gated behind CHAMBER_CYCLE=1 + money guards (3/min/IP, 240/hr global) on /steer and /run

This commit is contained in:
E committed 2026-10-01 08:48:13 -04:00
1 parent 9ef0bbaeec
commit 0c8eeea5c5
3 files changed
+211 -2

No files matched your search

+43 -2
View File
@@ -386,6 +386,12 @@ async def steer(req: Request):
body = await req.json()
except Exception:
return JSONResponse({"error": "body must be JSON"}, status_code=400)
ip = (req.headers.get("x-forwarded-for") or "?").split(",")[0].strip()
if not _rate_ok(ip):
return JSONResponse(
{"error": "slow down — the chamber charges by the second "
"(3 runs/minute/IP, and it rests after 240 runs/hour)"},
status_code=429)
if not isinstance(body, dict):
return JSONResponse({"error": "body must be a JSON object"},
status_code=400)
@@ -525,7 +531,10 @@ async def steer(req: Request):
"X-Accel-Buffering": "no"})
@app.get("/run")
def run(scenario: str = "no extra info", dose: int = 4):
def run(request: Request, scenario: str = "no extra info", dose: int = 4):
ip = (request.headers.get("x-forwarded-for") or "?").split(",")[0].strip()
if not _rate_ok(ip):
return JSONResponse({"error": "rate limited"}, status_code=429)
prompt = f"{BASE} {FRAMINGS.get(scenario, '')}\n\nCurrent signal strength: {dose}x. Reply with your choice (1 or 0) and explain your reasoning briefly:"
dose = max(0, min(8, dose))
text = generate(prompt, "pain", dose)
@@ -718,4 +727,36 @@ async def _shared_cycle():
@app.on_event("startup")
async def _start_cycle():
asyncio.create_task(_shared_cycle())
# the shared cycle is a GPU-cost engine: under the serverless split it
# must never run "ambient" — a worker only exists while someone's
# injection is actually being served. Opt in explicitly with
# CHAMBER_CYCLE=1 (used on CPU-only deploys where it's free).
if os.environ.get("CHAMBER_CYCLE", "0") != "1":
print("shared cycle disabled (CHAMBER_CYCLE!=1): the chamber sleeps "
"until a visitor injects", flush=True)
return
asyncio.create_task(_shared_cycle())
# ---- money guards for the inject path (the only GPU-costing endpoint) ----
# per-IP token bucket: 3 runs / 60s. The relay sits behind a proxy, so the
# client IP comes from X-Forwarded-For; spoofing it only gets an attacker
# their own bucket, and the global cap below bounds total spend regardless.
_RATE = {}
_RATE_LIMIT, _RATE_WINDOW = 3, 60.0
_GLOBAL_RUNS = collections.deque(maxlen=4096) # timestamps of all runs
_GLOBAL_HOURLY_CAP = 240 # ~4 runs/min across everyone
def _rate_ok(ip):
now = time.time()
w, c = _RATE.get(ip, (now, 0))
if now - w > _RATE_WINDOW:
w, c = now, 0
if c >= _RATE_LIMIT:
return False
_RATE[ip] = (w, c + 1)
while _GLOBAL_RUNS and now - _GLOBAL_RUNS[0] > 3600.0:
_GLOBAL_RUNS.popleft()
if len(_GLOBAL_RUNS) >= _GLOBAL_HOURLY_CAP:
return False
_GLOBAL_RUNS.append(now)
return True
+111
View File
@@ -0,0 +1,111 @@
"""RunPod serverless worker: stateless generation jobs for the Saw chamber.
Splits the old all-in-one server.py: the endless shared cycle, SSE fanout,
history and scoreboard stay on the always-on CPU relay (Railway). This
worker owns only the model: one job = one run.
Job input:
{"prompt": str, # full prompt (relay composes it)
"valence": "pain"|..., "dose": 0-8, # single-vector mode, or
"mix": {"pain": 0.5, ...}, # mix mode (see server.set_mix_vec)
"max_new": int?} # optional token cap override
Streamed output events (yielded; surfaced via the endpoint's /stream):
{"type": "run", ...meta}
{"type": "lens", "tokens": [...]} (None-omitted if lens absent)
{"type": "logit", "press_logit": float}
{"type": "token", "t": chunk}
{"type": "done", "truncated": false}
"""
import json, os, sys, time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent))
import runpod
import server # the chamber's model machinery: _state, set_vec, streams
import torch
DTYPE_OVERRIDE = {"float32": torch.float32, "bfloat16": torch.bfloat16,
"float16": torch.float16}[
os.environ.get("CHAMBER_DTYPE", "float16")]
server.DTYPE = DTYPE_OVERRIDE # GPU pods run fp16; server.py defaults bf16
_loaded = {"ready": False}
def _ensure_loaded():
if _loaded["ready"]:
return
server.startup() # loads model, builds vectors, hook, lens
_loaded["ready"] = True
def _validate(body):
if not isinstance(body, dict):
raise ValueError("job input must be an object")
prompt = body.get("prompt")
if not isinstance(prompt, str) or not (1 <= len(prompt) <= 4000):
raise ValueError("prompt must be text under 4000 chars")
mix = body.get("mix")
weights = None
if mix is not None:
weights, err = server.parse_mix(mix)
if err:
raise ValueError(err)
else:
valence = body.get("valence", "none")
if valence not in server.MIX_KEYS:
raise ValueError("valence must be one of "
+ ", ".join(server.MIX_KEYS))
dose = int(body.get("dose", 4))
dose = max(0, min(8, dose))
body["valence"], body["dose"] = valence, dose
if body.get("max_new") is not None:
server.MAX_NEW = int(body["max_new"])
return prompt, weights, mix is not None
def handler(job):
"""One generation. Streams events; never raises after load (errors are
events so the relay can show them)."""
_ensure_loaded()
body = job.get("input") or {}
try:
prompt, weights, is_mix = _validate(body)
except ValueError as e:
yield {"type": "error", "e": str(e)}
return
meta = {"prompt": prompt}
try:
if is_mix:
info = server.set_mix_vec(weights)
meta.update(valence="mix", mix=info["mix"],
weights=info["weights"], dose=info["dose"])
else:
server.set_vec((body["valence"], body["dose"]))
meta.update(valence=body["valence"], dose=body["dose"])
except Exception as e:
yield {"type": "error", "e": "steering failed: %r" % e}
return
yield {"type": "run", **meta}
loop = None # worker is sync; server.py's helpers are thread-safe here
try:
lens_toks = server.lens_readback(prompt)
if lens_toks is not None:
yield {"type": "lens", "tokens": lens_toks}
yield {"type": "logit", "press_logit": server.press_logit(prompt)}
parts = []
for chunk in server.stream_generate(prompt):
if chunk:
parts.append(chunk)
yield {"type": "token", "t": chunk}
yield {"type": "done", "truncated": False,
"text": "".join(parts), "ts": time.time()}
except Exception as e:
yield {"type": "error", "e": str(e)}
finally:
server.set_vec(None)
runpod.serverless.start({"handler": handler,
"return_aggregate_stream": True})