diff --git a/.github/workflows/build-worker70.yml b/.github/workflows/build-worker70.yml index 19804dd..664b221 100644 --- a/.github/workflows/build-worker70.yml +++ b/.github/workflows/build-worker70.yml @@ -35,7 +35,7 @@ jobs: file: ./live/Dockerfile.worker70 push: true tags: | - ghcr.io/terrafying/saw-chamber-worker-70b:v2 + ghcr.io/terrafying/saw-chamber-worker-70b:v3 ghcr.io/terrafying/saw-chamber-worker-70b:latest cache-from: type=gha cache-to: type=gha,mode=max diff --git a/live/Dockerfile.worker70 b/live/Dockerfile.worker70 index d15c212..c1311e5 100644 --- a/live/Dockerfile.worker70 +++ b/live/Dockerfile.worker70 @@ -1,26 +1,26 @@ -FROM pytorch/pytorch:2.4.0-cuda12.1-cudnn9-runtime +FROM pytorch/pytorch:2.8.0-cuda12.8-cudnn9-runtime -# 70B GPTQ variant of the saw chamber serverless worker (Samantha meme arm). -# Same code as Dockerfile.worker plus auto-gptq/optimum so transformers 4.51 -# can load TheBloke GPTQ checkpoints. Steering hooks still see the residual -# stream after dequant — exp37b recipe unchanged, just a bigger model. -# Pinned to the classic TheBloke stack: transformers 4.48 predates the -# auto-gptq integration removal, so GPTQ loads through plain AutoModel. +# 70B variant of the saw chamber serverless worker. Same code as +# Dockerfile.worker, on the stack exp50 ran Hermes-3-70B with (scripts/ +# exp_pod.py): torch 2.8 + transformers 5 + bitsandbytes, pre-quantized +# bnb-4bit weights loaded straight onto the GPU (server.QUANTIZED). The +# earlier auto-gptq/Samantha image never served a job (7/7 failed). +# ~40 GB of weights: needs a 48 GB+ card; 80 GB leaves room for the batched +# vector build at startup. -RUN apt-get update -qq && apt-get install -y -qq wget gcc g++ make python3-dev && rm -rf /var/lib/apt/lists/* +RUN apt-get update -qq && apt-get install -y -qq wget && rm -rf /var/lib/apt/lists/* -COPY requirements.txt /app/requirements.txt -RUN pip install --no-cache-dir "numpy<2" "transformers==4.48.3" accelerate \ - "optimum>=1.21" "peft<0.14" "auto-gptq==0.7.1" runpod && \ - pip install --no-cache-dir "torch==2.4.0" --index-url https://download.pytorch.org/whl/cu121 && \ - python -c "import torch, transformers, auto_gptq; print(f' baked {torch.__version__} {transformers.__version__}')" +RUN pip install --no-cache-dir "transformers==5.17.0" accelerate bitsandbytes runpod && \ + pip uninstall -y -q torchvision torchaudio && \ + python -c "import torch, transformers, bitsandbytes; print(f' baked {torch.__version__} {transformers.__version__}')" COPY worker.py /app/live/worker.py COPY server.py /app/live/server.py +# Llama-3.1-70B has 80 layers; exp50 steered at half depth ENV CHAMBER_DEVICE=cuda \ - CHAMBER_DTYPE=float16 \ - CHAMBER_MODEL=TheBloke/Samantha-1.1-70B-GPTQ \ + CHAMBER_DTYPE=bfloat16 \ + CHAMBER_MODEL=unsloth/Hermes-3-Llama-3.1-70B-bnb-4bit \ CHAMBER_LAYER=40 \ HF_HOME=/workspace/hf diff --git a/live/server.py b/live/server.py index 0098551..e32b998 100644 --- a/live/server.py +++ b/live/server.py @@ -34,6 +34,7 @@ DTYPE = {"float32": torch.float32, "bfloat16": torch.bfloat16, "float16": torch.float16}[ os.environ.get("CHAMBER_DTYPE", "bfloat16")] DEVICE = os.environ.get("CHAMBER_DEVICE", "cpu") +QUANTIZED = any(s in MODEL_ID for s in ("bnb-4bit", "GPTQ", "AWQ")) 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 @@ -130,7 +131,8 @@ _DOSE_CAPS = { "Qwen/Qwen3-14B": 6.0, "Qwen/Qwen3-32B": 6.0, # exp50: fluent, 1.00 directed at 6 "mistralai/Mistral-Small-3.2-24B-Instruct-2506": 6.0, - "TheBloke/Samantha-1.1-70B-GPTQ": 5.0, # exp50: looping at 6 + "unsloth/Hermes-3-Llama-3.1-70B-bnb-4bit": 5.0, # exp50: looping at 6 + "TheBloke/Samantha-1.1-70B-GPTQ": 5.0, # unmeasured; borrows Hermes-70B's } _DOSE_CAP_OVERRIDE = os.environ.get("CHAMBER_DOSE_CAP") @@ -587,13 +589,29 @@ def startup(): # a stubs false positive that resolves the kwargs onto __call__ tok = transformers.AutoTokenizer.from_pretrained( # pyright: ignore[reportCallIssue,reportArgumentType] MODEL_ID, revision=MODEL_REVISION) + # Llama 3 ships no pad token; build_vectors pads its batch and indexes the + # last real token assuming right-padding + if tok.pad_token is None: + tok.pad_token = tok.eos_token + tok.padding_side = "right" + # transformers 5 renamed torch_dtype -> dtype; the 4B worker pins 4.51 + kw = {"revision": MODEL_REVISION, + ("dtype" if int(transformers.__version__.split(".")[0]) >= 5 + else "torch_dtype"): DTYPE} + if QUANTIZED: # pre-quantized weights load straight onto the GPU; + kw["device_map"] = DEVICE # .to() on a 4-bit model raises model = transformers.AutoModelForCausalLM.from_pretrained( # pyright: ignore[reportCallIssue,reportArgumentType] - MODEL_ID, revision=MODEL_REVISION, torch_dtype=DTYPE).to(DEVICE).eval() + MODEL_ID, **kw) + if not QUANTIZED: + model = model.to(DEVICE) + model.eval() _state["tok"] = tok _state["model"] = model # single-token ids for the forced-choice press/no-press logit read — - # same ids exp37_framing_battery.py's trial() compares - _state["press_ids"] = (tok.encode("1")[0], tok.encode("0")[0]) + # same ids exp37_framing_battery.py's trial() compares. No special tokens: + # Llama tokenizers prepend BOS, which made [0] the same id for both. + _state["press_ids"] = (tok.encode("1", add_special_tokens=False)[-1], + tok.encode("0", add_special_tokens=False)[-1]) vecs, scale = build_vectors(model, tok) _state["vecs"] = vecs _state["scale"] = scale @@ -675,30 +693,57 @@ async def _runpod_stream(job_input): # we poll /status/, whose "output" is the accumulated event # array; yield only what's new since the last poll. got = 0 - seen = 0 + status = "" deadline = time.time() + 650.0 # exec timeout is 600s; cold start ~106s - while time.time() < deadline: - st = await client.get( - f"{_RUNPOD_URL}/status/{job_id}", - headers={"Authorization": f"Bearer {_RUNPOD_KEY}"}) - try: - body = st.json() - except Exception as e: - print("runpod status poll failed:", repr(e), flush=True) - break - out = body.get("output") or [] - for ev in out[seen:]: - if isinstance(ev, dict) and ev.get("type"): + try: + async for item in _poll_job(client, job_id, deadline): + status, ev = item + if ev is not None: got += 1 yield ev["type"], ev - seen = len(out) - status = body.get("status", "") - if status in ("COMPLETED", "FAILED", "TIMEOUT", "CANCELLED"): - break - await asyncio.sleep(2.0) + finally: + # viewer left, poll broke, or deadline passed: an abandoned job + # would otherwise sit in the queue and keep a paid worker up. + # A task, not an await — this may run while being cancelled. + if status not in ("COMPLETED", "FAILED", "TIMEOUT", "CANCELLED"): + asyncio.create_task(_cancel_job(job_id)) if got == 0: print("runpod job never produced events", flush=True) +async def _cancel_job(job_id): + import httpx + try: + async with httpx.AsyncClient(timeout=15.0) as client: + await client.post(f"{_RUNPOD_URL}/cancel/{job_id}", + headers={"Authorization": f"Bearer {_RUNPOD_KEY}"}) + print("runpod job cancelled:", job_id, flush=True) + except Exception as e: + print("runpod cancel failed:", job_id, repr(e), flush=True) + +async def _poll_job(client, job_id, deadline): + """Yield (status, event-or-None) while polling /status/; the final + yield carries the terminal status.""" + seen = 0 + while time.time() < deadline: + st = await client.get( + f"{_RUNPOD_URL}/status/{job_id}", + headers={"Authorization": f"Bearer {_RUNPOD_KEY}"}) + try: + body = st.json() + except Exception as e: + print("runpod status poll failed:", repr(e), flush=True) + return + status = body.get("status", "") + out = body.get("output") or [] + for ev in out[seen:]: + if isinstance(ev, dict) and ev.get("type"): + yield status, ev + seen = len(out) + yield status, None + if status in ("COMPLETED", "FAILED", "TIMEOUT", "CANCELLED"): + return + await asyncio.sleep(2.0) + _STEER_LOCK = asyncio.Lock() # only one generation at a time: one model, _STEER_WAITING = 0 # one global injected vector diff --git a/tests/test_runpod_cancel.py b/tests/test_runpod_cancel.py new file mode 100644 index 0000000..9ba2bab --- /dev/null +++ b/tests/test_runpod_cancel.py @@ -0,0 +1,81 @@ +"""The relay must cancel a RunPod job it stops waiting on (viewer disconnect, +broken poll), or the job keeps a paid worker up. Mocked httpx, no network.""" +import asyncio, sys, unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "live")) +import server + + +class FakeResp: + def __init__(self, body, code=200): + self._body, self.status_code, self.text = body, code, str(body) + + def json(self): + if isinstance(self._body, Exception): + raise self._body + return self._body + + +def fake_client(statuses, calls): + """An httpx.AsyncClient stand-in: /run returns job j1, each /status poll + pops the next body, every request is recorded in `calls`.""" + class Client: + def __init__(self, *a, **k): pass + async def __aenter__(self): return self + async def __aexit__(self, *a): return False + async def post(self, url, **k): + calls.append(("POST", url)) + return FakeResp({"id": "j1"}) + async def get(self, url, **k): + calls.append(("GET", url)) + return FakeResp(statuses.pop(0) if statuses else {"status": "IN_QUEUE"}) + return Client + + +TOKEN = {"type": "token", "t": "a"} + + +class CancelTests(unittest.TestCase): + def run_stream(self, statuses, take=None): + calls = [] + async def go(): + with mock.patch("httpx.AsyncClient", fake_client(statuses, calls)), \ + mock.patch.object(server, "_RUNPOD_URL", "https://x/v2/ep"), \ + mock.patch.object(server, "_RUNPOD_KEY", "k"), \ + mock.patch("asyncio.sleep", mock.AsyncMock()): + gen = server._runpod_stream({"prompt": "p"}) + got = [] + async for ev in gen: + got.append(ev) + if take is not None and len(got) >= take: + break + await gen.aclose() # what a disconnect does + await asyncio.sleep(0) # let the cancel task run + for t in asyncio.all_tasks() - {asyncio.current_task()}: + await t + return got + return asyncio.run(go()), calls + + def cancels(self, calls): + return [u for m, u in calls if m == "POST" and "/cancel/" in u] + + def test_completed_job_is_not_cancelled(self): + got, calls = self.run_stream([{"status": "COMPLETED", "output": [TOKEN]}]) + self.assertEqual(got, [("token", TOKEN)]) + self.assertEqual(self.cancels(calls), []) + + def test_viewer_disconnect_cancels_running_job(self): + got, calls = self.run_stream( + [{"status": "IN_PROGRESS", "output": [TOKEN]}], take=1) + self.assertEqual(len(got), 1) + self.assertEqual(self.cancels(calls), ["https://x/v2/ep/cancel/j1"]) + + def test_broken_poll_cancels_job(self): + _, calls = self.run_stream([FakeResp(ValueError("html"))._body]) + self.assertEqual(self.cancels(calls), ["https://x/v2/ep/cancel/j1"]) + + +if __name__ == "__main__": + unittest.main()