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++
Opt-in: keep what the expert cache learned across restarts (--expert-profile-save, #477)
Niko122131da8f5dca4a
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 4efc29766..e8e68dfdb 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -350,6 +350,14 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)add_test(NAME file_expert_source_test COMMAND file_expert_source_test)set_tests_properties(file_expert_source_test PROPERTIES TIMEOUT 60)endif()+ # #477: the learned expert profile (--expert-profile-save): its order and make_profile.py's file format (CPU only)+ if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/expert_profile_save_test.cpp")+ enable_testing()+ add_executable(expert_profile_save_test tests/core/expert_profile_save_test.cpp)+ target_link_libraries(expert_profile_save_test PRIVATE strata_engine)+ add_test(NAME expert_profile_save_test COMMAND expert_profile_save_test)+ set_tests_properties(expert_profile_save_test PROPERTIES TIMEOUT 60)+ endif()if(STRATA_BUILD_TESTS AND STRATA_NATIVE_EXPERTS)# native_experts.txt v2-v4 (the real packs' copies and the per-role shard column) and the arena filled from# synthetic GGUF shards at the real expert dimensionsdiff --git a/docs/DETAILS.md b/docs/DETAILS.mdindex acc986239..3cd68ccd1 100644--- a/docs/DETAILS.md+++ b/docs/DETAILS.md@@ -404,6 +404,17 @@ the OS file cache, so loading again takes seconds while that RAM is not needed e16 GB with Q2_0 in the low-RAM mode: unloading takes ~0.3 s, and a request to an unloaded model answered after4.6 s (text) or 14.7 s (a picture, image encoder on the CPU).+**Keep what the expert cache learned across restarts (opt-in, engine 0.1.36, #477):** a start fills the GPU's expert+cache from the shipped profile, and the adaptive tier (`--adapt-every`) then moves in the experts your requests use.+With `"expert_profile_save": "expert-profile-learned.bin"` in `strata-<model>.json` the engine saves that as a+profile - the experts in VRAM first, then the routing it counted since the start, then the shipped order - on a+clean exit and every 10 minutes between requests (`"expert_profile_save_every": 5` for another interval, `0` for+exit only), written to a temporary file and renamed, so a crash never leaves half a file. The next start begins from+it instead of the config's `--expert-profile` when it is a profile of the same model (else from the config's, as+before). A relative path is in the Strata folder; one file per model, and a profile per project works the same way+(point the key at another file). The file is a fingerprint of what you used the model for: it stays on your PC.+Without the key nothing is counted or written. Setup rewrites the config when run again: add the key again then.+---## Using itdiff --git a/include/strata/core/expert_cache.hpp b/include/strata/core/expert_cache.hppindex bf3b58313..4a708355f 100644--- a/include/strata/core/expert_cache.hpp+++ b/include/strata/core/expert_cache.hpp@@ -55,6 +55,24 @@ inline constexpr int32_t kNotResident = -1;bool read_expert_profile(const std::string& path, int64_t n_layers, int64_t n_expert,std::vector<std::pair<int32_t, int32_t>>& ranked, int64_t& slots, std::string& err);+/// #477 (--expert-profile-save): what the adaptive tier learned, as a profile ranking EVERY (layer, expert) pair -+/// the experts resident in VRAM now first (where the swaps left the cache), then the rest; within each, by `heat`+/// (the routing the adaptive tier counted since the start, descending), then by `prior` (the profile the engine+/// started from: an expert this run never routed keeps its old place), then by index. A start from it begins+/// where this one ended; one with more slots adds the hottest of the rest, one with fewer keeps the hottest.+/// `resident` and `heat`: n_layers x n_expert entries (`heat` may be empty: no counts, the prior decides).+std::vector<std::pair<int32_t, int32_t>> rank_learned_profile(int64_t n_layers, int64_t n_expert,+ const std::vector<uint8_t>& resident,+ const std::vector<double>& heat,+ const std::vector<std::pair<int32_t, int32_t>>& prior);++/// #477: writes `ranked` in tools/make_profile.py's format, byte for byte: `STRP`, `1, n_layers, n_expert,+/// n_ranked, n_ranked` (uint32), the pairs (uint16 layer, uint16 expert), then the n_layers x n_expert int32 table+/// of each pair's rank (-1: not ranked). Atomically: a `<path>.tmp` beside it, renamed over `path` once complete,+/// so a reader (the next start) never sees half a file. False with `err` when it could not be written.+bool write_expert_profile(const std::string& path, int64_t n_layers, int64_t n_expert,+ const std::vector<std::pair<int32_t, int32_t>>& ranked, std::string& err);+class ExpertCache {public:ExpertCache() = default;diff --git a/serve/server.py b/serve/server.pyindex 00b55ee4b..5e36519e7 100644--- a/serve/server.py+++ b/serve/server.py@@ -34,6 +34,7 @@ import reimport selectimport signalimport socket+import structimport subprocessimport sysimport tempfile@@ -661,6 +662,44 @@ def engine_args(cfg: dict) -> list[str]:# opt-in: an auto split runs on the first card alone when it holds every profiled expert and the KVif len(gpu_list(cfg)) > 1 and cfg.get("split_skip_if_fits") and "--split-skip-if-fits" not in args:args.append("--split-skip-if-fits")+ return learned_profile_args(cfg, args)+++def profile_shape(path: str) -> tuple[int, int] | None:+ """An expert profile's (layers, experts per layer), from its header (tools/make_profile.py's format), or None+ when the file is missing, is not one or is shorter than the pairs its header promises."""+ try:+ with open(path, "rb") as f:+ head = f.read(24)+ size = os.fstat(f.fileno()).st_size+ except OSError:+ return None+ if len(head) < 24 or head[:4] != b"STRP":+ return None+ _, nl, ne, _, n = struct.unpack("<5I", head[4:])+ return (nl, ne) if size >= 24 + 4 * n else None+++def learned_profile_args(cfg: dict, args: list[str]) -> list[str]:+ """#477 (opt-in): "expert_profile_save": "<path>" in the config has the engine (0.1.36+) save what its adaptive+ tier learned there - on QUIT and every "expert_profile_save_every" minutes (10 by default, 0 = at QUIT only) -+ and the next start begins from it instead of the config's --expert-profile, when it is a profile of the same+ model (its header's layers and experts match); otherwise from the config's own, as before. A relative path is+ the engine's (the config's "cwd"). Without the key, the arguments are the config's, unchanged."""+ save = cfg.get("expert_profile_save")+ if not isinstance(save, str) or not save.strip() or "--expert-profile-save" in args:+ return args+ args = args + ["--expert-profile-save", save]+ every = cfg.get("expert_profile_save_every")+ if isinstance(every, (int, float)) and not isinstance(every, bool) and every >= 0:+ args += ["--expert-profile-save-every", str(every)]+ if "--expert-profile" in args[:-1]:+ i = args.index("--expert-profile") + 1+ here = cfg.get("cwd") or "."+ learned = profile_shape(save if os.path.isabs(save) else os.path.join(here, save))+ base = profile_shape(args[i] if os.path.isabs(args[i]) else os.path.join(here, args[i]))+ if learned is not None and learned == base:+ args[i] = savereturn argsdiff --git a/serve/test_server.py b/serve/test_server.pyindex 2000f1ae6..d746693dc 100644--- a/serve/test_server.py+++ b/serve/test_server.py@@ -19,7 +19,7 @@ from unittest import mocksys.path.insert(0, str(Path(__file__).resolve().parents[1]))from serve.frontend import ChatTemplate # noqa: E402from serve.server import (CTX_SLACK, ByteTokenizer, EngineDied, GpuBusy, MockEngine, Service, StrataEngine, # noqa: E402- prompt_tokens_seen, request_timings, serve, start_failure_hint)+ engine_args, prompt_tokens_seen, request_timings, serve, start_failure_hint)from types import SimpleNamespace # noqa: E402ROOT = Path(__file__).resolve().parents[1]@@ -801,6 +801,48 @@ class DraftCounts(unittest.TestCase):self.assertEqual((m["totals"]["drafts_offered"], m["totals"]["drafts_accepted"]), (17, 10))+class LearnedProfile(unittest.TestCase):+ """#477: "expert_profile_save" in the config: the engine saves its learned profile there, and the next start+ begins from it when it is a profile of the same model; without the key the arguments are unchanged."""++ def write(self, path, nl=48, ne=512, n=4):+ sys.path.insert(0, str(ROOT / "tools"))+ import make_profile+ old = make_profile.N_LAYER+ make_profile.N_LAYER = nl+ try:+ make_profile.write_profile(path, [(i % nl, i // nl) for i in range(n)], n_expert=ne)+ finally:+ make_profile.N_LAYER = old++ def test_without_the_key_nothing_changes(self):+ args = ["--native", "x", "--expert-profile", "data/expert-profile.bin", "--adapt-every", "4"]+ self.assertEqual(engine_args({"args": list(args)}), args)+ self.assertEqual(engine_args({"args": list(args), "expert_profile_save": ""}), args)++ def test_save_and_start_from_it(self):+ d = Path(tempfile.mkdtemp())+ self.write(d / "base.bin")+ cfg = {"args": ["--expert-profile", "base.bin"], "cwd": str(d), "expert_profile_save": "learned.bin",+ "expert_profile_save_every": 5}+ # nothing saved yet: the config's profile, and the engine is told where to save+ self.assertEqual(engine_args(cfg), ["--expert-profile", "base.bin", "--expert-profile-save", "learned.bin",+ "--expert-profile-save-every", "5"])+ self.write(d / "learned.bin")+ self.assertEqual(engine_args(cfg)[:2], ["--expert-profile", "learned.bin"])+ self.write(d / "learned.bin", ne=256) # another model's: not used+ self.assertEqual(engine_args(cfg)[:2], ["--expert-profile", "base.bin"])+ (d / "learned.bin").write_bytes(b"STRP" + bytes(20)) # not a whole profile+ self.assertEqual(engine_args(cfg)[:2], ["--expert-profile", "base.bin"])+ self.write(d / "learned.bin")+ (d / "learned.bin").write_bytes((d / "learned.bin").read_bytes()[:30]) # truncated+ self.assertEqual(engine_args(cfg)[:2], ["--expert-profile", "base.bin"])++ def test_no_profile_in_the_args(self):+ cfg = {"args": ["--native", "x"], "expert_profile_save": "learned.bin"}+ self.assertEqual(engine_args(cfg), ["--native", "x", "--expert-profile-save", "learned.bin"])++class DraftHeadHint(unittest.TestCase):"""#474: a start that stopped at "the draft head does not fit" says what to change, from this start's log lines."""diff --git a/src/core/expert_cache.cpp b/src/core/expert_cache.cppindex 3588cd5d7..dc6444367 100644--- a/src/core/expert_cache.cpp+++ b/src/core/expert_cache.cpp@@ -3,7 +3,9 @@#include <cuda_runtime.h>+#include <algorithm>#include <cstdio>+#include <filesystem>#include <utility>#include <cstring>@@ -67,6 +69,77 @@ bool read_expert_profile(const std::string& path, int64_t n_layers, int64_t n_exreturn true;}+std::vector<std::pair<int32_t, int32_t>> rank_learned_profile(int64_t n_layers, int64_t n_expert,+ const std::vector<uint8_t>& resident,+ const std::vector<double>& heat,+ const std::vector<std::pair<int32_t, int32_t>>& prior) {+ const size_t n = (size_t) (n_layers * n_expert);+ std::vector<int64_t> prior_rank(n, INT64_MAX);+ for (size_t r = 0; r < prior.size(); ++r) {+ const auto [l, e] = prior[r];+ if (l >= 0 && l < n_layers && e >= 0 && e < n_expert) {+ int64_t& pr = prior_rank[(size_t) (l * n_expert + e)];+ if (pr == INT64_MAX) pr = (int64_t) r;+ }+ }+ std::vector<int64_t> order(n);+ for (size_t i = 0; i < n; ++i) order[i] = (int64_t) i;+ auto res = [&](int64_t i) { return (size_t) i < resident.size() && resident[(size_t) i] != 0; };+ auto ht = [&](int64_t i) { return (size_t) i < heat.size() ? heat[(size_t) i] : 0.0; };+ std::stable_sort(order.begin(), order.end(), [&](int64_t a, int64_t b) {+ if (res(a) != res(b)) return res(a);+ if (ht(a) != ht(b)) return ht(a) > ht(b);+ if (prior_rank[(size_t) a] != prior_rank[(size_t) b]) return prior_rank[(size_t) a] < prior_rank[(size_t) b];+ return a < b;+ });+ std::vector<std::pair<int32_t, int32_t>> ranked(n);+ for (size_t r = 0; r < n; ++r)+ ranked[r] = {(int32_t) (order[r] / n_expert), (int32_t) (order[r] % n_expert)};+ return ranked;+}++bool write_expert_profile(const std::string& path, int64_t n_layers, int64_t n_expert,+ const std::vector<std::pair<int32_t, int32_t>>& ranked, std::string& err) {+ if (n_layers <= 0 || n_expert <= 0 || n_layers > 65535 || n_expert > 65535) {+ err = "write_expert_profile: the model's layout does not fit the format";+ return false;+ }+ std::vector<int32_t> table((size_t) (n_layers * n_expert), -1);+ std::vector<uint16_t> pairs;+ pairs.reserve(ranked.size() * 2);+ for (size_t r = 0; r < ranked.size(); ++r) {+ const auto [l, e] = ranked[r];+ if (l < 0 || l >= n_layers || e < 0 || e >= n_expert) {+ err = "write_expert_profile: a ranked pair is out of range";+ return false;+ }+ table[(size_t) (l * n_expert + e)] = (int32_t) r;+ pairs.push_back((uint16_t) l);+ pairs.push_back((uint16_t) e);+ }+ const uint32_t hdr[5] = {1u, (uint32_t) n_layers, (uint32_t) n_expert, (uint32_t) ranked.size(),+ (uint32_t) ranked.size()};+ const std::string tmp = path + ".tmp";+ std::FILE* f = std::fopen(tmp.c_str(), "wb");+ if (f == nullptr) {+ err = "write_expert_profile: cannot create " + tmp;+ return false;+ }+ // the format is little-endian (make_profile.py's "<"): so is every machine this engine runs on+ bool ok = std::fwrite("STRP", 1, 4, f) == 4 && std::fwrite(hdr, 4, 5, f) == 5 &&+ (pairs.empty() || std::fwrite(pairs.data(), 2, pairs.size(), f) == pairs.size()) &&+ std::fwrite(table.data(), 4, table.size(), f) == table.size();+ ok = (std::fclose(f) == 0) && ok;+ std::error_code ec;+ if (ok) std::filesystem::rename(tmp, path, ec); // replaces an existing file (MoveFileEx / rename(2))+ if (!ok || ec) {+ std::filesystem::remove(tmp, ec);+ err = "write_expert_profile: cannot write " + path;+ return false;+ }+ return true;+}+ExpertCache::~ExpertCache() { close(); }#if defined(STRATA_USE_HIP)diff --git a/src/program/generate.cpp b/src/program/generate.cppindex 60b07ca4a..c447dd767 100644--- a/src/program/generate.cpp+++ b/src/program/generate.cpp@@ -303,6 +303,11 @@ struct Options {/// trace is what the plan's `h = 0.6447` refers to, and compulsory-miss measured 0.4864 because it fills/// with whatever the prompt touched FIRST. Empty means no profile.std::string expert_profile;+ /// #477 (--serve, opt-in): where to save what the adaptive tier learned, as a profile `--expert-profile` reads+ /// (the resident experts first, then the routing counted since the start); on QUIT and every+ /// `expert_profile_save_min` minutes between requests. Empty (the default): nothing is counted or written.+ std::string expert_profile_save;+ double expert_profile_save_min = 10.0;/// R4.2d: **ON by default**, because the measurement is unambiguous and the alternative is known-broken./// Without it, 17 of 10,562 layers had the hit work done when the pool returned; with it, 9,190. The/// A/B arm is `--no-hit-poke`.@@ -530,6 +535,10 @@ void usage() {" real graph that --stage-timing cannot give. Prints and exits.\n"" --expert-profile P R4.2e: pre-load the VRAM tier from a `profile.bin` (see\n"" tools/make_profile.py) instead of admitting on first use.\n"+ " --expert-profile-save P --serve, #477: save what the adaptive tier learned (the experts in\n"+ " VRAM, then the routing counted since the start) as a profile at P, on\n"+ " QUIT and every --expert-profile-save-every MIN minutes (default 10;\n"+ " 0 = on QUIT only) between requests; start from it with --expert-profile P\n"" --no-hit-poke R4.2d's A/B arm. The hit path pokes the driver once right after its\n"" launch so the GPU starts while the CPU pool runs; without it the work\n"" waits for the next driver entry and does not overlap at all.\n"@@ -1210,6 +1219,9 @@ int main(int argc, char** argv) {else if (a == "--expert-cache-per-layer") o.expert_cache_per_layer = true;else if (a == "--no-hit-poke") o.no_hit_poke = true;else if (a == "--expert-profile") o.expert_profile = next("--expert-profile");+ else if (a == "--expert-profile-save") o.expert_profile_save = next("--expert-profile-save");+ else if (a == "--expert-profile-save-every")+ o.expert_profile_save_min = std::atof(next("--expert-profile-save-every"));else if (a == "--gpu-stages") o.gpu_stages = true;else if (a == "--mmap-experts") o.mmap_experts = true;else if (a == "--shared-expert-arena") o.shared_expert_arena = next("--shared-expert-arena");@@ -2258,6 +2270,10 @@ int main(int argc, char** argv) {std::fprintf(stderr, "strata generate: profile %s: %zu ranked pairs, built for %lld slots\n",o.expert_profile.c_str(), profile.size(), (long long) pslots);}+ // #477: the whole ranking as loaded, the prior of --expert-profile-save's order (a layer split keeps only+ // CUDA0's pairs in `profile` below). Empty without --expert-profile-save.+ std::vector<std::pair<int32_t, int32_t>> profile_loaded;+ if (!o.expert_profile_save.empty()) profile_loaded = profile;// ---- layer split across GPUs: "auto" places the split points by a cost model of one decode window, measured on// the 5080 + 3090 rig (bench/results/2026-09-29-layer-split):// - every layer costs its GPU a time inversely proportional to SMs x clock (0.33 ms on an RTX 5080, 0.50 on a@@ -4490,6 +4506,17 @@ int main(int argc, char** argv) {drive.d.plan = ver.plan_sink();drive.d.pcie_num = std::max(0, std::min(256, (int) (o.pcie_frac * 256.0 + 0.5)));if (o.adapt_every > 0 && o.adapt_swaps > 0) drive.d.usage.assign((size_t) (g.n_layers * g.n_expert), 0.0f);+ // #477 --expert-profile-save: what the adaptive tier learned, kept across restarts (opt-in; off: `heat` stays+ // empty and nothing below runs). It needs the adaptive tier's counts and the residency table.+ std::vector<double> heat;+ if (!o.expert_profile_save.empty()) {+ if (drive.d.usage.empty() || host_res.empty())+ std::fprintf(stderr, "strata serve: --expert-profile-save needs the adaptive tier (--adapt-every and "+ "--adapt-swaps above 0) and --expert-profile: nothing will be saved\n");+ else+ heat.assign(drive.d.usage.size(), 0.0);+ }+ Clock::time_point profile_saved_at = Clock::now();cudaStream_t adapt_stream = nullptr;if (cudaStreamCreateWithFlags(&adapt_stream, cudaStreamNonBlocking) != cudaSuccess) {std::fprintf(stderr, "strata serve: cannot create the refill stream\n");@@ -4576,9 +4603,29 @@ int main(int argc, char** argv) {const strata::core::OnDevice on(st->dev);cudaEventRecord(st->adapt_ev, st->adapt_stream);}+ // #477: the routing counted since the start (each count adds up to 1 / (1 - 0.7) over its decays: the+ // sum is proportional to the routing itself) - only with --expert-profile-save, else `heat` is empty+ for (size_t i = 0; i < heat.size(); ++i) heat[i] += (double) drive.d.usage[i];for (float& v : drive.d.usage) v *= 0.7f;return true;};+ // #477: write the learned profile (between requests and at QUIT: a prompt's lent slots are back by then).+ // A swap still in flight counts as done - its expert is resident once the copy lands. `why`: for the log.+ auto save_profile = [&](const char* why) {+ if (heat.empty()) return;+ std::vector<uint8_t> resident(host_res.size(), 0);+ for (size_t i = 0; i < host_res.size(); ++i) resident[i] = host_res[i] >= 0;+ for (const auto& p : pending) resident[(size_t) p.first] = 1;+ std::string e;+ const auto ranked = strata::core::rank_learned_profile(g.n_layers, g.n_expert, resident, heat,+ profile_loaded);+ if (strata::core::write_expert_profile(o.expert_profile_save, g.n_layers, g.n_expert, ranked, e))+ std::fprintf(stderr, "strata serve: expert profile saved to %s (%s)\n", o.expert_profile_save.c_str(),+ why);+ else+ std::fprintf(stderr, "strata serve: the expert profile was not saved: %s\n", e.c_str());+ profile_saved_at = Clock::now();+ };// stdin is read on its own thread, so a STOP line reaches a request that is still running (the client went// away, or pressed Esc): the flag is checked between prompt chunks and between verify windows.std::atomic<bool> stop_req{false};@@ -4741,6 +4788,10 @@ int main(int argc, char** argv) {std::vector<float> img_rows;std::vector<const float*> row_ptr;while (next_line(line)) {+ // #477: every --expert-profile-save-every minutes, before the next request (at QUIT: after the loop)+ if (!heat.empty() && line != "QUIT" && o.expert_profile_save_min > 0 &&+ Clock::now() - profile_saved_at >= std::chrono::duration<double>(o.expert_profile_save_min * 60.0))+ save_profile("periodic");if (line == "QUIT") break;// the watchdog watches a request from here until this iteration ends, whichever way it endsstruct BusyScope {@@ -5719,6 +5770,7 @@ int main(int argc, char** argv) {remote_experts[(size_t) r].ms_begin() - begin_before[(size_t) r],remote_experts[(size_t) r].ms_wait() - wait_before[(size_t) r]);}+ save_profile("exit"); // #477: QUIT, or the server closed stdinreturn 0;}diff --git a/tests/core/expert_profile_save_test.cpp b/tests/core/expert_profile_save_test.cppnew file mode 100644index 000000000..6b6107026--- /dev/null+++ b/tests/core/expert_profile_save_test.cpp@@ -0,0 +1,80 @@+// #477: --expert-profile-save's profile - rank_learned_profile's order (resident first, then the counted routing, then+// the profile the engine started from) and write_expert_profile's file, byte for byte tools/make_profile.py's format,+// read back by read_expert_profile. CPU only: no device is touched.+#include "strata/core/expert_cache.hpp"++#include <cstdio>+#include <cstring>+#include <filesystem>+#include <string>+#include <utility>+#include <vector>++namespace {+int fails = 0;+void check(bool ok, const char* what) {+ if (!ok) {+ std::fprintf(stderr, "FAIL: %s\n", what);+ ++fails;+ }+}+} // namespace++int main() {+ using Pair = std::pair<int32_t, int32_t>;+ const int64_t L = 3, E = 4; // 12 pairs, index = layer * 4 + expert+ std::vector<uint8_t> resident(12, 0);+ resident[5] = 1; // (1, 1)+ resident[2] = 1; // (0, 2)+ std::vector<double> heat(12, 0.0);+ heat[2] = 1.0;+ heat[5] = 7.0;+ heat[11] = 9.0; // (2, 3): the hottest, but not resident+ heat[0] = 3.0;+ const std::vector<Pair> prior = {{2, 0}, {1, 3}, {0, 1}}; // a profile that ranks three pairs+ const std::vector<Pair> r = strata::core::rank_learned_profile(L, E, resident, heat, prior);+ check(r.size() == 12, "every pair is ranked");+ const std::vector<Pair> head = {{1, 1}, {0, 2}, {2, 3}, {0, 0}, {2, 0}, {1, 3}, {0, 1}, {0, 3}};+ for (size_t i = 0; i < head.size() && i < r.size(); ++i)+ check(r[i] == head[i], "resident by heat, then the rest by heat, then the prior, then the index");+ // no counts at all: the resident ones, then the prior's order+ const std::vector<Pair> r0 = strata::core::rank_learned_profile(L, E, resident, {}, prior);+ check(r0.size() == 12 && r0[0] == Pair(0, 2) && r0[1] == Pair(1, 1) && r0[2] == Pair(2, 0) &&+ r0[3] == Pair(1, 3) && r0[4] == Pair(0, 1) && r0[5] == Pair(0, 0), "without heat: resident, then prior");++ const std::filesystem::path dir = std::filesystem::temp_directory_path() / "strata_profile_save_test";+ std::filesystem::create_directories(dir);+ const std::string path = (dir / "learned.bin").string();+ std::string err;+ check(strata::core::write_expert_profile(path, L, E, r, err), "written");+ check(!std::filesystem::exists(path + ".tmp"), "no temporary file left");+ // the bytes make_profile.write_profile would write for the same ranking+ std::vector<uint8_t> want(4);+ std::memcpy(want.data(), "STRP", 4);+ auto u32 = [&](uint32_t v) { for (int b = 0; b < 4; ++b) want.push_back((uint8_t) (v >> (8 * b))); };+ auto u16 = [&](uint32_t v) { want.push_back((uint8_t) v); want.push_back((uint8_t) (v >> 8)); };+ for (uint32_t v : {1u, 3u, 4u, 12u, 12u}) u32(v);+ for (const Pair& p : r) { u16((uint32_t) p.first); u16((uint32_t) p.second); }+ std::vector<int32_t> table(12, -1);+ for (size_t i = 0; i < r.size(); ++i) table[(size_t) (r[i].first * E + r[i].second)] = (int32_t) i;+ for (int32_t v : table) u32((uint32_t) v);+ std::vector<uint8_t> got(want.size() + 1);+ if (std::FILE* f = std::fopen(path.c_str(), "rb")) {+ got.resize(std::fread(got.data(), 1, got.size(), f));+ std::fclose(f);+ }+ check(got == want, "the file is make_profile.py's format, byte for byte");+ std::vector<Pair> back;+ int64_t slots = 0;+ check(strata::core::read_expert_profile(path, L, E, back, slots, err) && back == r && slots == 12,+ "read back by the loader");+ // a second save replaces the first (the rename over an existing file)+ check(strata::core::write_expert_profile(path, L, E, r0, err), "written again");+ check(strata::core::read_expert_profile(path, L, E, back, slots, err) && back == r0, "replaced");+ check(!strata::core::write_expert_profile(path, L, E, {{3, 0}}, err), "a pair out of range is refused");+ check(strata::core::read_expert_profile(path, L, E, back, slots, err) && back == r0,+ "a refused save keeps the file");+ std::filesystem::remove_all(dir);+ if (fails == 0) std::puts("expert_profile_save_test: OK");+ return fails == 0 ? 0 : 1;+}