BlueSkyXN commited on
Commit
f01b4c0
·
1 Parent(s): b7f1562

Improve DiffusionGemma Space runtime diagnostics

Browse files
Files changed (6) hide show
  1. DEPLOY.md +17 -1
  2. README.md +29 -3
  3. app.py +108 -1
  4. scripts/build_llama_diffusion.sh +43 -2
  5. src/prepare.py +74 -1
  6. src/runner.py +5 -0
DEPLOY.md CHANGED
@@ -41,6 +41,17 @@ DEFAULT_MAX_TOKENS=512
41
  MAX_MAX_TOKENS=2048
42
  ```
43
 
 
 
 
 
 
 
 
 
 
 
 
44
  Recommended with persistent storage:
45
 
46
  ```text
@@ -57,6 +68,8 @@ After the Space is running:
57
 
58
  ```bash
59
  curl "$SPACE_URL/health"
 
 
60
  ```
61
 
62
  Then use the Gradio queue endpoint:
@@ -87,9 +100,12 @@ Look for errors like:
87
  nvcc not found
88
  CMake cannot find CUDA
89
  GGML_CUDA failed
 
90
  ```
91
 
92
- Then switch to a prebuilt binary:
 
 
93
 
94
  ```text
95
  BUILD_LLAMA_DIFFUSION=0
 
41
  MAX_MAX_TOKENS=2048
42
  ```
43
 
44
+ The qwen36 reference Space avoids runtime CUDA build drift by setting a prebuilt
45
+ runner URL and preparing it on startup. For this DiffusionGemma Space, use the
46
+ same pattern once a tested `llama-diffusion-cli` package is available:
47
+
48
+ ```text
49
+ BUILD_LLAMA_DIFFUSION=0
50
+ LLAMA_DIFFUSION_BIN_URL=https://.../llama-diffusion-cli-linux-cuda-package.tar.gz
51
+ PREPARE_RUNTIME_ON_STARTUP=1
52
+ DOWNLOAD_MODEL_ON_STARTUP=1
53
+ ```
54
+
55
  Recommended with persistent storage:
56
 
57
  ```text
 
68
 
69
  ```bash
70
  curl "$SPACE_URL/health"
71
+ curl "$SPACE_URL/v2/runtime"
72
+ curl "$SPACE_URL/v2/zerogpu/probe"
73
  ```
74
 
75
  Then use the Gradio queue endpoint:
 
100
  nvcc not found
101
  CMake cannot find CUDA
102
  GGML_CUDA failed
103
+ undefined reference to `cuda...@libcudart.so`
104
  ```
105
 
106
+ The build script adds NVIDIA Python package library paths and installs sibling
107
+ `.so` files next to `llama-diffusion-cli`. If CUDA linking still fails, switch
108
+ to a prebuilt binary:
109
 
110
  ```text
111
  BUILD_LLAMA_DIFFUSION=0
README.md CHANGED
@@ -30,6 +30,9 @@ gradio.Server
30
  llama-diffusion-cli subprocess
31
  /v1/models
32
  /v1/chat/completions
 
 
 
33
  ```
34
 
35
  The first version is **text-only** and **final-only**. `stream=true` is supported as a compatibility shim: it sends the final result as one OpenAI-style delta, not token-by-token streaming.
@@ -73,6 +76,17 @@ DOWNLOAD_MODEL_ON_STARTUP=0
73
  GRADIO_SSR_MODE=false
74
  ```
75
 
 
 
 
 
 
 
 
 
 
 
 
76
  If you attach persistent storage:
77
 
78
  ```text
@@ -110,7 +124,18 @@ The runner can be supplied in three ways:
110
  LLAMA_BUILD_CUDA=1
111
  ```
112
 
113
- Building inside the Space is convenient for the first test, but it is the least deterministic option. A prebuilt binary is preferable once you know which `llama.cpp` PR revision works.
 
 
 
 
 
 
 
 
 
 
 
114
 
115
  ## API usage
116
 
@@ -198,8 +223,9 @@ static/index.html
198
  6. Deploy.
199
  7. Inspect logs for `llama-diffusion-cli` build success.
