jbr-inference 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.
Files changed (34) hide show
  1. jbr_inference/__init__.py +1 -0
  2. jbr_inference/backends/__init__.py +1 -0
  3. jbr_inference/backends/gpu/__init__.py +1 -0
  4. jbr_inference/backends/gpu/adapter.py +163 -0
  5. jbr_inference/backends/gpu/config.py +71 -0
  6. jbr_inference/backends/gpu/lifecycle.py +231 -0
  7. jbr_inference/backends/gpu/server.py +119 -0
  8. jbr_inference/backends/npu/__init__.py +1 -0
  9. jbr_inference/backends/npu/adapter.py +98 -0
  10. jbr_inference/backends/npu/config.py +124 -0
  11. jbr_inference/backends/npu/convert_model.py +92 -0
  12. jbr_inference/backends/npu/inference.py +105 -0
  13. jbr_inference/backends/npu/server.py +221 -0
  14. jbr_inference/bench/__init__.py +1 -0
  15. jbr_inference/bench/runner.py +561 -0
  16. jbr_inference/models/__init__.py +1 -0
  17. jbr_inference/models/registry.py +279 -0
  18. jbr_inference/models/registry.toml +83 -0
  19. jbr_inference/serving/__init__.py +1 -0
  20. jbr_inference/serving/admin.py +389 -0
  21. jbr_inference/serving/app.py +254 -0
  22. jbr_inference/serving/backends/__init__.py +6 -0
  23. jbr_inference/serving/backends/base.py +80 -0
  24. jbr_inference/serving/backends/fake.py +97 -0
  25. jbr_inference/serving/download.py +283 -0
  26. jbr_inference/serving/errors.py +61 -0
  27. jbr_inference/serving/origin_guard.py +35 -0
  28. jbr_inference/serving/router.py +230 -0
  29. jbr_inference/serving/schemas.py +139 -0
  30. jbr_inference-0.1.0.dist-info/METADATA +121 -0
  31. jbr_inference-0.1.0.dist-info/RECORD +34 -0
  32. jbr_inference-0.1.0.dist-info/WHEEL +4 -0
  33. jbr_inference-0.1.0.dist-info/licenses/LICENSE +202 -0
  34. jbr_inference-0.1.0.dist-info/licenses/NOTICE +12 -0
