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++

Conversation cache: a picture is matched by its bytes' hash (from the server) and its grid, not by its embedding floats (#2228)

Niko1221cf1b0edf913f
diff --git a/serve/server.py b/serve/server.py
index eec1bf360..843dc0922 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 bbb176ada..93dcb26d7 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 9737cad4f..20e6b17a2 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=<hex>,<hex>,... (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<uint64_t> 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 933b55ca9..29a07e66f 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=<hex>,<hex>,... (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<uint64_t> 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)