200
  8. Call `/health`.
201
- 9. Run `scripts/call_space_direct.sh`.
202
- 10. Then test `/v1/chat/completions`.
 
203
 
204
  ## Known limitations
205
 
 
30
  llama-diffusion-cli subprocess
31
  /v1/models
32
  /v1/chat/completions
33
+ /v2/runtime
34
+ /v2/logs
35
+ /v2/zerogpu/probe
36
  ```
37
 
38
  The first version is **text-only** and **final-only**. `stream=true` is supported as a compatibility shim: it sends the final result as one OpenAI-style delta, not token-by-token streaming.
 
76
  GRADIO_SSR_MODE=false
77
  ```
78
 
79
+ The qwen36 reference Space is stable because it uses a prebuilt CUDA runner
80
+ package through `LLAMA_CLI_URL` and prepares it on startup. Use the same strategy
81
+ for DiffusionGemma once you have a tested `llama-diffusion-cli` package:
82
+
83
+ ```text
84
+ BUILD_LLAMA_DIFFUSION=0
85
+ LLAMA_DIFFUSION_BIN_URL=https://.../llama-diffusion-cli-linux-cuda-package.tar.gz
86
+ PREPARE_RUNTIME_ON_STARTUP=1
87
+ DOWNLOAD_MODEL_ON_STARTUP=1
88
+ ```
89
+
90
  If you attach persistent storage:
91
 
92
  ```text
 
124
  LLAMA_BUILD_CUDA=1
125
  ```
126
 
127
+ Building inside the Space is convenient for the first test, but it is the least deterministic option. The build script adds NVIDIA Python package library paths for CUDA/cuBLAS linking and copies sibling shared libraries next to `llama-diffusion-cli`, but a prebuilt binary package is still preferable once you know which `llama.cpp` PR revision works.
128
+
129
+ ## Diagnostics
130
+
131
+ ```text
132
+ GET /v2/runtime
133
+ GET /v2/logs
134
+ GET /v2/zerogpu/probe
135
+ GET /v2/zerogpu/probe?cli=1
136
+ ```
137
+
138
+ `/v2/zerogpu/probe` runs inside `@spaces.GPU` and is the direct way to confirm that ZeroGPU allocated a CUDA device. `?cli=1` probes the runner only if `llama-diffusion-cli` already exists; it does not trigger a build by itself.
139
 
140
  ## API usage
141
 
 
223
  6. Deploy.
224
  7. Inspect logs for `llama-diffusion-cli` build success.
225
  8. Call `/health`.
226
+ 9. Call `/v2/runtime` and `/v2/zerogpu/probe`.
227
+ 10. Run `scripts/call_space_direct.sh`.
228
+ 11. Then test `/v1/chat/completions`.
229
 
230
  ## Known limitations
231
 
app.py CHANGED
@@ -30,6 +30,8 @@ except Exception: # pragma: no cover - local development fallback only
30
 
31
  import json
32
  import os
 
 
33
  import threading
34
  import time
35
  import uuid
@@ -49,7 +51,7 @@ from src.openai import (
49
  make_sse_chunk,
50
  make_sse_done,
51
  )
52
- from src.prepare import prepare_runtime_if_requested, runtime_status
53
 
54
  prepare_runtime_if_requested()
55
 
@@ -120,6 +122,111 @@ async def v1_models() -> dict[str, Any]:
120
  return {"object": "list", "data": public_model_list()}
121
 
122
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  @app.post("/v1/chat/completions")
124
  async def v1_chat_completions(request: Request):
