From cf1b0edf913f7d534f8c1a32872fcd2123d480be Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 13 Oct 2026 07:33:16 +0200 Subject: [PATCH] Conversation cache: a picture is matched by its bytes' hash (from the server) and its grid, not by its embedding floats (#2228) The server already keys its encoder cache by the normalized picture bytes (sha256, the .sve file name); it now sends those keys with the request (img_keys=,..., in prompt order), and the engine's conversation cache uses key + grid for a picture when the count matches. Without the key (an older server) it hashes the embeddings as before. Old engines skip the unknown key. Measured for #2228 (one 1600x1000 screenshot-like picture, strata-vision, fresh processes and twice in one process): the CPU encoder gives the same bits on a TR PRO 3975WX at 8/15/16/32 threads and on a Xeon E5-2643 v3 (e2357d8e...), the GPU encoder on an RTX A4000 is reproducible too (92cf7818...), but CPU and GPU differ. So a picture's embeddings change when the encoder moves between CPU and GPU, or after an encoder update, and no longer on its own; with the byte key the cache's matching does not depend on that at all. CUDA/HIP and SYCL. Test: serve/test_server.py test_pictures_are_keyed_by_their_bytes_for_the_engine. --- serve/server.py | 13 +++++++++++++ serve/test_server.py | 25 +++++++++++++++++++++++++ src/program/generate.cpp | 21 ++++++++++++++++++++- sycl/src/program/generate.cpp | 20 +++++++++++++++++++- 4 files changed, 77 insertions(+), 2 deletions(-) diff --git a/serve/server.py b/serve/server.py index eec1bf36..843dc092 100644 --- a/serve/server.py +++ b/serve/server.py @@ -1039,6 +1039,11 @@ class StrataEngine: # extends: no conversation checkpoint for it (#830). It still reuses a cached prefix. Absent = as before. if sampling.get("strata_checkpoint") is False: keys += " ckpt=0" + # #2228: the pictures' keys (hex, in prompt order): the engine matches a picture by them, not by its embeddings + ik = sampling.get("strata_img_keys") + if isinstance(ik, list) and ik and all(isinstance(k, str) and k and all(c in "0123456789abcdef" for c in k) + for k in ik): + keys += " img_keys=" + ",".join(ik) # "strata_prefix" (resolved by Service.resolve_prefix to {"tokens": N}): the first N prompt tokens are a shared # prefix - the engine pins the checkpoint there. Absent or unresolved = as before. prefix = sampling.get("strata_prefix") @@ -3697,6 +3702,7 @@ class Service: if force and kwargs.get("enable_thinking", True) is False: ids = ids + self.tok.encode(force, parse_special=True) self.embeddings.path = None + self.embeddings.keys = None images = images_of(messages) if images: if self.vision is None: @@ -3772,6 +3778,10 @@ class Service: # one more for every retry of a 503. run() deletes it; drop_embeddings() if run() never starts. combined = combined_embeddings_path(self.vision.dir, sum(Path(p).stat().st_size for p, _ in encoded)) self.embeddings.path = combined # first, so a half-written one is found as well + # #2228: each picture's key is its normalized bytes' hash (the encoder's file name), so the engine's + # conversation cache matches a picture by what it is, not by its embedding floats: a picture encoded again + # (an encoder restart, the cache's eviction) with other bits still matches its checkpoints + self.embeddings.keys = [Path(p).stem[:16] for p, _ in encoded] write_temporary(combined, [p for p, _ in encoded]) if req is not None and req.get("strata_prefix") is not None: req["strata_prefix"] = self.resolve_prefix(req["strata_prefix"], messages, tools, kwargs, ids, bool(images)) @@ -3962,6 +3972,9 @@ class Service: looped, next_loop_check = False, LOOP_CHECK_EVERY # #728: reasoning that repeats whole passages raw_ids = [] # every generated id (STRATA_DEBUG: dump raw model text) emb, self.embeddings.path = getattr(self.embeddings, "path", None), None # this run's to delete now + img_keys, self.embeddings.keys = getattr(self.embeddings, "keys", None), None + if emb and img_keys: + sampling = {**(sampling or {}), "strata_img_keys": img_keys} # #2228: sent beside the embeddings file # Only a DONE line replaces engine.last, so a request that died, errored or was disconnected must not have # the PREVIOUS request's decode figures recorded as its own: each pass keeps its own DONE (a segment) if # one arrived. A reasoning-budget continuation is another native generation, not another API request, diff --git a/serve/test_server.py b/serve/test_server.py index bbb176ad..93dcb26d 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -324,6 +324,31 @@ class ImageMarkers(unittest.TestCase): self.assertIn("<|image_pad|> marks" if "docs" in text else "plain", tok.decode(ids)) svc.embeddings.path.unlink(missing_ok=True) + def test_pictures_are_keyed_by_their_bytes_for_the_engine(self): + """#2228: each picture's key (its normalized bytes' hash: the encoder's file name) goes to the engine as + img_keys=, in prompt order, so the conversation cache does not depend on the embedding floats.""" + import tempfile + tok = ByteTokenizer() + with tempfile.TemporaryDirectory() as d: + class Keyed(self.FakeVision): + def encode(self, source): + p = self.dir / ("0123456789abcdef0123456789abcdef.sve" if source == "a.png" else + "fedcba9876543210fedcba9876543210.sve") + p.write_bytes(b"rows") + return p, 3 + svc = Service(MockEngine(tok, "ok", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"), + vision=Keyed(d)) + msgs = [{"role": "user", "content": [{"type": "image", "source": "b.png"}, {"type": "text", "text": "and"}, + {"type": "image", "source": "a.png"}]}] + svc.prepare(msgs, None, {}) + self.assertEqual(svc.embeddings.keys, ["fedcba9876543210", "0123456789abcdef"]) + svc.embeddings.path.unlink(missing_ok=True) + keys = StrataEngine.sampling_keys({"strata_img_keys": ["fedcba9876543210", "0123456789abcdef"]}) + self.assertEqual(keys, " img_keys=fedcba9876543210,0123456789abcdef") + for bad in ([], ["XYZ"], ["ab cd"], "abc", [3]): # never sent malformed: the engine falls back to the embeddings + with self.subTest(bad=bad): + self.assertNotIn("img_keys", StrataEngine.sampling_keys({"strata_img_keys": bad})) + def test_anthropic_tool_result_image(self): """Claude Code's Read of a picture returns it inside a tool_result: it reaches the encoder, in place.""" import tempfile diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 9737cad4..20e6b17a 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -10391,6 +10391,10 @@ int main(int argc, char** argv) { // the missed experts and the draft-probability floor, for this request only double req_pcie_frac = o.pcie_frac, req_spec_min_p = o.spec_min_p; int req_aux_cpus = -1; // aux_cpus=0|1: --aux-cpus for this request (-1 = the start-up value) + // #2228: img_keys=,,... (GENI): each picture's key from the server (its normalized bytes' hash), + // in prompt order. With them the conversation cache matches a picture by its key and grid, not by its + // embedding floats, so a picture encoded again with other bits still matches. Absent: the embeddings' hash. + std::vector req_img_keys; if (endp != nullptr) { // GENI takes the same keys (#75: image requests were always greedy); its // embedding file path is the first token without an = for (;;) { @@ -10419,6 +10423,18 @@ int main(int argc, char** argv) { else if (key == "pcie_frac") req_pcie_frac = std::clamp((double) fv, 0.0, 1.0); else if (key == "spec_min_p") req_spec_min_p = std::clamp((double) fv, 0.0, 1.0); else if (key == "aux_cpus") req_aux_cpus = std::atoi(tok.c_str() + eq + 1) != 0 ? 1 : 0; + else if (key == "img_keys") { + req_img_keys.clear(); + const char* q = tok.c_str() + eq + 1; + while (*q != '\0') { + char* qe = nullptr; + const unsigned long long v = std::strtoull(q, &qe, 16); + if (qe == q) { req_img_keys.clear(); break; } + req_img_keys.push_back((uint64_t) v); + q = *qe == ',' ? qe + 1 : qe; + if (*qe != ',' && *qe != '\0') { req_img_keys.clear(); break; } + } + } // unknown keys are skipped: the ids start at the first token without '=' } } @@ -10487,7 +10503,10 @@ int main(int argc, char** argv) { { // what the conversation cache compares: a picture is its grid and its embeddings const int64_t grid[3] = {im.n, im.nx, im.ny}; uint64_t h = fnv1a(grid, sizeof grid); - h = fnv1a(img_rows.data() + im.off, (size_t) im.n * (size_t) g.n_embd * sizeof(float), h); + if (req_img_keys.size() == imgs.size()) // #2228: the server's key for picture k + h = fnv1a(&req_img_keys[k - 1], sizeof(uint64_t), h); + else + h = fnv1a(img_rows.data() + im.off, (size_t) im.n * (size_t) g.n_embd * sizeof(float), h); req_imgs.push_back({i, h}); } for (int64_t j = 0; j < im.n && ve.empty(); ++j) diff --git a/sycl/src/program/generate.cpp b/sycl/src/program/generate.cpp index 933b55ca..29a07e66 100644 --- a/sycl/src/program/generate.cpp +++ b/sycl/src/program/generate.cpp @@ -9544,6 +9544,9 @@ int main(int argc, char **argv) try { int req_ckpt = 1; // tuning keys (setup's calibration measures settings without restarting the engine): the PCIe share of // the missed experts and the draft-probability floor, for this request only + // #2228: img_keys=,,... (GENI): each picture's key from the server (its normalized bytes' hash), in + // prompt order; the conversation cache matches a picture by it and its grid instead of its embedding floats + std::vector req_img_keys; double req_pcie_frac = o.pcie_frac, req_spec_min_p = o.spec_min_p; if (endp != nullptr) { // GENI takes the same keys (#75: image requests were always greedy); its // embedding file path is the first token without an = @@ -9571,6 +9574,18 @@ int main(int argc, char **argv) try { else if (key == "logprobs") req_logprobs = std::clamp(std::atoi(tok.c_str() + eq + 1), -1, 20); else if (key == "pcie_frac") req_pcie_frac = std::clamp((double) fv, 0.0, 1.0); else if (key == "spec_min_p") req_spec_min_p = std::clamp((double) fv, 0.0, 1.0); + else if (key == "img_keys") { + req_img_keys.clear(); + const char* q = tok.c_str() + eq + 1; + while (*q != '\0') { + char* qe = nullptr; + const unsigned long long v = std::strtoull(q, &qe, 16); + if (qe == q) { req_img_keys.clear(); break; } + req_img_keys.push_back((uint64_t) v); + q = *qe == ',' ? qe + 1 : qe; + if (*qe != ',' && *qe != '\0') { req_img_keys.clear(); break; } + } + } // unknown keys are skipped: the ids start at the first token without '=' } } @@ -9632,7 +9647,10 @@ int main(int argc, char **argv) try { { // what the conversation cache compares: a picture is its grid and its embeddings const int64_t grid[3] = {im.n, im.nx, im.ny}; uint64_t h = fnv1a(grid, sizeof grid); - h = fnv1a(img_rows.data() + im.off, (size_t) im.n * (size_t) g.n_embd * sizeof(float), h); + if (req_img_keys.size() == imgs.size()) // #2228: the server's key for picture k + h = fnv1a(&req_img_keys[k - 1], sizeof(uint64_t), h); + else + h = fnv1a(img_rows.data() + im.off, (size_t) im.n * (size_t) g.n_embd * sizeof(float), h); req_imgs.push_back({i, h}); } for (int64_t j = 0; j < im.n && ve.empty(); ++j)