specbench-cli 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.
@@ -0,0 +1,660 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import platform
5
+ import re
6
+ import signal
7
+ import socket
8
+ import subprocess
9
+ import threading
10
+ import time
11
+ from collections import deque
12
+ from collections.abc import Iterable
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ import httpx
17
+
18
+ from speculation_benchmark.backends.base import CompletionResponse, CompletionTimings
19
+ from speculation_benchmark.config import (
20
+ GenerationConfig,
21
+ ModelSpec,
22
+ ServerConfig,
23
+ select_hf_sidecar_file,
24
+ sidecar_prefixes_for_spec_type,
25
+ )
26
+
27
+
28
+ def pick_free_port(host: str = "127.0.0.1") -> int:
29
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
30
+ sock.bind((host, 0))
31
+ return int(sock.getsockname()[1])
32
+
33
+
34
+ def detect_hardware_tag() -> str:
35
+ """Detect local GPU/host hardware label (e.g. 'NVIDIA GB10 (aarch64)')."""
36
+ arch = platform.machine()
37
+ try:
38
+ proc = subprocess.run(
39
+ ["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"],
40
+ capture_output=True,
41
+ text=True,
42
+ timeout=5,
43
+ check=False,
44
+ )
45
+ gpu = proc.stdout.strip().splitlines()[0].strip() if proc.returncode == 0 and proc.stdout.strip() else ""
46
+ if gpu:
47
+ if "GB10" in gpu:
48
+ return f"{gpu} (DGX Spark, {arch})"
49
+ return f"{gpu} ({arch})"
50
+ except Exception:
51
+ pass
52
+ return f"{platform.system()} ({arch})"
53
+
54
+
55
+ def parse_nvidia_smi_compute_apps(stdout: str, target_pids: set[int]) -> float | None:
56
+ """Parse `nvidia-smi --query-compute-apps=pid,used_memory --format=csv,noheader,nounits`."""
57
+ total_mib = 0.0
58
+ matched = False
59
+ for raw_line in stdout.splitlines():
60
+ line = raw_line.strip()
61
+ if not line:
62
+ continue
63
+ parts = [part.strip() for part in line.split(",")]
64
+ if len(parts) < 2:
65
+ continue
66
+ try:
67
+ pid = int(parts[0])
68
+ mem_mib = float(parts[1])
69
+ except ValueError:
70
+ continue
71
+ if pid in target_pids:
72
+ total_mib += mem_mib
73
+ matched = True
74
+ return total_mib if matched else None
75
+
76
+
77
+ def _pids_in_process_group(root_pid: int) -> set[int]:
78
+ pids = {root_pid}
79
+ try:
80
+ pgid = os.getpgid(root_pid)
81
+ except OSError:
82
+ return pids
83
+ proc_root = Path("/proc")
84
+ if proc_root.is_dir():
85
+ for entry in proc_root.iterdir():
86
+ if not entry.name.isdigit():
87
+ continue
88
+ try:
89
+ pid = int(entry.name)
90
+ if os.getpgid(pid) == pgid:
91
+ pids.add(pid)
92
+ except OSError:
93
+ continue
94
+ return pids
95
+
96
+
97
+ def query_process_gpu_memory_mib(root_pid: int) -> float | None:
98
+ """Query current GPU memory (MiB) used by `root_pid` and any children in its process group."""
99
+ target_pids = _pids_in_process_group(root_pid)
100
+ try:
101
+ proc = subprocess.run(
102
+ [
103
+ "nvidia-smi",
104
+ "--query-compute-apps=pid,used_memory",
105
+ "--format=csv,noheader,nounits",
106
+ ],
107
+ capture_output=True,
108
+ text=True,
109
+ timeout=5,
110
+ check=False,
111
+ )
112
+ if proc.returncode != 0:
113
+ return None
114
+ return parse_nvidia_smi_compute_apps(proc.stdout, target_pids)
115
+ except Exception:
116
+ return None
117
+
118
+
119
+ _CLAMP_RE = re.compile(r"clamping to\s+(\d+)", re.IGNORECASE)
120
+ _BLOCK_SIZE_RE = re.compile(r"\bblock_size\s*=\s*(\d+)")
121
+ _LOADING_DRAFT_RE = re.compile(
122
+ r"load(?:ing|ed)\s+draft\s+model\s*,?\s*['\"]([^'\"]+\.gguf)['\"]",
123
+ re.IGNORECASE,
124
+ )
125
+ _CACHED_GGUF_RE = re.compile(
126
+ r"(?:using cached file[^:]*:|downloading\s+(?:https?://\S+\s+to\s+)?)\s*['\"]?([^\s'\"]+\.gguf)['\"]?",
127
+ re.IGNORECASE,
128
+ )
129
+
130
+
131
+ def _normalize_gguf_filename(path_str: str, spec_type: str | None = None) -> str:
132
+ """Return clean GGUF filename, stripping llama.cpp's flattened `org_repo_` cache prefix when present."""
133
+ name = Path(path_str.strip().strip("'\"")).name
134
+ prefixes = sidecar_prefixes_for_spec_type(spec_type)
135
+ lower = name.lower()
136
+ for prefix in prefixes:
137
+ if lower.startswith(prefix):
138
+ return name
139
+ idx = lower.find(f"_{prefix}")
140
+ if idx != -1:
141
+ return name[idx + 1 :]
142
+ return name
143
+
144
+
145
+ def parse_loaded_draft_file(
146
+ log_lines: Iterable[str],
147
+ spec_type: str | None = None,
148
+ ) -> str | None:
149
+ """Inspect llama.cpp startup logs for the draft/sidecar GGUF filename actually loaded.
150
+
151
+ Prefers explicit `loading draft model '<path>'` lines, with a fallback to cached/downloaded
152
+ sidecar GGUF paths matching `--spec-type` prefixes (`dflash-`, `mtp-`, `eagle3-`, `dspark-`, ...).
153
+ """
154
+ prefixes = sidecar_prefixes_for_spec_type(spec_type)
155
+ fallback: str | None = None
156
+ for line in log_lines:
157
+ direct = _LOADING_DRAFT_RE.search(line)
158
+ if direct:
159
+ return _normalize_gguf_filename(direct.group(1), spec_type)
160
+ if prefixes and fallback is None:
161
+ cached = _CACHED_GGUF_RE.search(line)
162
+ if cached:
163
+ candidate = _normalize_gguf_filename(cached.group(1), spec_type)
164
+ if candidate.lower().startswith(prefixes):
165
+ fallback = candidate
166
+ return fallback
167
+
168
+
169
+ def _list_local_hf_cache_files(repo_id: str) -> list[str]:
170
+ """List filenames from the most recent local HF Hub snapshot for `repo_id`, if cached."""
171
+ try:
172
+ from huggingface_hub.constants import HF_HUB_CACHE
173
+
174
+ repo_dir = Path(HF_HUB_CACHE) / f"models--{repo_id.replace('/', '--')}" / "snapshots"
175
+ if not repo_dir.is_dir():
176
+ return []
177
+ snapshots = [p for p in repo_dir.iterdir() if p.is_dir()]
178
+ if not snapshots:
179
+ return []
180
+ latest = max(snapshots, key=lambda p: p.stat().st_mtime)
181
+ return [
182
+ str(p.relative_to(latest))
183
+ for p in latest.rglob("*.gguf")
184
+ if p.is_file() or p.is_symlink()
185
+ ]
186
+ except Exception:
187
+ return []
188
+
189
+
190
+ def discover_hf_sidecar_file(
191
+ model: ModelSpec,
192
+ hf_token: str | None = None,
193
+ ) -> str | None:
194
+ """Discover the auto-selected sidecar GGUF filename in a single-repo HF model for `--spec-type`.
195
+
196
+ Returns None if a separate `speculator_repo`/`speculator_file` is configured, if `--spec-type`
197
+ has no sidecar prefix (e.g. `ngram-*`), or if no matching sidecar exists (e.g. in-file MTP).
198
+ """
199
+ if model.speculator_repo or model.speculator_file:
200
+ return None
201
+ spec_type = model.resolved_spec_type
202
+ if not sidecar_prefixes_for_spec_type(spec_type):
203
+ return None
204
+
205
+ files: list[str] = []
206
+ try:
207
+ from huggingface_hub import HfApi
208
+
209
+ api = HfApi(token=hf_token)
210
+ files = list(api.list_repo_files(repo_id=model.model_repo_base))
211
+ except Exception:
212
+ files = _list_local_hf_cache_files(model.model_repo_base)
213
+
214
+ if not files:
215
+ return None
216
+ return select_hf_sidecar_file(
217
+ files,
218
+ spec_type=spec_type,
219
+ preferred_quant=model.resolved_model_quant,
220
+ )
221
+
222
+
223
+ def parse_effective_draft_n_max(
224
+ log_lines: Iterable[str],
225
+ requested_draft_n_max: int,
226
+ ) -> tuple[int, int | None]:
227
+ """Inspect llama.cpp startup logs for speculator draft-length clamping (e.g. DFlash block_size).
228
+
229
+ Returns `(effective_draft_n_max, detected_block_size)`.
230
+ """
231
+ if requested_draft_n_max <= 0:
232
+ return requested_draft_n_max, None
233
+
234
+ effective = requested_draft_n_max
235
+ block_size: int | None = None
236
+ for line in log_lines:
237
+ bs_match = _BLOCK_SIZE_RE.search(line)
238
+ if bs_match:
239
+ block_size = int(bs_match.group(1))
240
+ if block_size > 1:
241
+ effective = min(effective, block_size - 1)
242
+ clamp_match = _CLAMP_RE.search(line)
243
+ if clamp_match:
244
+ effective = min(effective, int(clamp_match.group(1)))
245
+ return effective, block_size
246
+
247
+
248
+ def detect_llama_version(llama_cmd: list[str]) -> str | None:
249
+ """Query llama / llama-server version without initializing CUDA."""
250
+ if not llama_cmd:
251
+ return None
252
+ env = os.environ.copy()
253
+ env["CUDA_VISIBLE_DEVICES"] = ""
254
+ candidates: list[list[str]] = []
255
+ if len(llama_cmd) >= 2 and llama_cmd[1] == "serve":
256
+ candidates.append([llama_cmd[0], "version"])
257
+ candidates.append([llama_cmd[0], "--version"])
258
+ for cmd in candidates:
259
+ try:
260
+ proc = subprocess.run(
261
+ cmd,
262
+ capture_output=True,
263
+ text=True,
264
+ timeout=10,
265
+ env=env,
266
+ check=False,
267
+ )
268
+ output = (proc.stdout or proc.stderr or "").strip()
269
+ if proc.returncode == 0 and output:
270
+ return output.splitlines()[0].strip()
271
+ except Exception:
272
+ continue
273
+ return None
274
+
275
+
276
+ def build_llama_serve_command(
277
+ model: ModelSpec,
278
+ server: ServerConfig,
279
+ draft_n_max: int,
280
+ port: int,
281
+ ) -> list[str]:
282
+ """Build the `llama serve` / `llama-server` CLI invocation for a given draft_n_max.
283
+
284
+ Supports:
285
+ - Single HF repo containing both model and bundled speculator (e.g. MTP): `-hf <model_repo>`
286
+ - Single HF repo with explicit draft file: `-hf <model_repo> -hfd <model_repo> -md <speculator_file>`
287
+ - Dual HF repos (target + separate speculator): `-hf <model_repo> -hfd <speculator_repo>`
288
+ - Baseline (draft_n_max == 0): `--spec-type none` with no draft model flags
289
+ """
290
+ cmd = list(server.llama_cmd)
291
+
292
+ cmd.extend(["-hf", model.model_repo])
293
+ if model.model_file:
294
+ cmd.extend(["-hff", model.model_file])
295
+
296
+ if model.no_mmproj:
297
+ cmd.append("--no-mmproj")
298
+ elif model.mmproj:
299
+ if model.mmproj.startswith(("http://", "https://")):
300
+ cmd.extend(["--mmproj-url", model.mmproj])
301
+ else:
302
+ cmd.extend(["--mmproj", model.mmproj])
303
+
304
+ if draft_n_max == 0:
305
+ cmd.extend(["--spec-type", "none"])
306
+ else:
307
+ spec_type = model.resolved_spec_type
308
+ spec_types = [t.strip() for t in spec_type.split(",") if t.strip()]
309
+
310
+ if model.speculator_repo:
311
+ cmd.extend(["-hfd", model.speculator_repo])
312
+ if model.speculator_file:
313
+ cmd.extend(["-md", model.speculator_file])
314
+ elif model.speculator_file:
315
+ cmd.extend(["-hfd", model.model_repo_base, "-md", model.speculator_file])
316
+
317
+ cmd.extend(["--spec-type", spec_type])
318
+
319
+ has_draft_type = any(t.startswith("draft-") for t in spec_types)
320
+ if has_draft_type:
321
+ cmd.extend(["--spec-draft-n-max", str(draft_n_max)])
322
+ if server.draft_n_min is not None:
323
+ cmd.extend(["--spec-draft-n-min", str(server.draft_n_min)])
324
+ if server.draft_p_min is not None:
325
+ cmd.extend(["--spec-draft-p-min", str(server.draft_p_min)])
326
+ else:
327
+ if "ngram-mod" in spec_types:
328
+ cmd.extend(["--spec-ngram-mod-n-max", str(draft_n_max)])
329
+ if "ngram-simple" in spec_types:
330
+ cmd.extend(["--spec-ngram-simple-size-m", str(draft_n_max)])
331
+ if "ngram-map-k" in spec_types:
332
+ cmd.extend(["--spec-ngram-map-k-size-m", str(draft_n_max)])
333
+ if "ngram-map-k4v" in spec_types:
334
+ cmd.extend(["--spec-ngram-map-k4v-size-m", str(draft_n_max)])
335
+
336
+ cmd.extend(["--host", server.host, "--port", str(port)])
337
+
338
+ if server.ctx_size is not None:
339
+ cmd.extend(["--ctx-size", str(server.ctx_size)])
340
+ if server.n_gpu_layers is not None:
341
+ cmd.extend(["-ngl", str(server.n_gpu_layers)])
342
+ if server.flash_attn is not None:
343
+ cmd.extend(["--flash-attn", server.flash_attn])
344
+ cmd.extend(["--parallel", str(server.parallel)])
345
+
346
+ if server.extra_args:
347
+ cmd.extend(server.extra_args)
348
+
349
+ return cmd
350
+
351
+
352
+ def parse_llama_completion(data: dict[str, Any], latency_s: float) -> CompletionResponse:
353
+ """Parse an OpenAI-compatible `/v1/chat/completions` payload from llama-server."""
354
+ usage = data.get("usage") or {}
355
+ raw_timings = data.get("timings") or {}
356
+
357
+ content = ""
358
+ finish_reason: str | None = None
359
+ choices = data.get("choices")
360
+ if isinstance(choices, list) and choices and isinstance(choices[0], dict):
361
+ choice = choices[0]
362
+ finish_reason = choice.get("finish_reason")
363
+ message = choice.get("message")
364
+ if isinstance(message, dict) and isinstance(message.get("content"), str):
365
+ content = message["content"]
366
+ elif isinstance(choice.get("text"), str):
367
+ content = choice["text"]
368
+
369
+ prompt_n = int(raw_timings.get("prompt_n") or usage.get("prompt_tokens") or 0)
370
+ predicted_n = int(raw_timings.get("predicted_n") or usage.get("completion_tokens") or 0)
371
+ draft_n = int(raw_timings.get("draft_n") or 0)
372
+ draft_n_accepted = int(raw_timings.get("draft_n_accepted") or 0)
373
+
374
+ def _opt_float(key: str) -> float | None:
375
+ val = raw_timings.get(key)
376
+ return float(val) if isinstance(val, (int, float)) else None
377
+
378
+ timings = CompletionTimings(
379
+ prompt_n=prompt_n,
380
+ predicted_n=predicted_n,
381
+ draft_n=draft_n,
382
+ draft_n_accepted=draft_n_accepted,
383
+ prompt_ms=_opt_float("prompt_ms"),
384
+ predicted_ms=_opt_float("predicted_ms"),
385
+ prompt_per_second=_opt_float("prompt_per_second"),
386
+ predicted_per_second=_opt_float("predicted_per_second"),
387
+ )
388
+
389
+ return CompletionResponse(
390
+ content=content,
391
+ finish_reason=finish_reason,
392
+ latency_s=latency_s,
393
+ timings=timings,
394
+ raw_usage=dict(usage) if isinstance(usage, dict) else {},
395
+ )
396
+
397
+
398
+ class LlamaCppServerBackend:
399
+ """Manages a local `llama serve` process per draft token count on DGX Spark."""
400
+
401
+ def __init__(
402
+ self,
403
+ model: ModelSpec,
404
+ server: ServerConfig,
405
+ log_dir: Path | None = None,
406
+ ) -> None:
407
+ self.model = model
408
+ self.server = server
409
+ self.log_dir = log_dir
410
+ self._proc: subprocess.Popen[str] | None = None
411
+ self._client: httpx.Client | None = None
412
+ self._log_thread: threading.Thread | None = None
413
+ self._log_tail: deque[str] = deque(maxlen=500)
414
+ self._log_file_handle: Any = None
415
+ self._port: int | None = None
416
+ self._last_cmd: list[str] = []
417
+ self._gpu_memory_peak_mib: float | None = None
418
+ self._requested_draft_n_max: int | None = None
419
+ self._effective_draft_n_max: int | None = None
420
+ self._detected_block_size: int | None = None
421
+ self._detected_speculator_file: str | None = None
422
+ self._detected_speculator_file_exact: bool = False
423
+ self._llama_version = detect_llama_version(server.llama_cmd)
424
+
425
+ @property
426
+ def base_url(self) -> str:
427
+ if self._port is None:
428
+ raise RuntimeError("LlamaCppServerBackend is not running.")
429
+ return f"http://{self.server.host}:{self._port}"
430
+
431
+ def gpu_memory_peak_mib(self) -> float | None:
432
+ return self._gpu_memory_peak_mib
433
+
434
+ def effective_draft_n_max(self) -> int | None:
435
+ return self._effective_draft_n_max
436
+
437
+ def detected_speculator_file(self) -> str | None:
438
+ return self._detected_speculator_file
439
+
440
+ def _sample_gpu_memory(self) -> None:
441
+ if self._proc is None or self._proc.poll() is not None:
442
+ return
443
+ current = query_process_gpu_memory_mib(self._proc.pid)
444
+ if current is None:
445
+ return
446
+ if self._gpu_memory_peak_mib is None or current > self._gpu_memory_peak_mib:
447
+ self._gpu_memory_peak_mib = current
448
+
449
+ def runtime_metadata(self) -> dict[str, Any]:
450
+ return {
451
+ "backend": "llama.cpp",
452
+ "llama_version": self._llama_version,
453
+ "llama_cmd": self._last_cmd,
454
+ "detected_speculator_file": self._detected_speculator_file,
455
+ }
456
+
457
+ def _update_detected_speculator(self, line: str) -> None:
458
+ spec_type = self.model.resolved_spec_type
459
+ direct = _LOADING_DRAFT_RE.search(line)
460
+ if direct:
461
+ self._detected_speculator_file = _normalize_gguf_filename(direct.group(1), spec_type)
462
+ self._detected_speculator_file_exact = True
463
+ return
464
+ if not self._detected_speculator_file_exact and self._detected_speculator_file is None:
465
+ found = parse_loaded_draft_file((line,), spec_type=spec_type)
466
+ if found:
467
+ self._detected_speculator_file = found
468
+
469
+ def _pump_logs(self, stream: Any, log_file: Any) -> None:
470
+ try:
471
+ for line in iter(stream.readline, ""):
472
+ stripped = line.rstrip("\n")
473
+ self._log_tail.append(stripped)
474
+ if self._requested_draft_n_max is not None and self._requested_draft_n_max > 0:
475
+ eff, bs = parse_effective_draft_n_max((stripped,), self._requested_draft_n_max)
476
+ if bs is not None:
477
+ self._detected_block_size = bs
478
+ if self._effective_draft_n_max is None or eff < self._effective_draft_n_max:
479
+ self._effective_draft_n_max = eff
480
+ self._update_detected_speculator(stripped)
481
+ if log_file is not None:
482
+ log_file.write(line)
483
+ log_file.flush()
484
+ except Exception:
485
+ pass
486
+ finally:
487
+ try:
488
+ stream.close()
489
+ except Exception:
490
+ pass
491
+
492
+ def _recent_logs(self, max_lines: int = 30) -> str:
493
+ lines = list(self._log_tail)[-max_lines:]
494
+ return "\n".join(lines)
495
+
496
+ def start(self, draft_n_max: int) -> None:
497
+ self.stop()
498
+
499
+ port = self.server.port if self.server.port > 0 else pick_free_port(self.server.host)
500
+ self._port = port
501
+ cmd = build_llama_serve_command(self.model, self.server, draft_n_max=draft_n_max, port=port)
502
+ self._last_cmd = cmd
503
+ self._log_tail.clear()
504
+ self._gpu_memory_peak_mib = None
505
+ self._requested_draft_n_max = draft_n_max
506
+ self._effective_draft_n_max = draft_n_max
507
+ self._detected_block_size = None
508
+ if draft_n_max > 0:
509
+ self._detected_speculator_file = None
510
+ self._detected_speculator_file_exact = False
511
+
512
+ env = os.environ.copy()
513
+ if self.server.hf_token:
514
+ env["HF_TOKEN"] = self.server.hf_token
515
+
516
+ log_handle = None
517
+ if self.log_dir is not None:
518
+ self.log_dir.mkdir(parents=True, exist_ok=True)
519
+ log_path = self.log_dir / f"llama_serve_draft_{draft_n_max}.log"
520
+ log_handle = log_path.open("w", encoding="utf-8")
521
+ self._log_file_handle = log_handle
522
+
523
+ self._proc = subprocess.Popen(
524
+ cmd,
525
+ stdout=subprocess.PIPE,
526
+ stderr=subprocess.STDOUT,
527
+ text=True,
528
+ bufsize=1,
529
+ env=env,
530
+ start_new_session=True,
531
+ )
532
+ assert self._proc.stdout is not None
533
+ self._log_thread = threading.Thread(
534
+ target=self._pump_logs,
535
+ args=(self._proc.stdout, log_handle),
536
+ daemon=True,
537
+ )
538
+ self._log_thread.start()
539
+
540
+ self._client = httpx.Client(timeout=self.server.request_timeout_s)
541
+ self._wait_until_healthy()
542
+ # Re-check buffered lines as well in case startup completed quickly.
543
+ tail_snapshot = list(self._log_tail)
544
+ eff, bs = parse_effective_draft_n_max(tail_snapshot, draft_n_max)
545
+ if bs is not None:
546
+ self._detected_block_size = bs
547
+ if self._effective_draft_n_max is None or eff < self._effective_draft_n_max:
548
+ self._effective_draft_n_max = eff
549
+ if draft_n_max > 0:
550
+ detected_file = parse_loaded_draft_file(
551
+ tail_snapshot,
552
+ spec_type=self.model.resolved_spec_type,
553
+ )
554
+ if detected_file and not self._detected_speculator_file_exact:
555
+ self._detected_speculator_file = detected_file
556
+ self._sample_gpu_memory()
557
+
558
+ def _wait_until_healthy(self) -> None:
559
+ assert self._proc is not None and self._client is not None
560
+ health_url = f"{self.base_url}/health"
561
+ deadline = time.monotonic() + self.server.startup_timeout_s
562
+
563
+ while time.monotonic() < deadline:
564
+ exit_code = self._proc.poll()
565
+ if exit_code is not None:
566
+ if self._log_thread is not None:
567
+ self._log_thread.join(timeout=1.0)
568
+ tail = self._recent_logs()
569
+ self.stop()
570
+ raise RuntimeError(
571
+ f"llama serve exited early with code {exit_code}.\n"
572
+ f"Command: {' '.join(self._last_cmd)}\n"
573
+ f"Recent server output:\n{tail}"
574
+ )
575
+ try:
576
+ resp = self._client.get(health_url, timeout=2.0)
577
+ if resp.status_code == 200:
578
+ return
579
+ # 503 is expected while llama-server is loading weights/speculator.
580
+ except httpx.HTTPError:
581
+ pass
582
+ time.sleep(0.5)
583
+
584
+ tail = self._recent_logs()
585
+ self.stop()
586
+ raise TimeoutError(
587
+ f"Timed out after {self.server.startup_timeout_s:.0f}s waiting for {health_url}.\n"
588
+ f"Command: {' '.join(self._last_cmd)}\n"
589
+ f"Recent server output:\n{tail}"
590
+ )
591
+
592
+ def complete(
593
+ self,
594
+ messages: list[dict[str, Any]],
595
+ generation: GenerationConfig,
596
+ ) -> CompletionResponse:
597
+ if self._client is None or self._port is None:
598
+ raise RuntimeError("LlamaCppServerBackend must be started before calling complete().")
599
+
600
+ payload: dict[str, Any] = {
601
+ "messages": messages,
602
+ "max_tokens": generation.max_tokens,
603
+ "temperature": generation.temperature,
604
+ "stream": False,
605
+ }
606
+ if generation.seed is not None:
607
+ payload["seed"] = generation.seed
608
+ if generation.extra_body:
609
+ payload.update(generation.extra_body)
610
+ payload["stream"] = False
611
+
612
+ endpoint = f"{self.base_url}/v1/chat/completions"
613
+ start = time.perf_counter()
614
+ response = self._client.post(endpoint, json=payload)
615
+ latency_s = time.perf_counter() - start
616
+ if response.status_code != 200:
617
+ body = response.text[:500].replace("\n", "\\n")
618
+ raise RuntimeError(f"HTTP {response.status_code} from {endpoint}: {body}")
619
+
620
+ self._sample_gpu_memory()
621
+ return parse_llama_completion(response.json(), latency_s=latency_s)
622
+
623
+ def stop(self) -> None:
624
+ self._sample_gpu_memory()
625
+ if self._client is not None:
626
+ try:
627
+ self._client.close()
628
+ except Exception:
629
+ pass
630
+ self._client = None
631
+
632
+ if self._proc is not None:
633
+ proc = self._proc
634
+ self._proc = None
635
+ if proc.poll() is None:
636
+ try:
637
+ os.killpg(os.getpgid(proc.pid), signal.SIGTERM)
638
+ except ProcessLookupError:
639
+ pass
640
+ try:
641
+ proc.wait(timeout=15.0)
642
+ except subprocess.TimeoutExpired:
643
+ try:
644
+ os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
645
+ except ProcessLookupError:
646
+ pass
647
+ proc.wait(timeout=5.0)
648
+
649
+ if self._log_thread is not None:
650
+ self._log_thread.join(timeout=2.0)
651
+ self._log_thread = None
652
+
653
+ if self._log_file_handle is not None:
654
+ try:
655
+ self._log_file_handle.close()
656
+ except Exception:
657
+ pass
658
+ self._log_file_handle = None
659
+
660
+ self._port = None