125
  """OpenAI-compatible convenience route.
 
30
 
31
  import json
32
  import os
33
+ import shlex
34
+ import subprocess
35
  import threading
36
  import time
37
  import uuid
 
51
  make_sse_chunk,
52
  make_sse_done,
53
  )
54
+ from src.prepare import prepare_runtime_if_requested, runtime_events, runtime_status
55
 
56
  prepare_runtime_if_requested()
57
 
 
122
  return {"object": "list", "data": public_model_list()}
123
 
124
 
125
+ def _probe_command(cmd: list[str], timeout: int = 12) -> dict[str, Any]:
126
+ try:
127
+ proc = subprocess.run(
128
+ cmd,
129
+ text=True,
130
+ capture_output=True,
131
+ timeout=timeout,
132
+ check=False,
133
+ )
134
+ return {
135
+ "cmd": shlex.join(cmd),
136
+ "returncode": proc.returncode,
137
+ "stdout_tail": (proc.stdout or "")[-2000:],
138
+ "stderr_tail": (proc.stderr or "")[-2000:],
139
+ }
140
+ except Exception as exc: # noqa: BLE001 - diagnostic endpoint
141
+ return {"cmd": shlex.join(cmd), "error": str(exc)}
142
+
143
+
144
+ @spaces.GPU(size=settings.zero_gpu_size, duration=60)
145
+ def _gpu_probe(include_cli: bool = False) -> dict[str, Any]:
146
+ diagnostics = [
147
+ _probe_command(["nvidia-smi", "-L"]),
148
+ _probe_command(["nvidia-smi"]),
149
+ _probe_command(["bash", "-lc", "printf 'CUDA_VISIBLE_DEVICES=%s\\nLD_LIBRARY_PATH=%s\\n' \"$CUDA_VISIBLE_DEVICES\" \"$LD_LIBRARY_PATH\""]),
150
+ _probe_command([
151
+ "bash",
152
+ "-lc",
153
+ "ls -l ${CUDA_HOME:-/usr/local/cuda}/lib64/libcudart.so* "
154
+ "${CUDA_HOME:-/usr/local/cuda}/lib64/libcublas.so* "
155
+ "/usr/local/lib/python*/site-packages/nvidia/*/lib/libcudart.so* "
156
+ "/usr/local/lib/python*/site-packages/nvidia/*/lib/libcublas.so* 2>/dev/null || true",
157
+ ]),
158
+ ]
159
+ cli_result = None
160
+ if include_cli and settings.llama_diffusion_bin.exists():
161
+ cli_result = _probe_command([str(settings.llama_diffusion_bin), "--help"])
162
+
163
+ return {
164
+ "ok": True,
165
+ "cuda_visible_devices": os.getenv("CUDA_VISIBLE_DEVICES", ""),
166
+ "diagnostics": diagnostics,
167
+ "llama_diffusion_cli_probe": cli_result,
168
+ "note": "This endpoint runs inside @spaces.GPU; a MIG value in CUDA_VISIBLE_DEVICES means ZeroGPU allocation is active.",
169
+ }
170
+
171
+
172
+ @app.get("/v2")
173
+ async def v2_index() -> dict[str, Any]:
174
+ return {
175
+ "object": "api.catalog",
176
+ "endpoints": [
177
+ {"method": "GET", "path": "/health"},
178
+ {"method": "GET", "path": "/v1/models"},
179
+ {"method": "GET", "path": "/v2/runtime"},
180
+ {"method": "GET", "path": "/v2/logs"},
181
+ {"method": "GET", "path": "/v2/zerogpu/probe"},
182
+ {"method": "POST", "path": "/v1/chat/completions"},
183
+ {"method": "POST", "path": "/gradio_api/call/chat"},
184
+ ],
185
+ "default_model": default_model_id(),
186
+ }
187
+
188
+
189
+ @app.get("/v2/runtime")
190
+ async def v2_runtime() -> dict[str, Any]:
191
+ return {
192
+ "ok": True,
193
+ "service": "diffusiongemma-gguf-zerogpu-api",
194
+ "default_model": default_model_id(),
195
+ "zero_gpu_size": settings.zero_gpu_size,
196
+ "runtime": runtime_status(),
197
+ "limits": {
198
+ "default_max_tokens": settings.default_max_tokens,
199
+ "max_max_tokens": settings.max_max_tokens,
200
+ "diffusion_max_steps": settings.diffusion_max_steps,
201
+ "api_time_limit_seconds": settings.api_time_limit_seconds,
202
+ "cli_timeout_seconds": settings.cli_timeout_seconds,
203
+ },
204
+ "build": {
205
+ "build_llama_diffusion": settings.build_llama_diffusion,
206
+ "llama_build_cuda": settings.llama_build_cuda,
207
+ "llama_cmake_extra_args": settings.llama_cmake_extra_args,
208
+ "llama_diffusion_bin_url": bool(settings.llama_diffusion_bin_url),
209
+ },
210
+ "paths": {
211
+ "data_dir": str(settings.data_dir),
212
+ "model_cache_dir": str(settings.model_cache_dir),
213
+ "bin_dir": str(settings.bin_dir),
214
+ "llama_src_dir": str(settings.llama_src_dir),
215
+ },
216
+ }
217
+
218
+
219
+ @app.get("/v2/logs")
220
+ async def v2_logs(limit: int = 100) -> dict[str, Any]:
221
+ return {"object": "event.list", "data": runtime_events(limit)}
222
+
223
+
224
+ @app.get("/v2/zerogpu/probe")
225
+ async def v2_zerogpu_probe(request: Request) -> dict[str, Any]:
226
+ include_cli = str(request.query_params.get("cli", "")).lower() in {"1", "true", "yes", "on"}
227
+ return _gpu_probe(include_cli=include_cli)
228
+
229
+
230
  @app.post("/v1/chat/completions")
231
  async def v1_chat_completions(request: Request):
232
  """OpenAI-compatible convenience route.
