deploy: sync from qagent 2b322e9
Browse files- .gitignore +5 -0
- Dockerfile +34 -0
- README.md +50 -4
- app.py +480 -0
- assets/hero_qaoa.svg +226 -0
- assets/quantum_labor_logo.svg +44 -0
- assets/styles.css +121 -0
- precomputed/benchmark_results.json +0 -0
- precomputed/dataset.json +0 -0
- requirements.txt +7 -0
- safety.py +162 -0
.gitignore
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.venv/
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.pyc
|
| 4 |
+
.pytest_cache/
|
| 5 |
+
.cache/
|
Dockerfile
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
# git is needed for the qagent install from GitHub below.
|
| 6 |
+
RUN apt-get update \
|
| 7 |
+
&& apt-get install -y --no-install-recommends git \
|
| 8 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 9 |
+
|
| 10 |
+
# Light deps only (Gradio + numpy + matplotlib). The Space does not run live
|
| 11 |
+
# QAOA, so torch / pennylane are intentionally absent.
|
| 12 |
+
COPY requirements.txt .
|
| 13 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 14 |
+
|
| 15 |
+
# Install qagent WITHOUT its declared deps (torch / pennylane / scipy): the
|
| 16 |
+
# Space only uses qagent.oracle (brute-force, greedy) and qagent.qaoa.encoding,
|
| 17 |
+
# all pure Python, plus the precomputed QAOA results JSON.
|
| 18 |
+
RUN pip install --no-cache-dir --no-deps \
|
| 19 |
+
"qagent @ git+https://github.com/Quantum-Labor/qagent.git@main"
|
| 20 |
+
|
| 21 |
+
COPY app.py .
|
| 22 |
+
COPY safety.py .
|
| 23 |
+
COPY assets/ ./assets/
|
| 24 |
+
COPY precomputed/ ./precomputed/
|
| 25 |
+
|
| 26 |
+
# HuggingFace Spaces expect the app on 0.0.0.0:7860. No SYSTEM=spaces: this Space
|
| 27 |
+
# has no OAuth (it is fully open), so Gradio never takes the OAuth code path and
|
| 28 |
+
# the hot-reload watcher warning that SYSTEM=spaces triggers is avoided.
|
| 29 |
+
ENV GRADIO_SERVER_NAME=0.0.0.0 \
|
| 30 |
+
GRADIO_SERVER_PORT=7860 \
|
| 31 |
+
PYTHONUNBUFFERED=1
|
| 32 |
+
EXPOSE 7860
|
| 33 |
+
|
| 34 |
+
CMD ["python", "-u", "app.py"]
|
README.md
CHANGED
|
@@ -1,10 +1,56 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji: 📊
|
| 4 |
colorFrom: purple
|
| 5 |
-
colorTo:
|
| 6 |
sdk: docker
|
|
|
|
| 7 |
pinned: false
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
---
|
| 9 |
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: QAgent
|
|
|
|
| 3 |
colorFrom: purple
|
| 4 |
+
colorTo: indigo
|
| 5 |
sdk: docker
|
| 6 |
+
app_port: 7860
|
| 7 |
pinned: false
|
| 8 |
+
license: apache-2.0
|
| 9 |
+
hardware: cpu-basic
|
| 10 |
+
tags:
|
| 11 |
+
- quantum-computing
|
| 12 |
+
- qaoa
|
| 13 |
+
- pennylane
|
| 14 |
+
- llm-agents
|
| 15 |
+
- tool-selection
|
| 16 |
+
- auto-deploy
|
| 17 |
---
|
| 18 |
|
| 19 |
+
# QAgent - quantum tool selection for LLM agents
|
| 20 |
+
|
| 21 |
+
This Space demonstrates [QAgent](https://github.com/Quantum-Labor/qagent): picking
|
| 22 |
+
the best subset of `k` tools from `N` candidates for an agent task, solved with the
|
| 23 |
+
Quantum Approximate Optimization Algorithm (QAOA). It is project 2 of 3 in the
|
| 24 |
+
Quantum Co-Processor program (after QVerify, alongside QRoute).
|
| 25 |
+
|
| 26 |
+
## What you can do here
|
| 27 |
+
|
| 28 |
+
- **Explore the qagent-mini-50 tasks.** Pick any of the 50 benchmark tasks; the
|
| 29 |
+
4x4 (or 4x2) tool grid highlights which tools the brute-force optimum, QAOA, and
|
| 30 |
+
greedy each select, with score cards and approximation ratios.
|
| 31 |
+
- **See the score landscape.** A chart plots the scores of every size-`k` subset
|
| 32 |
+
with markers showing exactly where QAOA, greedy, and the optimum fall - so you
|
| 33 |
+
can see how close QAOA gets and how far greedy misses.
|
| 34 |
+
- **Build an exploration history.** As you browse tasks, the session tracks the
|
| 35 |
+
QAOA vs greedy approximation ratio.
|
| 36 |
+
- **Verify live.** A button runs the pure-Python brute-force and greedy solvers
|
| 37 |
+
live (no precomputed lookup) and confirms they match the served numbers.
|
| 38 |
+
- **Read the leaderboard.** The qagent-mini-50 summary: exact-match and mean
|
| 39 |
+
approximation ratio for brute-force, greedy, and QAOA.
|
| 40 |
+
|
| 41 |
+
## Design notes
|
| 42 |
+
|
| 43 |
+
- **Precomputed QAOA.** QAOA on 16 qubits is slow on CPU, so the QAOA results are
|
| 44 |
+
precomputed with the documented v0.2 config (p=4, 160 steps, 1024 shots, seed 0,
|
| 45 |
+
x mixer) and served from JSON for an instant experience. The classical solvers
|
| 46 |
+
run live (they are pure Python and finish in milliseconds), which keeps the
|
| 47 |
+
served numbers honest and the Docker image small (no torch / pennylane).
|
| 48 |
+
- **Fully open.** There is no IBM hardware path and no quota to protect, so the
|
| 49 |
+
Space has no OAuth gating - anyone can use every feature.
|
| 50 |
+
- **Honest scope.** Simulator only; no quantum advantage is claimed. QAOA matches
|
| 51 |
+
the optimum on every N=8 task and reaches a 0.915 mean approximation ratio at
|
| 52 |
+
N=16, but exact-match at N=16 remains hard (the next step is Dicke-initialised
|
| 53 |
+
XY-QAOA). Full benchmarks and source: the GitHub repo.
|
| 54 |
+
|
| 55 |
+
Auto-deployed from the `qagent` repository `main` branch via a GitHub Action
|
| 56 |
+
(`HfApi.upload_folder`); see `docs/deploy.md` in the repo.
|
app.py
ADDED
|
@@ -0,0 +1,480 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""QAgent HuggingFace Space - QAOA tool selection, runs on CPU Basic.
|
| 2 |
+
|
| 3 |
+
The Space serves *precomputed* QAOA results (p=4, 160 steps, seed 0 - the
|
| 4 |
+
documented v0.2 config) for the 50 qagent-mini tasks, so the experience is
|
| 5 |
+
instant and needs no torch / pennylane in the image. The pure-Python classical
|
| 6 |
+
solvers (brute-force exact, greedy top-k) run *live* on demand so visitors can
|
| 7 |
+
confirm the served numbers are real. There is no IBM hardware path and no OAuth:
|
| 8 |
+
the Space is fully open.
|
| 9 |
+
|
| 10 |
+
Design (see README.md): a hero with the QAOA ansatz, a task explorer with a 4x4
|
| 11 |
+
tool grid that highlights which tools each solver picks, score cards with
|
| 12 |
+
approximation ratios, a score-landscape chart showing where QAOA / greedy /
|
| 13 |
+
optimal fall among all size-k subsets, an exploration history, and the
|
| 14 |
+
qagent-mini-50 leaderboard.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import json
|
| 20 |
+
import os
|
| 21 |
+
from datetime import UTC, datetime
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
from typing import Any
|
| 24 |
+
|
| 25 |
+
import gradio as gr
|
| 26 |
+
import matplotlib
|
| 27 |
+
|
| 28 |
+
matplotlib.use("Agg")
|
| 29 |
+
import matplotlib.pyplot as plt
|
| 30 |
+
from safety import RateLimiter, default_persist_path
|
| 31 |
+
|
| 32 |
+
from qagent.oracle.bruteforce import brute_force_best
|
| 33 |
+
from qagent.oracle.greedy import greedy_top_k
|
| 34 |
+
from qagent.qaoa.encoding import ToolScoring
|
| 35 |
+
|
| 36 |
+
HERE = Path(__file__).resolve().parent
|
| 37 |
+
RESULTS_PATH = HERE / "precomputed" / "benchmark_results.json"
|
| 38 |
+
ASSETS = HERE / "assets"
|
| 39 |
+
REPO_URL = "https://github.com/Quantum-Labor/qagent"
|
| 40 |
+
|
| 41 |
+
_RATE_LIMITER = RateLimiter(window_seconds=3, daily_cap=5000, persist_path=default_persist_path())
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _load_results() -> dict[str, Any]:
|
| 45 |
+
try:
|
| 46 |
+
return json.loads(RESULTS_PATH.read_text(encoding="utf-8")) # type: ignore[no-any-return]
|
| 47 |
+
except (FileNotFoundError, json.JSONDecodeError):
|
| 48 |
+
return {"config": {}, "summary": {}, "tasks": []}
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
RESULTS = _load_results()
|
| 52 |
+
TASKS: list[dict[str, Any]] = RESULTS.get("tasks", [])
|
| 53 |
+
TASK_BY_ID: dict[str, dict[str, Any]] = {t["id"]: t for t in TASKS}
|
| 54 |
+
|
| 55 |
+
# The source dataset (weights + full synergy matrix) is bundled so the live
|
| 56 |
+
# brute-force / greedy check reconstructs the exact scoring behind each task.
|
| 57 |
+
_DATASET_PATH = HERE / "precomputed" / "dataset.json"
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _load_dataset() -> dict[str, dict[str, Any]]:
|
| 61 |
+
try:
|
| 62 |
+
rows = json.loads(_DATASET_PATH.read_text(encoding="utf-8"))
|
| 63 |
+
return {r["id"]: r for r in rows}
|
| 64 |
+
except (FileNotFoundError, json.JSONDecodeError):
|
| 65 |
+
return {}
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
DATASET_BY_ID = _load_dataset()
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _read_asset(name: str) -> str:
|
| 72 |
+
try:
|
| 73 |
+
return (ASSETS / name).read_text(encoding="utf-8")
|
| 74 |
+
except FileNotFoundError:
|
| 75 |
+
return ""
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _client_ip(request: gr.Request | None) -> str:
|
| 79 |
+
if request is None:
|
| 80 |
+
return "unknown"
|
| 81 |
+
fwd = request.headers.get("x-forwarded-for") if request.headers else None
|
| 82 |
+
if fwd:
|
| 83 |
+
return fwd.split(",")[0].strip()
|
| 84 |
+
return getattr(request.client, "host", "unknown") or "unknown"
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
# --- rendering helpers (pure, unit-testable) --------------------------------
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def task_label(task: dict[str, Any]) -> str:
|
| 91 |
+
return f"{task['id']} · {task['tier']} · N={task['n_tools']} k={task['k']}"
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def task_choices() -> list[str]:
|
| 95 |
+
return [task_label(t) for t in TASKS]
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _label_to_id(label: str) -> str:
|
| 99 |
+
return label.split(" ", 1)[0]
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def render_tool_grid(task: dict[str, Any]) -> str:
|
| 103 |
+
optimal = set(task["optimal"]["subset"])
|
| 104 |
+
qaoa = set(task["qaoa"]["subset"])
|
| 105 |
+
greedy = set(task["greedy"]["subset"])
|
| 106 |
+
cards: list[str] = []
|
| 107 |
+
for tool in task["tools"]:
|
| 108 |
+
i = tool["index"]
|
| 109 |
+
w = tool["weight"]
|
| 110 |
+
classes = "qa-tool-card"
|
| 111 |
+
if i in optimal:
|
| 112 |
+
classes += " sel-optimal"
|
| 113 |
+
if i in qaoa:
|
| 114 |
+
classes += " sel-qaoa"
|
| 115 |
+
tags = []
|
| 116 |
+
if i in optimal:
|
| 117 |
+
tags.append('<span class="qa-tag optimal">optimal</span>')
|
| 118 |
+
if i in qaoa:
|
| 119 |
+
tags.append('<span class="qa-tag qaoa">qaoa</span>')
|
| 120 |
+
if i in greedy:
|
| 121 |
+
tags.append('<span class="qa-tag greedy">greedy</span>')
|
| 122 |
+
tags_html = f'<div class="qa-tags">{"".join(tags)}</div>' if tags else ""
|
| 123 |
+
bar = f'<div class="qa-tool-bar"><span style="width:{min(w, 1.0) * 100:.0f}%"></span></div>'
|
| 124 |
+
cards.append(
|
| 125 |
+
f'<div class="{classes}"><div class="qa-tool-name">{tool["name"]}</div>'
|
| 126 |
+
f'<div class="qa-tool-weight">w = {w:.3f}</div>{bar}{tags_html}</div>'
|
| 127 |
+
)
|
| 128 |
+
legend = (
|
| 129 |
+
'<div class="qa-legend">'
|
| 130 |
+
'<span><span class="dot" style="background:#34D399"></span>optimal (brute-force)</span>'
|
| 131 |
+
'<span><span class="dot" style="background:#67E8F9"></span>QAOA</span>'
|
| 132 |
+
'<span><span class="dot" style="background:#F59E0B"></span>greedy</span>'
|
| 133 |
+
"</div>"
|
| 134 |
+
)
|
| 135 |
+
return f'<div class="qa-tool-grid">{"".join(cards)}</div>{legend}'
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def render_scores(task: dict[str, Any]) -> str:
|
| 139 |
+
opt = task["optimal"]
|
| 140 |
+
qa = task["qaoa"]
|
| 141 |
+
gd = task["greedy"]
|
| 142 |
+
exact = "exact match" if qa["exact_match"] else "approximate"
|
| 143 |
+
|
| 144 |
+
def card(kind: str, title: str, score: float, sub: str) -> str:
|
| 145 |
+
return (
|
| 146 |
+
f'<div class="qa-score-card {kind}"><h4>{title}</h4>'
|
| 147 |
+
f'<div class="qa-score-val">{score:.3f}</div>'
|
| 148 |
+
f'<div class="qa-score-sub">{sub}</div></div>'
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
return (
|
| 152 |
+
'<div class="qa-scores">'
|
| 153 |
+
+ card(
|
| 154 |
+
"optimal",
|
| 155 |
+
"Optimal (brute-force)",
|
| 156 |
+
opt["score"],
|
| 157 |
+
f"{task['k']} of {task['n_tools']} tools",
|
| 158 |
+
)
|
| 159 |
+
+ card("qaoa", "QAOA", qa["score"], f"ratio {qa['approx_ratio']:.3f} · {exact}")
|
| 160 |
+
+ card("greedy", "Greedy top-k", gd["score"], f"ratio {gd['approx_ratio']:.3f}")
|
| 161 |
+
+ "</div>"
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def landscape_figure(task: dict[str, Any]) -> Any:
|
| 166 |
+
hist = task["score_hist"]
|
| 167 |
+
edges = hist["bin_edges"]
|
| 168 |
+
counts = hist["counts"]
|
| 169 |
+
centers = [(edges[i] + edges[i + 1]) / 2 for i in range(len(counts))]
|
| 170 |
+
width = (edges[1] - edges[0]) * 0.9 if len(edges) > 1 else 0.1
|
| 171 |
+
|
| 172 |
+
plt.style.use("dark_background")
|
| 173 |
+
fig, ax = plt.subplots(figsize=(7.6, 3.3), dpi=110)
|
| 174 |
+
fig.patch.set_facecolor("#0B0B16")
|
| 175 |
+
ax.set_facecolor("#0B0B16")
|
| 176 |
+
ax.bar(
|
| 177 |
+
centers, counts, width=width, color="#3A3460", edgecolor="none", label="all size-k subsets"
|
| 178 |
+
)
|
| 179 |
+
for score, color, label in [
|
| 180 |
+
(task["greedy"]["score"], "#F59E0B", "greedy"),
|
| 181 |
+
(task["qaoa"]["score"], "#22D3EE", "QAOA"),
|
| 182 |
+
(task["optimal"]["score"], "#34D399", "optimal"),
|
| 183 |
+
]:
|
| 184 |
+
ax.axvline(score, color=color, linewidth=2.2, label=label)
|
| 185 |
+
ax.set_xlabel("subset score", color="#9CA3AF", fontsize=10)
|
| 186 |
+
ax.set_ylabel(f"# subsets ({hist['n_subsets']})", color="#9CA3AF", fontsize=10)
|
| 187 |
+
ax.set_title("Score landscape: where each solver lands", color="#E5E7EB", fontsize=12, pad=10)
|
| 188 |
+
ax.tick_params(colors="#6B6788", labelsize=8)
|
| 189 |
+
for spine in ax.spines.values():
|
| 190 |
+
spine.set_color("#2A2440")
|
| 191 |
+
ax.legend(
|
| 192 |
+
facecolor="#15152A", edgecolor="#2A2440", labelcolor="#E5E7EB", fontsize=9, loc="upper left"
|
| 193 |
+
)
|
| 194 |
+
fig.tight_layout()
|
| 195 |
+
return fig
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def history_figure(history: list[dict[str, Any]]) -> Any:
|
| 199 |
+
plt.style.use("dark_background")
|
| 200 |
+
fig, ax = plt.subplots(figsize=(7.6, 2.8), dpi=110)
|
| 201 |
+
fig.patch.set_facecolor("#0B0B16")
|
| 202 |
+
ax.set_facecolor("#0B0B16")
|
| 203 |
+
if history:
|
| 204 |
+
xs = list(range(len(history)))
|
| 205 |
+
ax.plot(xs, [h["qaoa"] for h in history], "-o", color="#22D3EE", label="QAOA", linewidth=2)
|
| 206 |
+
ax.plot(
|
| 207 |
+
xs, [h["greedy"] for h in history], "-o", color="#F59E0B", label="greedy", linewidth=2
|
| 208 |
+
)
|
| 209 |
+
ax.axhline(1.0, color="#34D399", linewidth=1.2, linestyle="--", label="optimal")
|
| 210 |
+
ax.set_xticks(xs)
|
| 211 |
+
ax.set_xticklabels([h["id"] for h in history], rotation=45, ha="right", fontsize=7)
|
| 212 |
+
ax.set_ylim(0.5, 1.05)
|
| 213 |
+
ax.legend(
|
| 214 |
+
facecolor="#15152A",
|
| 215 |
+
edgecolor="#2A2440",
|
| 216 |
+
labelcolor="#E5E7EB",
|
| 217 |
+
fontsize=9,
|
| 218 |
+
loc="lower left",
|
| 219 |
+
)
|
| 220 |
+
else:
|
| 221 |
+
ax.text(
|
| 222 |
+
0.5,
|
| 223 |
+
0.5,
|
| 224 |
+
"Explore tasks to build a history",
|
| 225 |
+
ha="center",
|
| 226 |
+
va="center",
|
| 227 |
+
color="#6B6788",
|
| 228 |
+
fontsize=11,
|
| 229 |
+
transform=ax.transAxes,
|
| 230 |
+
)
|
| 231 |
+
ax.set_ylabel("approx ratio", color="#9CA3AF", fontsize=10)
|
| 232 |
+
ax.set_title("Approximation-ratio history (this session)", color="#E5E7EB", fontsize=12, pad=8)
|
| 233 |
+
ax.tick_params(colors="#6B6788", labelsize=8)
|
| 234 |
+
for spine in ax.spines.values():
|
| 235 |
+
spine.set_color("#2A2440")
|
| 236 |
+
fig.tight_layout()
|
| 237 |
+
return fig
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def _task_description(task: dict[str, Any]) -> str:
|
| 241 |
+
return (
|
| 242 |
+
f"**{task['id']}** · {task['tier']} pool · select **{task['k']}** of "
|
| 243 |
+
f"**{task['n_tools']}** tools. {task['description']}"
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def select_task(
|
| 248 |
+
label: str, history: list[dict[str, Any]]
|
| 249 |
+
) -> tuple[str, str, str, Any, Any, list[dict[str, Any]]]:
|
| 250 |
+
task = TASK_BY_ID[_label_to_id(label)]
|
| 251 |
+
history = [h for h in history if h["id"] != task["id"]]
|
| 252 |
+
history.append(
|
| 253 |
+
{
|
| 254 |
+
"id": task["id"],
|
| 255 |
+
"qaoa": task["qaoa"]["approx_ratio"],
|
| 256 |
+
"greedy": task["greedy"]["approx_ratio"],
|
| 257 |
+
}
|
| 258 |
+
)
|
| 259 |
+
history = history[-12:]
|
| 260 |
+
return (
|
| 261 |
+
_task_description(task),
|
| 262 |
+
render_tool_grid(task),
|
| 263 |
+
render_scores(task),
|
| 264 |
+
landscape_figure(task),
|
| 265 |
+
history_figure(history),
|
| 266 |
+
history,
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def verify_live(label: str, request: gr.Request | None = None) -> str:
|
| 271 |
+
"""Run brute-force + greedy live to prove the served numbers are real."""
|
| 272 |
+
verdict = _RATE_LIMITER.check_and_register(ip=_client_ip(request), now=datetime.now(UTC))
|
| 273 |
+
if not verdict.allowed:
|
| 274 |
+
return f"_{verdict.detail}_"
|
| 275 |
+
task = TASK_BY_ID[_label_to_id(label)]
|
| 276 |
+
entry = DATASET_BY_ID.get(task["id"])
|
| 277 |
+
if entry is None:
|
| 278 |
+
return "_Source scoring unavailable for live verification._"
|
| 279 |
+
sc = ToolScoring(
|
| 280 |
+
weights=tuple(entry["weights"]),
|
| 281 |
+
synergy=tuple(tuple(row) for row in entry["synergy"]),
|
| 282 |
+
)
|
| 283 |
+
k = task["k"]
|
| 284 |
+
bf_sub, bf_score = brute_force_best(sc, k)
|
| 285 |
+
gd_sub, gd_score = greedy_top_k(sc, k)
|
| 286 |
+
opt = task["optimal"]["score"]
|
| 287 |
+
bf_ok = abs(bf_score - opt) < 1e-6
|
| 288 |
+
return (
|
| 289 |
+
f"Live solve of **{task['id']}** (pure-Python, no precomputed lookup):\n\n"
|
| 290 |
+
f"- brute-force optimum: `{sorted(bf_sub)}` score **{bf_score:.4f}** "
|
| 291 |
+
f"{'matches' if bf_ok else 'DIFFERS FROM'} the served optimal `{opt:.4f}`\n"
|
| 292 |
+
f"- greedy top-k: `{sorted(gd_sub)}` score **{gd_score:.4f}**\n\n"
|
| 293 |
+
f"The served QAOA result (score {task['qaoa']['score']:.4f}, ratio "
|
| 294 |
+
f"{task['qaoa']['approx_ratio']:.3f}) was precomputed with p={RESULTS['config'].get('p')} "
|
| 295 |
+
f"on the PennyLane simulator."
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def leaderboard_markdown() -> str:
|
| 300 |
+
s = RESULTS.get("summary", {})
|
| 301 |
+
if not s:
|
| 302 |
+
return "_Leaderboard unavailable._"
|
| 303 |
+
|
| 304 |
+
def cell(exact: int, ratio: float, n: int) -> str:
|
| 305 |
+
return f"{100 * exact // n}% ({exact}/{n}) · {ratio:.3f}"
|
| 306 |
+
|
| 307 |
+
def row(group: str, g: dict[str, Any]) -> str:
|
| 308 |
+
n = g["n"]
|
| 309 |
+
gd = cell(g["greedy_exact"], g["greedy_ratio"], n)
|
| 310 |
+
qa = cell(g["qaoa_exact"], g["qaoa_ratio"], n)
|
| 311 |
+
return f"| {group} | 100% ({n}/{n}) | {gd} | {qa} |"
|
| 312 |
+
|
| 313 |
+
lines = [
|
| 314 |
+
"| Group | Brute-force | Greedy | QAOA |",
|
| 315 |
+
"| --- | --- | --- | --- |",
|
| 316 |
+
]
|
| 317 |
+
for key, name in [("small", "small (N=8, k=3)"), ("full", "full (N=16, k=5)"), ("all", "all")]:
|
| 318 |
+
if key in s:
|
| 319 |
+
lines.append(row(name, s[key]))
|
| 320 |
+
cfg = RESULTS.get("config", {})
|
| 321 |
+
note = (
|
| 322 |
+
"\n\nMetric: exact-match (and mean approximation ratio). QAOA config: "
|
| 323 |
+
f"p={cfg.get('p')}, {cfg.get('steps')} steps, {cfg.get('shots')} shots, "
|
| 324 |
+
f"seed {cfg.get('seed')}, x mixer. Brute-force is the oracle (100% by construction)."
|
| 325 |
+
)
|
| 326 |
+
return "\n".join(lines) + note
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
# --- UI ---------------------------------------------------------------------
|
| 330 |
+
|
| 331 |
+
_THEME = gr.themes.Base(
|
| 332 |
+
primary_hue="purple",
|
| 333 |
+
neutral_hue="slate",
|
| 334 |
+
font=[gr.themes.GoogleFont("Inter"), "ui-sans-serif", "system-ui", "sans-serif"],
|
| 335 |
+
font_mono=[gr.themes.GoogleFont("JetBrains Mono"), "ui-monospace", "monospace"],
|
| 336 |
+
).set(
|
| 337 |
+
body_background_fill="#0B0B16",
|
| 338 |
+
body_text_color="#E5E7EB",
|
| 339 |
+
background_fill_primary="#15152A",
|
| 340 |
+
background_fill_secondary="#0B0B16",
|
| 341 |
+
border_color_primary="#2A2440",
|
| 342 |
+
button_primary_background_fill="#7C3AED",
|
| 343 |
+
button_primary_background_fill_hover="#8B5CF6",
|
| 344 |
+
button_primary_text_color="#FFFFFF",
|
| 345 |
+
block_background_fill="#15152A",
|
| 346 |
+
block_border_color="#2A2440",
|
| 347 |
+
input_background_fill="#15152A",
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def _hero_html() -> str:
|
| 352 |
+
hero_svg = _read_asset("hero_qaoa.svg")
|
| 353 |
+
art = (
|
| 354 |
+
f'<div class="qa-hero-art">{hero_svg}</div>'
|
| 355 |
+
if hero_svg
|
| 356 |
+
else '<div class="qa-hero-art"></div>'
|
| 357 |
+
)
|
| 358 |
+
return f"""
|
| 359 |
+
<div class="qa-hero"><div class="qa-hero-inner">
|
| 360 |
+
{art}
|
| 361 |
+
<div class="qa-hero-copy">
|
| 362 |
+
<h1 class="qa-title">QAgent</h1>
|
| 363 |
+
<p class="qa-tagline">Quantum-optimized tool selection for LLM agents.
|
| 364 |
+
Pick the best subset of <b>k</b> tools from <b>N</b> with QAOA.</p>
|
| 365 |
+
<p class="qa-sub">Tools interact - some synergise, some are redundant - so the
|
| 366 |
+
optimal set is a combinatorial optimization, not a ranking. QAgent encodes
|
| 367 |
+
"select k of N" on one qubit per tool and solves it with the Quantum
|
| 368 |
+
Approximate Optimization Algorithm.</p>
|
| 369 |
+
<div class="qa-badges">
|
| 370 |
+
<span class="qa-badge">v0.2.0</span>
|
| 371 |
+
<a class="qa-badge" href="{REPO_URL}">GitHub</a>
|
| 372 |
+
<span class="qa-badge cyan">Project 2 of 3</span>
|
| 373 |
+
<span class="qa-badge green">simulator</span>
|
| 374 |
+
<span class="qa-badge amber">Apache-2.0</span>
|
| 375 |
+
</div>
|
| 376 |
+
</div>
|
| 377 |
+
</div></div>
|
| 378 |
+
"""
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
_WHAT = """
|
| 382 |
+
### What is this?
|
| 383 |
+
|
| 384 |
+
An LLM agent with many tools should only be handed a few per task - to fit a
|
| 385 |
+
context budget, cut cost, and reduce confusion. Picking the *k* individually most
|
| 386 |
+
relevant tools is greedy and often wrong, because tools have **pairwise
|
| 387 |
+
interactions**: a retriever plus a summariser synergise; two overlapping search
|
| 388 |
+
tools are redundant. The value of a tool set is
|
| 389 |
+
|
| 390 |
+
```
|
| 391 |
+
score(S) = sum of tool relevances + sum of pairwise interactions
|
| 392 |
+
```
|
| 393 |
+
|
| 394 |
+
and the task is to maximise it subject to choosing exactly *k* tools - a quadratic
|
| 395 |
+
binary optimization, exactly the structure QAOA targets.
|
| 396 |
+
"""
|
| 397 |
+
|
| 398 |
+
_HOW = """
|
| 399 |
+
### How it works (in 30 seconds)
|
| 400 |
+
|
| 401 |
+
- **Encode** the task as per-tool relevances and a pairwise interaction matrix.
|
| 402 |
+
- **Map** "select k of N" to N qubits (one-hot: qubit i = tool i in/out), folding
|
| 403 |
+
the cardinality constraint into the cost Hamiltonian as a penalty.
|
| 404 |
+
- **Optimize** a QAOA ansatz (cost layer + mixer) with PyTorch on the PennyLane
|
| 405 |
+
simulator; measure and keep the best valid subset.
|
| 406 |
+
- **Compare** against an exact brute-force oracle and a greedy top-k baseline.
|
| 407 |
+
|
| 408 |
+
This Space serves results precomputed with that pipeline; the classical solvers
|
| 409 |
+
run live so you can check the numbers.
|
| 410 |
+
"""
|
| 411 |
+
|
| 412 |
+
_ABOUT = f"""
|
| 413 |
+
### About
|
| 414 |
+
|
| 415 |
+
QAgent is project 2 of 3 in the Quantum Co-Processor program, after
|
| 416 |
+
[QVerify](https://github.com/Quantum-Labor/qverify) (quantum-assisted reasoning
|
| 417 |
+
verification) and alongside
|
| 418 |
+
[QRoute](https://github.com/Quantum-Labor/qroute) (a VQC mixture-of-experts
|
| 419 |
+
router). Source and full benchmarks: [{REPO_URL}]({REPO_URL}).
|
| 420 |
+
|
| 421 |
+
**Honest scope.** Simulator only; no quantum advantage is claimed. On
|
| 422 |
+
qagent-mini-50, QAOA matches the optimum on every N=8 task and reaches a 0.915
|
| 423 |
+
mean approximation ratio at N=16, but exact-match at N=16 remains hard (the
|
| 424 |
+
documented next step is Dicke-initialised XY-QAOA). The point is the architecture
|
| 425 |
+
and an honest baseline.
|
| 426 |
+
"""
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
def build_demo() -> gr.Blocks:
|
| 430 |
+
# In Gradio 6.x, theme and css are passed to launch(), not the Blocks
|
| 431 |
+
# constructor (where they are silently ignored) -- mirrors the QVerify Space.
|
| 432 |
+
with gr.Blocks(title="QAgent - quantum tool selection") as demo:
|
| 433 |
+
gr.HTML(_hero_html())
|
| 434 |
+
with gr.Row():
|
| 435 |
+
with gr.Column(scale=1):
|
| 436 |
+
gr.Markdown(_WHAT)
|
| 437 |
+
with gr.Column(scale=1):
|
| 438 |
+
gr.Markdown(_HOW)
|
| 439 |
+
|
| 440 |
+
gr.HTML('<div class="qa-section-title">Try it now</div>')
|
| 441 |
+
history = gr.State([])
|
| 442 |
+
default_label = task_choices()[0] if TASKS else None
|
| 443 |
+
task_dd = gr.Dropdown(
|
| 444 |
+
choices=task_choices(),
|
| 445 |
+
value=default_label,
|
| 446 |
+
label="qagent-mini-50 task",
|
| 447 |
+
info="Pick a task to see which tools each solver selects.",
|
| 448 |
+
)
|
| 449 |
+
task_desc = gr.Markdown()
|
| 450 |
+
grid = gr.HTML()
|
| 451 |
+
scores = gr.HTML()
|
| 452 |
+
with gr.Row():
|
| 453 |
+
verify_btn = gr.Button("Verify live (brute-force + greedy)", variant="primary")
|
| 454 |
+
verify_out = gr.Markdown()
|
| 455 |
+
with gr.Row():
|
| 456 |
+
landscape = gr.Plot(label="Score landscape")
|
| 457 |
+
history_plot = gr.Plot(label="History")
|
| 458 |
+
|
| 459 |
+
gr.HTML('<div class="qa-section-title">qagent-mini-50 leaderboard</div>')
|
| 460 |
+
gr.Markdown(leaderboard_markdown())
|
| 461 |
+
|
| 462 |
+
gr.Markdown(_ABOUT)
|
| 463 |
+
|
| 464 |
+
outputs = [task_desc, grid, scores, landscape, history_plot, history]
|
| 465 |
+
task_dd.change(select_task, inputs=[task_dd, history], outputs=outputs)
|
| 466 |
+
verify_btn.click(verify_live, inputs=[task_dd], outputs=[verify_out])
|
| 467 |
+
if default_label is not None:
|
| 468 |
+
demo.load(select_task, inputs=[task_dd, history], outputs=outputs)
|
| 469 |
+
return demo
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
demo = build_demo()
|
| 473 |
+
|
| 474 |
+
if __name__ == "__main__":
|
| 475 |
+
demo.launch(
|
| 476 |
+
theme=_THEME,
|
| 477 |
+
css=_read_asset("styles.css"),
|
| 478 |
+
server_name=os.environ.get("GRADIO_SERVER_NAME", "0.0.0.0"),
|
| 479 |
+
server_port=int(os.environ.get("GRADIO_SERVER_PORT", "7860")),
|
| 480 |
+
)
|
assets/hero_qaoa.svg
ADDED
|
|
assets/quantum_labor_logo.svg
ADDED
|
|
assets/styles.css
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* QAgent Space — luxury dark theme. Loaded by app.py into gr.Blocks(css=...). */
|
| 2 |
+
|
| 3 |
+
/* Hide Gradio's built-in footer (it localises to the viewer's browser language,
|
| 4 |
+
which surfaced as a stray non-English footer on the QVerify Space). */
|
| 5 |
+
footer { display: none !important; }
|
| 6 |
+
|
| 7 |
+
:root {
|
| 8 |
+
--qa-bg: #0B0B16;
|
| 9 |
+
--qa-surface: #15152A;
|
| 10 |
+
--qa-border: #2A2440;
|
| 11 |
+
--qa-violet: #7C3AED;
|
| 12 |
+
--qa-violet-soft: #A78BFA;
|
| 13 |
+
--qa-cyan: #22D3EE;
|
| 14 |
+
--qa-amber: #F59E0B;
|
| 15 |
+
--qa-green: #34D399;
|
| 16 |
+
--qa-text: #E5E7EB;
|
| 17 |
+
--qa-muted: #9CA3AF;
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
.qa-hero {
|
| 21 |
+
position: relative;
|
| 22 |
+
border-radius: 18px;
|
| 23 |
+
overflow: hidden;
|
| 24 |
+
border: 1px solid var(--qa-border);
|
| 25 |
+
background:
|
| 26 |
+
radial-gradient(1200px 300px at 20% -10%, rgba(124, 58, 237, 0.25), transparent),
|
| 27 |
+
radial-gradient(900px 300px at 90% 120%, rgba(34, 211, 238, 0.18), transparent),
|
| 28 |
+
#0B0B16;
|
| 29 |
+
margin-bottom: 8px;
|
| 30 |
+
}
|
| 31 |
+
.qa-hero-inner {
|
| 32 |
+
display: flex;
|
| 33 |
+
align-items: center;
|
| 34 |
+
gap: 28px;
|
| 35 |
+
padding: 30px 34px;
|
| 36 |
+
flex-wrap: wrap;
|
| 37 |
+
}
|
| 38 |
+
.qa-hero-art { flex: 1 1 520px; min-width: 320px; }
|
| 39 |
+
.qa-hero-art img { width: 100%; height: auto; display: block; border-radius: 12px; }
|
| 40 |
+
.qa-hero-copy { flex: 1 1 320px; min-width: 280px; }
|
| 41 |
+
.qa-title {
|
| 42 |
+
font-family: "Inter", system-ui, sans-serif;
|
| 43 |
+
font-weight: 800;
|
| 44 |
+
font-size: 44px;
|
| 45 |
+
letter-spacing: -0.02em;
|
| 46 |
+
margin: 0 0 6px;
|
| 47 |
+
background: linear-gradient(90deg, #FFFFFF, #A78BFA 60%, #22D3EE);
|
| 48 |
+
-webkit-background-clip: text;
|
| 49 |
+
background-clip: text;
|
| 50 |
+
color: transparent;
|
| 51 |
+
}
|
| 52 |
+
.qa-tagline { color: var(--qa-text); font-size: 17px; line-height: 1.5; margin: 0 0 14px; }
|
| 53 |
+
.qa-sub { color: var(--qa-muted); font-size: 13.5px; margin: 0 0 16px; }
|
| 54 |
+
|
| 55 |
+
.qa-badges { display: flex; flex-wrap: wrap; gap: 8px; }
|
| 56 |
+
.qa-badge {
|
| 57 |
+
display: inline-flex; align-items: center; gap: 6px;
|
| 58 |
+
font-family: "JetBrains Mono", ui-monospace, monospace;
|
| 59 |
+
font-size: 11.5px; font-weight: 600;
|
| 60 |
+
padding: 4px 10px; border-radius: 999px;
|
| 61 |
+
border: 1px solid var(--qa-border); background: #11101F; color: var(--qa-violet-soft);
|
| 62 |
+
text-decoration: none;
|
| 63 |
+
}
|
| 64 |
+
.qa-badge.cyan { color: #67E8F9; }
|
| 65 |
+
.qa-badge.green { color: var(--qa-green); }
|
| 66 |
+
.qa-badge.amber { color: var(--qa-amber); }
|
| 67 |
+
|
| 68 |
+
/* Tool grid */
|
| 69 |
+
.qa-tool-grid {
|
| 70 |
+
display: grid;
|
| 71 |
+
grid-template-columns: repeat(4, 1fr);
|
| 72 |
+
gap: 10px;
|
| 73 |
+
margin: 6px 0 4px;
|
| 74 |
+
}
|
| 75 |
+
.qa-tool-card {
|
| 76 |
+
border: 1px solid var(--qa-border);
|
| 77 |
+
border-radius: 12px;
|
| 78 |
+
background: var(--qa-surface);
|
| 79 |
+
padding: 10px 12px;
|
| 80 |
+
transition: transform 0.12s ease, border-color 0.12s ease, box-shadow 0.12s ease;
|
| 81 |
+
}
|
| 82 |
+
.qa-tool-card:hover { transform: translateY(-2px); border-color: #3A3460; }
|
| 83 |
+
.qa-tool-card.sel-optimal { border-color: var(--qa-green); box-shadow: 0 0 0 1px var(--qa-green) inset; }
|
| 84 |
+
.qa-tool-card.sel-qaoa { box-shadow: 0 0 14px rgba(34, 211, 238, 0.35); }
|
| 85 |
+
.qa-tool-name {
|
| 86 |
+
font-family: "JetBrains Mono", ui-monospace, monospace;
|
| 87 |
+
font-size: 12.5px; color: var(--qa-text); font-weight: 700;
|
| 88 |
+
}
|
| 89 |
+
.qa-tool-weight {
|
| 90 |
+
display: inline-block; margin-top: 6px;
|
| 91 |
+
font-family: "JetBrains Mono", monospace; font-size: 11px;
|
| 92 |
+
color: var(--qa-muted);
|
| 93 |
+
}
|
| 94 |
+
.qa-tool-bar { height: 5px; border-radius: 4px; background: #20203A; margin-top: 6px; overflow: hidden; }
|
| 95 |
+
.qa-tool-bar > span { display: block; height: 100%; background: linear-gradient(90deg, #7C3AED, #22D3EE); }
|
| 96 |
+
.qa-tags { display: flex; gap: 5px; margin-top: 8px; flex-wrap: wrap; }
|
| 97 |
+
.qa-tag {
|
| 98 |
+
font-family: "JetBrains Mono", monospace; font-size: 9.5px; font-weight: 700;
|
| 99 |
+
padding: 2px 7px; border-radius: 999px; letter-spacing: 0.03em;
|
| 100 |
+
}
|
| 101 |
+
.qa-tag.optimal { background: rgba(52, 211, 153, 0.16); color: var(--qa-green); }
|
| 102 |
+
.qa-tag.qaoa { background: rgba(34, 211, 238, 0.16); color: #67E8F9; }
|
| 103 |
+
.qa-tag.greedy { background: rgba(245, 158, 11, 0.16); color: var(--qa-amber); }
|
| 104 |
+
|
| 105 |
+
.qa-legend { display: flex; gap: 16px; flex-wrap: wrap; margin: 4px 0 2px; color: var(--qa-muted); font-size: 12px; }
|
| 106 |
+
.qa-legend .dot { display: inline-block; width: 9px; height: 9px; border-radius: 50%; margin-right: 6px; }
|
| 107 |
+
|
| 108 |
+
/* Score cards */
|
| 109 |
+
.qa-scores { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-top: 6px; }
|
| 110 |
+
.qa-score-card { border: 1px solid var(--qa-border); border-radius: 12px; background: var(--qa-surface); padding: 12px 14px; }
|
| 111 |
+
.qa-score-card h4 { margin: 0 0 6px; font-size: 12px; letter-spacing: 0.04em; text-transform: uppercase; color: var(--qa-muted); }
|
| 112 |
+
.qa-score-val { font-family: "JetBrains Mono", monospace; font-size: 22px; font-weight: 800; color: var(--qa-text); }
|
| 113 |
+
.qa-score-sub { font-family: "JetBrains Mono", monospace; font-size: 11.5px; color: var(--qa-muted); margin-top: 2px; }
|
| 114 |
+
.qa-score-card.optimal .qa-score-val { color: var(--qa-green); }
|
| 115 |
+
.qa-score-card.qaoa .qa-score-val { color: #67E8F9; }
|
| 116 |
+
.qa-score-card.greedy .qa-score-val { color: var(--qa-amber); }
|
| 117 |
+
|
| 118 |
+
.qa-section-title {
|
| 119 |
+
font-family: "Inter", sans-serif; font-weight: 800; font-size: 22px;
|
| 120 |
+
margin: 8px 0 2px; color: #FFFFFF; letter-spacing: -0.01em;
|
| 121 |
+
}
|
precomputed/benchmark_results.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
precomputed/dataset.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Verifier-only deps: the Space serves precomputed QAOA results and runs the
|
| 2 |
+
# pure-Python classical solvers (brute-force, greedy) live. qagent itself is
|
| 3 |
+
# installed --no-deps in the Dockerfile, so torch / pennylane / scipy are NOT
|
| 4 |
+
# pulled in -- the served paths do not need them, keeping the image small.
|
| 5 |
+
gradio>=5.0
|
| 6 |
+
numpy<2.1
|
| 7 |
+
matplotlib>=3.8
|
safety.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Lightweight rate limiting for the Space's live-solve path.
|
| 2 |
+
|
| 3 |
+
The Space serves precomputed QAOA results instantly, but it also runs the
|
| 4 |
+
pure-Python classical solvers (brute-force, greedy) live so visitors can confirm
|
| 5 |
+
the served numbers are real. Those solves are cheap (milliseconds), but a public
|
| 6 |
+
endpoint still warrants a guard against rapid-fire hammering. Two layers:
|
| 7 |
+
|
| 8 |
+
1. **Per-IP rate limit** - at most one live solve per ``window_seconds`` per
|
| 9 |
+
visitor IP (read from ``x-forwarded-for``, set by HF's reverse proxy).
|
| 10 |
+
2. **Global daily cap** - a generous ceiling on live solves per UTC day across
|
| 11 |
+
all visitors, persisted to JSON when a writable dir is available.
|
| 12 |
+
|
| 13 |
+
There is no IBM-quota guard here (this Space has no hardware path). Verdicts are
|
| 14 |
+
returned as a dataclass so the Gradio layer stays thin and the logic is trivially
|
| 15 |
+
unit-testable.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import json
|
| 21 |
+
import threading
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
from datetime import UTC, date, datetime
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
from typing import Literal
|
| 26 |
+
|
| 27 |
+
SafetyReason = Literal["rate_limited", "daily_cap"]
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@dataclass(frozen=True)
|
| 31 |
+
class SafetyVerdict:
|
| 32 |
+
"""Outcome of a :meth:`RateLimiter.check_and_register` call."""
|
| 33 |
+
|
| 34 |
+
allowed: bool
|
| 35 |
+
reason: SafetyReason | None
|
| 36 |
+
detail: str
|
| 37 |
+
daily_remaining: int
|
| 38 |
+
daily_cap: int
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class RateLimiter:
|
| 42 |
+
"""Per-IP + daily gate for the live-solve path. Thread-safe via one lock."""
|
| 43 |
+
|
| 44 |
+
def __init__(
|
| 45 |
+
self,
|
| 46 |
+
*,
|
| 47 |
+
window_seconds: int = 3,
|
| 48 |
+
daily_cap: int = 5000,
|
| 49 |
+
persist_path: Path | None = None,
|
| 50 |
+
) -> None:
|
| 51 |
+
if window_seconds < 0:
|
| 52 |
+
raise ValueError("window_seconds must be >= 0")
|
| 53 |
+
if daily_cap < 0:
|
| 54 |
+
raise ValueError("daily_cap must be >= 0")
|
| 55 |
+
self._window = window_seconds
|
| 56 |
+
self._cap = daily_cap
|
| 57 |
+
self._persist_path = persist_path
|
| 58 |
+
self._lock = threading.Lock()
|
| 59 |
+
self._last_ip: dict[str, float] = {}
|
| 60 |
+
self._day: date | None = None
|
| 61 |
+
self._count: int = 0
|
| 62 |
+
self._load_persisted()
|
| 63 |
+
|
| 64 |
+
def check_and_register(self, *, ip: str, now: datetime) -> SafetyVerdict:
|
| 65 |
+
"""Decide whether ``ip`` may run a live solve at ``now`` (commit-on-allow)."""
|
| 66 |
+
with self._lock:
|
| 67 |
+
self._roll_day_if_needed(now)
|
| 68 |
+
self._evict_stale_ips(now.timestamp())
|
| 69 |
+
|
| 70 |
+
if self._count >= self._cap:
|
| 71 |
+
return SafetyVerdict(
|
| 72 |
+
allowed=False,
|
| 73 |
+
reason="daily_cap",
|
| 74 |
+
detail=f"Daily limit of {self._cap} live solves reached. Resets midnight UTC.",
|
| 75 |
+
daily_remaining=0,
|
| 76 |
+
daily_cap=self._cap,
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
last = self._last_ip.get(ip)
|
| 80 |
+
if last is not None and (now.timestamp() - last) < self._window:
|
| 81 |
+
wait = self._window - int(now.timestamp() - last)
|
| 82 |
+
return SafetyVerdict(
|
| 83 |
+
allowed=False,
|
| 84 |
+
reason="rate_limited",
|
| 85 |
+
detail=f"Please wait {max(wait, 1)}s between live solves.",
|
| 86 |
+
daily_remaining=max(0, self._cap - self._count),
|
| 87 |
+
daily_cap=self._cap,
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
self._last_ip[ip] = now.timestamp()
|
| 91 |
+
self._count += 1
|
| 92 |
+
self._persist()
|
| 93 |
+
return SafetyVerdict(
|
| 94 |
+
allowed=True,
|
| 95 |
+
reason=None,
|
| 96 |
+
detail="ok",
|
| 97 |
+
daily_remaining=max(0, self._cap - self._count),
|
| 98 |
+
daily_cap=self._cap,
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
def daily_remaining(self, now: datetime) -> int:
|
| 102 |
+
with self._lock:
|
| 103 |
+
self._roll_day_if_needed(now)
|
| 104 |
+
return max(0, self._cap - self._count)
|
| 105 |
+
|
| 106 |
+
def daily_cap(self) -> int:
|
| 107 |
+
return self._cap
|
| 108 |
+
|
| 109 |
+
def _roll_day_if_needed(self, now: datetime) -> None:
|
| 110 |
+
today = now.astimezone(UTC).date()
|
| 111 |
+
if self._day != today:
|
| 112 |
+
self._day = today
|
| 113 |
+
self._count = 0
|
| 114 |
+
|
| 115 |
+
def _evict_stale_ips(self, now_ts: float) -> None:
|
| 116 |
+
if self._window <= 0:
|
| 117 |
+
self._last_ip.clear()
|
| 118 |
+
return
|
| 119 |
+
cutoff = now_ts - self._window
|
| 120 |
+
self._last_ip = {ip: ts for ip, ts in self._last_ip.items() if ts > cutoff}
|
| 121 |
+
|
| 122 |
+
def _load_persisted(self) -> None:
|
| 123 |
+
if self._persist_path is None:
|
| 124 |
+
return
|
| 125 |
+
try:
|
| 126 |
+
raw = json.loads(self._persist_path.read_text(encoding="utf-8"))
|
| 127 |
+
except (FileNotFoundError, json.JSONDecodeError):
|
| 128 |
+
return
|
| 129 |
+
if not isinstance(raw, dict):
|
| 130 |
+
return
|
| 131 |
+
try:
|
| 132 |
+
self._day = date.fromisoformat(str(raw.get("date")))
|
| 133 |
+
self._count = int(raw.get("count", 0))
|
| 134 |
+
except (TypeError, ValueError):
|
| 135 |
+
self._day = None
|
| 136 |
+
self._count = 0
|
| 137 |
+
|
| 138 |
+
def _persist(self) -> None:
|
| 139 |
+
if self._persist_path is None or self._day is None:
|
| 140 |
+
return
|
| 141 |
+
try:
|
| 142 |
+
self._persist_path.parent.mkdir(parents=True, exist_ok=True)
|
| 143 |
+
self._persist_path.write_text(
|
| 144 |
+
json.dumps({"date": self._day.isoformat(), "count": self._count}),
|
| 145 |
+
encoding="utf-8",
|
| 146 |
+
)
|
| 147 |
+
except OSError:
|
| 148 |
+
self._persist_path = None
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def default_persist_path() -> Path | None:
|
| 152 |
+
"""Return ``/data/qagent_quota.json`` when HF Persistent Storage is mounted."""
|
| 153 |
+
candidate = Path("/data")
|
| 154 |
+
if candidate.is_dir():
|
| 155 |
+
try:
|
| 156 |
+
test = candidate / ".qa_write_test"
|
| 157 |
+
test.write_text("x")
|
| 158 |
+
test.unlink()
|
| 159 |
+
except OSError:
|
| 160 |
+
return None
|
| 161 |
+
return candidate / "qagent_quota.json"
|
| 162 |
+
return None
|