quantcheck 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- quantcheck/__init__.py +3 -0
- quantcheck/auth/__init__.py +6 -0
- quantcheck/auth/base.py +74 -0
- quantcheck/auth/callback.py +73 -0
- quantcheck/auth/fake.py +40 -0
- quantcheck/auth/service.py +49 -0
- quantcheck/auth/store.py +63 -0
- quantcheck/auth/supabase.py +168 -0
- quantcheck/bench.py +38 -0
- quantcheck/candidates.py +138 -0
- quantcheck/cli.py +251 -0
- quantcheck/config.py +63 -0
- quantcheck/executors/__init__.py +0 -0
- quantcheck/hardware.py +52 -0
- quantcheck/limits.py +19 -0
- quantcheck/pipeline.py +172 -0
- quantcheck/prompt.py +67 -0
- quantcheck/recommend.py +131 -0
- quantcheck/report/__init__.py +0 -0
- quantcheck/report/html.py +38 -0
- quantcheck/report/templates/report.html.j2 +272 -0
- quantcheck/report/terminal.py +90 -0
- quantcheck/report/tokens.py +41 -0
- quantcheck/report/view.py +161 -0
- quantcheck/runners/__init__.py +3 -0
- quantcheck/runners/base.py +87 -0
- quantcheck/runners/fake.py +68 -0
- quantcheck/runners/llamacpp_runner.py +185 -0
- quantcheck/runners/mlx_runner.py +153 -0
- quantcheck/runners/toolparse.py +107 -0
- quantcheck/scoring/__init__.py +0 -0
- quantcheck/scoring/checks.py +342 -0
- quantcheck/scoring/fake_judge.py +50 -0
- quantcheck/scoring/judge.py +171 -0
- quantcheck/scoring/language.py +99 -0
- quantcheck/scoring/models.py +92 -0
- quantcheck/scoring/score.py +167 -0
- quantcheck/scoring/stats.py +60 -0
- quantcheck/settings.py +14 -0
- quantcheck/store.py +88 -0
- quantcheck/tests_io.py +169 -0
- quantcheck/ui/__init__.py +1 -0
- quantcheck/ui/app.py +534 -0
- quantcheck/ui/catalog.py +47 -0
- quantcheck/ui/chat.py +211 -0
- quantcheck/ui/compare.py +63 -0
- quantcheck/ui/downloads.py +172 -0
- quantcheck/ui/jobs.py +173 -0
- quantcheck/ui/modeldetail.py +97 -0
- quantcheck/ui/reviews.py +59 -0
- quantcheck/ui/security.py +45 -0
- quantcheck/ui/static/chat.js +312 -0
- quantcheck/ui/static/fonts/JetBrainsMono-latin-b87346.woff2 +0 -0
- quantcheck/ui/static/fonts/JetBrainsMono-latin-ext-9326b4.woff2 +0 -0
- quantcheck/ui/static/fonts/NotoSansDevanagari-devanagari-3819bb.woff2 +0 -0
- quantcheck/ui/static/fonts/NotoSansDevanagari-latin-ext-542103.woff2 +0 -0
- quantcheck/ui/static/fonts/NotoSansDevanagari-latin-f3aaed.woff2 +0 -0
- quantcheck/ui/static/fonts/NotoSansTamil-latin-17e6dc.woff2 +0 -0
- quantcheck/ui/static/fonts/NotoSansTamil-latin-ext-027c12.woff2 +0 -0
- quantcheck/ui/static/fonts/NotoSansTamil-tamil-a57d5e.woff2 +0 -0
- quantcheck/ui/static/fonts/Outfit-latin-ebadd8.woff2 +0 -0
- quantcheck/ui/static/fonts/Outfit-latin-ext-744997.woff2 +0 -0
- quantcheck/ui/static/fonts/README.md +14 -0
- quantcheck/ui/static/fonts.css +228 -0
- quantcheck/ui/static/index.html +24 -0
- quantcheck/ui/static/lab.css +768 -0
- quantcheck/ui/static/lab.js +896 -0
- quantcheck/ui/static/logo.svg +5 -0
- quantcheck/ui/static/review.js +127 -0
- quantcheck/ui/static/setup.js +132 -0
- quantcheck/ui/static/testsets.js +527 -0
- quantcheck/ui/summary.py +104 -0
- quantcheck/ui/system.py +101 -0
- quantcheck/ui/testsets.py +243 -0
- quantcheck-0.0.1.dist-info/METADATA +115 -0
- quantcheck-0.0.1.dist-info/RECORD +79 -0
- quantcheck-0.0.1.dist-info/WHEEL +4 -0
- quantcheck-0.0.1.dist-info/entry_points.txt +2 -0
- quantcheck-0.0.1.dist-info/licenses/LICENSE +202 -0
quantcheck/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"""Accounts (F9a): sign-in providers, the Keychain session store, and the CLI helpers."""
|
|
2
|
+
|
|
3
|
+
from quantcheck.auth import fake, supabase # noqa: F401 (importing registers providers)
|
|
4
|
+
from quantcheck.auth.base import AuthError, NetworkUnavailable, NotSignedIn, Session
|
|
5
|
+
|
|
6
|
+
__all__ = ["AuthError", "NetworkUnavailable", "NotSignedIn", "Session"]
|
quantcheck/auth/base.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Sign-in interface (F9a). A provider turns a browser sign-in into a Session.
|
|
2
|
+
|
|
3
|
+
Only identity and plan data live in a Session: email, name, plan and the tokens. Prompts,
|
|
4
|
+
answers, models and reports are never part of it.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import time
|
|
10
|
+
from abc import ABC, abstractmethod
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
|
|
13
|
+
from pydantic import BaseModel
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class AuthError(Exception):
|
|
17
|
+
"""Sign-in failed or was refused. The message is safe to show to the user."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class NetworkUnavailable(AuthError):
|
|
21
|
+
"""The sign-in service could not be reached (offline, DNS, timeout)."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class NotSignedIn(AuthError):
|
|
25
|
+
"""No usable session on this machine."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Session(BaseModel):
|
|
29
|
+
"""Who is signed in on this machine."""
|
|
30
|
+
|
|
31
|
+
access_token: str
|
|
32
|
+
refresh_token: str
|
|
33
|
+
expires_at: float # unix seconds when access_token stops being valid
|
|
34
|
+
email: str
|
|
35
|
+
name: str | None = None
|
|
36
|
+
plan: str = "free"
|
|
37
|
+
provider: str = ""
|
|
38
|
+
|
|
39
|
+
def expired(self, now: float | None = None, margin_s: float = 60.0) -> bool:
|
|
40
|
+
"""True when the access token is expired or about to be."""
|
|
41
|
+
return (time.time() if now is None else now) + margin_s >= self.expires_at
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class AuthProvider(ABC):
|
|
45
|
+
"""One sign-in service (Supabase now; others later). Registered by name."""
|
|
46
|
+
|
|
47
|
+
name: str
|
|
48
|
+
|
|
49
|
+
@abstractmethod
|
|
50
|
+
def login(self, open_url: Callable[[str], object], idp: str = "google") -> Session:
|
|
51
|
+
"""Run the browser sign-in. ``open_url`` opens the given URL in the user's browser."""
|
|
52
|
+
|
|
53
|
+
@abstractmethod
|
|
54
|
+
def refresh(self, session: Session) -> Session:
|
|
55
|
+
"""Get a new access token. Raises NetworkUnavailable offline, AuthError if refused."""
|
|
56
|
+
|
|
57
|
+
@abstractmethod
|
|
58
|
+
def logout(self, session: Session) -> None:
|
|
59
|
+
"""Revoke the session on the server if possible. Never raises for network problems."""
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
_PROVIDERS: dict[str, Callable[[], AuthProvider]] = {}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def register_provider(name: str, factory: Callable[[], AuthProvider]) -> None:
|
|
66
|
+
"""Register a provider factory under ``name``."""
|
|
67
|
+
_PROVIDERS[name] = factory
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def get_provider(name: str) -> AuthProvider:
|
|
71
|
+
"""Build the provider called ``name``."""
|
|
72
|
+
if name not in _PROVIDERS:
|
|
73
|
+
raise AuthError(f"unknown auth provider '{name}'. Known: {sorted(_PROVIDERS)}")
|
|
74
|
+
return _PROVIDERS[name]()
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""One-shot local web server that catches the browser's redirect after sign-in."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import threading
|
|
6
|
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
7
|
+
from urllib.parse import parse_qs, urlparse
|
|
8
|
+
|
|
9
|
+
from quantcheck.auth.base import AuthError
|
|
10
|
+
|
|
11
|
+
_PAGE = (
|
|
12
|
+
"<!doctype html><meta charset=utf-8><title>quantcheck</title>"
|
|
13
|
+
"<body style='font-family:system-ui;margin:3rem'><h2>{title}</h2><p>{text}</p></body>"
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class CallbackServer:
|
|
18
|
+
"""Listens on 127.0.0.1 (random free port) for exactly one redirect.
|
|
19
|
+
|
|
20
|
+
Query values are returned as a plain dict. Nothing is logged and the server only ever
|
|
21
|
+
accepts connections from this machine.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
def __init__(self, path: str = "/callback") -> None:
|
|
25
|
+
self.path = path
|
|
26
|
+
self.result: dict[str, str] | None = None
|
|
27
|
+
self._done = threading.Event()
|
|
28
|
+
outer = self
|
|
29
|
+
|
|
30
|
+
class Handler(BaseHTTPRequestHandler):
|
|
31
|
+
def do_GET(self) -> None: # noqa: N802 (http.server API)
|
|
32
|
+
url = urlparse(self.path)
|
|
33
|
+
if url.path != outer.path:
|
|
34
|
+
self.send_response(404)
|
|
35
|
+
self.end_headers()
|
|
36
|
+
return
|
|
37
|
+
outer.result = {k: v[0] for k, v in parse_qs(url.query).items()}
|
|
38
|
+
ok = "error" not in outer.result
|
|
39
|
+
body = _PAGE.format(
|
|
40
|
+
title="Signed in" if ok else "Sign-in failed",
|
|
41
|
+
text="You can close this tab and return to the terminal."
|
|
42
|
+
if ok
|
|
43
|
+
else "Return to the terminal for details.",
|
|
44
|
+
).encode()
|
|
45
|
+
self.send_response(200)
|
|
46
|
+
self.send_header("Content-Type", "text/html; charset=utf-8")
|
|
47
|
+
self.send_header("Content-Length", str(len(body)))
|
|
48
|
+
self.end_headers()
|
|
49
|
+
self.wfile.write(body)
|
|
50
|
+
outer._done.set()
|
|
51
|
+
|
|
52
|
+
def log_message(self, *args: object) -> None: # keep the terminal quiet
|
|
53
|
+
return
|
|
54
|
+
|
|
55
|
+
self._server = HTTPServer(("127.0.0.1", 0), Handler)
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def url(self) -> str:
|
|
59
|
+
"""The redirect URL to give to the sign-in service."""
|
|
60
|
+
return f"http://127.0.0.1:{self._server.server_address[1]}{self.path}"
|
|
61
|
+
|
|
62
|
+
def wait(self, timeout_s: float = 300.0) -> dict[str, str]:
|
|
63
|
+
"""Serve until the redirect arrives. Raises AuthError on timeout."""
|
|
64
|
+
thread = threading.Thread(target=self._server.serve_forever, daemon=True)
|
|
65
|
+
thread.start()
|
|
66
|
+
try:
|
|
67
|
+
if not self._done.wait(timeout_s):
|
|
68
|
+
raise AuthError("sign-in timed out: no answer from the browser in time")
|
|
69
|
+
assert self.result is not None
|
|
70
|
+
return self.result
|
|
71
|
+
finally:
|
|
72
|
+
self._server.shutdown()
|
|
73
|
+
self._server.server_close()
|
quantcheck/auth/fake.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Auth provider for tests: no browser, no network."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
|
|
8
|
+
from quantcheck.auth.base import AuthError, AuthProvider, NetworkUnavailable, Session
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class FakeAuthProvider(AuthProvider):
|
|
12
|
+
"""Returns canned sessions. ``offline`` and ``refuse`` simulate refresh failures."""
|
|
13
|
+
|
|
14
|
+
name = "fake"
|
|
15
|
+
|
|
16
|
+
def __init__(self, email: str = "raja@example.com", offline: bool = False,
|
|
17
|
+
refuse: bool = False) -> None: # fmt: skip
|
|
18
|
+
self.email, self.offline, self.refuse = email, offline, refuse
|
|
19
|
+
self.opened: list[str] = []
|
|
20
|
+
self.logged_out = 0
|
|
21
|
+
|
|
22
|
+
def _session(self) -> Session:
|
|
23
|
+
return Session(access_token="fake-access", refresh_token="fake-refresh",
|
|
24
|
+
expires_at=time.time() + 3600, email=self.email, name="Raja",
|
|
25
|
+
provider=self.name) # fmt: skip
|
|
26
|
+
|
|
27
|
+
def login(self, open_url: Callable[[str], object], idp: str = "google") -> Session:
|
|
28
|
+
open_url(f"fake://sign-in/{idp}")
|
|
29
|
+
self.opened.append(idp)
|
|
30
|
+
return self._session()
|
|
31
|
+
|
|
32
|
+
def refresh(self, session: Session) -> Session:
|
|
33
|
+
if self.offline:
|
|
34
|
+
raise NetworkUnavailable("offline")
|
|
35
|
+
if self.refuse:
|
|
36
|
+
raise AuthError("refresh token revoked")
|
|
37
|
+
return self._session()
|
|
38
|
+
|
|
39
|
+
def logout(self, session: Session) -> None:
|
|
40
|
+
self.logged_out += 1
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""What the CLI asks of the auth layer: is someone signed in, and is the session usable."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
|
|
7
|
+
from quantcheck.auth.base import (
|
|
8
|
+
AuthError,
|
|
9
|
+
AuthProvider,
|
|
10
|
+
NetworkUnavailable,
|
|
11
|
+
NotSignedIn,
|
|
12
|
+
Session,
|
|
13
|
+
get_provider,
|
|
14
|
+
)
|
|
15
|
+
from quantcheck.auth.store import KeyringSessionStore, SessionStore
|
|
16
|
+
|
|
17
|
+
DEFAULT_PROVIDER = "supabase"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def default_store() -> SessionStore:
|
|
21
|
+
"""The session store of this machine (the Keychain)."""
|
|
22
|
+
return KeyringSessionStore()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def default_provider() -> AuthProvider:
|
|
26
|
+
"""The configured provider (env QUANTCHECK_AUTH_PROVIDER, default supabase)."""
|
|
27
|
+
return get_provider(os.environ.get("QUANTCHECK_AUTH_PROVIDER", DEFAULT_PROVIDER))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def require_session(store: SessionStore, provider: AuthProvider) -> Session:
|
|
31
|
+
"""Return the signed-in session, refreshing it when it expired and we are online.
|
|
32
|
+
|
|
33
|
+
Offline with an expired token still works: the tool runs offline after sign-in. If the
|
|
34
|
+
service refuses the refresh (revoked, expired for good) the session is removed.
|
|
35
|
+
"""
|
|
36
|
+
session = store.load()
|
|
37
|
+
if session is None:
|
|
38
|
+
raise NotSignedIn("You are not signed in. Run `quantcheck login` first.")
|
|
39
|
+
if not session.expired():
|
|
40
|
+
return session
|
|
41
|
+
try:
|
|
42
|
+
fresh = provider.refresh(session)
|
|
43
|
+
except NetworkUnavailable:
|
|
44
|
+
return session
|
|
45
|
+
except AuthError as e:
|
|
46
|
+
store.clear()
|
|
47
|
+
raise NotSignedIn(f"Your sign-in is no longer valid ({e}). Run `quantcheck login`.") from e
|
|
48
|
+
store.save(fresh)
|
|
49
|
+
return fresh
|
quantcheck/auth/store.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Where the session lives: the macOS Keychain (never a plain file)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Protocol
|
|
6
|
+
|
|
7
|
+
from quantcheck.auth.base import Session
|
|
8
|
+
|
|
9
|
+
SERVICE = "quantcheck"
|
|
10
|
+
ACCOUNT = "session"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class SessionStore(Protocol):
|
|
14
|
+
"""Saves, loads and removes the one session of this machine."""
|
|
15
|
+
|
|
16
|
+
def load(self) -> Session | None: ...
|
|
17
|
+
def save(self, session: Session) -> None: ...
|
|
18
|
+
def clear(self) -> None: ...
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class KeyringSessionStore:
|
|
22
|
+
"""Session as JSON in the OS keychain through the ``keyring`` library."""
|
|
23
|
+
|
|
24
|
+
def load(self) -> Session | None:
|
|
25
|
+
import keyring
|
|
26
|
+
|
|
27
|
+
raw = keyring.get_password(SERVICE, ACCOUNT)
|
|
28
|
+
if not raw:
|
|
29
|
+
return None
|
|
30
|
+
try:
|
|
31
|
+
return Session.model_validate_json(raw)
|
|
32
|
+
except ValueError: # damaged entry: treat as signed out
|
|
33
|
+
return None
|
|
34
|
+
|
|
35
|
+
def save(self, session: Session) -> None:
|
|
36
|
+
import keyring
|
|
37
|
+
|
|
38
|
+
keyring.set_password(SERVICE, ACCOUNT, session.model_dump_json())
|
|
39
|
+
|
|
40
|
+
def clear(self) -> None:
|
|
41
|
+
import keyring
|
|
42
|
+
from keyring.errors import PasswordDeleteError
|
|
43
|
+
|
|
44
|
+
try:
|
|
45
|
+
keyring.delete_password(SERVICE, ACCOUNT)
|
|
46
|
+
except PasswordDeleteError:
|
|
47
|
+
pass # nothing stored
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class MemorySessionStore:
|
|
51
|
+
"""In-memory store for tests."""
|
|
52
|
+
|
|
53
|
+
def __init__(self, session: Session | None = None) -> None:
|
|
54
|
+
self.session = session
|
|
55
|
+
|
|
56
|
+
def load(self) -> Session | None:
|
|
57
|
+
return self.session
|
|
58
|
+
|
|
59
|
+
def save(self, session: Session) -> None:
|
|
60
|
+
self.session = session
|
|
61
|
+
|
|
62
|
+
def clear(self) -> None:
|
|
63
|
+
self.session = None
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""Supabase Auth provider: browser sign-in with PKCE, plain HTTPS, no SDK.
|
|
2
|
+
|
|
3
|
+
Settings come from the environment (never from code):
|
|
4
|
+
QUANTCHECK_SUPABASE_URL e.g. https://<project>.supabase.co
|
|
5
|
+
QUANTCHECK_SUPABASE_ANON_KEY the project's public anon key
|
|
6
|
+
|
|
7
|
+
Status: written against Supabase's published OpenAPI spec and tested with mocked HTTP only.
|
|
8
|
+
Not yet verified against a live project: whether /authorize accepts code_challenge (the spec
|
|
9
|
+
does not list it; supabase-js sends it), and which user_metadata key holds the name.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import base64
|
|
15
|
+
import hashlib
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import secrets
|
|
19
|
+
import time
|
|
20
|
+
import urllib.error
|
|
21
|
+
import urllib.parse
|
|
22
|
+
import urllib.request
|
|
23
|
+
from collections.abc import Callable
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
from quantcheck.auth.base import (
|
|
27
|
+
AuthError,
|
|
28
|
+
AuthProvider,
|
|
29
|
+
NetworkUnavailable,
|
|
30
|
+
Session,
|
|
31
|
+
register_provider,
|
|
32
|
+
)
|
|
33
|
+
from quantcheck.auth.callback import CallbackServer
|
|
34
|
+
|
|
35
|
+
TIMEOUT_S = 15.0
|
|
36
|
+
_SCOPES = {"google": "email profile", "github": "user:email"}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def http_json(method: str, url: str, headers: dict[str, str],
|
|
40
|
+
body: dict[str, Any] | None = None) -> tuple[int, dict[str, Any]]: # fmt: skip
|
|
41
|
+
"""One JSON request. Returns (status, json). Raises NetworkUnavailable if unreachable."""
|
|
42
|
+
data = json.dumps(body).encode() if body is not None else None
|
|
43
|
+
req = urllib.request.Request(url, data=data, method=method)
|
|
44
|
+
for k, v in headers.items():
|
|
45
|
+
req.add_header(k, v)
|
|
46
|
+
if data is not None:
|
|
47
|
+
req.add_header("Content-Type", "application/json")
|
|
48
|
+
try:
|
|
49
|
+
with urllib.request.urlopen(req, timeout=TIMEOUT_S) as resp: # noqa: S310 (https)
|
|
50
|
+
raw = resp.read()
|
|
51
|
+
return resp.status, json.loads(raw) if raw else {}
|
|
52
|
+
except urllib.error.HTTPError as e:
|
|
53
|
+
try:
|
|
54
|
+
payload = json.loads(e.read() or b"{}")
|
|
55
|
+
except ValueError:
|
|
56
|
+
payload = {}
|
|
57
|
+
return e.code, payload if isinstance(payload, dict) else {}
|
|
58
|
+
except (urllib.error.URLError, TimeoutError, OSError) as e:
|
|
59
|
+
raise NetworkUnavailable(f"cannot reach the sign-in service: {e}") from e
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def pkce_pair() -> tuple[str, str]:
|
|
63
|
+
"""A fresh (code_verifier, code_challenge) using the S256 method."""
|
|
64
|
+
verifier = secrets.token_urlsafe(64) # 86 chars, within the 43-128 PKCE limit
|
|
65
|
+
digest = hashlib.sha256(verifier.encode()).digest()
|
|
66
|
+
return verifier, base64.urlsafe_b64encode(digest).rstrip(b"=").decode()
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class SupabaseAuth(AuthProvider):
|
|
70
|
+
"""Sign in through a Supabase project (Google or GitHub)."""
|
|
71
|
+
|
|
72
|
+
name = "supabase"
|
|
73
|
+
|
|
74
|
+
def __init__(self, url: str | None = None, anon_key: str | None = None,
|
|
75
|
+
request: Callable[..., tuple[int, dict[str, Any]]] = http_json,
|
|
76
|
+
wait_for_redirect: Callable[[CallbackServer], dict[str, str]] | None = None,
|
|
77
|
+
) -> None: # fmt: skip
|
|
78
|
+
self.url = (url or os.environ.get("QUANTCHECK_SUPABASE_URL", "")).rstrip("/")
|
|
79
|
+
self.anon_key = anon_key or os.environ.get("QUANTCHECK_SUPABASE_ANON_KEY", "")
|
|
80
|
+
self._request = request
|
|
81
|
+
self._wait = wait_for_redirect or (lambda server: server.wait())
|
|
82
|
+
|
|
83
|
+
def _need_config(self) -> None:
|
|
84
|
+
if not self.url or not self.anon_key:
|
|
85
|
+
raise AuthError(
|
|
86
|
+
"sign-in is not configured: set QUANTCHECK_SUPABASE_URL and "
|
|
87
|
+
"QUANTCHECK_SUPABASE_ANON_KEY"
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
def _headers(self, token: str | None = None) -> dict[str, str]:
|
|
91
|
+
h = {"apikey": self.anon_key}
|
|
92
|
+
if token:
|
|
93
|
+
h["Authorization"] = f"Bearer {token}"
|
|
94
|
+
return h
|
|
95
|
+
|
|
96
|
+
def login(self, open_url: Callable[[str], object], idp: str = "google") -> Session:
|
|
97
|
+
self._need_config()
|
|
98
|
+
if idp not in _SCOPES:
|
|
99
|
+
raise AuthError(f"unknown sign-in method '{idp}'. Use one of: {sorted(_SCOPES)}")
|
|
100
|
+
verifier, challenge = pkce_pair()
|
|
101
|
+
server = CallbackServer()
|
|
102
|
+
query = urllib.parse.urlencode({
|
|
103
|
+
"provider": idp,
|
|
104
|
+
"scopes": _SCOPES[idp],
|
|
105
|
+
"redirect_to": server.url,
|
|
106
|
+
"code_challenge": challenge,
|
|
107
|
+
"code_challenge_method": "s256",
|
|
108
|
+
}) # fmt: skip
|
|
109
|
+
open_url(f"{self.url}/auth/v1/authorize?{query}")
|
|
110
|
+
params = self._wait(server)
|
|
111
|
+
if "error" in params:
|
|
112
|
+
raise AuthError(params.get("error_description") or params["error"])
|
|
113
|
+
code = params.get("code")
|
|
114
|
+
if not code:
|
|
115
|
+
raise AuthError("the browser came back without a sign-in code")
|
|
116
|
+
status, data = self._request(
|
|
117
|
+
"POST", f"{self.url}/auth/v1/token?grant_type=pkce", self._headers(),
|
|
118
|
+
{"auth_code": code, "code_verifier": verifier},
|
|
119
|
+
) # fmt: skip
|
|
120
|
+
if status != 200:
|
|
121
|
+
raise AuthError(_why("sign-in was refused", data))
|
|
122
|
+
return self._to_session(data)
|
|
123
|
+
|
|
124
|
+
def refresh(self, session: Session) -> Session:
|
|
125
|
+
self._need_config()
|
|
126
|
+
status, data = self._request(
|
|
127
|
+
"POST", f"{self.url}/auth/v1/token?grant_type=refresh_token", self._headers(),
|
|
128
|
+
{"refresh_token": session.refresh_token},
|
|
129
|
+
) # fmt: skip
|
|
130
|
+
if status >= 500:
|
|
131
|
+
raise NetworkUnavailable(f"sign-in service error ({status})")
|
|
132
|
+
if status != 200:
|
|
133
|
+
raise AuthError(_why("refresh was refused", data))
|
|
134
|
+
fresh = self._to_session(data)
|
|
135
|
+
return fresh.model_copy(update={"plan": session.plan})
|
|
136
|
+
|
|
137
|
+
def logout(self, session: Session) -> None:
|
|
138
|
+
if not self.url or not self.anon_key:
|
|
139
|
+
return
|
|
140
|
+
try:
|
|
141
|
+
self._request("POST", f"{self.url}/auth/v1/logout?scope=local",
|
|
142
|
+
self._headers(session.access_token)) # fmt: skip
|
|
143
|
+
except AuthError:
|
|
144
|
+
pass # signed out locally either way
|
|
145
|
+
|
|
146
|
+
def _to_session(self, data: dict[str, Any]) -> Session:
|
|
147
|
+
user = data.get("user") or {}
|
|
148
|
+
meta = user.get("user_metadata") or {}
|
|
149
|
+
email = user.get("email")
|
|
150
|
+
if not data.get("access_token") or not data.get("refresh_token") or not email:
|
|
151
|
+
raise AuthError("the sign-in service sent an incomplete answer")
|
|
152
|
+
expires_at = data.get("expires_at") or time.time() + float(data.get("expires_in", 3600))
|
|
153
|
+
return Session(
|
|
154
|
+
access_token=data["access_token"],
|
|
155
|
+
refresh_token=data["refresh_token"],
|
|
156
|
+
expires_at=float(expires_at),
|
|
157
|
+
email=email,
|
|
158
|
+
name=meta.get("full_name") or meta.get("name"),
|
|
159
|
+
provider=self.name,
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _why(prefix: str, data: dict[str, Any]) -> str:
|
|
164
|
+
detail = data.get("error_description") or data.get("msg") or data.get("error")
|
|
165
|
+
return f"{prefix}: {detail}" if detail else prefix
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
register_provider("supabase", SupabaseAuth)
|
quantcheck/bench.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Speed, memory and size per version (F7), summarised from the saved answers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from statistics import median
|
|
6
|
+
|
|
7
|
+
from pydantic import BaseModel
|
|
8
|
+
|
|
9
|
+
from quantcheck.store import CandidateRun
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class BenchSummary(BaseModel):
|
|
13
|
+
"""One row of the speed/memory table. None means "not measured"."""
|
|
14
|
+
|
|
15
|
+
label: str
|
|
16
|
+
tokens_per_s: float | None = None # median answer tokens per second
|
|
17
|
+
ttft_s: float | None = None # median time to first token
|
|
18
|
+
peak_memory_mb: float | None = None # highest peak over all prompts
|
|
19
|
+
file_size_mb: float | None = None
|
|
20
|
+
n: int = 0 # answers measured
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _med(values: list[float]) -> float | None:
|
|
24
|
+
return round(median(values), 3) if values else None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def summarize(run: CandidateRun) -> BenchSummary:
|
|
28
|
+
"""Median speed and worst-case memory over a version's answers."""
|
|
29
|
+
gens = [g for a in run.answers for g in (a.generation, a.followup) if g and not g.error]
|
|
30
|
+
mem = [g.peak_memory_mb for g in gens if g.peak_memory_mb is not None]
|
|
31
|
+
return BenchSummary(
|
|
32
|
+
label=run.label,
|
|
33
|
+
tokens_per_s=_med([g.gen_tps for g in gens if g.gen_tps]),
|
|
34
|
+
ttft_s=_med([g.ttft_s for g in gens if g.ttft_s is not None]),
|
|
35
|
+
peak_memory_mb=max(mem) if mem else None,
|
|
36
|
+
file_size_mb=run.file_size_mb,
|
|
37
|
+
n=len(gens),
|
|
38
|
+
)
|
quantcheck/candidates.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""Candidate: one model setup under test (Phase 1: a model version).
|
|
2
|
+
|
|
3
|
+
``resolve_candidates`` turns a model plus a list of version labels into
|
|
4
|
+
candidates, from a local folder or Hugging Face ids. It does no network I/O:
|
|
5
|
+
whether a Hugging Face repo really exists is found out when a runner loads it,
|
|
6
|
+
and a missing one is then skipped with a clear message.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from pydantic import BaseModel, Field
|
|
15
|
+
|
|
16
|
+
from quantcheck import limits
|
|
17
|
+
|
|
18
|
+
FORMATS = {"mlx": "mlx", "llamacpp": "gguf"} # runtime name -> model file format
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Candidate(BaseModel):
|
|
22
|
+
"""What is being tested. Later phases add serving settings and hardware."""
|
|
23
|
+
|
|
24
|
+
model: str # Hugging Face repo id or local path
|
|
25
|
+
format: str = "mlx" # mlx | gguf
|
|
26
|
+
quantization: str = "bf16" # the label, e.g. 8bit, 4bit, Q4_K_M
|
|
27
|
+
bits: int | None = None # parsed from the label; used to find the largest version
|
|
28
|
+
extra: dict = Field(default_factory=dict) # e.g. {"file_pattern": "*Q4_K_M*.gguf"}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Resolution(BaseModel):
|
|
32
|
+
"""Result of resolving versions: usable candidates plus clear skip reasons."""
|
|
33
|
+
|
|
34
|
+
candidates: list[Candidate]
|
|
35
|
+
skipped: dict[str, str] = Field(default_factory=dict) # label -> why
|
|
36
|
+
|
|
37
|
+
def largest(self) -> Candidate | None:
|
|
38
|
+
"""Highest-bit candidate: the default reference when no expected answer exists."""
|
|
39
|
+
known = [c for c in self.candidates if c.bits is not None]
|
|
40
|
+
return max(known, key=lambda c: c.bits or 0) if known else None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def parse_bits(label: str) -> int | None:
|
|
44
|
+
"""Bits per weight from a label: ``4bit`` -> 4, ``Q6_K`` -> 6, ``bf16`` -> 16."""
|
|
45
|
+
s = label.strip().lower()
|
|
46
|
+
if m := re.match(r"^(\d+)\s*-?\s*bit$", s):
|
|
47
|
+
return int(m.group(1))
|
|
48
|
+
if m := re.match(r"^i?q(\d+)", s):
|
|
49
|
+
return int(m.group(1))
|
|
50
|
+
if m := re.match(r"^b?f(16|32)$", s):
|
|
51
|
+
return int(m.group(1))
|
|
52
|
+
return None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _split_version(entry: str) -> tuple[str, str | None]:
|
|
56
|
+
"""``"4bit=org/repo"`` -> ("4bit", "org/repo"); ``"4bit"`` -> ("4bit", None)."""
|
|
57
|
+
label, sep, target = entry.partition("=")
|
|
58
|
+
return label.strip(), (target.strip() if sep else None)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _local_mlx(root: Path, label: str) -> Path | list[Path]:
|
|
62
|
+
subs = [d for d in sorted(root.iterdir()) if d.is_dir()]
|
|
63
|
+
exact = [d for d in subs if d.name.lower() == label.lower()]
|
|
64
|
+
if exact:
|
|
65
|
+
return exact[0]
|
|
66
|
+
return [d for d in subs if re.search(rf"(^|[-_.]){re.escape(label)}($|[-_.])", d.name, re.I)]
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _local_gguf(root: Path, label: str) -> list[Path]:
|
|
70
|
+
return [f for f in sorted(root.glob("*.gguf")) if label.lower() in f.name.lower()]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _resolve_local(root: Path, label: str, fmt: str) -> tuple[Candidate | None, str | None]:
|
|
74
|
+
found = _local_mlx(root, label) if fmt == "mlx" else _local_gguf(root, label)
|
|
75
|
+
if isinstance(found, Path):
|
|
76
|
+
found = [found]
|
|
77
|
+
if not found:
|
|
78
|
+
kind = "folder" if fmt == "mlx" else ".gguf file"
|
|
79
|
+
return None, f"no {kind} for '{label}' in {root}"
|
|
80
|
+
if len(found) > 1:
|
|
81
|
+
names = ", ".join(p.name for p in found)
|
|
82
|
+
return None, f"'{label}' is ambiguous in {root}: {names}"
|
|
83
|
+
return (
|
|
84
|
+
Candidate(model=str(found[0]), format=fmt, quantization=label, bits=parse_bits(label)),
|
|
85
|
+
None,
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _resolve_remote(model: str, label: str, target: str | None, fmt: str) -> Candidate:
|
|
90
|
+
if fmt == "mlx":
|
|
91
|
+
repo = target or f"{model}-{label}" # mlx-community naming: Qwen3-8B-4bit
|
|
92
|
+
return Candidate(model=repo, format=fmt, quantization=label, bits=parse_bits(label))
|
|
93
|
+
return Candidate(
|
|
94
|
+
model=target or model,
|
|
95
|
+
format=fmt,
|
|
96
|
+
quantization=label,
|
|
97
|
+
bits=parse_bits(label),
|
|
98
|
+
extra={"file_pattern": f"*{label}*.gguf"},
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def resolve_candidates(model: str, versions: list[str], runtime: str = "mlx") -> Resolution:
|
|
103
|
+
"""Turn ``model`` + version labels into candidates.
|
|
104
|
+
|
|
105
|
+
``model`` is a local folder holding one sub-folder (MLX) or ``.gguf`` file (GGUF)
|
|
106
|
+
per version, or a Hugging Face repo id. A version may be ``label`` or
|
|
107
|
+
``label=repo_or_path`` to point at an exact repo.
|
|
108
|
+
"""
|
|
109
|
+
if runtime not in FORMATS:
|
|
110
|
+
raise ValueError(f"Unknown runtime '{runtime}'. Known: {sorted(FORMATS)}")
|
|
111
|
+
if not versions:
|
|
112
|
+
raise ValueError("versions is empty")
|
|
113
|
+
if len(versions) > limits.MAX_VERSIONS:
|
|
114
|
+
raise ValueError(f"{len(versions)} versions; the limit is {limits.MAX_VERSIONS} per test")
|
|
115
|
+
fmt = FORMATS[runtime]
|
|
116
|
+
root = Path(model).expanduser()
|
|
117
|
+
is_local = root.is_dir()
|
|
118
|
+
|
|
119
|
+
candidates: list[Candidate] = []
|
|
120
|
+
skipped: dict[str, str] = {}
|
|
121
|
+
seen: set[str] = set()
|
|
122
|
+
for entry in versions:
|
|
123
|
+
label, target = _split_version(entry)
|
|
124
|
+
if not label or label in seen:
|
|
125
|
+
skipped[label or entry] = "empty or duplicate version label"
|
|
126
|
+
continue
|
|
127
|
+
seen.add(label)
|
|
128
|
+
if target:
|
|
129
|
+
candidates.append(_resolve_remote(model, label, target, fmt))
|
|
130
|
+
elif is_local:
|
|
131
|
+
cand, why = _resolve_local(root, label, fmt)
|
|
132
|
+
if cand:
|
|
133
|
+
candidates.append(cand)
|
|
134
|
+
else:
|
|
135
|
+
skipped[label] = why or "not found"
|
|
136
|
+
else:
|
|
137
|
+
candidates.append(_resolve_remote(model, label, None, fmt))
|
|
138
|
+
return Resolution(candidates=candidates, skipped=skipped)
|