@@ -0,0 +1 @@
1
+ """jbr-inference: modular local inference platform (NPU + GPU) behind a common API."""
@@ -0,0 +1 @@
1
+ """Espace de noms des adaptateurs de backend (gpu/, npu/) — jamais de couplage croisé entre eux."""
@@ -0,0 +1 @@
1
+ """Adaptateur backend GPU : llama.cpp-server (CUDA) derrière l'API commune."""
@@ -0,0 +1,163 @@
1
+ """Adaptateur backend GPU — implémente le protocole `Backend`.
2
+
3
+ Mode d'intégration RETENU : **proxy HTTP**, jamais l'embarquement direct de
4
+ `llama_cpp`. `LlamaCppGpuBackend` ne dépend que de `httpx` (déjà une dépendance
5
+ de base du projet) et proxifie chaque appel vers un llama.cpp-server (via
6
+ `llama-cpp-python[server]`, cf. `jbr_inference/backends/gpu/server.py`) déjà lancé en
7
+ subprocess séparé, dans le venv dédié `.venv-gpu`. Conséquence structurelle :
8
+ cette classe s'importe sans erreur depuis le venv de BASE (celui de `jbr_inference.serving`,
9
+ de la CI) — elle n'a jamais besoin de `llama_cpp` ni de CUDA au moment de
10
+ l'import, seulement au moment d'un appel réseau réel. C'est ce qui permet à
11
+ `jbr_inference/serving/app.py` de câbler ce backend par défaut sans coupler le venv de base
12
+ à CUDA : hors ligne (CI, pas de serveur GPU démarré), `health()` renvoie
13
+ `False` et le routeur répond 503 `backend_unavailable` — jamais une erreur
14
+ d'import, jamais un couplage venv.
15
+
16
+ `generate_stream` :
17
+ - Ouvre une connexion SSE streamée (`httpx.stream`) vers le llama.cpp-server
18
+ avec `stream: true` (celui-ci émet nativement du SSE OpenAI-compat).
19
+ - Relay chunk par chunk sans bufferiser : chaque `data: {...}` line est parsée,
20
+ le `delta.content` en est extrait et yielded au routeur.
21
+ - `data: [DONE]` marque la fin : le générateur s'arrête proprement.
22
+ - Toute `httpx.HTTPError` → `BackendUnavailableError` (panne réseau mid-stream
23
+ incluse).
24
+
25
+ Zéro couplage croisé : ce module n'importe et n'importera jamais rien sous
26
+ `jbr_inference/backends/npu/` (vérifié par
27
+ `tests/test_gpu_backend.py::test_backends_gpu_never_imports_npu`).
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import json
33
+ from collections.abc import Iterator
34
+ from typing import Any
35
+
36
+ import httpx
37
+
38
+ from jbr_inference.backends.gpu.config import GpuBackendConfig
39
+ from jbr_inference.serving.backends.base import BackendUnavailableError
40
+
41
+
42
+ class LlamaCppGpuBackend:
43
+ """Backend GPU — proxifie en HTTP vers un llama.cpp-server déjà lancé.
44
+
45
+ Implémente le protocole `Backend` (`jbr_inference/serving/backends/base.py`) : le
46
+ routeur ne connaît que cette interface, jamais llama.cpp directement.
47
+ """
48
+
49
+ name = "gpu"
50
+
51
+ def __init__(
52
+ self,
53
+ config: GpuBackendConfig | None = None,
54
+ *,
55
+ transport: httpx.BaseTransport | None = None,
56
+ ) -> None:
57
+ self._config = config or GpuBackendConfig.from_env()
58
+ self._client = httpx.Client(
59
+ base_url=self._config.base_url,
60
+ timeout=self._config.request_timeout_s,
61
+ transport=transport,
62
+ )
63
+
64
+ def health(self) -> bool:
65
+ """True si le serveur répond sur `/v1/models` — jamais ne lève."""
66
+ try:
67
+ resp = self._client.get("/v1/models")
68
+ except httpx.HTTPError:
69
+ return False
70
+ return resp.status_code == 200
71
+
72
+ def available_models(self) -> list[str]:
73
+ """Modèles effectivement servis par CE serveur (introspection réelle)."""
74
+ try:
75
+ resp = self._client.get("/v1/models")
76
+ resp.raise_for_status()
77
+ except httpx.HTTPError as exc:
78
+ raise BackendUnavailableError(
79
+ f"llama.cpp-server unreachable at {self._config.base_url}: {exc}"
80
+ ) from exc
81
+ return [item["id"] for item in resp.json().get("data", [])]
82
+
83
+ def generate(
84
+ self, *, model: str, messages: list[dict[str, str]], **params: Any
85
+ ) -> dict[str, Any]:
86
+ """`POST /v1/chat/completions` réel — traduit toute panne réseau en
87
+ `BackendUnavailableError` (le routeur la mappe en 503 clair, jamais
88
+ un 500 nu — cf. la défense en profondeur
89
+ complémentaire côté `jbr_inference/serving/app.py`).
90
+
91
+ Contrat V1 : voie bloquante, strictement inchangée — appelée ssi
92
+ `stream` est absent ou `False`.
93
+ """
94
+ payload: dict[str, Any] = {"model": model, "messages": messages}
95
+ if params.get("temperature") is not None:
96
+ payload["temperature"] = params["temperature"]
97
+ if params.get("max_tokens") is not None:
98
+ payload["max_tokens"] = params["max_tokens"]
99
+ try:
100
+ resp = self._client.post("/v1/chat/completions", json=payload)
101
+ resp.raise_for_status()
102
+ except httpx.HTTPError as exc:
103
+ raise BackendUnavailableError(
104
+ f"llama.cpp-server unreachable or errored at {self._config.base_url}: {exc}"
105
+ ) from exc
106
+ data = resp.json()
107
+ message = data["choices"][0]["message"]
108
+ return {"role": message.get("role", "assistant"), "content": message["content"]}
109
+
110
+ def generate_stream(
111
+ self, *, model: str, messages: list[dict[str, str]], **params: Any
112
+ ) -> Iterator[str]:
113
+ """Relay SSE streaming depuis le llama.cpp-server (OpenAI-compat natif).
114
+
115
+ Ouvre une connexion streamée (`httpx.stream`) avec `stream: true` dans
116
+ le payload — le serveur émet des `data: {...}` SSE lignes ; on extrait
117
+ `choices[0].delta.content` et on yield chunk par chunk sans bufferiser.
118
+
119
+ `data: [DONE]` : stop naturel du générateur (le routeur ajoute `[DONE]`
120
+ côté client SSE).
121
+
122
+ Toute `httpx.HTTPError` ou panne réseau mid-stream → `BackendUnavailableError`.
123
+ """
124
+ payload: dict[str, Any] = {"model": model, "messages": messages, "stream": True}
125
+ if params.get("temperature") is not None:
126
+ payload["temperature"] = params["temperature"]
127
+ if params.get("max_tokens") is not None:
128
+ payload["max_tokens"] = params["max_tokens"]
129
+ try:
130
+ with self._client.stream("POST", "/v1/chat/completions", json=payload) as response:
131
+ try:
132
+ response.raise_for_status()
133
+ except httpx.HTTPStatusError as exc:
134
+ raise BackendUnavailableError(
135
+ f"llama.cpp-server HTTP error {exc.response.status_code} at "
136
+ f"{self._config.base_url}: {exc}"
137
+ ) from exc
138
+ for line in response.iter_lines():
139
+ if not line.startswith("data: "):
140
+ continue
141
+ data_str = line[len("data: ") :]
142
+ if data_str.strip() == "[DONE]":
143
+ return
144
+ try:
145
+ chunk = json.loads(data_str)
146
+ except json.JSONDecodeError:
147
+ # Ligne malformée : on l'ignore (defensive, ne casse pas le flux).
148
+ continue
149
+ content = chunk.get("choices", [{}])[0].get("delta", {}).get("content")
150
+ if content:
151
+ yield content
152
+ except httpx.HTTPError as exc:
153
+ raise BackendUnavailableError(
154
+ f"llama.cpp-server stream error at {self._config.base_url}: {exc}"
155
+ ) from exc
156
+
157
+ def run(self, *, model: str, task: str, payload: dict[str, Any]) -> dict[str, Any]:
158
+ """Le backend GPU ne sert que `chat` (cf. `jbr_inference/models/registry.toml`) — le
159
+ routeur écarte déjà tout autre `task` avant d'atteindre ce point
160
+ (`task_not_supported`, 400). Levée défensive si jamais invoqué."""
161
+ raise NotImplementedError(
162
+ f"LlamaCppGpuBackend only serves task 'chat' via generate() (got task={task!r})"
163
+ )
@@ -0,0 +1,71 @@
1
+ """Configuration du backend GPU — jamais en dur.
2
+
3
+ Toute la configuration (base URL, port, chemin du modèle, paramètres GPU) se
4
+ pilote par variables d'environnement (préfixe `JBR_GPU_`), avec des valeurs
5
+ par défaut cohérentes avec `jbr_inference/models/registry.toml`. `GpuBackendConfig` est un
6
+ dataclass pur (aucune I/O au chargement, hormis la lecture de `os.environ`) —
7
+ `jbr_inference/backends/gpu/adapter.py` (le client HTTP) et `jbr_inference/backends/gpu/server.py`
8
+ (le
9
+ lanceur de subprocess) le consomment tous les deux, pour rester alignés sur
10
+ la même source de configuration.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ from dataclasses import dataclass
17
+
18
+ #: Modèle par défaut : Qwen2.5-7B-Instruct, GGUF Q4_K_M (cf. jbr_inference/backends/gpu/README.md
19
+ #: pour la justification du choix face au placeholder Llama 3.1 8B du registre initial).
20
+ _DEFAULT_MODEL_ID = "qwen2.5-7b-instruct-q4km"
21
+ _DEFAULT_MODEL_PATH = "models/weights/Qwen2.5-7B-Instruct-Q4_K_M.gguf"
22
+ _DEFAULT_HOST = "127.0.0.1"
23
+ _DEFAULT_PORT = 8081
24
+ # -1 : décharge toutes les couches sur GPU (un 7B Q4_K_M tient en 12 Go VRAM).
25
+ _DEFAULT_N_GPU_LAYERS = -1
26
+ _DEFAULT_N_CTX = 4096
27
+ _DEFAULT_TIMEOUT_S = 120.0
28
+ _DEFAULT_PYTHON_BIN = ".venv-gpu/bin/python"
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class GpuBackendConfig:
33
+ """Configuration résolue du backend GPU (llama.cpp-server CUDA).
34
+
35
+ - `base_url`/`request_timeout_s` : consommés par `jbr_inference/backends/gpu/adapter.py`
36
+ (le client HTTP qui proxifie vers le serveur déjà lancé).
37
+ - `model_path`/`model_alias`/`host`/`port`/`n_gpu_layers`/`n_ctx`/`python_bin` :
38
+ consommés par `jbr_inference/backends/gpu/server.py` (construction de la commande de
39
+ lancement du subprocess llama-cpp-python[server]).
40
+ """
41
+
42
+ model_id: str
43
+ model_path: str
44
+ model_alias: str
45
+ host: str
46
+ port: int
47
+ n_gpu_layers: int
48
+ n_ctx: int
49
+ python_bin: str
50
+ base_url: str
51
+ request_timeout_s: float
52
+
53
+ @classmethod
54
+ def from_env(cls) -> GpuBackendConfig:
55
+ """Résout la config depuis l'environnement (`JBR_GPU_*`), défauts documentés."""
56
+ model_id = os.environ.get("JBR_GPU_MODEL_ID", _DEFAULT_MODEL_ID)
57
+ host = os.environ.get("JBR_GPU_HOST", _DEFAULT_HOST)
58
+ port = int(os.environ.get("JBR_GPU_PORT", str(_DEFAULT_PORT)))
59
+ base_url = os.environ.get("JBR_GPU_BASE_URL", f"http://{host}:{port}")
60
+ return cls(
61
+ model_id=model_id,
62
+ model_path=os.environ.get("JBR_GPU_MODEL_PATH", _DEFAULT_MODEL_PATH),
63
+ model_alias=os.environ.get("JBR_GPU_MODEL_ALIAS", model_id),
64
+ host=host,
65
+ port=port,
66
+ n_gpu_layers=int(os.environ.get("JBR_GPU_N_GPU_LAYERS", str(_DEFAULT_N_GPU_LAYERS))),
67
+ n_ctx=int(os.environ.get("JBR_GPU_N_CTX", str(_DEFAULT_N_CTX))),
68
+ python_bin=os.environ.get("JBR_GPU_PYTHON_BIN", _DEFAULT_PYTHON_BIN),
69
+ base_url=base_url,
70
+ request_timeout_s=float(os.environ.get("JBR_GPU_TIMEOUT_S", str(_DEFAULT_TIMEOUT_S))),
71
+ )
@@ -0,0 +1,231 @@
1
+ """Manager de cycle de vie GPU — switch stop→start d'un seul LLM.
2
+
3
+ Contrainte matérielle : 12 Go VRAM ⇒ UN SEUL LLM chargé à la fois. Ce module
4
+ est le point unique qui possède le `subprocess.Popen` courant du llama.cpp-server
5
+ et le `model_id` actif.
6
+
7
+ `activate(model_id)` résout le `model_path` depuis le registre (champ
8
+ `endpoint.model_path` de l'entrée GPU), arrête le serveur courant (s'il tourne)
9
+ via `jbr_inference.backends.gpu.server.stop()`, puis lance le nouveau via `server.launch()` —
10
+ en réutilisant `_cuda_ld_library_path` + `build_launch_command` sans les réécrire.
11
+
12
+ Discipline PID stricte : n'agit QUE sur le `Popen` qu'il détient. Jamais de
13
+ `pkill`/`pgrep` par nom — un autre service local peut tourner sur la machine et ne doit jamais
14
+ être tué par inadvertance.
15
+
16
+ Usage typique (depuis `jbr_inference/serving/admin.py`) :
17
+
18
+ from jbr_inference.backends.gpu.lifecycle import GpuLifecycleManager
19
+ manager = GpuLifecycleManager(config=config, registry=registry)
20
+ manager.activate("qwen2.5-7b-instruct-q4km")
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import logging
26
+ import subprocess
27
+ import threading
28
+ from pathlib import Path
29
+
30
+ from jbr_inference.backends.gpu import server as gpu_server
31
+ from jbr_inference.backends.gpu.config import GpuBackendConfig
32
+ from jbr_inference.models.registry import ModelRegistry
33
+
34
+ logger = logging.getLogger(__name__)
35
+
36
+
37
+ class GpuLifecycleManager:
38
+ """Possède le subprocess llama.cpp-server courant et le model_id actif.
39
+
40
+ Thread-safe via un verrou interne (un seul activate à la fois — la VRAM
41
+ ne permet pas deux chargements simultanés).
42
+ """
43
+
44
+ def __init__(
45
+ self,
46
+ *,
47
+ config: GpuBackendConfig,
48
+ registry: ModelRegistry,
49
+ ) -> None:
50
+ self._config = config
51
+ self._registry = registry
52
+ self._proc: subprocess.Popen[bytes] | None = None
53
+ self._active_model_id: str | None = None
54
+ self._lock = threading.Lock()
55
+
56
+ @property
57
+ def active_model_id(self) -> str | None:
58
+ """Identifiant du modèle actuellement chargé (None si aucun serveur actif)."""
59
+ return self._active_model_id
60
+
61
+ @property
62
+ def proc(self) -> subprocess.Popen[bytes] | None:
63
+ """Subprocess Popen courant (None si aucun serveur actif)."""
64
+ return self._proc
65
+
66
+ def activate(self, model_id: str) -> None:
67
+ """Stop→start : charge `model_id`, déchargeant tout LLM précédent.
68
+
69
+ Résout `model_path` depuis le champ `endpoint.model_path` du registre.
70
+ Lève `ActivateError` si `model_id` est inconnu, n'est pas un backend gpu,
71
+ ou si `endpoint.model_path` est absent de son entrée registre.
72
+
73
+ Discipline PID stricte : seul le `Popen` interne est arrêté — jamais un
74
+ `pkill` par nom.
75
+ """
76
+ with self._lock:
77
+ entry = self._registry.get(model_id)
78
+ if entry is None:
79
+ raise ActivateError(
80
+ f"model_id {model_id!r} inconnu du registre.",
81
+ code="model_not_found",
82
+ )
83
+ if entry.backend != "gpu":
84
+ raise ActivateError(
85
+ f"model_id {model_id!r} n'est pas un backend gpu (backend={entry.backend!r}).",
86
+ code="not_gpu_backend",
87
+ )
88
+ model_path_raw: str = entry.endpoint.get("model_path", "")
89
+ if not model_path_raw:
90
+ raise ActivateError(
91
+ f"model_id {model_id!r} : champ endpoint.model_path absent ou vide "
92
+ f"dans registry.toml. Impossible d'activer via switch.",
93
+ code="model_path_missing",
94
+ )
95
+
96
+ # Stop le serveur courant avant tout nouveau lancement (un seul LLM en VRAM).
97
+ if self._proc is not None:
98
+ logger.info(
99
+ "lifecycle/gpu: arrêt du serveur courant (model_id=%r, pid=%d)",
100
+ self._active_model_id,
101
+ self._proc.pid,
102
+ )
103
+ gpu_server.stop(self._proc)
104
+ self._proc = None
105
+ self._active_model_id = None
106
+
107
+ # Construit une config dérivée avec le model_path résolu et le model_alias
108
+ # correspondant au model_id demandé.
109
+ model_path = _resolve_model_path(model_path_raw)
110
+ derived_config = _derive_config(self._config, model_id=model_id, model_path=model_path)
111
+
112
+ logger.info(
113
+ "lifecycle/gpu: lancement du serveur (model_id=%r, model_path=%r)",
114
+ model_id,
115
+ model_path,
116
+ )
117
+ proc = gpu_server.launch(derived_config)
118
+ self._proc = proc
119
+ self._active_model_id = model_id
120
+ logger.info(
121
+ "lifecycle/gpu: serveur lancé (model_id=%r, pid=%d)",
122
+ model_id,
123
+ proc.pid,
124
+ )
125
+
126
+ def deactivate(self, model_id: str) -> None:
127
+ """Décharge le modèle GPU et libère la VRAM, sans en charger un autre.
128
+
129
+ Valide `model_id` contre le registre (lève `ActivateError` si inconnu ou
130
+ backend≠gpu), puis arrête le subprocess courant s'il tourne.
131
+
132
+ Idempotente : si aucun modèle n'est chargé (ou si un modèle différent est
133
+ chargé mais que `model_id` est valide), l'arrêt est quand même effectué —
134
+ on ne lève jamais d'erreur quand il n'y a rien à décharger.
135
+
136
+ Discipline PID stricte : seul le `Popen` interne est arrêté — jamais un
137
+ `pkill` par nom.
138
+ """
139
+ with self._lock:
140
+ entry = self._registry.get(model_id)
141
+ if entry is None:
142
+ raise ActivateError(
143
+ f"model_id {model_id!r} inconnu du registre.",
144
+ code="model_not_found",
145
+ )
146
+ if entry.backend != "gpu":
147
+ raise ActivateError(
148
+ f"model_id {model_id!r} n'est pas un backend gpu (backend={entry.backend!r}).",
149
+ code="not_gpu_backend",
150
+ )
151
+ # Idempotent : on arrête le process détenu, s'il existe.
152
+ if self._proc is not None:
153
+ logger.info(
154
+ "lifecycle/gpu: déactivation (model_id=%r, pid=%d)",
155
+ self._active_model_id,
156
+ self._proc.pid,
157
+ )
158
+ gpu_server.stop(self._proc)
159
+ self._proc = None
160
+ self._active_model_id = None
161
+ else:
162
+ logger.info(
163
+ "lifecycle/gpu: deactivate — aucun serveur actif (model_id=%r), no-op.",
164
+ model_id,
165
+ )
166
+
167
+ def stop_current(self) -> None:
168
+ """Arrête le serveur courant s'il tourne (PID strict, jamais pkill)."""
169
+ with self._lock:
170
+ if self._proc is not None:
171
+ logger.info(
172
+ "lifecycle/gpu: arrêt explicite (model_id=%r, pid=%d)",
173
+ self._active_model_id,
174
+ self._proc.pid,
175
+ )
176
+ gpu_server.stop(self._proc)
177
+ self._proc = None
178
+ self._active_model_id = None
179
+
180
+
181
+ class ActivateError(Exception):
182
+ """Erreur sémantique de l'activation (modèle inconnu, backend non-gpu,
183
+ model_path manquant). Portée par le router admin pour construire un 404 typé."""
184
+
185
+ def __init__(self, message: str, *, code: str) -> None:
186
+ super().__init__(message)
187
+ self.code = code
188
+
189
+
190
+ # ---------------------------------------------------------------------------
191
+ # Helpers privés
192
+ # ---------------------------------------------------------------------------
193
+
194
+
195
+ def _resolve_model_path(raw: str) -> str:
196
+ """Résout le chemin du modèle en absolu si nécessaire.
197
+
198
+ `model_path` est stocké dans registry.toml comme chemin relatif à la racine du
199
+ repo (ex. "models/weights/Qwen2.5-7B-Instruct-Q4_K_M.gguf"). On le résout en
200
+ absolu à partir du répertoire courant au moment de l'appel — le serving est
201
+ normalement lancé depuis la racine du repo.
202
+ """
203
+ p = Path(raw)
204
+ if not p.is_absolute():
205
+ p = Path.cwd() / p
206
+ return str(p)
207
+
208
+
209
+ def _derive_config(
210
+ base: GpuBackendConfig,
211
+ *,
212
+ model_id: str,
213
+ model_path: str,
214
+ ) -> GpuBackendConfig:
215
+ """Construit une config dérivée avec model_id et model_path substitués.
216
+
217
+ Tous les autres champs (host, port, n_gpu_layers, n_ctx, python_bin, …)
218
+ sont hérités du `base` résolu depuis les variables d'env.
219
+ """
220
+ return GpuBackendConfig(
221
+ model_id=model_id,
222
+ model_path=model_path,
223
+ model_alias=model_id,
224
+ host=base.host,
225
+ port=base.port,
226
+ n_gpu_layers=base.n_gpu_layers,
227
+ n_ctx=base.n_ctx,
228
+ python_bin=base.python_bin,
229
+ base_url=base.base_url,
230
+ request_timeout_s=base.request_timeout_s,
231
+ )
@@ -0,0 +1,119 @@
1
+ """Lancement du llama.cpp-server (CUDA) en subprocess managé.
2
+
3
+ Le serveur réel tourne dans le venv dédié `.venv-gpu` (`llama-cpp-python[server]`,
4
+ jamais installé dans le venv de base — cf. `pyproject.toml`). Ce
5
+ module construit la commande de lancement (`build_launch_command`, pur et
6
+ testable hors-ligne) et un mince wrapper `launch()`/`stop()` autour de
7
+ `subprocess.Popen` pour l'exécution effective.
8
+
9
+ Usage typique (runbook, cf. `jbr_inference/backends/gpu/README.md`) :
10
+
11
+ from jbr_inference.backends.gpu.config import GpuBackendConfig
12
+ from jbr_inference.backends.gpu.server import launch, stop
13
+
14
+ config = GpuBackendConfig.from_env()
15
+ proc = launch(config)
16
+ ...
17
+ stop(proc)
18
+
19
+ Les bibliothèques CUDA (cudart/cublas) prébuild par wheel (pip, hors toolchain
20
+ système — cf. README) doivent être visibles au chargement du subprocess :
21
+ `launch()` complète `LD_LIBRARY_PATH` avec les répertoires `nvidia/*/lib` du
22
+ venv `.venv-gpu` avant de lancer la commande (cf. `_cuda_ld_library_path`).
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import os
28
+ import subprocess
29
+ from pathlib import Path
30
+
31
+ from jbr_inference.backends.gpu.config import GpuBackendConfig
32
+
33
+
34
+ def build_launch_command(config: GpuBackendConfig) -> list[str]:
35
+ """Commande `argv` pour lancer `llama-cpp-python[server]` avec offload CUDA.
36
+
37
+ Pure (aucune I/O, aucun subprocess) — testable hors-ligne. Chemins,
38
+ port, alias et paramètres GPU proviennent tous de `config` (jamais en
39
+ dur ici).
40
+ """
41
+ return [
42
+ config.python_bin,
43
+ "-m",
44
+ "llama_cpp.server",
45
+ "--model",
46
+ config.model_path,
47
+ "--model_alias",
48
+ config.model_alias,
49
+ "--host",
50
+ config.host,
51
+ "--port",
52
+ str(config.port),
53
+ "--n_gpu_layers",
54
+ str(config.n_gpu_layers),
55
+ "--n_ctx",
56
+ str(config.n_ctx),
57
+ ]
58
+
59
+
60
+ def _cuda_ld_library_path(config: GpuBackendConfig) -> str:
61
+ """Répertoires des libs CUDA (cudart/cublas) livrées par wheel pip dans le
62
+ venv du backend GPU (`nvidia-cuda-runtime-cu12`, `nvidia-cublas-cu12` —
63
+ cf. `jbr_inference/backends/gpu/README.md`), à préfixer à `LD_LIBRARY_PATH` pour que le
64
+ binding CUDA prébuild de `llama-cpp-python` trouve `libcudart.so.12` /
65
+ `libcublas.so.12` sans toolchain CUDA système installée.
66
+
67
+ Dérivé de `config.python_bin` (chemin vers l'interpréteur du venv dédié)
68
+ plutôt que d'un chemin en dur — reste correct si `.venv-gpu` est déplacé
69
+ ou renommé via `JBR_GPU_PYTHON_BIN`.
70
+
71
+ Correctif : `.venv-gpu/bin/python` est typiquement un
72
+ **symlink** vers l'interpréteur système/uv — `Path.resolve()` le suivrait
73
+ hors du venv (ex. `/usr` ou le store `uv python`), perdant le
74
+ `site-packages` local où les wheels `nvidia-*` sont installés. Seul
75
+ `.absolute()` est utilisé ici (normalise `.`/`..`, ne suit JAMAIS un
76
+ symlink). Le répertoire `pythonX.Y/` est découvert par glob plutôt que
77
+ déduit de `sys.version_info` de l'interpréteur APPELANT (ce module peut
78
+ être importé depuis le venv de base, dont la version Python peut différer
79
+ de celle de `.venv-gpu` — constaté à l'usage : appelant 3.14 vs venv
80
+ GPU 3.12, `LD_LIBRARY_PATH` calculé vide dans les deux cas).
81
+ """
82
+ venv_root = Path(config.python_bin).absolute().parent.parent
83
+ lib_dir = venv_root / "lib"
84
+ if not lib_dir.is_dir():
85
+ return ""
86
+ nvidia_roots = sorted(lib_dir.glob("python3.*/site-packages/nvidia"))
87
+ if not nvidia_roots:
88
+ return ""
89
+ lib_dirs = sorted(p for p in nvidia_roots[0].glob("*/lib") if p.is_dir())
90
+ return ":".join(str(p) for p in lib_dirs)
91
+
92
+
93
+ def launch(config: GpuBackendConfig) -> subprocess.Popen[bytes]:
94
+ """Lance le serveur en subprocess managé (ne bloque pas — le process
95
+ tourne en arrière-plan jusqu'à `stop()` ou un arrêt externe).
96
+
97
+ Le process hérite l'environnement courant, complété par le
98
+ `LD_LIBRARY_PATH` CUDA (cf. `_cuda_ld_library_path`).
99
+ """
100
+ env = dict(os.environ)
101
+ cuda_libs = _cuda_ld_library_path(config)
102
+ if cuda_libs:
103
+ existing = env.get("LD_LIBRARY_PATH", "")
104
+ env["LD_LIBRARY_PATH"] = f"{cuda_libs}:{existing}" if existing else cuda_libs
105
+ return subprocess.Popen(build_launch_command(config), env=env)
106
+
107
+
108
+ def stop(proc: subprocess.Popen[bytes], *, timeout_s: float = 15.0) -> None:
109
+ """Arrêt propre (SIGTERM puis attente) du subprocess lancé par `launch()`.
110
+
111
+ Discipline PID stricte : n'agit QUE sur le `Popen` fourni (jamais un
112
+ `pkill`/`pgrep` large sur le nom du process).
113
+ """
114
+ proc.terminate()
115
+ try:
116
+ proc.wait(timeout=timeout_s)
117
+ except subprocess.TimeoutExpired:
118
+ proc.kill()
119
+ proc.wait(timeout=timeout_s)
@@ -0,0 +1 @@
1
+ """Adaptateur backend NPU : encodeur NER/anonymisation OpenVINO, portable Linux."""