CPU fallback when ZeroGPU quota exhausted; GPU/CPU chip in topbar
Browse filesFiles changed (4)
- app.py+44-4
- backend/factory.py+17-4
- backend/real.py+33-5
- frontend/index.html+49-3
165 unmodified lines166167168169170171172173174175176177178165 unmodified linesreturn result@app.api(name="tick_decisions")@GPU(duration=90)def tick_decisions_api() -> dict:"""Drain pending agent decisions inside the GPU boundary."""_log_req("tick_decisions")n = TOWNLET.drain_decisions()result = {"decisions_run": n}_log_resp("tick_decisions", result)return result165 unmodified lines166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218165 unmodified linesreturn result@GPU(duration=90)def _drain_gpu() -> int:"""The hot path: drain inside a ZeroGPU fork. RealLLMBackend loads eachfork's Llama with n_gpu_layers=-1."""return TOWNLET.drain_decisions()def _drain_cpu() -> int:"""Quota-exhausted fallback: drain in the parent process withn_gpu_layers=0. ZeroGPU isn't touched, so this works even when theGPU allocator is empty. ~1-3 tokens/sec on 2 vCPU — slow but the simkeeps running. Llama is cached in the parent across drains, so onlythe first call pays the model load."""import osos.environ["TOWNLET_FORCE_CPU"] = "1"try:return TOWNLET.drain_decisions()finally:# Keep the env var set for the rest of the process — once we've# paid the CPU load cost we want all subsequent drains to reuse# the same cached Llama. The next GPU attempt is still cheap to# try (~1s for the fork to fail), so the wrapper's try/except# remains the source of truth on which mode each call uses.pass@app.api(name="tick_decisions")def tick_decisions_api() -> dict:"""Try ZeroGPU first; on quota-exhaustion (or any GPU init error) fallback to a CPU drain in the parent process. The sim never stalls; itjust runs slower when ZeroGPU is empty."""_log_req("tick_decisions")try:n = _drain_gpu()mode = "gpu"except RuntimeError as e:msg = str(e)if "No CUDA GPUs" in msg or "quota" in msg.lower() or "ZeroGPU" in msg:print(f"[townlet] GPU unavailable ({msg[:80]}); CPU fallback engaged", flush=True)n = _drain_cpu()mode = "cpu"else:raiseresult = {"decisions_run": n, "mode": mode}_log_resp("tick_decisions", result)return result
13 unmodified lines1415161718193 unmodified lines23242526272829303132333435363738394013 unmodified linesfrom __future__ import annotationsfrom game.models import DEFAULT_MODEL_ID, get_specfrom . import config3 unmodified lines_image: ImageBackend | None = Nonedef get_llm(model_id: str = DEFAULT_MODEL_ID) -> LLMBackend:if model_id not in _llms:get_spec(model_id) # validates idif config.USE_REAL_MODELS:from .real import RealLLMBackend_llms[model_id] = RealLLMBackend(model_id)else:from .mock import MockLLMBackend_llms[model_id] = MockLLMBackend(model_id)return _llms[model_id]def get_image() -> ImageBackend:13 unmodified lines14151617181920213 unmodified lines252627282930313233343536373839404142434445464748495051525313 unmodified linesfrom __future__ import annotationsimport osfrom game.models import DEFAULT_MODEL_ID, get_specfrom . import config3 unmodified lines_image: ImageBackend | None = Nonedef _cache_key(model_id: str) -> str:"""GPU and CPU Llama instances are loaded with different `n_gpu_layers`and can't be reused across modes. Cache them under separate keys so theCPU-fallback path (parent process, TOWNLET_FORCE_CPU=1) and the GPUpath (forked workers, no env var) don't collide."""mode = "cpu" if os.getenv("TOWNLET_FORCE_CPU") == "1" else "gpu"return f"{model_id}::{mode}"def get_llm(model_id: str = DEFAULT_MODEL_ID) -> LLMBackend:key = _cache_key(model_id)if key not in _llms:get_spec(model_id) # validates idif config.USE_REAL_MODELS:from .real import RealLLMBackend_llms[key] = RealLLMBackend(model_id)else:from .mock import MockLLMBackend_llms[key] = MockLLMBackend(model_id)return _llms[key]def get_image() -> ImageBackend:
16 unmodified lines1718192021224 unmodified lines27282930313221 unmodified lines5455565758596061626364656667686970717216 unmodified linesfrom __future__ import annotationsfrom typing import TYPE_CHECKINGfrom game.models import get_spec4 unmodified linesfrom llama_cpp import Llamaclass RealLLMBackend:"""A small GGUF LLM via llama-cpp-python, keyed by `model_id` in the roster.21 unmodified lines# n_ctx: smolagents' CodeAgent system prompt is large (tool defs# + examples). Combined with our composite perception prompt this# blows past 4096 tokens. Nemotron 3 4B trained at 1M ctx;# 16384 is safe headroom on Spaces; smaller locally.# n_gpu_layers: -1 (all on GPU) is what Zero-GPU needs. On a# Mac (Intel especially) the Metal integrated GPU times out on# batches this size — kIOAccelCommandBufferCallbackErrorTimeout# surfaces as `llama_decode -3`. Fall back to CPU there.on_spaces = config.IS_SPACESself._llm = Llama.from_pretrained(repo_id=self._spec.repo_id,filename=self._spec.gguf_filename,n_gpu_layers=-1 if on_spaces else 0,n_ctx=16384 if on_spaces else 8192,n_batch=16384 if on_spaces else 512,flash_attn=on_spaces,verbose=False,)return self._llm16 unmodified lines171819202122234 unmodified lines2829303132333435363738394021 unmodified lines626364656667686970717273747576777879808182838485868788899091929394959697989910016 unmodified linesfrom __future__ import annotationsimport osfrom typing import TYPE_CHECKINGfrom game.models import get_spec4 unmodified linesfrom llama_cpp import Llamadef force_cpu_mode() -> bool:"""When set, RealLLMBackend loads with `n_gpu_layers=0` and reducedcontext — usable on the Space's 2 vCPU when ZeroGPU quota is gone.Toggled by app.py's tick_decisions fallback path."""return os.getenv("TOWNLET_FORCE_CPU") == "1"class RealLLMBackend:"""A small GGUF LLM via llama-cpp-python, keyed by `model_id` in the roster.21 unmodified lines# n_ctx: smolagents' CodeAgent system prompt is large (tool defs# + examples). Combined with our composite perception prompt this# blows past 4096 tokens. Nemotron 3 4B trained at 1M ctx;# 16384 is safe headroom on Spaces; smaller locally / on CPU.# n_gpu_layers: -1 (all on GPU) is what Zero-GPU needs. On a# Mac (Intel especially) the Metal integrated GPU times out on# batches this size — kIOAccelCommandBufferCallbackErrorTimeout# surfaces as `llama_decode -3`. Fall back to CPU there.# When TOWNLET_FORCE_CPU=1 (the quota-exhausted fallback path# set by app.py's tick_decisions wrapper) we force 0 GPU# layers and shrink the context — slower per token but the# sim keeps running without the GPU.on_spaces = config.IS_SPACEScpu_only = force_cpu_mode()if cpu_only:gpu_layers = 0n_ctx = 4096n_batch = 256use_flash = Falseelif on_spaces:gpu_layers = -1n_ctx = 16384n_batch = 16384use_flash = Trueelse:gpu_layers = 0n_ctx = 8192n_batch = 512use_flash = Falseself._llm = Llama.from_pretrained(repo_id=self._spec.repo_id,filename=self._spec.gguf_filename,n_gpu_layers=gpu_layers,n_ctx=n_ctx,n_batch=n_batch,flash_attn=use_flash,verbose=False,)return self._llm
145 unmodified lines146147148149150151549 unmodified lines701702703704705706516 unmodified lines122312241225122612271228644 unmodified lines187318741875187618771878187918801881188218831884145 unmodified lines.tl-sent-negative .tl-sent-pip { background: var(--red); }.tl-sent-positive { color: var(--green); }.tl-sent-positive .tl-sent-pip { background: var(--green); }/* ====== middle band ====== */.tl-mid { flex: 1; display: flex; gap: 14px; padding: 14px; min-height: 0; }549 unmodified lines<span class="tl-sentiment tl-sent-neutral" id="sent-chip"><span class="tl-sent-pip"></span><span id="sent-text">neutral</span></span></div></div>516 unmodified linesconst elInfoModal = document.getElementById("info-modal");const elInfoClose = document.getElementById("info-close");const elInfoDotText = document.getElementById("info-dot-text");const elReset = document.getElementById("reset-btn");const elPanelEmpty = document.getElementById("panel-empty");const elPanelBody = document.getElementById("panel-body");644 unmodified lines// previous to resolve, which clamps the effective cadence to the// call duration itself.let tickInFlight = false;setInterval(async () => {if (tickInFlight) return;tickInFlight = true;try { await client.predict("/tick_decisions", {}); }catch (e) { console.warn("tick_decisions failed", e); }finally { tickInFlight = false; }}, 5000);refresh();}145 unmodified lines146147148149150151152153154155156157158159160161549 unmodified lines711712713714715716717718719720516 unmodified lines123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260644 unmodified lines19051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930145 unmodified lines.tl-sent-negative .tl-sent-pip { background: var(--red); }.tl-sent-positive { color: var(--green); }.tl-sent-positive .tl-sent-pip { background: var(--green); }.tl-mode {display: inline-flex; align-items: center; gap: 6px;padding: 2px 9px; border-radius: 8px;border: 1.5px solid currentColor;font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase;}.tl-mode-pip { width: 7px; height: 7px; border-radius: 50%; background: currentColor; }.tl-mode-unknown { color: var(--ink-soft); }.tl-mode-gpu { color: var(--green); }.tl-mode-cpu { color: var(--red); }/* ====== middle band ====== */.tl-mid { flex: 1; display: flex; gap: 14px; padding: 14px; min-height: 0; }549 unmodified lines<span class="tl-sentiment tl-sent-neutral" id="sent-chip"><span class="tl-sent-pip"></span><span id="sent-text">neutral</span></span><span class="tl-meta-dot">·</span><span class="tl-mode tl-mode-unknown" id="mode-chip" title="Which compute the last tick used. CPU appears when ZeroGPU quota is empty — the sim keeps running, just slower."><span class="tl-mode-pip"></span><span id="mode-text">—</span></span></div></div>516 unmodified linesconst elInfoModal = document.getElementById("info-modal");const elInfoClose = document.getElementById("info-close");const elInfoDotText = document.getElementById("info-dot-text");const elModeChip = document.getElementById("mode-chip");const elModeText = document.getElementById("mode-text");function setModeChip(mode) {// mode is "gpu", "cpu", or null/undefined for unknown.if (!elModeChip || !elModeText) return;elModeChip.classList.remove("tl-mode-unknown", "tl-mode-gpu", "tl-mode-cpu");if (mode === "gpu") {elModeChip.classList.add("tl-mode-gpu");elModeText.textContent = "GPU";} else if (mode === "cpu") {elModeChip.classList.add("tl-mode-cpu");elModeText.textContent = "CPU";} else {elModeChip.classList.add("tl-mode-unknown");elModeText.textContent = "—";}}const elReset = document.getElementById("reset-btn");const elPanelEmpty = document.getElementById("panel-empty");const elPanelBody = document.getElementById("panel-body");644 unmodified lines// previous to resolve, which clamps the effective cadence to the// call duration itself.let tickInFlight = false;let lastMode = null;setInterval(async () => {if (tickInFlight) return;tickInFlight = true;try {const res = await client.predict("/tick_decisions", {});const payload = res?.data?.[0];const mode = payload?.mode;if (mode) {setModeChip(mode);if (mode !== lastMode) {console.log("[townlet] tick mode:", mode, mode === "cpu" ? "(ZeroGPU quota empty — CPU fallback active)" : "");lastMode = mode;}}} catch (e) {console.warn("tick_decisions failed", e);} finally {tickInFlight = false;}}, 5000);refresh();}
app.py+44-4
backend/factory.py+17-4
backend/real.py+33-5
frontend/index.html+49-3