scripts/build_llama_diffusion.sh CHANGED
@@ -6,6 +6,9 @@ LLAMA_BIN_DIR="${LLAMA_BIN_DIR:-/data/bin}"
6
  LLAMA_DIFFUSION_BIN="${LLAMA_DIFFUSION_BIN:-${LLAMA_BIN_DIR}/llama-diffusion-cli}"
7
  LLAMA_BUILD_CUDA="${LLAMA_BUILD_CUDA:-1}"
8
  LLAMA_CMAKE_EXTRA_ARGS="${LLAMA_CMAKE_EXTRA_ARGS:-}"
 
 
 
9
 
10
  mkdir -p "${LLAMA_BIN_DIR}"
11
 
@@ -31,6 +34,42 @@ if [[ "${LLAMA_BUILD_CUDA}" == "1" || "${LLAMA_BUILD_CUDA}" == "true" ]]; then
31
  CMAKE_ARGS+=("-DGGML_CUDA=ON")
32
  fi
33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  if [[ -n "${LLAMA_CMAKE_EXTRA_ARGS}" ]]; then
35
  # shellcheck disable=SC2206
36
  EXTRA_ARGS=( ${LLAMA_CMAKE_EXTRA_ARGS} )
@@ -38,14 +77,16 @@ if [[ -n "${LLAMA_CMAKE_EXTRA_ARGS}" ]]; then
38
  fi
39
 
40
  echo "[build] cmake args: ${CMAKE_ARGS[*]}"
41
- cmake -B build "${CMAKE_ARGS[@]}"
42
- cmake --build build -j "$(nproc)" --config Release --target llama-diffusion-cli
43
 
44
  if [[ ! -x build/bin/llama-diffusion-cli ]]; then
45
  echo "[build] build/bin/llama-diffusion-cli was not produced" >&2
46
  exit 1
47
  fi
48
 
 
 
49
  cp build/bin/llama-diffusion-cli "${LLAMA_DIFFUSION_BIN}"
50
  chmod +x "${LLAMA_DIFFUSION_BIN}"
51
  echo "[build] Installed ${LLAMA_DIFFUSION_BIN}"
 
6
  LLAMA_DIFFUSION_BIN="${LLAMA_DIFFUSION_BIN:-${LLAMA_BIN_DIR}/llama-diffusion-cli}"
7
  LLAMA_BUILD_CUDA="${LLAMA_BUILD_CUDA:-1}"
8
  LLAMA_CMAKE_EXTRA_ARGS="${LLAMA_CMAKE_EXTRA_ARGS:-}"
9
+ LLAMA_CMAKE_EXE_LINKER_FLAGS="${LLAMA_CMAKE_EXE_LINKER_FLAGS:-}"
10
+ LLAMA_CMAKE_SHARED_LINKER_FLAGS="${LLAMA_CMAKE_SHARED_LINKER_FLAGS:-}"
11
+ CMAKE_BUILD_PARALLEL="${CMAKE_BUILD_PARALLEL:-$(nproc)}"
12
 
