From 698b02e1a2039c38c7d9fa747193fb3c6021455b Mon Sep 17 00:00:00 2001 From: Robert Karl Date: Tue, 20 Oct 2026 10:33:30 -0700 Subject: [PATCH] frontend: a picture encoded once is a picture encoded once (USTRAT-15) A chat client resends the whole conversation every turn, pictures included, and the vision encoder is the slow part of a request: 6 s a screenshot on 16 CPU threads, 18 s on 6, every turn, while the engine reuses the prompt's KV prefix in a fraction of a second. Upstream's Python server kept the encoder's output per picture in an LRU of 64 files keyed by the SHA-256 of the picture's bytes (serve/server.py, class Vision); this is that cache for the C++ front end, in memory. frontend/picture_cache.hpp (header-only, no llama.cpp): PictureCache keeps PictureRows (the projector's output, n_tok rows of the embedding width) under mtmd's chunk id, which is the SHA-256 of the bitmap's bytes. Shared pointers, so a request keeps the rows it is writing when the cache lets go of them; two limits, entries and bytes, the newest entry always kept. engine_key() turns the id into the 64-bit key the engine's conversation cache takes (img_keys= on the GENI line, #2228), so a picture encoded again with other bits still matches its KV prefix. encode_pictures is now six short functions: open the file, fill it, find the chunk, its id, its rows (cache or encoder), its grid, write the record. --picture-cache N (default 64, 1 GiB) sets the size; 0 turns it off. frontend/tests/picture_cache_test.cpp: hit/miss and counters, LRU order and the entry limit, the byte limit and the oversize newest entry, a held entry outliving its eviction and a key replaced, off and an empty key, the engine keys, eight threads at once. In make test. Co-Authored-By: Claude Fable 5.1 --- CMakeLists.txt | 5 + Makefile | 3 +- frontend/main.cpp | 11 ++ frontend/picture_cache.hpp | 175 ++++++++++++++++++++ frontend/strata_context.cpp | 223 ++++++++++++++++++-------- frontend/strata_context.hpp | 2 + frontend/tests/picture_cache_test.cpp | 146 +++++++++++++++++ 7 files changed, 493 insertions(+), 72 deletions(-) create mode 100644 frontend/picture_cache.hpp create mode 100644 frontend/tests/picture_cache_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 3d67c01..8a4db48 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2175,6 +2175,11 @@ if(STRATA_FRONTEND AND STRATA_NATIVE_EXPERTS) add_executable(literals_test EXCLUDE_FROM_ALL frontend/tests/literals_test.cpp) target_include_directories(literals_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/frontend ${STRATA_GGML_DIR}/vendor) target_compile_features(literals_test PRIVATE cxx_std_20) + add_executable(picture_cache_test EXCLUDE_FROM_ALL frontend/tests/picture_cache_test.cpp) + target_include_directories(picture_cache_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/frontend) + target_compile_features(picture_cache_test PRIVATE cxx_std_20) + find_package(Threads REQUIRED) + target_link_libraries(picture_cache_test PRIVATE Threads::Threads) endif() if(STRATA_BUILD_TESTS) diff --git a/Makefile b/Makefile index a192148..debed9a 100644 --- a/Makefile +++ b/Makefile @@ -74,9 +74,10 @@ frontend: # backpressure, child exit, ERR) and the HTTP surface a coding agent touches (frontend/tests/e2e.sh). Needs python3 # and curl; no GPU and no model. Runs in the CUDA-free build directory, so it works on the build box and on a laptop. test: frontend - cmake --build $(BUILD_DIR)-frontend -j $(JOBS) --target engine_test literals_test + cmake --build $(BUILD_DIR)-frontend -j $(JOBS) --target engine_test literals_test picture_cache_test $(BUILD_DIR)-frontend/bin/engine_test frontend/tests/fake-engine.py $(BUILD_DIR)-frontend/bin/literals_test + $(BUILD_DIR)-frontend/bin/picture_cache_test frontend/tests/e2e.sh $(BUILD_DIR)-frontend/bin/unbiased-strata clean: diff --git a/frontend/main.cpp b/frontend/main.cpp index 7fddb6d..9498907 100644 --- a/frontend/main.cpp +++ b/frontend/main.cpp @@ -20,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -55,6 +56,8 @@ void usage() { " handed to the engine (Qwen family); on the CPU (--threads N) unless --mmproj-gpu\n" " --mmproj-gpu encode on the card: about 1 GB of VRAM plus work buffers, taken before the engine\n" " sizes its expert cache only if the encoder loads first; for cards with room\n" + " --picture-cache N keep the encoded rows of the last N pictures (default 64, up to 1 GiB) so a chat\n" + " that resends its pictures every turn encodes each once; 0 turns it off\n" " -- everything after it is passed to the engine; --serve is added\n" "\n" "example (Qwen3.6-35B-A3B from its GGUF):\n" @@ -91,6 +94,7 @@ int main(int argc, char ** argv) { std::vector engine_args; std::vector llama_argv; bool mmproj_gpu = false; // the vision encoder on the card: only where the engine leaves room (a 48 GB card) + long picture_cache = 64; // --picture-cache N: encoded pictures kept for the turns that resend them llama_argv.push_back(argv[0]); for (int i = 1; i < argc; ++i) { const std::string a = argv[i]; @@ -113,6 +117,12 @@ int main(int argc, char ** argv) { mmproj_gpu = true; continue; } + if (a == "--picture-cache") { + if (i + 1 >= argc) { usage(); return 2; } + picture_cache = std::strtol(argv[++i], nullptr, 10); + if (picture_cache < 0) { usage(); return 2; } + continue; + } llama_argv.push_back(argv[i]); } if (engine_exe.empty()) { @@ -153,6 +163,7 @@ int main(int argc, char ** argv) { llama_numa_init(params.numa); strata_context ctx_server; + ctx_server.set_picture_cache((size_t) picture_cache, (size_t) 1 << 30); server_http_context ctx_http; if (!ctx_http.init(params)) { SRV_ERR("%s", "failed to initialize HTTP server\n"); diff --git a/frontend/picture_cache.hpp b/frontend/picture_cache.hpp new file mode 100644 index 0000000..16df5e0 --- /dev/null +++ b/frontend/picture_cache.hpp @@ -0,0 +1,175 @@ +// UnbiasedStrata: a picture encoded once is a picture encoded once. +// +// A chat client resends the whole conversation on every turn, pictures included, and the vision encoder is the slow +// part of a request (USTRAT-15: 6 s a screenshot on 16 CPU threads, 18 s on 6; the engine then reuses the prompt's +// KV prefix in a fraction of a second). Upstream Strata's Python server kept the encoder's output per picture in an +// LRU of 64 files keyed by the SHA-256 of the picture's bytes (serve/server.py, class Vision). This is that cache +// for the C++ front end, in memory: mtmd already names every bitmap by the SHA-256 of its bytes, so the key is the +// chunk's id and the rows are the projector's output (n_tok rows of the model's embedding width). +// +// Entries are shared pointers: a request keeps the rows it is writing even when the cache lets go of them, so +// nothing is ever evicted from under a caller (upstream's #1072). Two limits, entries and bytes; the newest entry is +// always kept, even alone over the byte limit, so a request never fails for cache room. +// +// Header-only, free of llama.cpp, so frontend/tests/picture_cache_test.cpp runs it without a model. +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace strata_frontend { + +struct PictureRows { + int32_t n_tok = 0; // rows + int32_t nx = 0; // the grid the rows make (columns) + int32_t ny = 0; // (lines) + int32_t width = 0; // floats a row + std::vector embd; // n_tok * width + + size_t bytes() const { return sizeof(PictureRows) + embd.size() * sizeof(float); } +}; + +class PictureCache { +public: + using Rows = std::shared_ptr; + + struct Stats { + uint64_t hits = 0; + uint64_t misses = 0; + uint64_t evictions = 0; + }; + + explicit PictureCache(size_t max_entries = 64, size_t max_bytes = size_t(1) << 30) { + configure(max_entries, max_bytes); + } + + // the limits; drops what is held. 0 entries turns the cache off: put() hands the rows back uncached. + void configure(size_t max_entries, size_t max_bytes) { + std::lock_guard lock(mu_); + max_entries_ = max_entries; + max_bytes_ = max_bytes; + items_.clear(); + order_.clear(); + bytes_ = 0; + } + + bool enabled() const { return max_entries_ > 0; } + size_t max_entries() const { return max_entries_; } + size_t max_bytes() const { return max_bytes_; } + + // the rows of a picture seen before, now the most recently used; nullptr for a picture not held + Rows find(const std::string & key) { + std::lock_guard lock(mu_); + auto it = items_.find(key); + if (it == items_.end()) { + ++stats_.misses; + return nullptr; + } + order_.splice(order_.end(), order_, it->second.pos); + ++stats_.hits; + return it->second.rows; + } + + // remembers the rows under `key` (replacing an older entry of that key) and returns them + Rows put(const std::string & key, PictureRows rows) { + Rows shared = std::make_shared(std::move(rows)); + if (!enabled() || key.empty()) { + return shared; + } + std::lock_guard lock(mu_); + drop_locked(key); + order_.push_back(key); + items_[key] = Item{shared, std::prev(order_.end())}; + bytes_ += shared->bytes(); + evict_locked(); + return shared; + } + + size_t size() const { + std::lock_guard lock(mu_); + return items_.size(); + } + + size_t bytes() const { + std::lock_guard lock(mu_); + return bytes_; + } + + Stats stats() const { + std::lock_guard lock(mu_); + return stats_; + } + + // The key the engine's conversation cache takes (img_keys=,...): the first 64 bits of the SHA-256 hex id + // mtmd gives a bitmap. 0 for an id that is not at least 16 hex digits, and 0 is never sent. + static uint64_t engine_key(const std::string & id) { + if (id.size() < 16) { + return 0; + } + const std::string head = id.substr(0, 16); + char * end = nullptr; + const unsigned long long v = std::strtoull(head.c_str(), &end, 16); + return (end == head.c_str() + 16) ? (uint64_t) v : 0; + } + + static std::string hex(uint64_t v) { + char b[17]; + std::snprintf(b, sizeof b, "%016llx", (unsigned long long) v); + return b; + } + + // ",,..." for the GENI line; empty when any key is 0 (the engine then keys on the rows themselves) + static std::string hex_list(const std::vector & keys) { + std::string out; + for (uint64_t k : keys) { + if (k == 0) { + return std::string(); + } + out += (out.empty() ? "" : ",") + hex(k); + } + return out; + } + +private: + struct Item { + Rows rows; + std::list::iterator pos; // its place in order_ + }; + + void drop_locked(const std::string & key) { + auto it = items_.find(key); + if (it == items_.end()) { + return; + } + bytes_ -= it->second.rows->bytes(); + order_.erase(it->second.pos); + items_.erase(it); + } + + // the least recently used go first, down to the limits; the newest entry stays whatever its size + void evict_locked() { + while (items_.size() > 1 && (items_.size() > max_entries_ || bytes_ > max_bytes_)) { + drop_locked(order_.front()); + ++stats_.evictions; + } + } + + mutable std::mutex mu_; + size_t max_entries_ = 0; + size_t max_bytes_ = 0; + size_t bytes_ = 0; + Stats stats_; + std::list order_; // least recently used first + std::unordered_map items_; +}; + +} // namespace strata_frontend diff --git a/frontend/strata_context.cpp b/frontend/strata_context.cpp index bf70f54..8dde30c 100644 --- a/frontend/strata_context.cpp +++ b/frontend/strata_context.cpp @@ -6,6 +6,7 @@ #include "strata_context.hpp" #include "engine.hpp" #include "literals.hpp" +#include "picture_cache.hpp" #include "server-common.h" #include "server-task.h" @@ -67,6 +68,7 @@ struct Slot { int32_t n_predict = -1; std::string images_path; // the request's picture rows for GENI (step 8); unlinked when the slot is released + std::vector image_keys; // one per picture, for img_keys= on the GENI line (0: none) bool active() const { return task != nullptr; } @@ -180,6 +182,7 @@ struct strata_context_impl { int32_t vision_width = 0; // the projector's output width, checked against the model's embedding int32_t image_pad_id = -1; // the token whose runs in the ids the engine replaces with picture rows bool p_mmproj_gpu = false; + strata_frontend::PictureCache pictures; // encoded rows per picture (--picture-cache N; 64 pictures, 1 GiB) // the texts of the vocabulary's control tokens and marker-like added tokens: inside a message they are text // (literals.hpp, USTRAT-14) @@ -338,7 +341,7 @@ struct strata_context_impl { t.id, t.params.sampling.grammar.grammar.size()); } - const std::string header = gen_header(t, slot.n_predict, slot.images_path); + const std::string header = gen_header(t, slot.n_predict, slot.images_path, slot.image_keys); if (!engine.send_request(header, ids)) { send_error(t, "the engine is not running", ERROR_TYPE_UNAVAILABLE); slot.release(); @@ -356,7 +359,8 @@ struct strata_context_impl { // `GEN key=value...` from the request's sampling parameters. Absent keys mean greedy to the engine // (generate.cpp: "Absent = greedy"), so temperature <= 0 sends none of them. - std::string gen_header(const server_task & t, int32_t max_new, const std::string & images_path = std::string()) const { + std::string gen_header(const server_task & t, int32_t max_new, const std::string & images_path = std::string(), + const std::vector & image_keys = {}) const { const auto & s = t.params.sampling; std::string h = (images_path.empty() ? "GEN " : "GENI ") + std::to_string(max_new); char b[128]; @@ -388,6 +392,11 @@ struct strata_context_impl { if (!images_path.empty()) { // GENI [key=value ...] image_pad= : the engine reads strata-vision records from the // file and places them at the runs of image_pad (src/poly/main.cpp take_pictures, generate.cpp for strata) + // img_keys= (#2228): the conversation cache matches a picture by its key and grid, not its rows + const std::string keys = strata_frontend::PictureCache::hex_list(image_keys); + if (!keys.empty()) { + h += " img_keys=" + keys; + } h += " image_pad=" + std::to_string(image_pad_id) + " " + images_path; } return h; @@ -478,6 +487,8 @@ struct strata_context_impl { p_mmproj_gpu = p.mmproj_use_gpu; LOG_INF("vision: %s, rows of %d, encoder on the %s (%d CPU threads), at most %d rows a picture, image_pad=%d\n", p.mmproj.path.c_str(), vision_width, cp.use_gpu ? "GPU" : "CPU", cp.n_threads, cp.image_max_tokens, image_pad_id); + LOG_INF("vision: the rows of the last %zu pictures (%zu MiB at most) are kept for the turns that resend them\n", + pictures.max_entries(), pictures.max_bytes() >> 20); return true; } @@ -488,79 +499,16 @@ struct strata_context_impl { err = "images need the server started with --mmproj"; return false; } - char name[] = "/tmp/unbiased-strata-pictures-XXXXXX"; - const int fd = ::mkstemp(name); - if (fd < 0) { - err = "cannot create the pictures file"; - return false; - } - slot.images_path = name; - std::FILE * f = ::fdopen(fd, "wb"); + std::FILE * f = open_pictures_file(err); if (f == nullptr) { - ::close(fd); - err = "cannot open the pictures file"; return false; } - const size_t n = t.tokens.size(); - int n_pictures = 0; - ids.reserve(n); - for (size_t i = 0; i < n;) { - if (t.tokens[i] != LLAMA_TOKEN_NULL) { - ids.push_back(t.tokens[i]); - ++i; - continue; - } - const mtmd_input_chunk * ch = nullptr; - try { - ch = t.tokens.find_chunk(i).get(); - } catch (const std::exception &) { - ch = nullptr; - } - if (ch == nullptr || mtmd_input_chunk_get_type(ch) != MTMD_INPUT_CHUNK_TYPE_IMAGE) { - std::fclose(f); - err = "only pictures are supported, not audio or video"; - return false; - } - const int32_t n_tok = (int32_t) mtmd_input_chunk_get_n_tokens(ch); - const auto t0 = std::chrono::steady_clock::now(); - if (mtmd_encode_chunk(mctx, ch) != 0) { - std::fclose(f); - err = "the vision encoder failed"; - return false; - } - const float * embd = mtmd_get_output_embd(mctx); - const mtmd_image_tokens * it = mtmd_input_chunk_get_tokens_image(ch); - if (embd == nullptr || it == nullptr || n_tok < 1) { - std::fclose(f); - err = "the vision encoder returned nothing"; - return false; - } - // the grid from the decoder positions of the last row (strata-vision does the same) - const mtmd_decoder_pos last = mtmd_image_tokens_get_decoder_pos(it, 0, (size_t) n_tok - 1); - int32_t nx = (int32_t) last.x + 1, ny = (int32_t) last.y + 1; - if (n_tok > 1 && nx == n_tok && ny == n_tok) { - ny = 1; - } - if ((int64_t) nx * ny != n_tok) { - std::fclose(f); - err = string_format("picture %d: %d rows are not a grid (tiled encoders are not supported)", n_pictures + 1, n_tok); - return false; - } - const int32_t hdr[5] = {0x31455653, n_tok, nx, ny, vision_width}; - const size_t count = (size_t) n_tok * (size_t) vision_width; - if (std::fwrite(hdr, sizeof hdr, 1, f) != 1 || std::fwrite(embd, sizeof(float), count, f) != count) { - std::fclose(f); - err = "short write to the pictures file"; - return false; - } - ids.insert(ids.end(), (size_t) n_tok, image_pad_id); - ++n_pictures; - const double ms = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); - SRV_INF("task %d: picture %d: %d rows (%dx%d) encoded in %.0f ms on the %s\n", t.id, n_pictures, n_tok, nx, ny, ms, - p_mmproj_gpu ? "GPU" : "CPU"); - i += (size_t) n_tok; + const bool filled = fill_pictures(t, f, ids, err); + const bool closed = std::fclose(f) == 0; + if (!filled) { + return false; } - if (std::fclose(f) != 0) { + if (!closed) { err = "cannot write the pictures file"; return false; } @@ -571,6 +519,135 @@ struct strata_context_impl { return true; } + // the request's pictures file (slot.images_path, unlinked when the slot is released) + std::FILE * open_pictures_file(std::string & err) { + char name[] = "/tmp/unbiased-strata-pictures-XXXXXX"; + const int fd = ::mkstemp(name); + if (fd < 0) { + err = "cannot create the pictures file"; + return nullptr; + } + slot.images_path = name; + std::FILE * f = ::fdopen(fd, "wb"); + if (f == nullptr) { + ::close(fd); + err = "cannot open the pictures file"; + } + return f; + } + + // the ids with every picture's rows written to `f` and image_pad in their place; slot.image_keys for the GENI line + bool fill_pictures(const server_task & t, std::FILE * f, std::vector & ids, std::string & err) { + const size_t n = t.tokens.size(); + ids.reserve(n); + slot.image_keys.clear(); + for (size_t i = 0; i < n;) { + if (t.tokens[i] != LLAMA_TOKEN_NULL) { + ids.push_back(t.tokens[i]); + ++i; + continue; + } + const mtmd_input_chunk * ch = image_chunk(t, i); + if (ch == nullptr) { + err = "only pictures are supported, not audio or video"; + return false; + } + const auto rows = picture_rows(ch, t.id, (int) slot.image_keys.size() + 1, err); + if (rows == nullptr) { + return false; + } + if (!write_rows(f, *rows)) { + err = "short write to the pictures file"; + return false; + } + ids.insert(ids.end(), (size_t) rows->n_tok, image_pad_id); + slot.image_keys.push_back(strata_frontend::PictureCache::engine_key(chunk_id(ch))); + i += (size_t) rows->n_tok; + } + return true; + } + + // the image chunk at position i of the task's tokens, nullptr for anything else + static const mtmd_input_chunk * image_chunk(const server_task & t, size_t i) { + const mtmd_input_chunk * ch = nullptr; + try { + ch = t.tokens.find_chunk(i).get(); + } catch (const std::exception &) { + return nullptr; + } + if (ch == nullptr || mtmd_input_chunk_get_type(ch) != MTMD_INPUT_CHUNK_TYPE_IMAGE) { + return nullptr; + } + return ch; + } + + // mtmd names a bitmap by the SHA-256 of its bytes; the chunk carries it (empty for a placeholder) + static std::string chunk_id(const mtmd_input_chunk * ch) { + const char * id = mtmd_input_chunk_get_id(ch); + return id == nullptr ? std::string() : std::string(id); + } + + // one picture's rows: the cache's copy when the picture was seen before, else encoded now and remembered + strata_frontend::PictureCache::Rows picture_rows(const mtmd_input_chunk * ch, int task_id, int index, std::string & err) { + const std::string key = chunk_id(ch); + if (auto hit = pictures.find(key)) { + SRV_INF("task %d: picture %d: %d rows (%dx%d) from the cache\n", task_id, index, hit->n_tok, hit->nx, hit->ny); + return hit; + } + const auto t0 = std::chrono::steady_clock::now(); + strata_frontend::PictureRows rows; + if (!encode_rows(ch, index, rows, err)) { + return nullptr; + } + const double ms = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + SRV_INF("task %d: picture %d: %d rows (%dx%d) encoded in %.0f ms on the %s\n", task_id, index, rows.n_tok, rows.nx, rows.ny, ms, + p_mmproj_gpu ? "GPU" : "CPU"); + return pictures.put(key, std::move(rows)); + } + + // the projector's output for one chunk + bool encode_rows(const mtmd_input_chunk * ch, int index, strata_frontend::PictureRows & rows, std::string & err) { + const int32_t n_tok = (int32_t) mtmd_input_chunk_get_n_tokens(ch); + if (mtmd_encode_chunk(mctx, ch) != 0) { + err = "the vision encoder failed"; + return false; + } + const float * embd = mtmd_get_output_embd(mctx); + const mtmd_image_tokens * it = mtmd_input_chunk_get_tokens_image(ch); + if (embd == nullptr || it == nullptr || n_tok < 1) { + err = "the vision encoder returned nothing"; + return false; + } + if (!picture_grid(it, n_tok, rows.nx, rows.ny)) { + err = string_format("picture %d: %d rows are not a grid (tiled encoders are not supported)", index, n_tok); + return false; + } + rows.n_tok = n_tok; + rows.width = vision_width; + rows.embd.assign(embd, embd + (size_t) n_tok * (size_t) vision_width); + return true; + } + + // the grid from the decoder positions of the last row (strata-vision does the same) + static bool picture_grid(const mtmd_image_tokens * it, int32_t n_tok, int32_t & nx, int32_t & ny) { + const mtmd_decoder_pos last = mtmd_image_tokens_get_decoder_pos(it, 0, (size_t) n_tok - 1); + nx = (int32_t) last.x + 1; + ny = (int32_t) last.y + 1; + if (n_tok > 1 && nx == n_tok && ny == n_tok) { + ny = 1; + } + return (int64_t) nx * ny == n_tok; + } + + // one strata-vision record: the header, then the rows + static bool write_rows(std::FILE * f, const strata_frontend::PictureRows & r) { + const int32_t hdr[5] = {0x31455653, r.n_tok, r.nx, r.ny, r.width}; + if (std::fwrite(hdr, sizeof hdr, 1, f) != 1) { + return false; + } + return std::fwrite(r.embd.data(), sizeof(float), r.embd.size(), f) == r.embd.size(); + } + void cancel_current() { if (!slot.active() || slot.cancelled) { return; @@ -1178,6 +1255,10 @@ bool strata_context::start_engine(const common_params & params, const std::strin return impl->engine.start(engine_exe, argv, err); } +void strata_context::set_picture_cache(size_t entries, size_t bytes) { + impl->pictures.configure(entries, bytes); +} + bool strata_context::load(common_params & params, std::string & err) { auto & I = *impl; I.params = params; diff --git a/frontend/strata_context.hpp b/frontend/strata_context.hpp index 508dee6..79c250e 100644 --- a/frontend/strata_context.hpp +++ b/frontend/strata_context.hpp @@ -32,6 +32,8 @@ struct strata_context { // Loads the vocabulary and chat template from the GGUF (vocab only, no tensors) and waits for the engine's READY. bool load(common_params & params, std::string & err); + // --picture-cache: how many pictures' encoded rows are kept for the turns that resend them (0: none); before load() + void set_picture_cache(size_t entries, size_t bytes); // Blocks the calling thread running the task loop until terminate(). void start_loop(); diff --git a/frontend/tests/picture_cache_test.cpp b/frontend/tests/picture_cache_test.cpp new file mode 100644 index 0000000..c554097 --- /dev/null +++ b/frontend/tests/picture_cache_test.cpp @@ -0,0 +1,146 @@ +// UnbiasedStrata: frontend/picture_cache.hpp without a model. +// +// c++ -std=c++20 -pthread -I frontend frontend/tests/picture_cache_test.cpp -o picture_cache_test && ./picture_cache_test +// +// Cases: +// 1. a miss, then a hit that returns the same rows; the counters +// 2. least recently used goes first: a find() refreshes an entry, the entry count limit evicts the stalest +// 3. the byte limit evicts; the newest entry stays even alone over the limit +// 4. rows a caller holds outlive their eviction; a put() of a held key replaces without double counting +// 5. off (0 entries) and an empty key: put() hands the rows back and holds nothing +// 6. engine_key, hex and hex_list: mtmd's SHA-256 id becomes the engine's 64-bit key; a bad id is 0 and sends nothing +// 7. many threads putting and finding at once keep the invariants +#include "picture_cache.hpp" + +#include +#include +#include +#include + +using strata_frontend::PictureCache; +using strata_frontend::PictureRows; + +static int failures = 0; +#define CHECK(cond) do { if (!(cond)) { std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); ++failures; } } while (0) + +static PictureRows rows_of(int32_t n_tok, int32_t width, float fill) { + PictureRows r; + r.n_tok = n_tok; + r.nx = n_tok; + r.ny = 1; + r.width = width; + r.embd.assign((size_t) n_tok * (size_t) width, fill); + return r; +} + +static std::string key_of(int i) { + return "k" + std::to_string(i); +} + +int main() { + // 1. miss, hit, counters + { + PictureCache c(4, 1 << 20); + CHECK(c.enabled() && c.size() == 0 && c.bytes() == 0); + CHECK(c.find("a") == nullptr); + auto put = c.put("a", rows_of(3, 2, 1.5f)); + CHECK(put != nullptr && put->n_tok == 3 && put->embd.size() == 6 && put->embd[5] == 1.5f); + auto hit = c.find("a"); + CHECK(hit == put); + CHECK(c.size() == 1 && c.bytes() == put->bytes()); + const auto s = c.stats(); + CHECK(s.hits == 1 && s.misses == 1 && s.evictions == 0); + } + // 2. LRU order and the entry limit + { + PictureCache c(3, 1 << 20); + for (int i = 0; i < 3; ++i) c.put(key_of(i), rows_of(1, 1, (float) i)); + CHECK(c.find(key_of(0)) != nullptr); // k0 is now the most recent; k1 the stalest + c.put(key_of(3), rows_of(1, 1, 3.0f)); // over the limit: k1 goes + CHECK(c.size() == 3); + CHECK(c.find(key_of(1)) == nullptr); + CHECK(c.find(key_of(0)) != nullptr && c.find(key_of(2)) != nullptr && c.find(key_of(3)) != nullptr); + CHECK(c.stats().evictions == 1); + } + // 3. the byte limit; the newest stays + { + const size_t one = rows_of(4, 4, 0.f).bytes(); + PictureCache c(100, one * 2 + one / 2); // room for two + c.put("a", rows_of(4, 4, 0.f)); + c.put("b", rows_of(4, 4, 0.f)); + CHECK(c.size() == 2 && c.bytes() == 2 * one); + c.put("c", rows_of(4, 4, 0.f)); // a goes + CHECK(c.size() == 2 && c.find("a") == nullptr && c.find("b") != nullptr); + auto big = c.put("big", rows_of(64, 64, 0.f)); // alone over the limit: kept, everything else gone + CHECK(c.size() == 1 && c.find("big") == big && c.bytes() == big->bytes()); + CHECK(c.bytes() > c.max_bytes()); + } + // 4. a held entry outlives eviction; replacing a key + { + PictureCache c(1, 1 << 20); + auto a = c.put("a", rows_of(2, 2, 7.f)); + c.put("b", rows_of(2, 2, 8.f)); // a evicted + CHECK(c.find("a") == nullptr); + CHECK(a->embd[0] == 7.f && a.use_count() == 1); + auto b2 = c.put("b", rows_of(5, 5, 9.f)); // same key, new rows + CHECK(c.size() == 1 && c.bytes() == b2->bytes() && c.find("b") == b2); + CHECK(c.stats().evictions == 1); + } + // 5. off, and an empty key + { + PictureCache off(0, 1 << 20); + CHECK(!off.enabled()); + auto r = off.put("a", rows_of(1, 1, 0.f)); + CHECK(r != nullptr && r->n_tok == 1 && off.size() == 0 && off.find("a") == nullptr); + PictureCache on(4, 1 << 20); + auto e = on.put("", rows_of(1, 1, 0.f)); + CHECK(e != nullptr && on.size() == 0); + on.configure(0, 0); + CHECK(!on.enabled() && on.size() == 0 && on.bytes() == 0); + } + // 6. keys for the engine + { + const std::string sha = "0123456789abcdefFEDCBA98765432100123456789abcdef0123456789abcdef"; + CHECK(PictureCache::engine_key(sha) == 0x0123456789abcdefULL); + CHECK(PictureCache::engine_key("FFFFFFFFFFFFFFFF") == ~0ULL); + CHECK(PictureCache::engine_key("0123456789abcde") == 0); // 15 digits + CHECK(PictureCache::engine_key("0123456789abcdeg00") == 0); // not hex + CHECK(PictureCache::engine_key("") == 0); + CHECK(PictureCache::hex(0x0123456789abcdefULL) == "0123456789abcdef"); + CHECK(PictureCache::hex(1) == "0000000000000001"); + CHECK(PictureCache::hex_list({1, 0x10}) == "0000000000000001,0000000000000010"); + CHECK(PictureCache::hex_list({1, 0, 2}).empty()); + CHECK(PictureCache::hex_list({}).empty()); + } + // 7. threads + { + PictureCache c(8, 1 << 20); + std::vector threads; + for (int t = 0; t < 8; ++t) { + threads.emplace_back([&c, t] { + for (int i = 0; i < 500; ++i) { + const std::string k = key_of((t * 7 + i) % 20); + auto r = c.find(k); + if (r == nullptr) r = c.put(k, rows_of(1 + i % 3, 2, (float) t)); + if (r->embd.empty()) std::abort(); + } + }); + } + for (auto & th : threads) th.join(); + CHECK(c.size() <= 8 && c.size() >= 1); + const auto s = c.stats(); + CHECK(s.hits + s.misses == 8 * 500); + size_t sum = 0; + for (int i = 0; i < 20; ++i) { + if (auto r = c.find(key_of(i))) sum += r->bytes(); + } + CHECK(sum == c.bytes()); + } + + if (failures == 0) { + std::printf("picture_cache_test: all checks passed\n"); + return 0; + } + std::fprintf(stderr, "picture_cache_test: %d failure(s)\n", failures); + return 1; +}