serve: the image encoder only while there are pictures ("elastic": true in the vision section)
Opt-in, with the config's "vram_elastic": the GPU encoder does not start with the server or a load. A picture's turn makes the expert cache keep "elastic_mib" (default 2048) free on top of the reserve and starts the encoder; after "elastic_idle_s" (default 120) without a picture a thread stops it between requests and the cache grows back to the reserve (0 when no POST /v1/vram was made: the start's reserve left it a segment or more smaller). A POST /v1/vram while the encoder runs stacks on its share; an unload stops it. Without "vram_elastic" the server says so and starts the encoder as before. serve/test_vision_elastic.py pins each case; docs in VRAM_ELASTIC.md and DETAILS.md.
This commit is contained in:
1 parent
e8b4551173
commit
ca41a6b957
4 files changed
+253
-8
No files matched your search
@@ -1506,6 +1506,16 @@ like `nvidia-smi`) to the `"vision"` section of `strata-<model>.json`: the encod
|
||||
`--vram-reserve-mib` in `"args"` to 700 as well, so the engine's cards keep that VRAM for the expert cache. The
|
||||
encoder's card needs code in the ready-made encoder (RTX 20/30/40/50).
|
||||
|
||||
**The encoder only while there are pictures (opt-in, `"elastic": true` in the `"vision"` section, with the config's
|
||||
`"vram_elastic": true`; [VRAM_ELASTIC.md](VRAM_ELASTIC.md#the-image-encoder-on-demand)):** the GPU encoder does not start
|
||||
with the server, so the expert cache keeps all of the VRAM. The first picture's turn makes the cache keep
|
||||
`"elastic_mib"` (default 2048) free and starts the encoder there (a few seconds); later pictures use it as it is, and
|
||||
after `"elastic_idle_s"` (default 120) without a picture it stops and the cache takes the VRAM back. Measured on an R9700
|
||||
32 GB (gfx1201, Linux, UD-IQ4_XS, the BF16 encoder at up to 1,024 tokens, #2189 for HIP's virtual memory): the encoder
|
||||
took 1,339 MiB and started in 4.7 s (2.7 s the next time); a request with one picture took 8.6 s with the start and
|
||||
5.0 s on a later cold start, and 2 / 5 / 10 pictures with the encoder running took 3.8 / 5.6 / 9.0 s (~0.45 s to encode
|
||||
each, the same as on a second card). Without the key nothing changes.
|
||||
|
||||
### Sending a picture
|
||||
|
||||
**Terminal chat:** type `/image <path to a picture>`, press Enter, then type your question.
|
||||
|
||||
@@ -105,6 +105,25 @@ expert outside the cache), but I have not run a fault-injection test of these tw
|
||||
- `GET /v1/status` has a `vram` object with the last figures the engine reported (empty until the first successful
|
||||
call) and `elastic`.
|
||||
|
||||
## The image encoder on demand
|
||||
|
||||
With `"elastic": true` in the config's `"vision"` section (and `"vram_elastic": true`; without it the server says so
|
||||
and starts the encoder with the model, as before) the GPU encoder is not started with the server or with a load:
|
||||
|
||||
- **A picture's turn** (the same FIFO turn an encode always takes): if the encoder is not running, the engine's
|
||||
`VRAM` command first keeps `"elastic_mib"` (default 2048) free on top of the reserve - the last `POST /v1/vram`, or 0
|
||||
when none was made - and then the encoder starts. If the cache cannot shrink (the resident low-RAM mode, an engine
|
||||
without `--vram-elastic`) it starts anyway, as a non-elastic encoder would, and the log says why.
|
||||
- **Idle** for `"elastic_idle_s"` (default 120) without a picture: a thread stops the encoder between requests and
|
||||
sends `VRAM` with that reserve again, so the cache grows back to the size it had (0, not the start's reserve: that
|
||||
would leave it a segment or more smaller).
|
||||
- **`POST /v1/vram` while the encoder runs** keeps the asked reserve on top of the encoder's share; the encoder's stop
|
||||
then goes back to the asked reserve.
|
||||
- An unload of the model stops the encoder too. The log lines start with `[strata] images:` **(code; the unit tests in
|
||||
`serve/test_vision_elastic.py` pin each case)**.
|
||||
|
||||
`--vram-elastic` turns `--kv-grow` off (the engine says so at start): with both asked, the whole K/V is in VRAM.
|
||||
|
||||
## What to build on
|
||||
|
||||
For automation: treat only `200` with `status: "ok"` as a call that ran, then check `vram_free_mib >= reserve_mib`
|
||||
|
||||
+101
-8
@@ -2094,7 +2094,13 @@ class Vision:
|
||||
self.stopped = True
|
||||
self.lock = threading.Lock()
|
||||
self.cache: dict[str, tuple[Path, int]] = {}
|
||||
if not lazy:
|
||||
# opt-in (the vision section's "elastic": true, with the config's "vram_elastic"): the encoder starts with the
|
||||
# first picture and stops after elastic_idle_s without one; while it runs, the engine's expert cache keeps
|
||||
# elastic_mib of VRAM free for it (Service._vision_up / _vision_idle_down)
|
||||
self.elastic = cfg.get("elastic") is True
|
||||
self.elastic_mib = int(cfg.get("elastic_mib") or 2048)
|
||||
self.elastic_idle_s = float(cfg.get("elastic_idle_s") or 120)
|
||||
if not lazy and not self.elastic:
|
||||
self._start()
|
||||
|
||||
def _start(self):
|
||||
@@ -2937,6 +2943,9 @@ class Service:
|
||||
self.vram_free_wait_s = 15.0 # how long a full card is waited on (memory given back)
|
||||
self.before_load_strict = False # #1997: refuse (503) whenever it fails
|
||||
self.vram_reserve = None # #533: the last POST /v1/vram reserve (None: the start's)
|
||||
self.vram_reserve_asked = False # a POST /v1/vram was made (vram_reserve None is then asked)
|
||||
self.vision_held = False # an elastic encoder holds VRAM the expert cache gave it
|
||||
self.last_image_at = 0.0 # when an image turn last ended (the elastic encoder's idle)
|
||||
self.reasoning_loop_recovery = False
|
||||
self.reasoning_budget_tokens = 0 # #123: the config's default thinking budget (0: none)
|
||||
self.repeat_stop_tokens = REPEAT_STOP_TOKENS # #606: one token this many times in a row ends a reply (0: off)
|
||||
@@ -3060,7 +3069,78 @@ class Service:
|
||||
return value if value > 0 else None
|
||||
|
||||
def _vision_down(self) -> bool:
|
||||
return self.vision is not None and hasattr(self.vision, "alive") and not self.vision.alive()
|
||||
"""The encoder should run and does not (the engine's load starts it again). An elastic encoder is down
|
||||
between pictures by design: it starts in the image turn (_vision_up), not with the engine."""
|
||||
return (self.vision is not None and hasattr(self.vision, "alive") and not self.vision.alive()
|
||||
and not getattr(self.vision, "elastic", False))
|
||||
|
||||
def _engine_reserve(self) -> int | None:
|
||||
"""The VRAM the engine keeps free for other programs outside an elastic encoder's turn: the last POST /v1/vram
|
||||
reserve, or 0 when none was asked (the cache grows back to its full size; None would leave the reserve the engine
|
||||
started with, a segment or more below the size it had)."""
|
||||
return self.vram_reserve if self.vram_reserve_asked else 0
|
||||
|
||||
def _vision_up(self):
|
||||
"""The image turn's start for an elastic encoder that is not running (the caller holds self.fifo): the expert
|
||||
cache first keeps the encoder's elastic_mib of VRAM free on top of the reserve, then the encoder starts (load and
|
||||
warm-up, a few seconds). If the cache cannot shrink (an engine without --vram-elastic, the resident low-RAM mode)
|
||||
the encoder starts anyway, as a non-elastic one would."""
|
||||
v = self.vision
|
||||
if not getattr(v, "elastic", False) or v.alive():
|
||||
return
|
||||
if hasattr(self.engine, "vram") and self.loaded():
|
||||
try:
|
||||
out = self.engine.vram((self._engine_reserve() or 0) + v.elastic_mib)
|
||||
self.vision_held = True
|
||||
print(f"[strata] images: the expert cache keeps {v.elastic_mib} MiB free for the image encoder "
|
||||
f"({out.get('expert_cache_mib')} of {out.get('expert_cache_full_mib')} MiB left)", flush=True)
|
||||
except ValueError as e:
|
||||
print(f"[strata] images: the expert cache did not make room for the image encoder ({e}); starting "
|
||||
"it anyway", flush=True)
|
||||
free0, t0 = self.free_vram_mib(), time.time()
|
||||
v.restart()
|
||||
free1 = self.free_vram_mib()
|
||||
took = f", {free0 - free1} MiB of VRAM" if free0 is not None and free1 is not None else ""
|
||||
print(f"[strata] images: the image encoder started in {time.time() - t0:.1f} s{took}", flush=True)
|
||||
|
||||
def _vision_idle_down(self, force: bool = False) -> str:
|
||||
"""An elastic encoder idle for elastic_idle_s (or force) stops, and the expert cache takes its VRAM back:
|
||||
"down", "busy" (a request holds the turn, or a picture came more recently) or "nothing" (not elastic or not
|
||||
holding anything)."""
|
||||
v = self.vision
|
||||
if not getattr(v, "elastic", False) or not (self.vision_held or v.alive()):
|
||||
return "nothing"
|
||||
if not force and time.time() - self.last_image_at < v.elastic_idle_s:
|
||||
return "busy"
|
||||
if not self.fifo.acquire(blocking=False):
|
||||
return "busy"
|
||||
try:
|
||||
v.unload()
|
||||
if self.vision_held and hasattr(self.engine, "vram") and self.loaded():
|
||||
out = self.engine.vram(self._engine_reserve())
|
||||
print(f"[strata] images: the image encoder stopped after {v.elastic_idle_s:g} s without a picture; "
|
||||
f"the expert cache took its VRAM back ({out.get('expert_cache_mib')} of "
|
||||
f"{out.get('expert_cache_full_mib')} MiB)", flush=True)
|
||||
self.vision_held = False
|
||||
return "down"
|
||||
finally:
|
||||
self.fifo.release()
|
||||
|
||||
def start_vision_idle(self):
|
||||
v = self.vision
|
||||
if not getattr(v, "elastic", False):
|
||||
return
|
||||
print(f"[strata] images: the image encoder starts with the first picture and stops after {v.elastic_idle_s:g} s "
|
||||
f"without one; while it runs the expert cache keeps {v.elastic_mib} MiB free for it", flush=True)
|
||||
|
||||
def loop():
|
||||
while True:
|
||||
time.sleep(max(1.0, min(30.0, v.elastic_idle_s / 4)))
|
||||
try:
|
||||
self._vision_idle_down()
|
||||
except Exception as e: # tried again at the next turn; the thread keeps running
|
||||
print(f"[strata] images: stopping the idle image encoder: {e}", flush=True)
|
||||
threading.Thread(target=loop, daemon=True).start()
|
||||
|
||||
def free_vram_mib(self) -> int | None:
|
||||
"""Free VRAM on the engine's (first) GPU, from NVML (AMD backend: amdgpu's sysfs files, #301); None when it can't
|
||||
@@ -3182,11 +3262,12 @@ class Service:
|
||||
raise ModelBusy("a request is still running; try again when it has finished")
|
||||
try:
|
||||
if not self.loaded():
|
||||
self.vram_reserve = reserve_mib
|
||||
self.vram_reserve, self.vram_reserve_asked = reserve_mib, True
|
||||
return {"status": "not loaded", "reserve_mib": reserve_mib,
|
||||
"note": "applied when the model loads"}
|
||||
out = self.engine.vram(reserve_mib)
|
||||
self.vram_reserve = reserve_mib
|
||||
# an elastic encoder that runs keeps its VRAM on top of the asked reserve
|
||||
out = self.engine.vram((reserve_mib or 0) + self.vision.elastic_mib if self.vision_held else reserve_mib)
|
||||
self.vram_reserve, self.vram_reserve_asked = reserve_mib, True
|
||||
print(f"[strata] VRAM: {out.get('vram_free_mib')} MiB free, expert cache {out.get('expert_cache_mib')} of "
|
||||
f"{out.get('expert_cache_full_mib')} MiB ({out.get('expert_slots')} experts)", flush=True)
|
||||
return {"status": "ok", **out}
|
||||
@@ -3265,6 +3346,7 @@ class Service:
|
||||
self.engine.unload()
|
||||
if self.vision is not None and hasattr(self.vision, "unload"):
|
||||
self.vision.unload()
|
||||
self.vision_held = False
|
||||
print(f"[strata] model unloaded{f' after {idle_for:.0f} s idle' if idle_for else ''}; "
|
||||
"the next request loads it again", flush=True)
|
||||
return "unloaded"
|
||||
@@ -3633,8 +3715,12 @@ class Service:
|
||||
# "reading the prompt" with CPU and GPU busy, for good (reproduced). So encoding takes its turn in the
|
||||
# same FIFO as the requests.
|
||||
with self._turn(cancel):
|
||||
encoded = (self.vision.encode_all(images, cancel) if hasattr(self.vision, "encode_all")
|
||||
else [self.vision.encode(src) for src in images])
|
||||
self._vision_up()
|
||||
try:
|
||||
encoded = (self.vision.encode_all(images, cancel) if hasattr(self.vision, "encode_all")
|
||||
else [self.vision.encode(src) for src in images])
|
||||
finally:
|
||||
self.last_image_at = time.time()
|
||||
# one <|image_pad|> per image -> one per image token. Only the markers the template writes for an image
|
||||
# (right after <|vision_start|>) are images: the same text inside a message (an agent reading these docs,
|
||||
# #150) is kept as plain text, or it took an image's place and the counts no longer matched.
|
||||
@@ -6394,12 +6480,18 @@ def main() -> int:
|
||||
print(f"[strata] sampling defaults from the config: {pretty}", flush=True)
|
||||
lazy = a.lazy or cfg.get("lazy_load") is True
|
||||
if cfg.get("vision"):
|
||||
print("loading the vision encoder ..." if not lazy else
|
||||
elastic = cfg["vision"].get("elastic") is True and cfg.get("vram_elastic") is True
|
||||
print("the vision encoder starts with the first picture (elastic) ..." if elastic else
|
||||
"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()}
|
||||
if vcfg.get("elastic") is True and cfg.get("vram_elastic") is not True:
|
||||
print('[strata] the vision section\'s "elastic" needs "vram_elastic": true (the expert cache gives the '
|
||||
"encoder its VRAM): the encoder starts with the model instead", flush=True)
|
||||
vcfg["elastic"] = False
|
||||
vision = Vision(vcfg, log=open(cfg["log"], "a", encoding="utf-8") if cfg.get("log") else None,
|
||||
env=vision_env(cfg, env), lazy=lazy)
|
||||
print("model unloaded; the first request loads it ..." if lazy else
|
||||
@@ -6585,6 +6677,7 @@ def main() -> int:
|
||||
atexit.register(hub.close) # the servers Strata started end with it
|
||||
httpd = serve(svc, host=a.host, port=a.port)
|
||||
svc.start_idle_unload()
|
||||
svc.start_vision_idle()
|
||||
here = "127.0.0.1" if a.host in ("0.0.0.0", "", "::") else a.host
|
||||
print(f"ready: http://{here}:{a.port}/v1 (OpenAI: /v1/chat/completions, Anthropic: /v1/messages, "
|
||||
f"context {engine.max_context} tokens{', images on' if vision else ''}"
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
"""The elastic image encoder (the vision section's "elastic": true with "vram_elastic"): the first picture makes the
|
||||
expert cache keep the encoder's VRAM free and then starts it, later pictures use it as it is, an idle encoder stops and
|
||||
the cache takes its VRAM back, a POST /v1/vram reserve stacks on the encoder's share, and the engine's load never starts
|
||||
it on its own."""
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from serve.frontend import ChatTemplate
|
||||
from serve.server import ByteTokenizer, Service, Vision
|
||||
from serve.test_vram import VramEngine
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
IMAGE = {"type": "image", "source": "x.png"}
|
||||
|
||||
|
||||
class ElasticVision:
|
||||
"""An encoder process stand-in: starts, stops, and turns every picture into three image tokens."""
|
||||
def __init__(self, d, elastic=True):
|
||||
self.elastic, self.elastic_mib, self.elastic_idle_s = elastic, 2048, 60.0
|
||||
self.up, self.starts, self.unloads = False, 0, 0
|
||||
self.dir = Path(d)
|
||||
self.rows = self.dir / "img.sve"
|
||||
self.rows.write_bytes(b"rows")
|
||||
|
||||
def alive(self):
|
||||
return self.up
|
||||
|
||||
def restart(self):
|
||||
self.up, self.starts = True, self.starts + 1
|
||||
|
||||
def unload(self):
|
||||
self.up, self.unloads = False, self.unloads + 1
|
||||
|
||||
def encode(self, source):
|
||||
assert self.up, "a picture reached an encoder that was not started"
|
||||
return self.rows, 3
|
||||
|
||||
|
||||
class Elastic(unittest.TestCase):
|
||||
def setUp(self):
|
||||
d = tempfile.mkdtemp()
|
||||
self.tok = ByteTokenizer()
|
||||
self.engine = VramEngine(self.tok)
|
||||
self.engine.loaded = True
|
||||
self.vision = ElasticVision(d)
|
||||
self.svc = Service(self.engine, self.tok, ChatTemplate(ROOT / "serve/chat_template.jinja"), vision=self.vision)
|
||||
self.addCleanup(self.drop_embeddings)
|
||||
|
||||
def drop_embeddings(self):
|
||||
path = getattr(getattr(self.svc, "embeddings", None), "path", None)
|
||||
if path is not None:
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
def picture(self):
|
||||
self.svc.prepare([{"role": "user", "content": [{"type": "text", "text": "what is it"}, IMAGE]}], None, {})
|
||||
|
||||
def test_the_first_picture_makes_room_then_starts_the_encoder(self):
|
||||
self.picture()
|
||||
self.assertEqual(self.engine.calls, [2048]) # the cache keeps the encoder's share free first
|
||||
self.assertEqual(self.vision.starts, 1)
|
||||
self.assertTrue(self.svc.vision_held)
|
||||
self.picture() # the next one uses the running encoder
|
||||
self.assertEqual(self.engine.calls, [2048])
|
||||
self.assertEqual(self.vision.starts, 1)
|
||||
|
||||
def test_an_idle_encoder_stops_and_the_cache_grows_back_whole(self):
|
||||
self.picture()
|
||||
self.assertEqual(self.svc._vision_idle_down(), "busy") # a picture came just now
|
||||
self.svc.last_image_at = time.time() - 61
|
||||
with self.svc.fifo: # a request holds the turn
|
||||
self.assertEqual(self.svc._vision_idle_down(), "busy")
|
||||
self.assertEqual(self.svc._vision_idle_down(), "down")
|
||||
self.assertFalse(self.vision.up)
|
||||
self.assertFalse(self.svc.vision_held)
|
||||
self.assertEqual(self.engine.calls, [2048, 0]) # 0, not None: the full size, not the start's reserve
|
||||
self.assertEqual(self.svc._vision_idle_down(), "nothing")
|
||||
self.picture() # and the next picture starts it again
|
||||
self.assertEqual(self.vision.starts, 2)
|
||||
self.assertEqual(self.engine.calls, [2048, 0, 2048])
|
||||
|
||||
def test_a_vram_reserve_stacks_on_the_encoders_share(self):
|
||||
self.svc.vram(4000)
|
||||
self.picture()
|
||||
self.assertEqual(self.engine.calls, [4000, 6048])
|
||||
self.svc.vram(1000) # asked while the encoder runs
|
||||
self.assertEqual(self.engine.calls[-1], 3048)
|
||||
self.svc.last_image_at = 0
|
||||
self.svc._vision_idle_down()
|
||||
self.assertEqual(self.engine.calls[-1], 1000) # back to the asked reserve, not to 0
|
||||
|
||||
def test_an_engine_that_cannot_shrink_still_gets_its_encoder(self):
|
||||
self.engine.elastic = False
|
||||
self.picture()
|
||||
self.assertEqual(self.vision.starts, 1)
|
||||
self.assertFalse(self.svc.vision_held)
|
||||
self.svc.last_image_at = 0
|
||||
self.assertEqual(self.svc._vision_idle_down(), "down")
|
||||
self.assertEqual(self.engine.calls, [2048]) # the refused shrink only: nothing to give back
|
||||
|
||||
def test_the_load_never_starts_an_elastic_encoder(self):
|
||||
self.assertFalse(self.svc._vision_down())
|
||||
self.svc.vision = ElasticVision(tempfile.mkdtemp(), elastic=False)
|
||||
self.assertTrue(self.svc._vision_down()) # a non-elastic encoder that is down is started again
|
||||
|
||||
def test_an_unload_lets_go_of_the_share(self):
|
||||
self.picture()
|
||||
self.assertEqual(self.svc.unload(), "unloaded")
|
||||
self.assertFalse(self.svc.vision_held)
|
||||
self.assertFalse(self.vision.up)
|
||||
|
||||
def test_the_config_keys(self):
|
||||
v = Vision({"exe": "e", "mmproj": "m", "model": "t", "elastic": True, "elastic_mib": 3000,
|
||||
"elastic_idle_s": 30}, lazy=False) # elastic: nothing starts with the server
|
||||
self.assertTrue(v.elastic and v.elastic_mib == 3000 and v.elastic_idle_s == 30 and not v.alive())
|
||||
v = Vision({"exe": "e", "mmproj": "m", "model": "t"}, lazy=True)
|
||||
self.assertFalse(v.elastic)
|
||||
self.assertEqual((v.elastic_mib, v.elastic_idle_s), (2048, 120.0))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user