13
  mkdir -p "${LLAMA_BIN_DIR}"
14
 
 
34
  CMAKE_ARGS+=("-DGGML_CUDA=ON")
35
  fi
36
 
37
+ NVIDIA_LIB_DIRS=()
38
+ while IFS= read -r lib_dir; do
39
+ [[ -n "${lib_dir}" && -d "${lib_dir}" ]] && NVIDIA_LIB_DIRS+=("${lib_dir}")
40
+ done < <(python - <<'PY'
41
+ from pathlib import Path
42
+ import site
43
+
44
+ seen = set()
45
+ for root in [*site.getsitepackages(), site.getusersitepackages()]:
46
+ if not root:
47
+ continue
48
+ base = Path(root) / "nvidia"
49
+ if not base.exists():
50
+ continue
51
+ for path in base.glob("*/lib"):
52
+ if path.is_dir():
53
+ value = str(path)
54
+ if value not in seen:
55
+ seen.add(value)
56
+ print(value)
57
+ PY
58
+ )
59
+
60
+ if [[ "${#NVIDIA_LIB_DIRS[@]}" -gt 0 ]]; then
61
+ NVIDIA_LD_PATH="$(IFS=:; echo "${NVIDIA_LIB_DIRS[*]}")"
62
+ export LD_LIBRARY_PATH="${NVIDIA_LD_PATH}${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}"
63
+
64
+ LINK_FLAGS=""
65
+ for lib_dir in "${NVIDIA_LIB_DIRS[@]}"; do
66
+ LINK_FLAGS+=" -L${lib_dir} -Wl,-rpath,${lib_dir} -Wl,-rpath-link,${lib_dir}"
67
+ done
68
+ LINK_FLAGS+=" -Wl,--allow-shlib-undefined"
69
+ CMAKE_ARGS+=("-DCMAKE_EXE_LINKER_FLAGS=${LINK_FLAGS} ${LLAMA_CMAKE_EXE_LINKER_FLAGS}")
70
+ CMAKE_ARGS+=("-DCMAKE_SHARED_LINKER_FLAGS=${LINK_FLAGS} ${LLAMA_CMAKE_SHARED_LINKER_FLAGS}")
71
+ fi
72
+
73
  if [[ -n "${LLAMA_CMAKE_EXTRA_ARGS}" ]]; then
74
  # shellcheck disable=SC2206
75
  EXTRA_ARGS=( ${LLAMA_CMAKE_EXTRA_ARGS} )
 
77
  fi
78
 
79
  echo "[build] cmake args: ${CMAKE_ARGS[*]}"
80
+ cmake -B build -DCMAKE_BUILD_TYPE=Release "${CMAKE_ARGS[@]}"
81
+ cmake --build build -j "${CMAKE_BUILD_PARALLEL}" --config Release --target llama-diffusion-cli
82
 
83
  if [[ ! -x build/bin/llama-diffusion-cli ]]; then
84
  echo "[build] build/bin/llama-diffusion-cli was not produced" >&2
85
  exit 1
86
  fi
87
 
88
+ shopt -s nullglob
89
+ cp -a build/bin/lib*.so* "${LLAMA_BIN_DIR}/"
90
  cp build/bin/llama-diffusion-cli "${LLAMA_DIFFUSION_BIN}"
91
  chmod +x "${LLAMA_DIFFUSION_BIN}"
92
  echo "[build] Installed ${LLAMA_DIFFUSION_BIN}"
src/prepare.py CHANGED
@@ -1,12 +1,16 @@
1
  from __future__ import annotations
2
 
 
3
  import os
4
  import shutil
 
5
  import stat
6
  import subprocess
7
  import tarfile
8
  import tempfile
9
  import zipfile
 
 
10
  from pathlib import Path
11
  from urllib.request import urlretrieve
12
 
@@ -17,6 +21,52 @@ from src.errors import ApiError
17
 
18
 
19
  _runtime_notes: list[str] = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
 
22
  def runtime_status() -> dict[str, object]:
