Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

serve: a request with more than 64 unique images keeps its own encoded files (#1072)

Niko122147aafa9eb5c6
diff --git a/serve/server.py b/serve/server.py
index b1d7a2471..4030a34a7 100644
--- a/serve/server.py
+++ b/serve/server.py
@@ -1735,12 +1735,23 @@ class Vision:
im.save(out, format="PNG")
return out.getvalue()
- def encode(self, source: str | bytes) -> tuple[Path, int]:
- """-> (embeddings file, number of image tokens). `source`: what load() reads, or the image's bytes."""
+ def encode_all(self, sources: list) -> list[tuple[Path, int]]:
+ """encode() for every image of one request: the files of this request's earlier images are never evicted to
+ make room for a later one (#1072: with more than 64 unique images the first was deleted before the request
+ had read it)."""
+ out: list[tuple[Path, int]] = []
+ for src in sources:
+ out.append(self.encode(src, keep=[p for p, _ in out]))
+ return out
+
+ def encode(self, source: str | bytes, keep=()) -> tuple[Path, int]:
+ """-> (embeddings file, number of image tokens). `source`: what load() reads, or the image's bytes.
+ `keep`: files the caller still needs (never evicted by this call)."""
data = self.normalize(source if isinstance(source, bytes) else self.load(source))
key = hashlib.sha256(data).hexdigest()[:32]
with self.lock:
if key in self.cache:
+ self.cache[key] = self.cache.pop(key) # most recently used last
return self.cache[key]
img, out = self.dir / f"{key}.img", self.dir / f"{key}.sve"
img.write_bytes(data)
@@ -1754,9 +1765,12 @@ class Vision:
raise ValueError("the image could not be read: " + (line[4:] if line.startswith("ERR") else
"the vision encoder stopped"))
self.cache[key] = (out, int(line.split()[1]))
- if len(self.cache) > 64: # oldest first
- old = next(iter(self.cache))
- self.cache.pop(old)[0].unlink(missing_ok=True)
+ held = {str(p) for p in keep} | {str(out)}
+ for old in list(self.cache): # oldest first, but never one still in use
+ if len(self.cache) <= 64:
+ break
+ if str(self.cache[old][0]) not in held:
+ self.cache.pop(old)[0].unlink(missing_ok=True)
return self.cache[key]
def close(self):
@@ -2765,7 +2779,8 @@ 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.fifo:
- encoded = [self.vision.encode(src) for src in images]
+ encoded = (self.vision.encode_all(images) if hasattr(self.vision, "encode_all")
+ else [self.vision.encode(src) for src in images])
# 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.
diff --git a/serve/test_server.py b/serve/test_server.py
index 590cf05ca..34f608021 100644
--- a/serve/test_server.py
+++ b/serve/test_server.py
@@ -3864,6 +3864,57 @@ class VisionArgs(unittest.TestCase):
["--max-tokens", "1024", "--min-tokens", "768"])
+class VisionCacheEviction(unittest.TestCase):
+ """#1072: the cache of encoded images keeps 64; a request's own images are never evicted for a later one."""
+
+ def make(self, d):
+ import serve.server as server
+ v = server.Vision.__new__(server.Vision)
+ v.dir, v.cache, v.lock = d, {}, threading.Lock()
+ v.load = lambda src: src
+
+ class Pipe:
+ def __init__(self):
+ self.last = ""
+
+ def write(self, text):
+ self.last = text
+
+ def flush(self):
+ (d / self.last.split()[2]).write_bytes(b"x")
+
+ def readline(self):
+ return "OK 3" + chr(10)
+
+ pipe = Pipe()
+ v.proc = SimpleNamespace(stdin=pipe, stdout=pipe)
+ v.normalize = staticmethod(lambda data: data)
+ return v
+
+ def test_one_request_with_more_than_64_images_keeps_all_its_files(self):
+ with tempfile.TemporaryDirectory() as t:
+ d = Path(t)
+ v = self.make(d)
+ done = v.encode_all([f"image {i}".encode() for i in range(70)])
+ self.assertEqual(len(done), 70)
+ self.assertTrue(all(p.exists() for p, _ in done))
+ # the next request's image shrinks the cache back to 64, oldest first
+ p, _ = v.encode(b"another one")
+ self.assertEqual(len(v.cache), 64)
+ self.assertTrue(p.exists())
+ self.assertEqual(len(list(d.glob("*.sve"))), 64)
+
+ def test_plain_encode_still_evicts_the_oldest(self):
+ with tempfile.TemporaryDirectory() as t:
+ d = Path(t)
+ v = self.make(d)
+ first, _ = v.encode(b"first")
+ for i in range(64):
+ v.encode(f"image {i}".encode())
+ self.assertEqual(len(v.cache), 64)
+ self.assertFalse(first.exists())
+
+
class VisionShutdown(unittest.TestCase):
"""#914: ending the server removes the encoder's scratch directory; unloading keeps it."""