qsiv-runtime 0.1.0__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.
- qsiv_runtime/__init__.py +20 -0
- qsiv_runtime/__main__.py +8 -0
- qsiv_runtime/_download.py +37 -0
- qsiv_runtime/_launch.py +61 -0
- qsiv_runtime/_pins.py +10 -0
- qsiv_runtime/_ports.py +142 -0
- qsiv_runtime/_preflight.py +152 -0
- qsiv_runtime/_protocol.py +80 -0
- qsiv_runtime/cli.py +82 -0
- qsiv_runtime/client.py +308 -0
- qsiv_runtime/data/qsiv-linux-py312.lock +71 -0
- qsiv_runtime/doctor.py +93 -0
- qsiv_runtime/errors.py +45 -0
- qsiv_runtime/paths.py +105 -0
- qsiv_runtime/py.typed +0 -0
- qsiv_runtime/service.py +319 -0
- qsiv_runtime/setup.py +145 -0
- qsiv_runtime-0.1.0.dist-info/METADATA +123 -0
- qsiv_runtime-0.1.0.dist-info/RECORD +23 -0
- qsiv_runtime-0.1.0.dist-info/WHEEL +4 -0
- qsiv_runtime-0.1.0.dist-info/entry_points.txt +2 -0
- qsiv_runtime-0.1.0.dist-info/licenses/LICENSE +21 -0
- qsiv_runtime-0.1.0.dist-info/licenses/THIRD_PARTY.md +26 -0
qsiv_runtime/__init__.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Local QSIV decision model: shared GPU service, stdlib-only client, setup and doctor."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .client import QSIVClient
|
|
6
|
+
from .doctor import doctor
|
|
7
|
+
from .errors import Cause, QSIVDiagnostic, QSIVUnavailable
|
|
8
|
+
from .setup import setup
|
|
9
|
+
|
|
10
|
+
__version__ = "0.1.0"
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"Cause",
|
|
14
|
+
"QSIVClient",
|
|
15
|
+
"QSIVDiagnostic",
|
|
16
|
+
"QSIVUnavailable",
|
|
17
|
+
"__version__",
|
|
18
|
+
"doctor",
|
|
19
|
+
"setup",
|
|
20
|
+
]
|
qsiv_runtime/__main__.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Runs inside the GPU virtualenv (where huggingface_hub is installed): fetch the pinned snapshot.
|
|
2
|
+
|
|
3
|
+
This is the only code that downloads, and only `qsiv-runtime setup` runs it."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from ._pins import QSIV_REVISION
|
|
11
|
+
|
|
12
|
+
ALLOW_PATTERNS = [
|
|
13
|
+
"qsiv/*",
|
|
14
|
+
"tokenizer/*",
|
|
15
|
+
"pyproject.toml",
|
|
16
|
+
"LICENSE",
|
|
17
|
+
"NOTICE",
|
|
18
|
+
"config.json",
|
|
19
|
+
"calibration.json",
|
|
20
|
+
"qsiv_fp8.safetensors",
|
|
21
|
+
"qsiv_fp8.safetensors.sha256",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def download(directory: Path) -> None:
|
|
26
|
+
from huggingface_hub import snapshot_download
|
|
27
|
+
|
|
28
|
+
snapshot_download(
|
|
29
|
+
"djinn-san/QSIV",
|
|
30
|
+
revision=QSIV_REVISION,
|
|
31
|
+
local_dir=str(directory),
|
|
32
|
+
allow_patterns=ALLOW_PATTERNS,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
if __name__ == "__main__":
|
|
37
|
+
download(Path(sys.argv[1]))
|
qsiv_runtime/_launch.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""How the service process is launched: a scrubbed environment and a minimal PYTHONPATH."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
from collections.abc import Mapping
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Final
|
|
10
|
+
|
|
11
|
+
from .paths import ENV_SOCKET_DIRECTORY
|
|
12
|
+
|
|
13
|
+
_SECRET_WORDS: Final = (
|
|
14
|
+
"API_KEY",
|
|
15
|
+
"APIKEY",
|
|
16
|
+
"TOKEN",
|
|
17
|
+
"SECRET",
|
|
18
|
+
"PASSWORD",
|
|
19
|
+
"PASSWD",
|
|
20
|
+
"CREDENTIAL",
|
|
21
|
+
"PRIVATE_KEY",
|
|
22
|
+
"ACCESS_KEY",
|
|
23
|
+
)
|
|
24
|
+
_SECRET_SEGMENT: Final = "AUTH"
|
|
25
|
+
PACKAGE_DIRECTORY: Final = Path(__file__).resolve().parent
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def stage_package(directory: Path) -> Path:
|
|
29
|
+
"""A directory holding only a `qsiv_runtime` symlink, for PYTHONPATH (Q12).
|
|
30
|
+
|
|
31
|
+
The package's own parent directory cannot be used: for a wheel install it is the host
|
|
32
|
+
environment's whole site-packages, which would shadow the pinned packages of the GPU
|
|
33
|
+
environment. The symlink is replaced atomically, so concurrent launches are safe."""
|
|
34
|
+
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
35
|
+
link = directory / "qsiv_runtime"
|
|
36
|
+
if not (link.is_symlink() and link.resolve() == PACKAGE_DIRECTORY):
|
|
37
|
+
pending = directory / f".qsiv_runtime.{os.getpid()}"
|
|
38
|
+
pending.unlink(missing_ok=True)
|
|
39
|
+
pending.symlink_to(PACKAGE_DIRECTORY, target_is_directory=True)
|
|
40
|
+
os.replace(pending, link)
|
|
41
|
+
return directory
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def is_secret_name(name: str) -> bool:
|
|
45
|
+
"""The scrub rule (S26), case-insensitive: the name contains API_KEY, APIKEY, TOKEN, SECRET,
|
|
46
|
+
PASSWORD, PASSWD, CREDENTIAL, PRIVATE_KEY or ACCESS_KEY anywhere, or has a whole
|
|
47
|
+
`_`/`-`/`.`-separated segment equal to AUTH (SSH_AUTH_SOCK; AUTHOR and OAUTH_X stay)."""
|
|
48
|
+
upper = name.upper()
|
|
49
|
+
return any(w in upper for w in _SECRET_WORDS) or _SECRET_SEGMENT in re.split(r"[_.\-]", upper)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def build_service_env(environ: Mapping[str, str], socket_directory: Path) -> dict[str, str]:
|
|
53
|
+
"""No secrets (S26), Hugging Face offline, only the staged package on PYTHONPATH (Q12: the GPU
|
|
54
|
+
virtualenv does not have qsiv_runtime installed), and PYTHONSAFEPATH so the working directory
|
|
55
|
+
is not put on sys.path (python >= 3.11; older interpreters ignore the variable)."""
|
|
56
|
+
env = {k: v for k, v in environ.items() if not is_secret_name(k)}
|
|
57
|
+
env.update(HF_HUB_OFFLINE="1", TRANSFORMERS_OFFLINE="1", PYTHONSAFEPATH="1")
|
|
58
|
+
env[ENV_SOCKET_DIRECTORY] = str(socket_directory)
|
|
59
|
+
staged = str(stage_package(socket_directory / "pythonpath"))
|
|
60
|
+
env["PYTHONPATH"] = staged # never the caller's PYTHONPATH: only the staged symlink directory
|
|
61
|
+
return env
|
qsiv_runtime/_pins.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""The pinned QSIV revision and weights checksum (copied from agemem)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Final
|
|
6
|
+
|
|
7
|
+
QSIV_REVISION: Final = "f1ee842daf758c0ab535cf7d281c85439d6e4b25"
|
|
8
|
+
QSIV_SHA256: Final = "c44a08dafe091b0ed565a8efe511600b81e8f427feee56fc14c1d30d9466b9fc"
|
|
9
|
+
WEIGHTS_FP8: Final = "qsiv_fp8.safetensors"
|
|
10
|
+
WEIGHTS_REFERENCE: Final = "model.safetensors"
|
qsiv_runtime/_ports.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Seams the tests fake: clock, machine facts, service launcher, command runner."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import subprocess
|
|
6
|
+
import time
|
|
7
|
+
from collections.abc import Mapping, Sequence
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Protocol
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Clock(Protocol):
|
|
14
|
+
def monotonic(self) -> float: ...
|
|
15
|
+
|
|
16
|
+
def sleep(self, seconds: float) -> None: ...
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class GpuInfo:
|
|
21
|
+
name: str
|
|
22
|
+
compute_capability: tuple[int, int]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Machine(Protocol):
|
|
26
|
+
def system(self) -> str: ... # "Linux"
|
|
27
|
+
|
|
28
|
+
def machine(self) -> str: ... # "x86_64"
|
|
29
|
+
|
|
30
|
+
def gpus(self) -> Sequence[GpuInfo]: ... # nvidia-smi; empty when none
|
|
31
|
+
|
|
32
|
+
def which(self, program: str) -> str | None: ...
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class ServiceProcess(Protocol):
|
|
36
|
+
def poll(self) -> int | None: ...
|
|
37
|
+
|
|
38
|
+
def terminate(self) -> None: ...
|
|
39
|
+
|
|
40
|
+
def wait(self) -> int: ...
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class Launcher(Protocol):
|
|
44
|
+
def start(
|
|
45
|
+
self, argv: Sequence[str], env: Mapping[str, str], log_path: Path
|
|
46
|
+
) -> ServiceProcess: ...
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class CommandRunner(Protocol):
|
|
50
|
+
def run(self, command: Sequence[str], env: Mapping[str, str] | None = None) -> None:
|
|
51
|
+
"""Run a command to completion; raise on a nonzero exit."""
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class SystemClock:
|
|
55
|
+
def monotonic(self) -> float:
|
|
56
|
+
return time.monotonic()
|
|
57
|
+
|
|
58
|
+
def sleep(self, seconds: float) -> None:
|
|
59
|
+
time.sleep(seconds)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class SystemMachine:
|
|
63
|
+
"""Real platform facts; the GPU list comes from nvidia-smi and is empty when it is unusable."""
|
|
64
|
+
|
|
65
|
+
def system(self) -> str:
|
|
66
|
+
import platform
|
|
67
|
+
|
|
68
|
+
return platform.system()
|
|
69
|
+
|
|
70
|
+
def machine(self) -> str:
|
|
71
|
+
import platform
|
|
72
|
+
|
|
73
|
+
return platform.machine()
|
|
74
|
+
|
|
75
|
+
def gpus(self) -> Sequence[GpuInfo]:
|
|
76
|
+
try:
|
|
77
|
+
completed = subprocess.run(
|
|
78
|
+
["nvidia-smi", "--query-gpu=name,compute_cap", "--format=csv,noheader,nounits"],
|
|
79
|
+
check=True,
|
|
80
|
+
capture_output=True,
|
|
81
|
+
text=True,
|
|
82
|
+
timeout=10,
|
|
83
|
+
)
|
|
84
|
+
devices = []
|
|
85
|
+
for row in completed.stdout.splitlines():
|
|
86
|
+
name, capability = row.rsplit(",", 1)
|
|
87
|
+
major, minor = (int(part) for part in capability.strip().split("."))
|
|
88
|
+
devices.append(GpuInfo(name.strip(), (major, minor)))
|
|
89
|
+
return devices
|
|
90
|
+
except (OSError, subprocess.SubprocessError, ValueError):
|
|
91
|
+
return []
|
|
92
|
+
|
|
93
|
+
def which(self, program: str) -> str | None:
|
|
94
|
+
import shutil
|
|
95
|
+
|
|
96
|
+
return shutil.which(program)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class SubprocessLauncher:
|
|
100
|
+
"""Starts the detached service with its stderr appended to the private log."""
|
|
101
|
+
|
|
102
|
+
def start(self, argv: Sequence[str], env: Mapping[str, str], log_path: Path) -> ServiceProcess:
|
|
103
|
+
import os
|
|
104
|
+
import threading
|
|
105
|
+
|
|
106
|
+
log_fd = os.open(log_path, os.O_CREAT | os.O_APPEND | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
|
|
107
|
+
try:
|
|
108
|
+
process = subprocess.Popen(
|
|
109
|
+
list(argv),
|
|
110
|
+
stdin=subprocess.DEVNULL,
|
|
111
|
+
stdout=subprocess.DEVNULL,
|
|
112
|
+
stderr=log_fd,
|
|
113
|
+
env=dict(env),
|
|
114
|
+
cwd=log_path.parent, # the private socket directory, never the caller's cwd
|
|
115
|
+
start_new_session=True,
|
|
116
|
+
)
|
|
117
|
+
finally:
|
|
118
|
+
os.close(log_fd)
|
|
119
|
+
# Reap the detached service if this client stays alive after it exits.
|
|
120
|
+
threading.Thread(target=process.wait, daemon=True).start()
|
|
121
|
+
return process
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class SubprocessRunner:
|
|
125
|
+
def run(self, command: Sequence[str], env: Mapping[str, str] | None = None) -> None:
|
|
126
|
+
import os
|
|
127
|
+
import sys
|
|
128
|
+
import tempfile
|
|
129
|
+
|
|
130
|
+
base = dict(os.environ if env is None else env)
|
|
131
|
+
base["PYTHONSAFEPATH"] = "1"
|
|
132
|
+
# Keep stdout clean for callers; progress goes to stderr. Run from an empty temp dir so
|
|
133
|
+
# nothing planted in the caller's working directory can shadow a module.
|
|
134
|
+
with tempfile.TemporaryDirectory(prefix="qsiv-runtime-run-") as cwd:
|
|
135
|
+
subprocess.run(
|
|
136
|
+
list(command),
|
|
137
|
+
check=True,
|
|
138
|
+
stdout=sys.stderr,
|
|
139
|
+
stderr=sys.stderr,
|
|
140
|
+
env=base,
|
|
141
|
+
cwd=cwd,
|
|
142
|
+
)
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"""Checks shared by the client and doctor: platform, GPU, install, marker, socket directory."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import stat
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from ._pins import QSIV_REVISION, QSIV_SHA256, WEIGHTS_FP8, WEIGHTS_REFERENCE
|
|
11
|
+
from ._ports import Machine
|
|
12
|
+
from .errors import Cause, QSIVDiagnostic, QSIVUnavailable
|
|
13
|
+
from .paths import INSTALL_MARKER, LEGACY_INSTALL_MARKER, ResolvedPaths
|
|
14
|
+
|
|
15
|
+
SETUP_HINT = "Run: qsiv-runtime setup"
|
|
16
|
+
_MINIMUM = {"fp8": (8, 9), "reference": (8, 0)}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def weights_name(runtime: str) -> str:
|
|
20
|
+
return WEIGHTS_FP8 if runtime == "fp8" else WEIGHTS_REFERENCE
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
DOCTOR_HINT = "Run `qsiv-runtime doctor`, or use another provider"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def tool_hint(diagnostic: QSIVDiagnostic) -> str | None:
|
|
27
|
+
"""The hint for doctor/setup output: no self-referential "run doctor" advice."""
|
|
28
|
+
if diagnostic.hint == DOCTOR_HINT:
|
|
29
|
+
return "Or use another provider"
|
|
30
|
+
return diagnostic.hint
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _no_gpu(runtime: str, found: str) -> QSIVUnavailable:
|
|
34
|
+
capability = "8.9 or higher (FP8)" if runtime == "fp8" else "8.0 or higher"
|
|
35
|
+
return QSIVUnavailable(
|
|
36
|
+
"QSIV needs Linux x86_64 and an NVIDIA GPU with compute capability "
|
|
37
|
+
f"{capability}; found: {found}",
|
|
38
|
+
QSIVDiagnostic(Cause.NO_GPU, DOCTOR_HINT),
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def check_platform(machine: Machine, runtime: str) -> None:
|
|
43
|
+
if machine.system() != "Linux" or machine.machine().lower() not in ("x86_64", "amd64"):
|
|
44
|
+
raise _no_gpu(runtime, f"{machine.system()} {machine.machine()}")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def check_gpu(machine: Machine, runtime: str) -> str:
|
|
48
|
+
"""Raise F1 unless a GPU meets the runtime's minimum; return a one-line description."""
|
|
49
|
+
gpus = machine.gpus()
|
|
50
|
+
if not gpus:
|
|
51
|
+
raise _no_gpu(runtime, "no NVIDIA GPU")
|
|
52
|
+
best = max(gpus, key=lambda gpu: gpu.compute_capability)
|
|
53
|
+
major, minor = best.compute_capability
|
|
54
|
+
if best.compute_capability < _MINIMUM[runtime]:
|
|
55
|
+
raise _no_gpu(runtime, f"{best.name} ({major}.{minor})")
|
|
56
|
+
return f"{best.name} ({major}.{minor})"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def check_machine(machine: Machine, runtime: str) -> None:
|
|
60
|
+
check_platform(machine, runtime)
|
|
61
|
+
check_gpu(machine, runtime)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _not_installed(paths: ResolvedPaths) -> QSIVUnavailable:
|
|
65
|
+
checked = ", ".join(str(path) for path in paths.checked or (paths.model_directory,))
|
|
66
|
+
return QSIVUnavailable(
|
|
67
|
+
"QSIV is not installed",
|
|
68
|
+
QSIVDiagnostic(
|
|
69
|
+
Cause.NOT_INSTALLED, f"{SETUP_HINT} (checked: {checked})", None, {"checked": checked}
|
|
70
|
+
),
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def check_artifacts(paths: ResolvedPaths) -> None:
|
|
75
|
+
model = paths.model_directory
|
|
76
|
+
required = ("config.json", "calibration.json", "tokenizer", weights_name(paths.runtime))
|
|
77
|
+
if not model.is_dir() or any(not (model / name).exists() for name in required):
|
|
78
|
+
raise _not_installed(paths)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def check_python(paths: ResolvedPaths) -> None:
|
|
82
|
+
if not paths.python.is_file():
|
|
83
|
+
raise _not_installed(paths)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _marker_matches(path: Path) -> bool:
|
|
87
|
+
try:
|
|
88
|
+
data = json.loads(path.read_text())
|
|
89
|
+
except (OSError, ValueError):
|
|
90
|
+
return False
|
|
91
|
+
return (
|
|
92
|
+
isinstance(data, dict)
|
|
93
|
+
and data.get("revision") == QSIV_REVISION
|
|
94
|
+
and data.get("weights_sha256") == QSIV_SHA256
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def bad_checksum() -> QSIVUnavailable:
|
|
99
|
+
return QSIVUnavailable(
|
|
100
|
+
"QSIV runtime is not installed (setup did not complete)",
|
|
101
|
+
QSIVDiagnostic(Cause.BAD_CHECKSUM, SETUP_HINT),
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def check_marker(paths: ResolvedPaths) -> None:
|
|
106
|
+
"""The install marker must carry the pinned revision and checksum (F8). The agemem marker
|
|
107
|
+
counts too. Only the FP8 weights are pinned, so the reference runtime has no marker check."""
|
|
108
|
+
if paths.runtime != "fp8":
|
|
109
|
+
return
|
|
110
|
+
model = paths.model_directory
|
|
111
|
+
if not any(_marker_matches(model / name) for name in (INSTALL_MARKER, LEGACY_INSTALL_MARKER)):
|
|
112
|
+
raise bad_checksum()
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def check_install(paths: ResolvedPaths) -> None:
|
|
116
|
+
check_artifacts(paths)
|
|
117
|
+
check_python(paths)
|
|
118
|
+
check_marker(paths)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _problem(path: Path, uid: int) -> str | None:
|
|
122
|
+
try:
|
|
123
|
+
info = os.lstat(path)
|
|
124
|
+
except FileNotFoundError:
|
|
125
|
+
return None
|
|
126
|
+
if stat.S_ISLNK(info.st_mode):
|
|
127
|
+
return "symlink"
|
|
128
|
+
if not stat.S_ISDIR(info.st_mode):
|
|
129
|
+
return "not a directory"
|
|
130
|
+
if info.st_uid != uid:
|
|
131
|
+
return "owned by another user"
|
|
132
|
+
if info.st_mode & 0o077:
|
|
133
|
+
return f"mode {info.st_mode & 0o777:04o}"
|
|
134
|
+
return None
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def check_private_directory(path: Path, uid: int | None = None) -> None:
|
|
138
|
+
"""Raise F7 when the directory exists and is a symlink, foreign or not mode 0700."""
|
|
139
|
+
problem = _problem(path, getattr(os, "getuid", lambda: 0)() if uid is None else uid)
|
|
140
|
+
if problem is not None:
|
|
141
|
+
raise QSIVUnavailable(
|
|
142
|
+
f"QSIV socket directory {path} is not private ({problem}, expected 0700)",
|
|
143
|
+
QSIVDiagnostic(Cause.UNSAFE_DIRECTORY, "Remove or fix the directory"),
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def ensure_private_directory(path: Path, uid: int | None = None) -> Path:
|
|
148
|
+
"""Create the directory with mode 0700 if missing; refuse an unsafe one (F7)."""
|
|
149
|
+
check_private_directory(path, uid)
|
|
150
|
+
path.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
151
|
+
check_private_directory(path, uid)
|
|
152
|
+
return path
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""JSON lines, one object per line, UTF-8, and the strict validation of a service answer."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
from collections.abc import Mapping
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import Final, Literal, TypedDict
|
|
10
|
+
|
|
11
|
+
from .errors import Cause, QSIVDiagnostic, QSIVError, QSIVUnavailable
|
|
12
|
+
from .paths import Runtime
|
|
13
|
+
|
|
14
|
+
PROTOCOL_VERSION: Final = 1
|
|
15
|
+
|
|
16
|
+
# client -> service {"protocol": 1, "config": [python, model_directory, runtime]}
|
|
17
|
+
# service -> client {"ready": true} | {"error": str, "diagnostic": {"cause": ..., ...}}
|
|
18
|
+
# client -> service {"request": {"state": str, "questions": [WireQuestion, ...]}}
|
|
19
|
+
# service -> client {"answers": [{"p_true": float}, ...]} | {"error": str, "diagnostic": {...}}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class ServiceConfig:
|
|
24
|
+
python: str # not resolved: its path selects the virtualenv
|
|
25
|
+
model_directory: str # resolved
|
|
26
|
+
runtime: Runtime
|
|
27
|
+
|
|
28
|
+
def as_wire(self) -> list[str]:
|
|
29
|
+
return [self.python, self.model_directory, self.runtime]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class WireQuestion(TypedDict):
|
|
33
|
+
type: Literal["noul"]
|
|
34
|
+
text: str
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class ProtocolError(QSIVError):
|
|
38
|
+
"""A line that is not one JSON object."""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def encode(message: Mapping[str, object]) -> bytes:
|
|
42
|
+
return (json.dumps(message, separators=(",", ":")) + "\n").encode()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def decode(line: bytes) -> dict[str, object]:
|
|
46
|
+
try:
|
|
47
|
+
value = json.loads(line)
|
|
48
|
+
except ValueError as exc: # includes UnicodeDecodeError
|
|
49
|
+
raise ProtocolError("malformed message") from exc
|
|
50
|
+
if not isinstance(value, dict):
|
|
51
|
+
raise ProtocolError("message is not an object")
|
|
52
|
+
return value
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def invalid_answer(expected: int, got: str) -> QSIVUnavailable:
|
|
56
|
+
return QSIVUnavailable(
|
|
57
|
+
f"QSIV returned an invalid answer (expected {expected} probabilities in [0, 1], got {got})",
|
|
58
|
+
QSIVDiagnostic(Cause.INVALID_ANSWER, "Retry; `qsiv-runtime doctor` if it repeats"),
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def validate_probabilities(answers: object, expected: int) -> list[float]:
|
|
63
|
+
"""Whole-answer check: a list of the expected length; each p_true an int or float, not bool,
|
|
64
|
+
finite, within [0, 1]. One bad value rejects everything (S12)."""
|
|
65
|
+
if not isinstance(answers, list):
|
|
66
|
+
raise invalid_answer(expected, "no list")
|
|
67
|
+
if len(answers) != expected:
|
|
68
|
+
raise invalid_answer(expected, str(len(answers)))
|
|
69
|
+
result: list[float] = []
|
|
70
|
+
for answer in answers:
|
|
71
|
+
value = answer.get("p_true") if isinstance(answer, dict) else None
|
|
72
|
+
if (
|
|
73
|
+
isinstance(value, bool)
|
|
74
|
+
or not isinstance(value, (int, float))
|
|
75
|
+
or not math.isfinite(value)
|
|
76
|
+
or not 0 <= value <= 1
|
|
77
|
+
):
|
|
78
|
+
raise invalid_answer(expected, "an invalid value")
|
|
79
|
+
result.append(float(value))
|
|
80
|
+
return result
|
qsiv_runtime/cli.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""`qsiv-runtime setup | doctor`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import subprocess
|
|
7
|
+
import sys
|
|
8
|
+
from collections.abc import Mapping, Sequence
|
|
9
|
+
|
|
10
|
+
from . import _preflight
|
|
11
|
+
from ._ports import CommandRunner, Machine
|
|
12
|
+
from .doctor import doctor
|
|
13
|
+
from .errors import QSIVError, QSIVUnavailable
|
|
14
|
+
from .setup import setup
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _parser() -> argparse.ArgumentParser:
|
|
18
|
+
parser = argparse.ArgumentParser(
|
|
19
|
+
prog="qsiv-runtime", description="Local QSIV model: install it and check the machine."
|
|
20
|
+
)
|
|
21
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
22
|
+
install = commands.add_parser(
|
|
23
|
+
"setup", help="create the GPU environment and download the weights"
|
|
24
|
+
)
|
|
25
|
+
install.add_argument("--model-directory", help="where the model goes")
|
|
26
|
+
install.add_argument("--venv-directory", help="where the GPU virtualenv goes")
|
|
27
|
+
install.add_argument("--dry-run", action="store_true", help="print the plan, change nothing")
|
|
28
|
+
check = commands.add_parser("doctor", help="check this machine and the install (read-only)")
|
|
29
|
+
check.add_argument("--model-directory")
|
|
30
|
+
check.add_argument("--python", help="interpreter of the GPU virtualenv")
|
|
31
|
+
check.add_argument("--runtime", choices=["fp8", "reference"])
|
|
32
|
+
check.add_argument("--verify", action="store_true", help="also hash the weights (slow)")
|
|
33
|
+
return parser
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def main(
|
|
37
|
+
argv: Sequence[str] | None = None,
|
|
38
|
+
*,
|
|
39
|
+
machine: Machine | None = None,
|
|
40
|
+
runner: CommandRunner | None = None,
|
|
41
|
+
environ: Mapping[str, str] | None = None,
|
|
42
|
+
) -> int:
|
|
43
|
+
"""Exit 0 only on success; doctor exits 0 only when every check passes."""
|
|
44
|
+
args = _parser().parse_args(argv)
|
|
45
|
+
if args.command == "doctor":
|
|
46
|
+
report = doctor(
|
|
47
|
+
args.model_directory,
|
|
48
|
+
args.python,
|
|
49
|
+
args.runtime,
|
|
50
|
+
verify=args.verify,
|
|
51
|
+
machine=machine,
|
|
52
|
+
environ=environ,
|
|
53
|
+
)
|
|
54
|
+
for check in report.checks:
|
|
55
|
+
status = "ok " if check.ok else "FAIL"
|
|
56
|
+
cause = f" [{check.cause.value}]" if check.cause else ""
|
|
57
|
+
print(f"{status} {check.name}: {check.detail}{cause}")
|
|
58
|
+
return 0 if report.ok else 1
|
|
59
|
+
try:
|
|
60
|
+
result = setup(
|
|
61
|
+
args.model_directory,
|
|
62
|
+
args.venv_directory,
|
|
63
|
+
dry_run=args.dry_run,
|
|
64
|
+
machine=machine,
|
|
65
|
+
runner=runner,
|
|
66
|
+
)
|
|
67
|
+
except QSIVUnavailable as exc:
|
|
68
|
+
shown = _preflight.tool_hint(exc.diagnostic)
|
|
69
|
+
hint = f" {shown}" if shown else ""
|
|
70
|
+
print(f"qsiv-runtime: {exc.message}.{hint}", file=sys.stderr)
|
|
71
|
+
return 1
|
|
72
|
+
except (QSIVError, subprocess.CalledProcessError) as exc:
|
|
73
|
+
print(f"qsiv-runtime: {exc}", file=sys.stderr)
|
|
74
|
+
return 1
|
|
75
|
+
if result.dry_run:
|
|
76
|
+
print(f"Plan (nothing was changed): model {result.model_directory}")
|
|
77
|
+
for command in result.commands:
|
|
78
|
+
print(" " + " ".join(command))
|
|
79
|
+
else:
|
|
80
|
+
print(f"Installed QSIV {result.revision[:12]} in {result.model_directory}")
|
|
81
|
+
print(f"Runtime python: {result.runtime_python}")
|
|
82
|
+
return 0
|