@@ -24,6 +74,10 @@ def runtime_status() -> dict[str, object]:
24
  "bin": str(settings.llama_diffusion_bin),
25
  "bin_exists": settings.llama_diffusion_bin.exists(),
26
  "model_cache_dir": str(settings.model_cache_dir),
 
 
 
 
27
  "notes": list(_runtime_notes[-20:]),
28
  }
29
 
@@ -42,6 +96,7 @@ def _find_binary(root: Path) -> Path | None:
42
 
43
  def _download_prebuilt_binary(url: str) -> None:
44
  settings.bin_dir.mkdir(parents=True, exist_ok=True)
 
45
  with tempfile.TemporaryDirectory() as td:
46
  tempdir = Path(td)
47
  archive_path = tempdir / "llama-diffusion-download"
@@ -63,9 +118,20 @@ def _download_prebuilt_binary(url: str) -> None:
63
 
64
  if not binary or not binary.exists():
65
  raise ApiError("runtime_error", "Could not find llama-diffusion-cli in downloaded artifact", 500)
66
- shutil.copy2(binary, settings.llama_diffusion_bin)
 
 
 
 
 
 
 
 
 
 
67
  _mark_executable(settings.llama_diffusion_bin)
68
  _runtime_notes.append(f"Installed prebuilt binary from {url}")
 
69
 
70
 
71
  def build_llama_diffusion() -> None:
@@ -73,12 +139,14 @@ def build_llama_diffusion() -> None:
73
  if not script.exists():
74
  raise ApiError("runtime_error", f"Missing build script: {script}", 500)
75
 
 
76
  env = dict(os.environ)
77
  env.setdefault("LLAMA_SRC_DIR", str(settings.llama_src_dir))
78
  env.setdefault("LLAMA_BIN_DIR", str(settings.bin_dir))
79
  env.setdefault("LLAMA_DIFFUSION_BIN", str(settings.llama_diffusion_bin))
80
  env.setdefault("LLAMA_BUILD_CUDA", "1" if settings.llama_build_cuda else "0")
81
  env.setdefault("LLAMA_CMAKE_EXTRA_ARGS", settings.llama_cmake_extra_args)
 
82
 
83
  proc = subprocess.run(
84
  ["bash", str(script)],
@@ -88,17 +156,20 @@ def build_llama_diffusion() -> None:
88
  timeout=int(os.getenv("LLAMA_BUILD_TIMEOUT_SECONDS", "1800")),
89
  )
90
  if proc.returncode != 0:
 
91
  raise ApiError(
92
  "runtime_error",
93
  "Failed to build llama-diffusion-cli. stderr tail: " + proc.stderr[-4000:],
94
  500,
95
  )
96
  _runtime_notes.append("Built llama-diffusion-cli from llama.cpp DiffusionGemma PR")
 
97
 
98
 
99
  def ensure_runner_binary() -> Path:
100
  if settings.llama_diffusion_bin.exists():
101
  _mark_executable(settings.llama_diffusion_bin)
 
102
  return settings.llama_diffusion_bin
103
 
104
  if settings.llama_diffusion_bin_url:
@@ -120,6 +191,7 @@ def ensure_runner_binary() -> Path:
120
 
121
  def ensure_model_file(repo_id: str, filename: str) -> str:
122
  settings.model_cache_dir.mkdir(parents=True, exist_ok=True)
 
123
  path = hf_hub_download(
124
  repo_id=repo_id,
125
  filename=filename,
@@ -127,6 +199,7 @@ def ensure_model_file(repo_id: str, filename: str) -> str:
127
  token=os.getenv("HF_TOKEN") or None,
128
  )
129
  _runtime_notes.append(f"Model ready: {repo_id}/{filename}")
 
130
  return path
131
 
132
 
 
1
  from __future__ import annotations
2
 
3
+ import json
4
  import os
5
  import shutil
6
+ import site
7
  import stat
8
  import subprocess
9
  import tarfile
10
  import tempfile
11
  import zipfile
12
+ from collections import deque
13
+ from datetime import UTC, datetime
14
  from pathlib import Path
15
  from urllib.request import urlretrieve
