Download app.py from fmorgens/NextBoard: direct link, hf CLI and curl.
- Browser
- Download file 14.2 kB
-
https://huggingface.co/spaces/fmorgens/NextBoard/resolve/main/app.py
- Command line
-
hf download hf://spaces/fmorgens/NextBoard/app.py
-
curl -L -o app.py https://huggingface.co/spaces/fmorgens/NextBoard/resolve/main/app.py
14.2 kB
| """ | |
| NextBoard play Space: Gradio (Server mode) as the API, our own page on top. | |
| One model move is normally one GPU call: api.py's attempt loop runs inside a | |
| @spaces.GPU function and streams each generated board back to the page. Boards are | |
| generated one square per step (engine.PLAN). A long run of retries continues in | |
| another call after CALL_BUDGET seconds, so no call outlives its GPU_SECONDS. | |
| Models come from a manifest (models.json) in a public Hub model repo. It is | |
| re-read every few minutes and weights are downloaded on first use, so a new | |
| checkpoint needs no redeploy (see README_DEPLOY.md). | |
| The page can also run the model in the visitor's browser (WebGPU or WebAssembly, see | |
| nb_engine.js and nb_worker.js). Then this server only hands out the page and the model | |
| list; the ONNX file comes straight from the Hub. The /move API is the "Hugging Face GPU" | |
| backend. | |
| """ | |
| import spaces # noqa: I001 (must be imported before torch on ZeroGPU) | |
| import json | |
| import os | |
| import re | |
| import threading | |
| import time | |
| from collections import OrderedDict | |
| from pathlib import Path | |
| os.environ.setdefault("TOKENIZERS_PARALLELISM", "false") | |
| import gradio as gr # noqa: E402 | |
| import torch # noqa: E402 | |
| from fastapi import HTTPException # noqa: E402 | |
| from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Response # noqa: E402 | |
| from huggingface_hub import hf_hub_download, snapshot_download # noqa: E402 | |
| import engine # noqa: E402 | |
| from chess_boards import board_from_history # noqa: E402 | |
| from illegal_moves import PIECE_TOKENS # noqa: E402 | |
| MODEL_REPO = os.environ.get("NEXTBOARD_MODEL_REPO", "fmorgens/NextBoard") | |
| LOCAL_MODELS = os.environ.get("NEXTBOARD_LOCAL_MODELS") # a local folder instead of the Hub (tests) | |
| MANIFEST_FILE = "models.json" | |
| MANIFEST_TTL = 300 # seconds between manifest checks | |
| MAX_LOADED = 3 # models kept in memory | |
| MAX_ATTEMPTS = 50 # boards generated per move before giving up (as index.html asks api.py) | |
| GPU_SECONDS = 20 # GPU time requested per call | |
| CALL_BUDGET = 12 # seconds of boards per GPU call; a move that needs more retries continues in | |
| # another call (one square per step makes a board ~4x slower than tail16) | |
| MAX_BOARDS = 1200 # longest game history accepted | |
| OUTCOMES = {"<white>", "<black>", "<draw>"} | |
| HERE = Path(__file__).resolve().parent | |
| NAME = r"[A-Za-z0-9][A-Za-z0-9._-]*" | |
| BROWSER_FILES = {"config.json", "tokenizer.json"} # read by the page's own engine, next to the ONNX file | |
| # Cross-origin isolation lets the page's WebAssembly backend use several threads (SharedArrayBuffer). | |
| # The page asks for it with these headers. Inside the huggingface.co frame it also needs the | |
| # `custom_headers` in README.md: they make huggingface.co send the same policy and allow the frame to be | |
| # isolated. That page then only shows a frame whose document allows cross-origin embedding, hence the | |
| # resource policy. "credentialless" keeps the CDN scripts and images loading without CORS headers. | |
| ISOLATION = {"Cross-Origin-Opener-Policy": "same-origin", "Cross-Origin-Embedder-Policy": "credentialless", | |
| "Cross-Origin-Resource-Policy": "cross-origin"} | |
| _lock = threading.Lock() | |
| _manifest = {"time": 0.0, "models": []} | |
| _folders: dict[str, str] = {} # model id -> local folder with its files | |
| _cpu_bundles: "OrderedDict[str, engine.Bundle]" = OrderedDict() # main process, inherited by GPU workers | |
| _device_bundles: "OrderedDict[str, engine.Bundle]" = OrderedDict() # inside the GPU worker | |
| # --- manifest and weights --- | |
| def _onnx_entry(onnx) -> dict | None: | |
| """The manifest's record of a model's ONNX file (for the in-browser backends), if it has one.""" | |
| if not isinstance(onnx, dict) or not re.fullmatch(NAME, str(onnx.get("file", ""))): | |
| return None | |
| if not isinstance(onnx.get("bytes"), int) or not re.fullmatch(r"[0-9a-f]{64}", str(onnx.get("sha256", ""))): | |
| return None | |
| return {"file": onnx["file"], "bytes": onnx["bytes"], "sha256": onnx["sha256"]} | |
| def files_url(entry: dict) -> str: | |
| """Where the page downloads a model's files from: the Hub, or this server in local tests.""" | |
| if LOCAL_MODELS: | |
| return f"nb/files/{entry['path']}/" | |
| return f"https://huggingface.co/{MODEL_REPO}/resolve/main/{entry['path']}/" | |
| def _read_manifest() -> list[dict]: | |
| if LOCAL_MODELS: | |
| path = Path(LOCAL_MODELS) / MANIFEST_FILE | |
| else: | |
| path = Path(hf_hub_download(MODEL_REPO, MANIFEST_FILE)) # revalidates against the Hub | |
| models = [] | |
| for m in json.loads(path.read_text(encoding="utf-8")).get("models", []): | |
| model_id, folder = str(m.get("id", "")), str(m.get("path") or m.get("id", "")) | |
| if not re.fullmatch(NAME, model_id) or not re.fullmatch(NAME, folder): | |
| continue | |
| models.append({"id": model_id, "path": folder, "label": str(m.get("label") or model_id), | |
| "params": m.get("params"), "step": m.get("step"), "date": m.get("date"), | |
| "note": str(m.get("note") or ""), "default": bool(m.get("default")), | |
| "onnx": _onnx_entry(m.get("onnx"))}) | |
| if models and not any(m["default"] for m in models): | |
| models[0]["default"] = True | |
| return models | |
| def get_models() -> list[dict]: | |
| """The manifest, at most MANIFEST_TTL seconds old. A failed refresh keeps the last good one.""" | |
| with _lock: | |
| if time.time() - _manifest["time"] > MANIFEST_TTL or not _manifest["models"]: | |
| try: | |
| _manifest["models"] = _read_manifest() | |
| except Exception as e: # Hub hiccup: keep what we have | |
| print(f"Could not refresh {MANIFEST_FILE}: {type(e).__name__}: {e}") | |
| _manifest["time"] = time.time() | |
| return _manifest["models"] | |
| def find_model(model_id: str) -> dict: | |
| models = get_models() | |
| if not models: | |
| raise gr.Error("No models are available right now.") | |
| for m in models: | |
| if m["id"] == model_id: | |
| return m | |
| if model_id: | |
| raise gr.Error(f"Unknown model: {model_id}") | |
| return next(m for m in models if m["default"]) | |
| def model_folder(entry: dict) -> str: | |
| """Local folder with the model's files, downloading them on first use.""" | |
| with _lock: | |
| folder = _folders.get(entry["id"]) | |
| if folder is None: | |
| if LOCAL_MODELS: | |
| folder = str(Path(LOCAL_MODELS) / entry["path"]) | |
| else: | |
| root = snapshot_download(MODEL_REPO, allow_patterns=[f"{entry['path']}/*"]) | |
| folder = str(Path(root) / entry["path"]) | |
| with _lock: | |
| _folders[entry["id"]] = folder | |
| return folder | |
| def _remember(cache: OrderedDict, key: str, value): | |
| cache[key] = value | |
| cache.move_to_end(key) | |
| while len(cache) > MAX_LOADED: | |
| cache.popitem(last=False) | |
| def load_on_cpu(entry: dict) -> str: | |
| """Loads a model in the server process, so GPU workers forked later already have it.""" | |
| folder = model_folder(entry) | |
| with _lock: | |
| if entry["id"] in _cpu_bundles: | |
| _cpu_bundles.move_to_end(entry["id"]) | |
| return folder | |
| bundle = engine.load_bundle(folder, device="cpu") | |
| with _lock: | |
| _remember(_cpu_bundles, entry["id"], bundle) | |
| return folder | |
| def _device_bundle(model_id: str, folder: str) -> engine.Bundle: | |
| """The model on the device that plays (inside the GPU worker on ZeroGPU).""" | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| bundle = _device_bundles.get(model_id) | |
| if bundle is None: | |
| cpu = _cpu_bundles.get(model_id) | |
| if cpu is None: # a worker forked before this model was loaded | |
| cpu = engine.load_bundle(folder, device="cpu") | |
| bundle = cpu if device == "cpu" else engine.make_bundle(cpu.model, cpu.tokenizer, cpu.config, device) | |
| _remember(_device_bundles, model_id, bundle) | |
| else: | |
| _device_bundles.move_to_end(model_id) | |
| return bundle | |
| # --- one move = one GPU call --- | |
| def gpu_board_attempts(model_id: str, folder: str, history: list, outcome: str, first_attempt: int = 0, | |
| temperature: float = engine.START_TEMPERATURE): | |
| bundle = _device_bundle(model_id, folder) | |
| started = time.perf_counter() | |
| for attempt in engine.board_attempts(bundle, history, outcome, MAX_ATTEMPTS, | |
| first_attempt=first_attempt, time_budget=CALL_BUDGET, | |
| temperature=temperature): | |
| attempt["seconds"] = round(time.perf_counter() - started, 3) | |
| yield attempt | |
| def check_request(history, outcome) -> tuple[list, str]: | |
| if not isinstance(history, list) or not history: | |
| raise gr.Error("History cannot be empty") | |
| if len(history) > MAX_BOARDS: | |
| raise gr.Error("History is too long") | |
| for board in history: | |
| if not isinstance(board, list) or len(board) != 64 or any(t not in PIECE_TOKENS for t in board): | |
| raise gr.Error("Every board must be 64 square tokens") | |
| outcome = str(outcome).lower() | |
| if outcome not in OUTCOMES: | |
| raise gr.Error("Outcome must be <white>, <black> or <draw>") | |
| if board_from_history(history) is None: | |
| raise gr.Error("Failed to parse original board state") | |
| return history, outcome | |
| def check_temperature(value) -> float: | |
| try: | |
| temperature = float(value) | |
| except (TypeError, ValueError): | |
| raise gr.Error("Temperature must be a number") | |
| if not engine.MIN_TEMPERATURE <= temperature <= engine.MAX_TEMPERATURE: # also rejects NaN | |
| raise gr.Error(f"Temperature must be between {engine.MIN_TEMPERATURE} and {engine.MAX_TEMPERATURE}") | |
| return temperature | |
| app = gr.Server(title="NextBoard", docs_url=None, redoc_url=None) | |
| def move(history: list, outcome: str, model: str = "", temperature: float = engine.START_TEMPERATURE) -> dict: | |
| """Generates the model's next board for a game. | |
| history: every board of the game so far, each a list of 64 square tokens (a8 ... h1). | |
| outcome: the result the model plays for: <white>, <black> or <draw>. | |
| model: a model id from /nb/models; empty for the default. | |
| temperature: temperature of the first attempt, 0.1 (default) to 1.5. Retries rise from it | |
| towards 1.0; from 1.0 upwards it stays constant. | |
| Streams one message per generated board ("attempt"), then a "done" message. | |
| If no generated board was a legal move, "done" has success = false; no move is made up. | |
| """ | |
| history, outcome = check_request(history, outcome) | |
| temperature = check_temperature(temperature) | |
| entry = find_model(str(model or "")) | |
| folder = load_on_cpu(entry) | |
| started = time.perf_counter() | |
| summary, last, gpu_seconds, calls = [], None, 0.0, 0 | |
| while not (last and last["valid"]) and (last["attempt"] if last else 0) < MAX_ATTEMPTS: | |
| first = last["attempt"] if last else 0 # 0-based index of the next attempt | |
| call_seconds = 0.0 | |
| calls += 1 | |
| for attempt in gpu_board_attempts(entry["id"], folder, history, outcome, first, temperature): | |
| summary.append({k: attempt[k] for k in ("attempt", "temperature", "valid", "move", "problem")}) | |
| last, call_seconds = attempt, attempt["seconds"] | |
| yield attempt | |
| gpu_seconds += call_seconds | |
| if not last or last["attempt"] <= first: # the call produced no board: stop | |
| break | |
| success = bool(last and last["valid"]) | |
| yield {"type": "done", "success": success, "model": entry["id"], "attempts": summary, | |
| "final": last if success else None, | |
| "gpu_seconds": round(gpu_seconds, 3) if last else None, "gpu_calls": calls, | |
| "seconds": round(time.perf_counter() - started, 3)} | |
| def index(): | |
| return HTMLResponse((HERE / "index.html").read_text(encoding="utf-8"), | |
| headers={"Cache-Control": "no-cache", **ISOLATION}) | |
| def script(name: str): | |
| """The page's own scripts: the move generation (nb_engine.js) and the model worker (nb_worker.js).""" | |
| if name not in ("engine", "worker"): | |
| raise HTTPException(status_code=404) | |
| return Response((HERE / f"nb_{name}.js").read_text(encoding="utf-8"), media_type="text/javascript", | |
| headers={"Cache-Control": "no-cache", **ISOLATION}) | |
| def local_file(folder: str, name: str): | |
| """Model files for the in-browser backends in local tests. On the Space they come from the Hub.""" | |
| entry = next((m for m in get_models() if m["path"] == folder), None) if LOCAL_MODELS else None | |
| if entry is None or not (name in BROWSER_FILES or (entry["onnx"] and name == entry["onnx"]["file"])): | |
| raise HTTPException(status_code=404) | |
| return FileResponse(Path(LOCAL_MODELS) / folder / name, headers={"Cache-Control": "no-cache"}) | |
| def models(): | |
| """The model list for the page. `files` is the folder with a model's config.json, tokenizer.json | |
| and, when `onnx` is set, the ONNX file the in-browser backends run.""" | |
| public = [{**{k: m[k] for k in ("id", "label", "params", "step", "date", "note", "default", "onnx")}, | |
| "files": files_url(m)} for m in get_models()] | |
| return JSONResponse({"models": public, "max_attempts": MAX_ATTEMPTS, | |
| "temperature": {"min": engine.MIN_TEMPERATURE, "max": engine.MAX_TEMPERATURE, | |
| "default": engine.START_TEMPERATURE}}, | |
| headers={"Cache-Control": "no-store"}) | |
| def preload(): | |
| """Load the listed models before serving, default first, so the first move is quick.""" | |
| try: | |
| for entry in sorted(get_models(), key=lambda m: not m["default"])[:MAX_LOADED]: | |
| load_on_cpu(entry) | |
| print(f"Loaded {entry['id']}") | |
| except Exception as e: # the Space still starts; models load on first use | |
| print(f"Preload failed: {type(e).__name__}: {e}") | |
| if __name__ == "__main__": | |
| preload() | |
| app.launch(show_error=True, ssr_mode=False) | |