serve: lazy-load vision encoder with model
Rebased onto the 0.1.40.1 Vision (work_dir, #480 absolute paths). Added tests for the lazy encoder (nothing starts, restart starts it, a failed start is killed); the --lazy help no longer says text-only. A live smoke with a vision config and --lazy is still to run. (PR #673)
This commit is contained in:
1 parent
f3019d00b3
commit
d125bef795
3 files changed
+130
-24
No files matched your search
+6
-4
@@ -1380,12 +1380,14 @@ Strata itself: [MIT](../LICENSE). The model files are not part of it; their lice
|
||||
- The experimental speed projection's vector (`data/experimental-speed-projection/`): Qwen Community License 1.0,
|
||||
made from the model's activations (see its README).
|
||||
|
||||
### Start the text API without occupying the GPU
|
||||
### Start the API without loading the model
|
||||
|
||||
`serve/server.py --engine strata --config strata-<model>.json --lazy` (or `"lazy_load": true` in that
|
||||
config) starts the lightweight HTTP API without spawning the native engine. The first generation request
|
||||
loads it through the existing reload path, including `before_load` and `min_free_vram_mib`. Eager startup
|
||||
remains the default. This option is text-only: a vision configuration with lazy startup is rejected explicitly.
|
||||
config) starts the lightweight HTTP API without starting the native engine or the vision encoder. The first
|
||||
generation request, or `POST /load`, starts the vision encoder first when configured, then loads the engine through
|
||||
the existing reload path, including `before_load` and `min_free_vram_mib`. This also works with image requests:
|
||||
the load finishes before Strata encodes the image. `POST /unload` stops both processes. Eager startup remains the
|
||||
default.
|
||||
|
||||
`POST /v1/load` and `/v1/unload` are JSON control aliases for integrations, accepting `{}` or
|
||||
`{"model":"<configured model>"}` and returning model status. They require the configured API key,
|
||||
|
||||
+53
-20
@@ -1628,7 +1628,7 @@ class Vision:
|
||||
pass
|
||||
return Path(tempfile.mkdtemp(prefix="strata-vision-"))
|
||||
|
||||
def __init__(self, cfg: dict, log=None, env: dict | None = None):
|
||||
def __init__(self, cfg: dict, log=None, env: dict | None = None, lazy: bool = False):
|
||||
absolute = lambda p: os.path.abspath(p) if os.path.dirname(str(p)) else p # the encoder runs in its own dir (#480) # noqa: E731
|
||||
args = [absolute(cfg["exe"]), "--mmproj", absolute(cfg["mmproj"]), "--model", absolute(cfg["model"])]
|
||||
if cfg.get("gpu"):
|
||||
@@ -1641,10 +1641,12 @@ class Vision:
|
||||
args += ["--min-tokens", str(cfg["min_tokens"])]
|
||||
self.dir = self.work_dir()
|
||||
self.spawn = (args, log, env) # to start it again after an unload
|
||||
self.stopped = False
|
||||
self._start()
|
||||
self.proc = None
|
||||
self.stopped = True
|
||||
self.lock = threading.Lock()
|
||||
self.cache: dict[str, tuple[Path, int]] = {}
|
||||
if not lazy:
|
||||
self._start()
|
||||
|
||||
def _start(self):
|
||||
args, log, env = self.spawn
|
||||
@@ -1655,11 +1657,18 @@ class Vision:
|
||||
contain(self.proc)
|
||||
line = self.proc.stdout.readline()
|
||||
if not line.startswith("READY"):
|
||||
proc, self.proc = self.proc, None
|
||||
self.stopped = True
|
||||
try:
|
||||
proc.kill()
|
||||
proc.wait(timeout=5)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
pass
|
||||
raise RuntimeError("the vision encoder did not start: " + line.strip())
|
||||
self.stopped = False
|
||||
|
||||
def alive(self) -> bool:
|
||||
return not self.stopped and self.proc.poll() is None
|
||||
return self.proc is not None and not self.stopped and self.proc.poll() is None
|
||||
|
||||
def unload(self):
|
||||
"""Stop the encoder process (its VRAM or RAM goes back); the encoded images stay cached on disk."""
|
||||
@@ -1668,10 +1677,13 @@ class Vision:
|
||||
|
||||
def restart(self):
|
||||
"""Start the encoder again after an unload (or if it died); the cache of encoded images is kept."""
|
||||
try:
|
||||
self.proc.kill()
|
||||
except OSError:
|
||||
pass
|
||||
if self.proc is not None:
|
||||
try:
|
||||
self.proc.kill()
|
||||
except OSError:
|
||||
pass
|
||||
self.proc = None
|
||||
self.stopped = True
|
||||
self._start()
|
||||
|
||||
@staticmethod
|
||||
@@ -1781,12 +1793,24 @@ class Vision:
|
||||
return self.cache[key]
|
||||
|
||||
def close(self):
|
||||
proc, self.proc = self.proc, None
|
||||
if proc is None:
|
||||
self.stopped = True
|
||||
return
|
||||
try:
|
||||
self.proc.stdin.write("QUIT\n")
|
||||
self.proc.stdin.flush()
|
||||
self.proc.wait(timeout=10)
|
||||
proc.stdin.write("QUIT\n")
|
||||
proc.stdin.flush()
|
||||
proc.wait(timeout=10)
|
||||
except Exception:
|
||||
self.proc.kill()
|
||||
try:
|
||||
proc.kill()
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
proc.wait(timeout=10)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
pass
|
||||
self.stopped = True
|
||||
|
||||
def shutdown(self):
|
||||
"""#914: close() for good: the server ends, so the encoder's directory (one ~10 MB .sve per image, on a tmpfs
|
||||
@@ -2391,9 +2415,14 @@ class Service:
|
||||
if free is not None and free < self.min_free_vram_mib:
|
||||
raise GpuBusy(f"the GPU is in use by another program: {free} MiB of VRAM free, the model needs "
|
||||
f"{self.min_free_vram_mib} (min_free_vram_mib) - it stays unloaded until that is free")
|
||||
vision_started = False
|
||||
if self._vision_down(): # first, as at a start: a GPU encoder takes its VRAM before
|
||||
print("[strata] starting the vision encoder again ...", flush=True) # the engine sizes its cache
|
||||
self.vision.restart()
|
||||
print("[strata] starting the vision encoder ...", flush=True) # the engine sizes its cache
|
||||
try:
|
||||
self.vision.restart()
|
||||
except Exception as e:
|
||||
raise EngineDied(f"the vision encoder failed to start: {e}") from e
|
||||
vision_started = True
|
||||
if self.loaded():
|
||||
return
|
||||
if getattr(self.engine, "unloaded", False):
|
||||
@@ -2402,7 +2431,12 @@ class Service:
|
||||
code = self.engine.exit_code() if hasattr(self.engine, "exit_code") else None
|
||||
print(f"[strata] the engine had stopped (exit code {code}); starting it again "
|
||||
"(a minute or two) ...", flush=True)
|
||||
self.engine.restart()
|
||||
try:
|
||||
self.engine.restart()
|
||||
except Exception:
|
||||
if vision_started:
|
||||
self.vision.unload()
|
||||
raise
|
||||
print("[strata] the engine is running again", flush=True)
|
||||
if self.vram_reserve is not None and hasattr(self.engine, "vram"): # #533: the reserve asked for last
|
||||
try:
|
||||
@@ -4965,7 +4999,7 @@ def main() -> int:
|
||||
ap.add_argument("--mcp-config", help="a JSON file with MCP servers in Claude Desktop's format ({\"mcpServers\": "
|
||||
"{...}}); the web app's chat can use their tools (also \"mcp_servers\" in "
|
||||
"the config)")
|
||||
ap.add_argument("--lazy", action="store_true", help="start the text-only API unloaded; load on first request")
|
||||
ap.add_argument("--lazy", action="store_true", help="start the API unloaded (the engine and the vision encoder start with the first request)")
|
||||
ap.add_argument("--api-monitor", action="store_true",
|
||||
help="the API request monitor at /api-monitor: keeps the last 100 requests' prompts and answers in "
|
||||
"memory (also \"api_monitor\": true in the config; off by default)")
|
||||
@@ -5016,16 +5050,15 @@ def main() -> int:
|
||||
pretty = ", ".join(f"{k}={v}" for k, v in sampling_defaults.items())
|
||||
print(f"[strata] sampling defaults from the config: {pretty}", flush=True)
|
||||
lazy = a.lazy or cfg.get("lazy_load") is True
|
||||
if lazy and cfg.get("vision"):
|
||||
ap.error("lazy loading is text-only; disable vision in the config")
|
||||
if cfg.get("vision"):
|
||||
print("loading the vision encoder ...", flush=True)
|
||||
print("loading the vision encoder ..." if not lazy else
|
||||
"vision encoder unloaded; it starts with the model ...", flush=True)
|
||||
# relative paths are the config's cwd's, as for the engine below
|
||||
vcfg = {k: (os.path.abspath(os.path.join(cfg.get("cwd") or ".", v))
|
||||
if k in ("exe", "mmproj", "model") and isinstance(v, str) and not os.path.isabs(v) else v)
|
||||
for k, v in cfg["vision"].items()}
|
||||
vision = Vision(vcfg, log=open(cfg["log"], "a", encoding="utf-8") if cfg.get("log") else None,
|
||||
env=vision_env(cfg, env))
|
||||
env=vision_env(cfg, env), lazy=lazy)
|
||||
print("model unloaded; the first request loads it ..." if lazy else
|
||||
"loading the model (the first start takes a minute or two) ...", flush=True)
|
||||
if layer_split_of(cfg):
|
||||
|
||||
@@ -8,6 +8,7 @@ import contextlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import socket
|
||||
import sys
|
||||
import tempfile
|
||||
@@ -4185,6 +4186,76 @@ class VisionCacheEviction(unittest.TestCase):
|
||||
self.assertFalse(first.exists())
|
||||
|
||||
|
||||
class LazyVision(unittest.TestCase):
|
||||
"""#673: with --lazy the image encoder is not started either; it starts with the model, and an encoder that fails
|
||||
to start leaves nothing running."""
|
||||
|
||||
def make(self, ready=True):
|
||||
import serve.server as server
|
||||
started = []
|
||||
|
||||
class Proc:
|
||||
def __init__(self):
|
||||
self.stdin = io.StringIO()
|
||||
self.stdout = io.StringIO("READY 1" + chr(10) if ready else "oops" + chr(10))
|
||||
self.killed = False
|
||||
|
||||
def poll(self):
|
||||
return None
|
||||
|
||||
def kill(self):
|
||||
self.killed = True
|
||||
|
||||
def wait(self, timeout=None):
|
||||
return 0
|
||||
|
||||
def popen(what, args, **kw):
|
||||
p = Proc()
|
||||
started.append(p)
|
||||
return p
|
||||
|
||||
with mock.patch.object(server, "popen", popen), mock.patch.object(server, "contain"):
|
||||
v = server.Vision({"exe": "strata-vision", "mmproj": "m.gguf", "model": "t.gguf"}, lazy=True)
|
||||
self.addCleanup(lambda: shutil.rmtree(v.dir, ignore_errors=True))
|
||||
return v, started, popen
|
||||
|
||||
def test_lazy_starts_nothing_and_alive_says_so(self):
|
||||
v, started, _ = self.make()
|
||||
self.assertEqual(started, [])
|
||||
self.assertFalse(v.alive())
|
||||
|
||||
def test_restart_starts_it_and_close_ends_it(self):
|
||||
import serve.server as server
|
||||
v, started, popen = self.make()
|
||||
with mock.patch.object(server, "popen", popen), mock.patch.object(server, "contain"):
|
||||
v.restart()
|
||||
self.assertTrue(v.alive())
|
||||
self.assertEqual(len(started), 1)
|
||||
v.close()
|
||||
self.assertFalse(v.alive())
|
||||
|
||||
def test_a_failed_start_kills_the_process_and_raises(self):
|
||||
import serve.server as server
|
||||
v, started, _ = self.make(ready=False)
|
||||
|
||||
def popen(what, args, **kw):
|
||||
class P:
|
||||
stdin, stdout, killed = io.StringIO(), io.StringIO("oops" + chr(10)), False
|
||||
|
||||
def kill(self):
|
||||
P.killed = True
|
||||
|
||||
def wait(self, timeout=None):
|
||||
return 0
|
||||
started.append(P)
|
||||
return P()
|
||||
with mock.patch.object(server, "popen", popen), mock.patch.object(server, "contain"):
|
||||
with self.assertRaises(RuntimeError):
|
||||
v.restart()
|
||||
self.assertTrue(started[-1].killed)
|
||||
self.assertFalse(v.alive())
|
||||
|
||||
|
||||
class VisionShutdown(unittest.TestCase):
|
||||
"""#914: ending the server removes the encoder's scratch directory; unloading keeps it."""
|
||||
|
||||
|
||||
Reference in new issue
Block a user