16
 
 
21
 
22
 
23
  _runtime_notes: list[str] = []
24
+ _events: deque[dict[str, object]] = deque(maxlen=200)
25
+
26
+
27
+ def log_event(event: str, **fields: object) -> None:
28
+ record: dict[str, object] = {
29
+ "ts": datetime.now(UTC).isoformat(timespec="seconds"),
30
+ "event": event,
31
+ **fields,
32
+ }
33
+ _events.append(record)
34
+ print(json.dumps(record, ensure_ascii=False, default=str), flush=True)
35
+
36
+
37
+ def runtime_events(limit: int = 100) -> list[dict[str, object]]:
38
+ limit = max(1, min(limit, 200))
39
+ return list(_events)[-limit:]
40
+
41
+
42
+ def nvidia_library_paths() -> list[str]:
43
+ paths: list[str] = []
44
+ seen: set[str] = set()
45
+ roots = [*site.getsitepackages(), site.getusersitepackages()]
46
+ for root in roots:
47
+ if not root:
48
+ continue
49
+ base = Path(root) / "nvidia"
50
+ if not base.exists():
51
+ continue
52
+ for candidate in base.glob("*/lib"):
53
+ if candidate.is_dir():
54
+ value = str(candidate)
55
+ if value not in seen:
56
+ seen.add(value)
57
+ paths.append(value)
58
+ return paths
59
+
60
+
61
+ def ld_library_path_for(binary_path: Path | None = None) -> str:
62
+ paths: list[str] = []
63
+ if binary_path:
64
+ paths.append(str(binary_path.resolve().parent))
65
+ paths.extend(nvidia_library_paths())
66
+ existing = os.getenv("LD_LIBRARY_PATH", "")
67
+ if existing:
68
+ paths.append(existing)
69
+ return ":".join(paths)
70
 
71
 
72
  def runtime_status() -> dict[str, object]:
 
74
  "bin": str(settings.llama_diffusion_bin),
75
  "bin_exists": settings.llama_diffusion_bin.exists(),
76
  "model_cache_dir": str(settings.model_cache_dir),
77
+ "model_file": str(settings.model_cache_dir / settings.gguf_filename),
78
+ "model_file_exists": (settings.model_cache_dir / settings.gguf_filename).exists(),
79
+ "nvidia_library_paths": nvidia_library_paths(),
80
+ "ld_library_path": ld_library_path_for(settings.llama_diffusion_bin),
81
  "notes": list(_runtime_notes[-20:]),
82
  }
83
 
 
96
 
97
  def _download_prebuilt_binary(url: str) -> None:
98
  settings.bin_dir.mkdir(parents=True, exist_ok=True)
99
+ log_event("runner.download.start", url=url)
100
  with tempfile.TemporaryDirectory() as td:
101
  tempdir = Path(td)
102
  archive_path = tempdir / "llama-diffusion-download"
 
118
 
119
  if not binary or not binary.exists():
120
  raise ApiError("runtime_error", "Could not find llama-diffusion-cli in downloaded artifact", 500)
121
+
122
+ # Keep sibling shared libraries with the binary. This mirrors the qwen36
123
+ # Space strategy: a CUDA runner package is not just the executable.
124
+ for child in binary.parent.iterdir():
125
+ target = settings.bin_dir / child.name
126
+ if child.is_file() or child.is_symlink():
127
+ shutil.copy2(child, target)
128
+ elif child.is_dir() and child.name in {"lib", "lib64"}:
129
+ if target.exists():
130
+ shutil.rmtree(target)
131
+ shutil.copytree(child, target, symlinks=True)
132
  _mark_executable(settings.llama_diffusion_bin)
133
  _runtime_notes.append(f"Installed prebuilt binary from {url}")
134
+ log_event("runner.download.finish", bin=str(settings.llama_diffusion_bin))
135
 
136
 
137
  def build_llama_diffusion() -> None:
 
139
  if not script.exists():
140
  raise ApiError("runtime_error", f"Missing build script: {script}", 500)
141
 
142
+ log_event("runner.build.start", script=str(script))
143
  env = dict(os.environ)
