CUDApp
CUDA++: AIEN’s GPU machine-code toolchain, runtime and driver client for NVIDIA GPUs without the CUDA toolkit. Hardware coverage and driver replacement limits are explicit.
Brought by drakestapleton
CUDApp / tools / localrouter / setup.py
| 1 | #!/usr/bin/env python3 |
| 2 | # SPDX-License-Identifier: MIT |
| 3 | """Prepare and probe an isolated, text-only LocalRouter -> Omega candidate.""" |
| 4 | import argparse |
| 5 | import hashlib |
| 6 | import http.client |
| 7 | import json |
| 8 | import os |
| 9 | from pathlib import Path |
| 10 | import re |
| 11 | import socket |
| 12 | import sys |
| 13 | import time |
| 14 | |
| 15 | |
| 16 | MAX_BODY = 2 * 1024 * 1024 |
| 17 | MODEL_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,95}\Z") |
| 18 | |
| 19 | |
| 20 | def require(ok, message): |
| 21 | if not ok: |
| 22 | raise ValueError(message) |
| 23 | |
| 24 | |
| 25 | def engine_of(cfg): |
| 26 | command = cfg["tools"][0]["options"]["server"] |
| 27 | return command[command.index("--engine") + 1] |
| 28 | |
| 29 | |
| 30 | def make_config(*, server, model_dir, model_id, engine, resident_bytes, |
| 31 | working_bytes, data_dir, router_port, backend_port, reserve_bytes): |
| 32 | cfg = { |
| 33 | "host": "127.0.0.1", "port": router_port, "data_dir": data_dir, |
| 34 | "reserve_bytes": reserve_bytes, "gpu_lock": "", |
| 35 | "defaults": {"chat_completion": model_id}, |
| 36 | "voice": {"tools": False, "manage_models": False, "speculate": False, |
| 37 | "prime_chat": False}, |
| 38 | "tools": [{ |
| 39 | "id": model_id, "kind": "chat", "engine": "openai_server", |
| 40 | "name": "Omega text candidate", "weights": model_dir, |
| 41 | "resident_bytes": resident_bytes, "working_bytes": working_bytes, |
| 42 | "keep_loaded": False, "idle_ttl_s": 300, "priority": 100, |
| 43 | "load_timeout_s": 900, "generate_timeout_s": 180, |
| 44 | "options": { |
| 45 | "port": backend_port, "health": "/health", "stop_timeout_s": 30, |
| 46 | "server": [server, "--engine", engine, "--model-dir", "{weights}", |
| 47 | "--bind", "127.0.0.1", "--port", "{port}", |
| 48 | "--model-id", "{id}", "--max-context", "4096"], |
| 49 | }, |
| 50 | }], |
| 51 | } |
| 52 | validate_config(cfg) |
| 53 | return cfg |
| 54 | |
| 55 | |
| 56 | def validate_config(cfg): |
| 57 | """Validate only this setup profile, not arbitrary LocalRouter configurations.""" |
| 58 | require(cfg.get("host") == "127.0.0.1", "candidate must bind 127.0.0.1") |
| 59 | require(cfg.get("gpu_lock") == "", "LocalRouter must not hold a shared GPU lock in this text-only profile") |
| 60 | tools = cfg.get("tools", []) |
| 61 | require(len(tools) == 1, "candidate must contain exactly one text tool; mixed GPU scheduling is unqualified") |
| 62 | tool = tools[0] |
| 63 | require(tool.get("kind") == "chat" and tool.get("engine") == "openai_server", "expected one openai_server chat tool") |
| 64 | require(MODEL_ID.fullmatch(tool.get("id", "")), "model id must be a simple name, not a path") |
| 65 | require(cfg.get("defaults", {}).get("chat_completion") == tool["id"], "default model must match the backend model id") |
| 66 | require(tool.get("keep_loaded") is False, "candidate must load on demand, not at daemon startup") |
| 67 | voice = cfg.get("voice", {}) |
| 68 | require(all(voice.get(k) is False for k in ("tools", "manage_models", "speculate", "prime_chat")), |
| 69 | "disable voice tool calling, model management, speculation and priming") |
| 70 | opts = tool.get("options", {}) |
| 71 | command = opts.get("server", []) |
| 72 | require(isinstance(command, list) and all(isinstance(x, str) for x in command), "server command must be an argv array") |
| 73 | require(len(command) == 13, "unexpected server command; regenerate this candidate profile") |
| 74 | engine = command[2] |
| 75 | require(engine in ("stub", "omega"), "engine must be stub or omega") |
| 76 | require(command[1:] == ["--engine", engine, "--model-dir", "{weights}", "--bind", "127.0.0.1", |
| 77 | "--port", "{port}", "--model-id", "{id}", "--max-context", "4096"], |
| 78 | "server must use the inspected loopback, port and model-id contract") |
| 79 | require("env" not in opts, "this profile must not override Omega's lock environment") |
| 80 | for path in (command[0], tool.get("weights", ""), cfg.get("data_dir", "")): |
| 81 | require(Path(path).is_absolute() and not any(c in path for c in "\x00\n\r{}"), |
| 82 | "server, model and data paths must be absolute and contain no template braces or control characters") |
| 83 | ports = (cfg.get("port"), opts.get("port")) |
| 84 | require(all(type(p) is int and 1024 <= p <= 65535 and p != 18091 for p in ports), |
| 85 | "use unprivileged candidate ports; live motor port 18091 is reserved") |
| 86 | require(ports[0] != ports[1], "router and backend ports must differ") |
| 87 | for key, value in (("resident_bytes", tool.get("resident_bytes")), |
| 88 | ("working_bytes", tool.get("working_bytes")), |
| 89 | ("reserve_bytes", cfg.get("reserve_bytes"))): |
| 90 | require(type(value) is int and 0 <= value < 2**63, key + " must be a bounded nonnegative byte count") |
| 91 | require(cfg["reserve_bytes"] > 0, "keep a nonzero OS reserve") |
| 92 | require(engine == "stub" or tool["resident_bytes"] > 0, "Omega requires an explicit nonzero measured resident budget") |
| 93 | |
| 94 | |
| 95 | def check_files(cfg): |
| 96 | validate_config(cfg) |
| 97 | tool = cfg["tools"][0] |
| 98 | server = Path(tool["options"]["server"][0]) |
| 99 | require(server.is_file() and os.access(server, os.X_OK), "server binary does not exist or is not executable: " + str(server)) |
| 100 | model = Path(tool["weights"]) |
| 101 | require(model.is_dir(), "model directory does not exist: " + str(model)) |
| 102 | if engine_of(cfg) == "omega": |
| 103 | require((model / "tokenizer.json").is_file(), "Omega model directory needs tokenizer.json and its supported checkpoint") |
| 104 | |
| 105 | |
| 106 | def check_ports(cfg): |
| 107 | for port in (cfg["port"], cfg["tools"][0]["options"]["port"]): |
| 108 | try: |
| 109 | with socket.socket() as sock: |
| 110 | sock.bind(("127.0.0.1", port)) |
| 111 | except OSError as exc: |
| 112 | raise ValueError(f"candidate port {port} is unavailable; do not stop its owner") from exc |
| 113 | |
| 114 | |
| 115 | def check_completion(value, model): |
| 116 | require(isinstance(value, dict) and value.get("model") == model and "error" not in value, "completion error or wrong model") |
| 117 | choices = value.get("choices", []) |
| 118 | require(len(choices) == 1, "expected one completion choice") |
| 119 | choice = choices[0] |
| 120 | msg = choice.get("message", {}) |
| 121 | require(msg.get("role") == "assistant" and not msg.get("tool_calls"), "expected a plain-text assistant response") |
| 122 | text = msg.get("content") |
| 123 | require(isinstance(text, str) and text.strip(), "completion has no text") |
| 124 | require(choice.get("finish_reason") in ("stop", "length"), "completion has no successful finish reason") |
| 125 | return text |
| 126 | |
| 127 | |
| 128 | def check_sse(lines, model): |
| 129 | text = [] |
| 130 | finished = False |
| 131 | data = [] |
| 132 | for raw in lines: |
| 133 | line = raw.rstrip("\r\n") |
| 134 | if line.startswith(":"): |
| 135 | continue |
| 136 | if line.startswith("data:"): |
| 137 | data.append(line[5:].lstrip(" ")) |
| 138 | continue |
| 139 | if line or not data: |
| 140 | continue |
| 141 | payload = "\n".join(data) |
| 142 | data.clear() |
| 143 | if payload == "[DONE]": |
| 144 | require(finished and "".join(text).strip(), "SSE ended without text and a finish reason") |
| 145 | return len("".join(text)) |
| 146 | event = json.loads(payload) |
| 147 | require(isinstance(event, dict) and "error" not in event and event.get("model") == model, |
| 148 | "SSE contains an error or wrong model") |
| 149 | for choice in event.get("choices", []): |
| 150 | delta = choice.get("delta", {}) |
| 151 | require(not delta.get("tool_calls"), "unexpected tool call in text-only SSE") |
| 152 | if delta.get("content") is not None: |
| 153 | require(isinstance(delta["content"], str), "invalid content delta") |
| 154 | text.append(delta["content"]) |
| 155 | if choice.get("finish_reason") is not None: |
| 156 | require(choice["finish_reason"] in ("stop", "length"), "SSE failed finish reason") |
| 157 | finished = True |
| 158 | raise ValueError("SSE truncated: no complete [DONE] event") |
| 159 | |
| 160 | |
| 161 | def request(port, method, path, payload=None, *, timeout=180, stream_model=None): |
| 162 | """Literal loopback only; no proxies, redirects or arbitrary upstream URLs.""" |
| 163 | conn = http.client.HTTPConnection("127.0.0.1", port, timeout=timeout) |
| 164 | try: |
| 165 | body = None if payload is None else json.dumps(payload).encode() |
| 166 | conn.request(method, path, body, {"Content-Type": "application/json"}) |
| 167 | response = conn.getresponse() |
| 168 | if stream_model is not None and response.status == 200: |
| 169 | require(response.getheader("Content-Type", "").startswith("text/event-stream"), "expected SSE content type") |
| 170 | def lines(): |
| 171 | total = 0 |
| 172 | deadline = time.monotonic() + timeout |
| 173 | while True: |
| 174 | require(time.monotonic() < deadline, "SSE deadline exceeded") |
| 175 | if conn.sock: |
| 176 | conn.sock.settimeout(max(0.01, deadline - time.monotonic())) |
| 177 | raw = response.readline(65537) |
| 178 | if not raw: |
| 179 | return |
| 180 | total += len(raw) |
| 181 | require(len(raw) <= 65536 and total <= MAX_BODY, "SSE exceeds smoke-test size limit") |
| 182 | yield raw.decode("utf-8") |
| 183 | return response.status, {"text_chars": check_sse(lines(), stream_model)} |
| 184 | raw = response.read(MAX_BODY + 1) |
| 185 | require(len(raw) <= MAX_BODY, "response exceeds smoke-test size limit") |
| 186 | return response.status, json.loads(raw) |
| 187 | finally: |
| 188 | conn.close() |
| 189 | |
| 190 | |
| 191 | def exercise(cfg, timeout): |
| 192 | """Explicitly sends short generation requests to an already running candidate.""" |
| 193 | validate_config(cfg) |
| 194 | tool = cfg["tools"][0] |
| 195 | model, port = tool["id"], cfg["port"] |
| 196 | upstream = tool["options"]["port"] |
| 197 | checks = [] |
| 198 | def expect(name, actual, expected): |
| 199 | require(actual == expected, f"{name}: expected {expected}, got {actual}") |
| 200 | checks.append(name) |
| 201 | status, listed = request(port, "GET", "/v1/models", timeout=timeout) |
| 202 | expect("router_models", status, 200) |
| 203 | require(any(x.get("id") == model for x in listed.get("data", [])), "candidate model is not listed by router") |
| 204 | messages = [{"role": "user", "content": "Reply with a short greeting."}] |
| 205 | payload = {"model": model, "messages": messages, "temperature": 0, "max_tokens": 64} |
| 206 | status, reply = request(port, "POST", "/v1/chat/completions", payload, timeout=timeout) |
| 207 | expect("whole_chat", status, 200) |
| 208 | first = check_completion(reply, model) |
| 209 | status, health = request(upstream, "GET", "/health", timeout=timeout) |
| 210 | expect("backend_health", status, 200) |
| 211 | require(health.get("model") == model and health.get("engine") == engine_of(cfg), "backend health model or engine mismatch") |
| 212 | status, listed = request(upstream, "GET", "/v1/models", timeout=timeout) |
| 213 | expect("backend_models", status, 200) |
| 214 | require(any(x.get("id") == model for x in listed.get("data", [])), "backend model mismatch") |
| 215 | second = dict(payload, messages=messages + [{"role": "assistant", "content": first}, |
| 216 | {"role": "user", "content": "Now reply with another short greeting."}]) |
| 217 | status, reply = request(port, "POST", "/v1/chat/completions", second, timeout=timeout) |
| 218 | expect("second_turn", status, 200) |
| 219 | check_completion(reply, model) |
| 220 | status, _ = request(port, "POST", "/v1/chat/completions", dict(payload, stream=True), |
| 221 | timeout=timeout, stream_model=model) |
| 222 | expect("streamed_chat", status, 200) |
| 223 | function = {"type": "function", "function": {"name": "smoke_noop", "parameters": {"type": "object", "properties": {}}}} |
| 224 | status, _ = request(port, "POST", "/v1/chat/completions", dict(payload, tools=[function]), timeout=timeout) |
| 225 | expect("tool_call_rejected", status, 400) |
| 226 | status, _ = request(port, "POST", "/v1/chat/completions", dict(payload, model="missing-smoke-model"), timeout=timeout) |
| 227 | expect("unknown_model_rejected", status, 404) |
| 228 | return {"http_protocol": "PASS", "engine": engine_of(cfg), "checks": checks, |
| 229 | "gpu_qualification": "NOT_RUN", "lifecycle_qualification": "NOT_RUN", |
| 230 | "cuda_free_provenance": "NOT_RUN", |
| 231 | "note": "HTTP checks do not establish GPU correctness, memory budgets, lifecycle or deployed library provenance."} |
| 232 | |
| 233 | |
| 234 | def main(argv=None): |
| 235 | parser = argparse.ArgumentParser(description=__doc__) |
| 236 | sub = parser.add_subparsers(dest="action", required=True) |
| 237 | generate = sub.add_parser("config", help="print candidate JSON; starts nothing") |
| 238 | generate.add_argument("--server", required=True) |
| 239 | generate.add_argument("--model-dir", required=True) |
| 240 | generate.add_argument("--data-dir", required=True) |
| 241 | generate.add_argument("--model-id", default="omega-candidate") |
| 242 | generate.add_argument("--engine", choices=("omega", "stub"), default="omega") |
| 243 | generate.add_argument("--resident-bytes", type=int, required=True) |
| 244 | generate.add_argument("--working-bytes", type=int, required=True) |
| 245 | generate.add_argument("--reserve-bytes", type=int, default=8 * 1024**3) |
| 246 | generate.add_argument("--router-port", type=int, default=8192) |
| 247 | generate.add_argument("--backend-port", type=int, default=18092) |
| 248 | for name in ("check", "probe"): |
| 249 | p = sub.add_parser(name, help="check setup without launching any process") |
| 250 | p.add_argument("--config", type=Path, required=True) |
| 251 | if name == "probe": |
| 252 | p.add_argument("--exercise", action="store_true", help="send short generation requests to the running candidate") |
| 253 | p.add_argument("--timeout", type=int, default=180) |
| 254 | args = parser.parse_args(argv) |
| 255 | try: |
| 256 | if args.action == "config": |
| 257 | fields = vars(args).copy() |
| 258 | fields.pop("action") |
| 259 | cfg = make_config(**fields) |
| 260 | check_files(cfg) |
| 261 | print(json.dumps(cfg, indent=2)) |
| 262 | else: |
| 263 | raw = args.config.read_bytes() |
| 264 | cfg = json.loads(raw) |
| 265 | validate_config(cfg) |
| 266 | if args.action == "check": |
| 267 | check_files(cfg) |
| 268 | check_ports(cfg) |
| 269 | result = {"setup": "PASS", "processes_started": 0, "gpu_qualification": "NOT_RUN"} |
| 270 | elif args.exercise: |
| 271 | require(1 <= args.timeout <= 1800, "timeout must be 1..1800 seconds") |
| 272 | result = exercise(cfg, args.timeout) |
| 273 | else: |
| 274 | status, value = request(cfg["port"], "GET", "/v1/models", timeout=10) |
| 275 | require(status == 200 and any(x.get("id") == cfg["tools"][0]["id"] for x in value.get("data", [])), |
| 276 | "candidate model not listed") |
| 277 | result = {"router_listing": "PASS", "generation": "NOT_RUN", "gpu_qualification": "NOT_RUN"} |
| 278 | result["config_sha256"] = hashlib.sha256(raw).hexdigest() |
| 279 | print(json.dumps(result, indent=2)) |
| 280 | return 0 |
| 281 | except (ValueError, KeyError, TypeError, IndexError, AttributeError, OSError, http.client.HTTPException) as exc: |
| 282 | print(f"localrouter setup: FAIL: {exc}", file=sys.stderr) |
| 283 | return 1 |
| 284 | |
| 285 | |
| 286 | if __name__ == "__main__": |
| 287 | sys.exit(main()) |