Skip to content

Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.

ds41 serve: stop memory growth on long prompts (#125) (#128)

Yaniss Amazouz64b0a91a12cd
diff --git a/tools/ds41/ds41_env.sh b/tools/ds41/ds41_env.sh
index 093619c..283ef73 100644
--- a/tools/ds41/ds41_env.sh
+++ b/tools/ds41/ds41_env.sh
@@ -26,8 +26,16 @@ DS41_PACK=${DS41_PACK:-$HOME/models/ds41-1017-yamz}
DS41_ENGRAM_DIR=${DS41_ENGRAM_DIR-$HOME/models/ds41-1017/engram_fp8}
DS41_TIER=${DS41_TIER:-auto}
DS41_VALIDATE=${DS41_VALIDATE:-1}
-# shellcheck disable=SC1091
-source "${DS41_PYENV:-$H/ds41box/pyenv.sh}" "$ROOT" || { echo "ds41: python env ${DS41_PYENV:-$H/ds41box/pyenv.sh} failed" >&2; return 5 2>/dev/null || exit 5; }
+# Python env: DS41_PYENV=<script> (sourced with the repo root) if set, else the repo's standard Strix Halo env (tools/strix_halo/env.sh,
+# venv at $EXL3_VENV or <repo>/.venv; needs ml_dtypes installed in it).
+# shellcheck disable=SC1090,SC1091
+if [ -n "${DS41_PYENV:-}" ]; then
+ source "$DS41_PYENV" "$ROOT" || { echo "ds41: python env $DS41_PYENV failed" >&2; return 5 2>/dev/null || exit 5; }
+else
+ source "$ROOT/tools/strix_halo/env.sh" >/dev/null || { echo "ds41: tools/strix_halo/env.sh failed" >&2; return 5 2>/dev/null || exit 5; }
+ export PATH="$EXL3_VENV/bin:$PATH" PYTHONPATH="$ROOT${PYTHONPATH:+:$PYTHONPATH}"
+ unset CUDA_VISIBLE_DEVICES
+fi
export HIP_VISIBLE_DEVICES=0
[ -f "$DS41_PACK/config.json" ] || { echo "ds41: no pack at $DS41_PACK (config.json missing)" >&2; return 2 2>/dev/null || exit 2; }
if ! ls "$ROOT"/exllamav3_ext*.so >/dev/null 2>&1; then
@@ -40,7 +48,7 @@ pack_gib=$(du -cbL "$DS41_PACK"/*.safetensors 2>/dev/null | tail -1 | awk '{prin
avail=$(mem_gib)
budget_set=${DS41_BUDGET_GIB:+1}
# DS41_BUDGET_GIB=auto: the pool takes what is free AFTER the non-expert weights are loaded, minus a reserve for what grows later:
-# prefill workspace (~chunk/4096 GiB, measured 8 GiB at chunk 32768), prefix snapshots (DS41_PFX_GIB, 4), KV + runtime (1.5), margin (DS41_AUTO_MARGIN_GIB, 2)
+# prefill workspace (chunk/4096 + 6 GiB: peak torch use above the weights, measured 3-7 GiB at chunk 4096 on 8K-80K prompts, 8 GiB at chunk 32768), prefix snapshots (DS41_PFX_GIB, 4), KV + runtime (1.5), margin (DS41_AUTO_MARGIN_GIB, 2)
# Default since 20/10 (briefs/ds41_pool.md): auto, 86 GiB pool vs 78 on a quiet box, -13.5 % GB read per session, tokhash identical.
if [ "${DS41_BUDGET_GIB:-auto}" = auto ]; then
DS41_AUTO=1; DS41_BUDGET_GIB=$(( avail - 30 ))
@@ -55,7 +63,7 @@ if [ "$DS41_TIER" = 1 ]; then
export EXL3_EXPERT_RING=${EXL3_EXPERT_RING:-128} # pinned staging entries (12.7 MiB each): 128 = 1.6 GiB instead of 4 GiB at the old 320
if [ "${DS41_AUTO:-}" = 1 ]; then
export EXL3_EXPERT_BUDGET_GIB=auto
- export EXL3_EXPERT_RESERVE_GIB=$(LC_ALL=C awk -v c="${DS41_CHUNK:-4096}" -v p="${DS41_PFX_GIB:-4}" -v m="${DS41_AUTO_MARGIN_GIB:-2}" 'BEGIN{printf "%.1f", c/4096+p+1.5+m}')
+ export EXL3_EXPERT_RESERVE_GIB=$(LC_ALL=C awk -v c="${DS41_CHUNK:-4096}" -v p="${DS41_PFX_GIB:-4}" -v m="${DS41_AUTO_MARGIN_GIB:-2}" 'BEGIN{printf "%.1f", c/4096+6+p+1.5+m}')
fi
export EXL3_EXPERT_HALFLIFE=${EXL3_EXPERT_HALFLIFE:-16}
export EXL3_EXPERT_AHEAD=${EXL3_EXPERT_AHEAD:-0}
diff --git a/tools/ds41/ds41_model.py b/tools/ds41/ds41_model.py
index 4dbf4bc..42a3fe8 100644
--- a/tools/ds41/ds41_model.py
+++ b/tools/ds41/ds41_model.py
@@ -359,6 +359,9 @@ class PortEngine:
if os.environ.get("DS41_PFX_LOG") == "1":
print(f"[prefix] prompt={len(ids)} cached={stats.get('cached_tokens', 0)} lcp_miss={stats.get('prefix_lcp', 0)} "
f"store={len(store) if store is not None else 0}x{(store.nbytes() >> 20) if store is not None else 0}MiB", file=sys.stderr, flush=True)
+ if os.environ.get("DS41_EMPTY_CACHE", "1") != "0":
+ import torch
+ torch.cuda.empty_cache() # hand the prefill workspace back: the caching allocator would keep the largest request's blocks
t1 = time.perf_counter()
t_first = t_first or t1
stats.update({"cached_tokens": stats.get("cached_tokens", 0), "new_tokens": n_new, "prompt_tokens": len(ids),
diff --git a/tools/ds41/serve.py b/tools/ds41/serve.py
index f5c3ff7..0e96241 100644
--- a/tools/ds41/serve.py
+++ b/tools/ds41/serve.py
@@ -143,6 +143,26 @@ ROUTES = {"/health": ("GET",), "/v1/models": ("GET",), "/metrics": ("GET",), "/v
"/v1/ds41/score": ("POST",)}
+def _memlog(prompt_tokens: int, new_tokens: int) -> None:
+ """DS41_MEMLOG=<csv>: one row per finished request (host and torch memory), to chase memory growth."""
+ path = os.environ.get("DS41_MEMLOG")
+ if not path:
+ return
+ import glob
+ import time
+ import torch
+ mi = {k: int(v.split()[0]) // 1024 for k, v in (ln.split(":") for ln in open("/proc/meminfo")) if k in ("MemAvailable", "SwapFree")}
+ rss = int([ln for ln in open("/proc/self/status") if ln.startswith("VmRSS")][0].split()[1]) // 1024
+ gtt = sum(int(open(f).read()) for f in glob.glob("/sys/class/drm/card*/device/mem_info_gtt_used")) // 2**20
+ new = not os.path.exists(path)
+ with open(path, "a") as f:
+ if new:
+ f.write("t,prompt,new,mem_avail_mib,swap_free_mib,rss_mib,gtt_mib,torch_alloc_mib,torch_reserved_mib,torch_peak_reserved_mib\n")
+ f.write(f"{time.time():.0f},{prompt_tokens},{new_tokens},{mi['MemAvailable']},{mi['SwapFree']},{rss},{gtt},"
+ f"{torch.cuda.memory_allocated() >> 20},{torch.cuda.memory_reserved() >> 20},{torch.cuda.max_memory_reserved() >> 20}\n")
+ torch.cuda.reset_peak_memory_stats()
+
+
def create_app(engine: Any, model_id: str, defaults: Defaults | None = None) -> web.Application:
"""Build the HTTP layer around an engine (the real one, or ds41_engine.StubEngine in tests)."""
defaults = defaults or Defaults()
@@ -222,6 +242,7 @@ def create_app(engine: Any, model_id: str, defaults: Defaults | None = None) ->
raise web.HTTPBadRequest(reason=str(exc)) from exc
def observe(st: dict[str, Any], prompt_tokens: int) -> None:
+ _memlog(prompt_tokens, int(st.get("new_tokens", 0)))
num_draft = int(getattr(getattr(engine, "greedy_generator", None), "num_draft_tokens", 0) or 0)
accepted = int(st.get("accepted_draft_tokens", 0))
rejected = int(st.get("rejected_draft_tokens", 0))