144
  env.setdefault("LLAMA_SRC_DIR", str(settings.llama_src_dir))
145
  env.setdefault("LLAMA_BIN_DIR", str(settings.bin_dir))
146
  env.setdefault("LLAMA_DIFFUSION_BIN", str(settings.llama_diffusion_bin))
147
  env.setdefault("LLAMA_BUILD_CUDA", "1" if settings.llama_build_cuda else "0")
148
  env.setdefault("LLAMA_CMAKE_EXTRA_ARGS", settings.llama_cmake_extra_args)
149
+ env["LD_LIBRARY_PATH"] = ld_library_path_for(settings.llama_diffusion_bin)
150
 
151
  proc = subprocess.run(
152
  ["bash", str(script)],
 
156
  timeout=int(os.getenv("LLAMA_BUILD_TIMEOUT_SECONDS", "1800")),
157
  )
158
  if proc.returncode != 0:
159
+ log_event("runner.build.failed", stderr_tail=proc.stderr[-1200:])
160
  raise ApiError(
161
  "runtime_error",
162
  "Failed to build llama-diffusion-cli. stderr tail: " + proc.stderr[-4000:],
163
  500,
164
  )
165
  _runtime_notes.append("Built llama-diffusion-cli from llama.cpp DiffusionGemma PR")
166
+ log_event("runner.build.finish", bin=str(settings.llama_diffusion_bin))
167
 
168
 
169
  def ensure_runner_binary() -> Path:
170
  if settings.llama_diffusion_bin.exists():
171
  _mark_executable(settings.llama_diffusion_bin)
172
+ log_event("runner.cache_hit", bin=str(settings.llama_diffusion_bin))
173
  return settings.llama_diffusion_bin
174
 
175
  if settings.llama_diffusion_bin_url:
 
191
 
192
  def ensure_model_file(repo_id: str, filename: str) -> str:
193
  settings.model_cache_dir.mkdir(parents=True, exist_ok=True)
194
+ log_event("model.download.start", repo_id=repo_id, filename=filename)
195
  path = hf_hub_download(
196
  repo_id=repo_id,
197
  filename=filename,
 
199
  token=os.getenv("HF_TOKEN") or None,
200
  )
201
  _runtime_notes.append(f"Model ready: {repo_id}/{filename}")
202
+ log_event("model.download.finish", path=str(path))
203
  return path
204
 
205
 
src/runner.py CHANGED
@@ -2,11 +2,13 @@ from __future__ import annotations
2
 
3
  import re
4
  import shlex
 
5
  import subprocess
6
  from typing import Any
7
 
8
  from src.config import settings
9
  from src.errors import ApiError
 
10
 
11
  _LOG_LINE_PATTERNS = [
12
  re.compile(r"^llama_.*", re.IGNORECASE),
@@ -52,12 +54,15 @@ def clean_cli_output(stdout: str, prompt: str | None = None) -> str:
52
 
53
 
54
  def _run_once(cmd: list[str], prompt: str | None) -> subprocess.CompletedProcess[str]:
 
 
55
  return subprocess.run(
56
  cmd,
57
  input=prompt,
58
  text=True,
59
  capture_output=True,
60
  timeout=settings.cli_timeout_seconds,
 
61
  )
62
 
63
 
 
2
 
3
  import re
4
  import shlex
5
+ import os
6
  import subprocess
7
  from typing import Any
8
 
9
  from src.config import settings
10
  from src.errors import ApiError
11
+ from src.prepare import ld_library_path_for
12
 
13
  _LOG_LINE_PATTERNS = [
14
  re.compile(r"^llama_.*", re.IGNORECASE),
 
54
 
55
 
56
  def _run_once(cmd: list[str], prompt: str | None) -> subprocess.CompletedProcess[str]:
57
+ env = dict(os.environ)
58
+ env["LD_LIBRARY_PATH"] = ld_library_path_for(settings.llama_diffusion_bin)
59
  return subprocess.run(
60
  cmd,
61
  input=prompt,
62
  text=True,
63
  capture_output=True,
64
  timeout=settings.cli_timeout_seconds,
65
+ env=env,
66
  )
67
 
68