From 991203f2a9460465f27c703896295eaa51218d65 Mon Sep 17 00:00:00 2001 From: Jeremiah Ritchey <44681828+jeremiahritchey@users.noreply.github.com> Date: Tue, 29 Sep 2026 18:40:24 +0000 Subject: [PATCH 01/22] Integrate validated conversation snapshot core with upstream 0.1.25 --- CMakeLists.txt | 33 ++- docs/DETAILS.md | 32 ++- docs/plans/multi-conversation-cache.md | 240 +++++++++++++++++ docs/plans/shared-conversation-snapshots.md | 147 ++++++++++ docs/plans/shared-conversation-validation.md | 135 ++++++++++ include/strata/core/conversation_cache.hpp | 146 ++++++++++ include/strata/core/conversation_memory.hpp | 19 ++ include/strata/core/conversation_snapshot.hpp | 55 ++++ src/core/conversation_cache_test.cpp | 92 +++++++ src/core/conversation_checked.hpp | 24 ++ src/core/conversation_memory.cpp | 51 ++++ src/core/conversation_memory_test.cpp | 49 ++++ src/core/conversation_snapshot.cpp | 190 +++++++++++++ src/core/conversation_snapshot_test.cpp | 232 ++++++++++++++++ src/core/conversation_state.cpp | 250 ++++++++++++++++++ src/core/conversation_validation_test.cpp | 182 +++++++++++++ src/program/generate.cpp | 216 ++++++++++----- tools/conversation_cache_http_smoke.py | 137 ++++++++++ tools/conversation_cache_isolation.py | 156 +++++++++++ tools/conversation_cache_parity.py | 219 +++++++++++++++ tools/conversation_cache_soak.py | 176 ++++++++++++ tools/test_conversation_cache_http_smoke.py | 71 +++++ tools/test_conversation_cache_isolation.py | 82 ++++++ tools/test_conversation_cache_parity.py | 154 +++++++++++ tools/test_conversation_cache_soak.py | 73 +++++ 25 files changed, 3089 insertions(+), 72 deletions(-) create mode 100644 docs/plans/multi-conversation-cache.md create mode 100644 docs/plans/shared-conversation-snapshots.md create mode 100644 docs/plans/shared-conversation-validation.md create mode 100644 include/strata/core/conversation_cache.hpp create mode 100644 include/strata/core/conversation_memory.hpp create mode 100644 include/strata/core/conversation_snapshot.hpp create mode 100644 src/core/conversation_cache_test.cpp create mode 100644 src/core/conversation_checked.hpp create mode 100644 src/core/conversation_memory.cpp create mode 100644 src/core/conversation_memory_test.cpp create mode 100644 src/core/conversation_snapshot.cpp create mode 100644 src/core/conversation_snapshot_test.cpp create mode 100644 src/core/conversation_state.cpp create mode 100644 src/core/conversation_validation_test.cpp create mode 100644 tools/conversation_cache_http_smoke.py create mode 100644 tools/conversation_cache_isolation.py create mode 100644 tools/conversation_cache_parity.py create mode 100644 tools/conversation_cache_soak.py create mode 100644 tools/test_conversation_cache_http_smoke.py create mode 100644 tools/test_conversation_cache_isolation.py create mode 100644 tools/test_conversation_cache_parity.py create mode 100644 tools/test_conversation_cache_soak.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 10cdc871..9f05042a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -50,8 +50,19 @@ if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/tests/CMakeLists.txt AND EXISTS ${CMAKE_CU set(_strata_tests_default ON) endif() option(STRATA_BUILD_TESTS "Build the test suite" ${_strata_tests_default}) +option(STRATA_BUILD_CONVERSATION_TESTS "Build standalone conversation cache tests" OFF) option(STRATA_WERROR "Treat compiler warnings as errors" OFF) +if(STRATA_BUILD_CONVERSATION_TESTS) + enable_testing() + add_executable(conversation_cache_test src/core/conversation_cache_test.cpp) + target_include_directories(conversation_cache_test PRIVATE include) + add_test(NAME conversation_cache_test COMMAND conversation_cache_test) + add_executable(conversation_memory_test src/core/conversation_memory_test.cpp src/core/conversation_memory.cpp) + target_include_directories(conversation_memory_test PRIVATE include) + add_test(NAME conversation_memory_test COMMAND conversation_memory_test) +endif() + if(STRATA_ENABLE_CUDA) enable_language(CUDA) # `enable_language(CUDA)` gives the .cu compile rules but NOT the imported targets, so `CUDA::cudart` has to @@ -294,7 +305,8 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) # library is the honest shape of the dependency graph: core knows about devices and weights, kernels know # about arithmetic, and this one knows the ORDER the arithmetic happens in. add_library(strata_engine STATIC src/core/layer.cpp src/core/session.cpp src/core/expert_source.cpp src/core/remote_experts.cpp - src/core/expert_cache.cpp src/core/native_head.cpp src/core/native_dense.cpp src/core/verify.cpp src/core/mtp.cpp) + src/core/expert_cache.cpp src/core/native_head.cpp src/core/native_dense.cpp src/core/verify.cpp src/core/mtp.cpp + src/core/conversation_snapshot.cpp src/core/conversation_state.cpp src/core/conversation_memory.cpp) target_include_directories(strata_engine PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) target_link_libraries(strata_engine PUBLIC strata_core strata_kernels strata_kernels_cpu ${_strata_gpu_runtime_target}) if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/file_expert_source_test.cpp") @@ -304,6 +316,25 @@ 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() + if(STRATA_BUILD_CONVERSATION_TESTS) + add_executable(conversation_snapshot_test src/core/conversation_snapshot_test.cpp) + target_link_libraries(conversation_snapshot_test PRIVATE strata_engine) + add_test(NAME conversation_snapshot_test COMMAND conversation_snapshot_test) + set_tests_properties(conversation_snapshot_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + add_executable(conversation_validation_test src/core/conversation_validation_test.cpp) + target_link_libraries(conversation_validation_test PRIVATE strata_engine) + add_test(NAME conversation_validation_test COMMAND conversation_validation_test) + set_tests_properties(conversation_validation_test PROPERTIES ENVIRONMENT "CUDA_VISIBLE_DEVICES=-1" TIMEOUT 120) + if(NOT STRATA_ENABLE_HIP AND UNIX AND NOT APPLE AND CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") + add_executable(conversation_transfer_test src/core/conversation_validation_test.cpp) + target_compile_definitions(conversation_transfer_test PRIVATE CONVERSATION_TEST_TRANSFERS) + target_link_options(conversation_transfer_test PRIVATE + -Wl,--wrap=cudaMemcpy -Wl,--wrap=cudaDeviceSynchronize -Wl,--wrap=cudaGetLastError) + target_link_libraries(conversation_transfer_test PRIVATE strata_engine) + add_test(NAME conversation_transfer_test COMMAND conversation_transfer_test) + set_tests_properties(conversation_transfer_test PROPERTIES ENVIRONMENT "CUDA_VISIBLE_DEVICES=-1" TIMEOUT 120) + endif() + endif() # `strata generate` (P2.S6). The FIRST user-facing program: everything under it is a component, and this is # what composes them into a token. No tokenizer - the prompt arrives as ids - because Gate C1 compares logits diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 1217072e..d8a7765d 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -371,9 +371,35 @@ prompt when that is 2,048 tokens or more (engine 0.1.20; PR #62 + #65), so that system prompts and tool lists. Engine options: `--prompt-cache N` (0 = off), `--prompt-cache-every N`, `--prompt-cache-root N` (0 = no system-prompt checkpoint), `--turn-token ID`. -**Current limits (v1):** one request at a time, and one conversation's history in the KV cache at a time (switching -between two chats re-reads the part where they diverge; the shared prefix, such as the system prompt, is reused); images -only when set up with them (below); no video. **Temperature / top_p / top_k / min_p / +**Multiple conversations (opt-in).** Add `--conversation-cache-mib 8192 +--conversation-cache-slots 4` to the engine arguments to park up to four conversations +in a bounded 8 GiB host-RAM cache. This preserves controller/worker histories when +their requests alternate; it does not execute requests concurrently. No client session +ID is required: only exact token/image prefixes with matching steering mode are reused. +The default budget is 0 (disabled); `--prompt-cache 0` also disables parking. + +Snapshots contain running state, checkpoints, used K/V pages, and draft-layer K/V. +They add host RAM, not another model or VRAM allocation. The byte budget also counts +an incoming snapshot during a switch; oldest parked entries are evicted first. +Oversized snapshots or host allocation failures fall back to ordinary prompt processing. +`--conversation-cache-min-free-mib N` (default 2560) additionally requires that +physical-RAM headroom remain available: the engine checks before allocation and +again after capture. Unknown telemetry or insufficient RAM skips parking. Windows +uses `GlobalMemoryStatusEx`, Linux uses `MemAvailable`; these are host-level samples, +not a reservation or enforcement of container/job memory limits. An 8 GiB budget +is a cap, not a recommendation for every machine. + +The shared snapshot core validates all layers and checkpoints before applying any +state. Invalid entries are discarded; transfer/synchronization failure is fatal +rather than permission to continue with partial state. Indexer spare keys and the +moving spare row are preserved, including checkpoint rewinds. These development +changes and the optional disk-tier boundary are described in the +[shared-core proposal](plans/shared-conversation-snapshots.md). +The engine log reports parking, restoration, bytes and evictions. Snapshots are not +persisted across restarts. See [the design and validation gates](plans/multi-conversation-cache.md). + +**Current limits (v1):** one request at a time, and one conversation cached at a time (switching between two chats +re-reads the other one unless the opt-in cache above is enabled); images only when set up with them (below); no video. **Temperature / top_p / top_k / min_p / seed** are honored per request (OpenAI and Anthropic fields); with the default adaptive expert tier a sampled result is not reproducible run to run - for seed-reproducible output add `--adapt-every 100000` (static residency) to the engine arguments. The run config's optional `sampling` block sets the defaults for requests that leave the fields out diff --git a/docs/plans/multi-conversation-cache.md b/docs/plans/multi-conversation-cache.md new file mode 100644 index 00000000..0a2cb070 --- /dev/null +++ b/docs/plans/multi-conversation-cache.md @@ -0,0 +1,240 @@ +# Multi-conversation caching + +## Objective and evidence + +Keep Pi controller and worker conversations warm when their requests interleave, +without requiring a Pi-specific session ID or changing the generated prompt. +The existing server caches one conversation. Observed controller requests reread +46,856, 46,974, and 47,644 tokens after worker requests, spending 143 seconds in +prompt processing. A subsequent packet capture verified 21 continuing turns with +unchanged history and reasoning: do not modify Pi's reasoning serialization. + +This feature does not shorten tool results or fix the separate, unproven cause of +one historical within-conversation 12,038-token replay. + +## Design + +- Opt-in engine flags: `--conversation-cache-mib N` (default 0/off) and + `--conversation-cache-slots N` (default 4 parked conversations). +- Keep existing single-conversation behavior and fast-path cost when disabled. +- Search the active state and parked states for the longest exact token prefix. + Images and control-vector mode must also match. Prefer active state on ties. +- Before overwriting an eligible active state, snapshot its running state, + checkpoints, main-layer K/V, completed indexer rows, and draft-layer K/V. +- Park in ordinary host RAM, not additional VRAM. Preserve graph-bound addresses + by copying back into existing allocations. Streamed K/V snapshots use the + authoritative host pools; restore invalidates main-layer residency maps and + refills the draft ring before reuse. +- Save only used pages, not the full maximum context allocation. Full pages + preserve the page/head/cell layout, including partially filled final pages. +- Evict least-recently-active parked entries to satisfy slot and byte limits. + Count an incoming restore image against the byte budget during an exchange. + An oversized snapshot or allocation failure skips parking, not inference. +- Cache misses retain normal prompt processing; image or steering changes cannot + reuse incompatible state. No persistence to disk and no raw conversation logs. +- Keep checkpoint fallback available inside each parked conversation. + +The budget covers snapshot payload allocations, including retained checkpoint +buffers. It is additional to the active engine's normal state/checkpoint memory; +allocator bookkeeping and small container overhead are not exact RSS accounting. + +## Correctness gates + +1. CPU policy tests: A/B/A reuse, checkpoint fallback, image identity, steering + isolation, longest prefix and ties, byte/slot eviction, oversized entries, + disabled cache, short/equal prompts, and in-flight restore accounting. +2. Snapshot tests: byte-exact save/restore across FP16, INT8 and Q4 K/V, resident + and streamed layouts, draft rings, partial pages, and indexer boundaries. +3. Full engine builds; disabled option retains existing behavior. +4. Controlled A/B/A serving parity versus an uninterrupted A baseline, including + returning through a checkpoint, with fixed expert residency and deterministic + sampling. Verify restore tokens and compare running/KV state hashes. +5. Measure long-context switching time and memory bounds; test budget eviction + and cancellation. Do not claim end-to-end speedups from component tests. + +## Operational constraints + +Full-model tests load private engines and require an available GPU. Run them in +a maintenance window or on separate hardware; do not load a second model beside +a production engine unless there is sufficient GPU and host memory. + +## Status + +This document's historical results describe the original prototype and its +0.1.15 integration. The separate 0.1.18 development branch now has a +[shared-core proposal and acceptance checklist](shared-conversation-snapshots.md). +Its audit found that the original snapshots/fingerprints omitted `idx_dead` and +the moving indexer spare row; the new core preserves these and the new harnesses +require the expanded fingerprint. Earlier parity results remain valid only for +the fields and fixtures actually measured, not those previously omitted fields. + +Feature implemented; all five correctness gates above have passing evidence for +the original feature revision `9d154ed`, before the upstream integration below. +Verified on 2026-09-28: + +- Full CUDA 13.4 / SM89 portable-AVX2 engine build and help smoke test pass. +- CPU policy: 35 checks pass, also under AddressSanitizer/UBSan. +- GPU snapshots: 891 checks pass across FP16/INT8/Q4, resident/streamed/ring + storage, zero/full/partial pages, indexer boundaries, malformed payloads, and + incompatible geometry, and invalid/overflowing extents. GPU fixtures are small + and do not load a model. +- All 17 existing Python server tests pass using mock engines. +- 12 CLI parsing checks pass; new C++ modules pass `-Wall -Wextra -Werror`. +- Seventeen harness unit tests pass normally and under Python `-O`, including + rejection of incomplete evidence, native-IQ window configuration, byte-pressure + evidence validation, offline HTTP orchestration, and no-traffic dry-run checks. + +Full-model IQ3_S gates passed in an isolated test window, using a 262144-token +context, INT8 K/V with 32768 +resident cells, and the same 8000 expert slots in each paired run: + +- Single-token decoding: A/B/A and parked-checkpoint recovery reproduce both + output tokens and byte-exact main-model state fingerprints. +- Speculative decoding (`--spec 4`, suffix drafting off, fixed expert residency): + the same checks pass with 49909-token A and 49911-token B. Main-model state + fingerprints also match, although this gate only requires output parity. +- Initial A prompt read: 48.809 seconds. Returning to A after B: 49909 tokens + reused, 22 new tokens read, 1.961 seconds of prompt processing including + parking/restoring. This is a synthetic switching result, not a general decode + speedup or a matched uncached A/B/A replay benchmark. +- Returning through A's checkpoint: 49924 tokens reused, 7 read, 1.101 seconds. + Parking A used 1352930652 bytes; parking the continued A used 1471553864 bytes. + Restoring a parked state took 182–201 ms in this long-context run. +- HTTP checks on the candidate with normal production speculative/adaptive + settings: A/B/A returns the same text, reusing 1957 of 1964 prompt tokens. + Five intervening distinct conversations evict A; requesting it again reads + from zero. Logs show four parked slots and increasing eviction counts. +- HTTP streaming disconnect after five output tokens: the engine stays alive, + serves an unrelated B, then restores 1054 of the cancelled A's 1061 tokens. + The frontend and engine remained running without a restart throughout these checks. +- Byte pressure: a 400 MiB cache holds each ~254 MiB snapshot individually, but + not two. A/B/C/A produced two byte-driven evictions with only one parked slot + occupied. Output and main-model state match the cache-disabled sequence. +- Oversized snapshots: with a 1 MiB budget, all three attempted parks are skipped; + ordinary inference continues with output and state matching the baseline. +- In-flight budget: A/B/A and checkpoint recovery also pass at 400 MiB. Two + outgoing parks are skipped while the incoming snapshot is held, preserving the + restore and keeping allocated parked/transfer payload within the budget. +- Image isolation: real `GENI` requests with synthetic embeddings reject reuse + when embedding values or image-grid geometry change. Returning to the original + image restores 773 of 780 tokens with exact output/main-model state parity. +- Steering isolation: nonzero synthetic control vectors in both add and project + modes change actual model state. Switching on/off never reuses incompatible + state; returning to each mode restores 766 of 773 tokens with exact output and + main-model state parity. These are cache tests, not steering-quality tests. +- The packaged HTTP smoke test also passes against the restored service: + A/B/A, four-slot eviction, disconnect cancellation and cached recovery. Engine + and frontend remained running without a restart throughout that test. + +Raw synthetic test evidence is retained locally in the ignored +`logs/conversation-validation-2026-09-28/`: `spec1-supported`, `spec4-long`, +`pressure`, `oversized`, `exchange`, `image`, `steering-add`, and `steering-project` +(each contains engine logs and `results.json`), plus `http-smoke.json` for the +packaged HTTP check. +The original `spec1` attempt failed at startup because native IQ packs require +engine `--spec >= 2`; the harness now uses the supported configuration below. + +`tools/conversation_cache_parity.py` prepares the controlled runtime gate. It +defaults to a dry run and requires `--run` to launch private model processes. +Provide `--config`, `--engine`, and a new `--output` directory. Run first with +`--spec 1` for byte-exact main-model state, then `--spec 4` for speculative output +parity. The single-token gate configures engine `--spec 2 --mtp-max-t 1` because +native IQ packs require a speculative-capable engine even with one-token decode +windows. It compares an uninterrupted A/A+ baseline against A/B/A+, then exercises +a parked checkpoint by switching away and repeating A+. It never connects to an +existing HTTP server. Use only in a separately authorized GPU test window. + +The image tests exercise the serving engine's embedding-input and M-RoPE paths, +not a vision encoder or image-recognition quality. The live Pi configuration +remains text-only with no control vector loaded. + +### Reproducible checks + +The parity script now accepts `--scenario pressure` and `--scenario oversized`. +Both run A/B/C/A with one output token per request, compare against the same +cache-disabled sequence, and require output and main-model state parity. For +this IQ3_S model at the default 128 paragraphs, use `--cache-mib 400` for byte +pressure (one snapshot fits, two do not) and `--cache-mib 1` for oversized skips. +The byte-pressure gate rejects slot-limit eviction as insufficient evidence; +the oversized gate requires all three attempted parks to be skipped. Both gates +passed in the full-model test window. + +`--scenario exchange --cache-mib 400` instead runs the A/B/A continuation and +checkpoint sequence while requiring two outgoing parks to be skipped because an +incoming snapshot is still held. This specifically tests the temporary byte +budget during restoration, in addition to ordinary byte-driven eviction. This +gate also passed. + +`tools/conversation_cache_isolation.py` takes the same `--config`, `--engine`, +`--output`, and explicit `--run` arguments. Run `--scenario image`, `--scenario add`, +and `--scenario project` in separate new output directories. All three gates +passed. They generate small deterministic embedding/control-vector fixtures and +load baseline/candidate engines sequentially. Do not run any model gate beside +the production engine unless sufficient GPU capacity is separately available. + +For standalone component tests, configure with +`-DSTRATA_BUILD_CONVERSATION_TESTS=ON`; build `conversation_cache_test` and, with +CUDA enabled, `conversation_snapshot_test`. Run: + +```sh +ctest --test-dir build-conversations -R '^conversation_(cache|snapshot)_test$' --output-on-failure +python -m unittest tools.test_conversation_cache_parity tools.test_conversation_cache_isolation tools.test_conversation_cache_http_smoke +``` + +`tools/conversation_cache_http_smoke.py --output NEW_RESULTS.json` defaults to +no traffic. Adding `--run` targets `http://127.0.0.1:11434` (override with `--url`) +and exercises A/B/A, slot eviction, streaming cancellation, and recovery. Use +only with an exclusive idle test endpoint: it intentionally displaces cached +conversations. An idle check cannot lock out new clients, so pause other clients +first. Both the one-off sequence and the packaged script have passed against the +real cache-enabled HTTP server. + +### Upstream integration (2026-09-28) + +Merged upstream `main` at `d551edf` (engine 0.1.15). The serving INFO-line +conflict was resolved by retaining both engine-version reporting and the +conversation-cache settings. Upstream prefill/MMQ and AVX2 changes are retained. + +The merged tree passes a separate CUDA 13.4 / SM89 portable-AVX2 engine build, +35 CPU cache-policy checks, 891 GPU snapshot checks, 12 CLI parsing/help checks, +and 35 Python tests (17 cache-harness tests and 18 server tests). + +The merge itself did not restart or reconfigure the running engine. In a +subsequently authorized maintenance window, all eight full-model gates passed +on merged revision `eb6a392`: single-token reuse/checkpoint state parity, long +speculative reuse/checkpoint parity, byte-pressure eviction, oversized snapshots, +incoming/outgoing exchange budgeting, image identity, and control-vector +isolation in add/project modes. The 12-request HTTP smoke test also passed on +an exclusive localhost endpoint with normal adaptive settings, including slot +eviction, streaming cancellation, and cached recovery without a process restart. + +The merged long-context test used 51133-token A and 51135-token B, fixed 8700 +expert slots, INT8 KV with 32768 resident cells, spec 4, and suffix drafting off. +Initial A read took 46.558 seconds. Returning after B reused 51133 tokens and +read 22 in 1.363 seconds including parking/restoring; checkpoint recovery reused +51148 tokens and read 7 in 0.580 seconds. Both restored outputs and main-model +state fingerprints match the uninterrupted baseline. This synthetic switch test +is not a matched performance comparison against the original feature binary. + +Evidence is retained locally under the ignored +`logs/upstream-merge-validation-20260928-F1emt1/` directory, including paired +engine logs/results and `http-smoke.json`. The earlier measurements above remain +specific to the original feature revision. + +## Deployment and rollback + +The original Pi trial used an 8192 MiB host-RAM budget and four parked slots, with +the existing text-only model configuration otherwise unchanged. HTTP health +and generation checks pass; image/steering tests ran in separate private engines. + +After the upstream-integration gates passed, the merged engine was deployed +with the same 8192 MiB/four-slot cache settings. The normal launch configuration +selects the merged binary; the prior binary and configuration are preserved for +rollback. Final HTTP generation and idle/empty-queue health checks passed. + +To try this feature, preserve the original binary and configuration, then add +the two opt-in flags to the engine arguments and restart in a maintenance window. +To disable parking, remove the flags or set `--conversation-cache-mib 0` and +restart. To roll back the binary, gracefully stop the candidate, verify its engine +exited, then start the original binary with the original configuration. Never +start both model processes on the same GPU without sufficient free memory. diff --git a/docs/plans/shared-conversation-snapshots.md b/docs/plans/shared-conversation-snapshots.md new file mode 100644 index 00000000..e692c303 --- /dev/null +++ b/docs/plans/shared-conversation-snapshots.md @@ -0,0 +1,147 @@ +# Shared conversation snapshots: convergence proposal + +Status: proposed interface and development work for issues/PRs #41, #52 and #57. +This is not an agreed integration-owner assignment, a merged upstream feature, +or a claim that the disk tier already uses this core. Development starts at +upstream `b38c183` (0.1.18); the deployed/tested 0.1.15 branch remains separate. + +## Boundaries + +1. **Snapshot core:** own the in-memory representation, checked sizing, + capture, complete non-mutating validation, and restore into existing session + allocations. Validate all layers, running state and checkpoints before the + first destination write. No cache policy, filesystem I/O or client markers. +2. **RAM policy:** longest compatible exact prefix, active wins ties, bounded + payload bytes and slots, LRU eviction. Incoming/outgoing exchange payloads + count together. Off by default. A failed admission is a normal cache miss. +3. **Disk adapter (separate contribution):** use the same state representation, + but do not serialize C++ structs, pointers or native vector layouts. Define a + versioned envelope and bounded streaming/staging explicitly before integration. + +The serve loop selects a resume point and publishes new token/image/checkpoint +metadata only after successful restore. It must not infer that a failed transfer +left the old session usable. + +## State checklist + +| State | Representation or reconstruction | +|---|---| +| Token/image identity and steering | Exact IDs, image identity/grid hashes, immutable engine steering configuration plus per-request enabled state | +| GDN | Recurrences and convolution history, in live state and every retained checkpoint | +| PLE | Normalized history; previous token window reconstructed from the checkpoint IDs | +| QSA KV | Used, page-rounded identity-layout cells, all codes/scales for FP16/INT8/Q4; authoritative host pools for streamed layers | +| Indexer | Completed pooled rows, raw tail, per-sequence spare key (`idx_dead`), and block-position metadata; rebuild the spare pooled row at the selected resume point | +| MTP | Used authoritative draft KV; refill its resident ring at the selected resume point | +| Residency | Invalidate replaceable streamed maps; keep graph-bound addresses stable; do not treat outgoing VRAM slots as authoritative | +| Compatibility | Runtime geometry, layout and buffer extents; persistent identity additionally binds exact weights/tokenizer/steering/schema | + +The first #57 implementation omitted `idx_dead` and block-position metadata; +fixtures with identical opening tokens can mask the spare-key omission. Include +distinct spare keys in the component regression and different opening prefixes +in future model gates. Do not describe earlier state hashes as coverage of these +previously unmeasured fields. Scratch recomputed before use (attention scores, +step/position uploads, graph intermediates) is not part of the persisted state. + +## Failure contract + +- Invalid snapshot: reject before CUDA synchronization/copies or destination + writes; discard that entry and retain a valid active prefix or perform normal + clean prefill. Do not discard the outgoing state before validating the incoming + candidate. +- Allocation/admission failure: skip parking, preserving active inference. +- Transfer/synchronization failure: return a distinct fatal outcome. The caller + reports an error and exits so the server can restart on the next request. A + future clean-reset recovery needs its own proof that the CUDA context remains + usable; validation does **not** make GPU failures transactional. +- Resume metadata is committed only after successful state application. + +## Memory admission + +Keep logical byte/slot capacity separate from physical-memory headroom. Proposed +flag: `--conversation-cache-min-free-mib` (default 2560, matching #41's starting +floor). Before allocating, require known available physical memory sufficient +for the estimated new payload plus that floor. Check again after capture; if the +floor is no longer met, discard the temporary image. Telemetry already includes +incoming images and parked allocations: do not subtract them a second time. + +Use `GlobalMemoryStatusEx` on Windows and `MemAvailable` on Linux. Unknown or +malformed telemetry declines parking. These are instantaneous admission samples, +not a reservation against other processes. Host telemetry alone does not enforce +cgroup/job limits; container-aware limits and Windows runtime verification need +review. Disabled caching must not sample telemetry or allocate snapshots. + +## Disk interface questions for review + +- A spill consumes an evicted immutable snapshot. If persistence fails, should + eviction still drop it, or may policy retain it within the existing bound? +- A promoted snapshot must reserve its staging bytes before reading. Either use + an explicitly bounded whole-image reservation or a validated streaming format; + a digest pass alone is not safe if the file can change before the apply pass. +- Bind model/weights, tokenizer, all geometry/KV layout, control vectors and + scales, image identity, and schema. The current RAM-only steering boolean is + not a persistent model identity. +- Use atomic publication and reject truncated/corrupt/foreign snapshots. Specify + local permissions, retention/deletion and privacy: disk contains conversation + tokens and model state, unlike the current RAM-only feature. +- Eviction-only spilling does not promise that the latest active turn survives + a crash. Decide whether shutdown/periodic persistence is a separate opt-in. + +## Acceptance and remaining work + +Use #57's existing component/parity harnesses as a starting point, not a complete +acceptance contract. Add CPU tests for unknown/low memory, arithmetic boundaries, +late-layer and checkpoint rejection before mutation, PLE mismatch, zero-QSA and +256/512-expert geometries; GPU round trips with distinct indexer spare keys; +transfer-failure tests; and a dry-run-by-default known-answer 30-cycle soak. + +Full-model testing must cover histories beyond resident KV at several lengths, +including near the configured limit, and compare exact answers plus the restored +state. Add real-encoder image smoke separately from synthetic embeddings. +Persistence/restart/corruption/staging tests belong with the disk adapter. +A controlled real Pi/Hermes task comparison still needs reproducible task inputs, +independent success validation, timings and peak memory. No existing synthetic +benchmark substitutes for that evidence. + +No unified PR should claim the whole contract until these gates and the +collaborators' interface/ownership review are complete. + +## Development checks + +Revision-specific results and coverage limits are in the +[validation record](shared-conversation-validation.md). + +The first development pass implements the RAM-side shared core and host-memory +admission; it does not connect the NVMe tier or define a stable disk ABI. Configure +with `-DSTRATA_BUILD_CONVERSATION_TESTS=ON` and build/run these targets: + +```sh +cmake --build build --target conversation_cache_test conversation_memory_test conversation_snapshot_test conversation_validation_test +ctest --test-dir build -R '^conversation_(cache|memory|snapshot|validation)_test$' --output-on-failure +python -m unittest tools.test_conversation_cache_parity tools.test_conversation_cache_isolation tools.test_conversation_cache_http_smoke tools.test_conversation_cache_soak +``` + +`conversation_validation_test` links CUDA but runs with devices hidden and checks +invalid-image rejection without CUDA initialization. On GNU/Clang ELF platforms, +also build `conversation_transfer_test`: link-wrapped host copies/synchronization +inject first-copy, partial-copy and final-sync failures into the real restore +control flow. This demonstrates fail-closed outcomes, not hardware-context recovery. +Run that target with `ctest --test-dir build -R '^conversation_transfer_test$' --output-on-failure`. +`conversation_snapshot_test` uses small real-GPU fixtures, including distinct spare +keys, early checkpoint rewinds and both expert-count metadata variants. Geometry +fixtures are not a full-model Coder run. + +The private parity script's `--scenario admission --min-free-mib N` gate requires +three physical-memory admission skips, no budget-related skips, and unchanged +output/state. Choose an `N` above the machine's available physical RAM to test +denial without actually exhausting memory. + +`tools/conversation_cache_soak.py` defaults to no I/O or model loading. With +`--config CONFIG --engine ENGINE --output NEW_DIRECTORY --run`, it runs at least +30 A/B/A cycles across three approximate lengths (`--prompt-tokens 2048,40000,120000`). +Select lengths for the test configuration: the largest must cross resident KV and +reach at least 90% of maximum context, while leaving room for the continuation. +It checks known secret-code answers, token/state parity against uninterrupted +baselines, cache reuse and a steady-state retained-payload plateau. Request-end RSS +samples are diagnostics, not a transient peak-memory bound. This is a synthetic +soak, not the requested real Pi/Hermes task benchmark. Run all model gates only in +an exclusive GPU window; no existing HTTP service is contacted by these scripts. diff --git a/docs/plans/shared-conversation-validation.md b/docs/plans/shared-conversation-validation.md new file mode 100644 index 00000000..0f549c23 --- /dev/null +++ b/docs/plans/shared-conversation-validation.md @@ -0,0 +1,135 @@ +# Shared snapshot core: validation record + +Date: 2026-09-28. Engine source: `3657b8f`, based on upstream `b38c183` +(0.1.18). This is development-branch evidence for the RAM tier/shared core, +not acceptance of a combined RAM/NVMe implementation or a deployment report. + +## Configuration and provenance + +- Linux, AMD EPYC 7532, approximately 247 GiB physical RAM, NVIDIA RTX 4090. +- GCC 15.2, CUDA 13.4, SM 89, portable/AVX2 CPU kernels. +- Qwen3.8-Flash-Next-GSQ-RCO IQ3_S; INT8 KV, 131,072-token maximum context, + 32,768 resident KV cells, automatic prefill sizing, 8,817 expert slots. +- Paired engines run sequentially with fixed expert residency. Baseline has + conversation caching disabled; candidate normally has an 8,192 MiB budget, + four parked slots and a 2,560 MiB physical-memory floor. Pressure/oversize/ + exchange/admission gates explicitly change the relevant limit. +- Tested executable SHA-256: + `f31d1fe2eecf7d27f440ea1ddfdb39133a16f471c70c1869491582614a16c2f9`. + +Do not infer a speedup over the earlier 0.1.15 results: maximum context, +expert residency and prefill configuration differ. These tests compare cache +behavior within this revision, not engine versions. + +## Component and offline checks + +| Gate | Result | +|---|---| +| CPU RAM ownership/prefix/budget policy | 35 checks passed | +| Available-memory parsing/admission boundaries | 23 checks passed | +| Real-GPU KV and complete-session fixtures | 1,071 checks passed | +| Whole-image rejection before mutation, devices hidden | 780 checks passed | +| Wrapped transfer/synchronization failure control flow | 1,020 checks passed (includes the 780 validation checks) | +| CPU policy/memory and host validation/transfer tests under ASan/UBSan | Passed | +| Python server tests plus cache-harness tests | 45 tests passed | +| Cache-harness tests under Python `-O` | 22 tests passed | +| CLI parsing, help, disabled-feature warnings | 20 checks passed | + +GPU fixtures cover FP16/INT8/Q4 KV, resident/streamed layouts, distinct indexer +spare keys, checkpoint rewind, and 256/512-expert geometry metadata. Host fixtures +also cover zero-QSA and PLE-present/absent layouts. Small geometry fixtures do not +constitute a full Coder/pruned-model run. Link-wrapped host failures exercise the +real restore control flow, not actual CUDA hardware-context recovery. + +## Full-model private-engine gates + +All nine gates below passed with this executable: + +1. Single-token A/B/A and checkpoint output/main-model state parity. +2. Long speculative A/B/A and checkpoint recovery beyond resident KV. +3. Byte-pressure eviction and correct cold fallback. +4. Oversized-entry rejection without disrupting inference. +5. Incoming/outgoing exchange-budget enforcement. +6. Image-content/grid identity isolation using synthetic embeddings. +7. Add-mode control-vector identity isolation. +8. Project-mode control-vector identity isolation. +9. Physical-memory admission denied by a 1 TiB floor: three admission skips, + no budget skips or parked entries, and output/state parity for A/B/C/A. + +State comparisons include GDN, PLE, indexer tail, `idx_dead`, pooled rows +including the spare row, main KV, previous PLE tokens and consumed length. +Unused draft cells are not part of the main-model fingerprint; draft snapshot +copies are covered by the component fixtures. Earlier prototype fingerprints +did not include `idx_dead` and must not be treated as equivalent coverage. + +In the long speculative gate (`spec=4`, `mtp_max=4`, lookup disabled): + +| Candidate request | Prompt tokens | Reused | Prompt-path time | +|---|---:|---:|---:| +| Initial A | 51,133 | 0 | 23.3721 s | +| Initial B | 51,135 | 0 | 22.3445 s | +| A continuation after B | 51,155 | 51,133 | 1.2371 s | +| A checkpoint continuation | 51,155 | 51,148 | 0.5659 s | + +Return-path times include parking/restoration and the remaining new prompt +tokens, but not decoding. Both A continuations matched uninterrupted baseline +outputs and the complete main-model fingerprints listed above. These synthetic +requests are not a controlled real-agent task benchmark. + +## Known-answer soak + +`tools/conversation_cache_soak.py --prompt-tokens 2048,40000,120000 --cycles 30` +passed against the same executable. Actual prompt lengths were 2,026, 39,985 and +119,987 tokens (the largest is 91.5% of maximum context). Single-token decode +was enforced with `spec=2`, `mtp_max=1` and lookup disabled. + +Each conversation contains a distinct secret word inside its history. After an +unrelated worker request, all 30 returns produced the expected word and exactly +matched uninterrupted baseline output tokens and main-model state fingerprints. +Each size was restored ten times; the final three retained-payload samples per +size were identical: + +| Active conversation length | Parked payload after its answer | +|---|---:| +| 2,026 tokens | 4,099,851,588 bytes | +| 39,985 tokens | 3,283,651,392 bytes | +| 119,987 tokens | 1,824,199,544 bytes | + +Occupancy differs because the active conversation is not parked; these figures +are not the snapshot sizes of the active conversations. Maximum logged parked +payload was 4,249,016,776 bytes, below the 8 GiB budget. The policy also accounts +for an incoming image held during exchange; the logged parked count alone does +not measure that transient total. Request-end RSS was sampled as a diagnostic, +not as a peak-memory bound or a proof against every allocator leak. Thirty cycles +establish this finite regression gate, not indefinite stability. + +## Private HTTP smoke + +All 12 requests in `tools/conversation_cache_http_smoke.py` passed on a separate +localhost-only endpoint using the same executable and normal adaptive settings +(reported `spec=6`, `mtp_max=4`, lookup 3, 8,816 expert slots). This was not the +fixed-residency/single-token configuration used for deterministic state parity. + +- A/B/A preserved the answer and reused 1,987 of 1,994 prompt tokens. +- Exceeding the four-slot limit evicted A; its next request correctly reused zero. +- A streaming disconnect cancelled after five output tokens; an unrelated + request then succeeded, and returning to the cancelled conversation reused + 1,085 of 1,092 prompt tokens. +- Frontend and engine process identities remained unchanged throughout the + smoke. The private test instance was then stopped; no production endpoint or + configuration was replaced. + +## Remaining acceptance work + +- Real vision encoder/image-recognition smoke (current image gate uses synthetic + embeddings); full-model 256-expert/Coder coverage. +- Windows runtime/memory-pressure review, including constrained-memory hardware; + Linux container/job-limit-aware admission is not implemented. +- Controlled real Pi/Hermes task with fixed initial files, tool limits, + independent success checks, wall-time breakdown and peak memory. +- Agreed ownership/interface for the unified PR, NVMe adapter, bounded staging, + persistent compatibility identity, corruption/restart/durability tests. + +No private conversations, raw request captures, local configuration files or +machine-specific paths are needed to reproduce these synthetic fixtures. +See [the design and test commands](shared-conversation-snapshots.md). diff --git a/include/strata/core/conversation_cache.hpp b/include/strata/core/conversation_cache.hpp new file mode 100644 index 00000000..42409d3d --- /dev/null +++ b/include/strata/core/conversation_cache.hpp @@ -0,0 +1,146 @@ +// CPU-only ownership and matching policy for --serve's parked conversations. +// Token equality, image identity, and steering mode are all required for reuse. +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace strata::core { + +struct ConversationImageKey { + int64_t start = 0; + uint64_t hash = 0; + bool operator==(const ConversationImageKey&) const = default; +}; + +struct ConversationCheckpoint { + std::vector ids; + std::vector imgs; + std::vector gdn, ple, tails, dead, block_pos; + uint64_t used = 0; // upstream root-pinned/LRU checkpoint retention + // Ordinary layer-split checkpoints retain each device's running state. + // Whole-session parking is currently single-GPU and rejects these parts. + std::vector stage_parts; + + size_t bytes() const { + size_t n = ids.capacity() * sizeof(int32_t) + imgs.capacity() * sizeof(ConversationImageKey) + + gdn.capacity() + ple.capacity() + tails.capacity() + dead.capacity() + block_pos.capacity() + + stage_parts.capacity() * sizeof(ConversationCheckpoint); + for (const auto& part : stage_parts) n += part.bytes(); + return n; + } +}; + +// Identity-layout K/V pages and completed indexer rows. For streamed layers the +// source is the authoritative host pool, NOT the replaceable VRAM slots. +struct ConversationKv { + int format = 0; + int64_t cells = 0, heads = 0, head_dim = 0, page_size = 0, pooled_rows = 0, idx_dim = 0; + std::vector k, v, k_scale, v_scale, pooled; + size_t bytes() const { + return k.capacity() + v.capacity() + k_scale.capacity() + v_scale.capacity() + pooled.capacity(); + } +}; + +struct SavedConversation { + // Runtime compatibility only; NOT a model/weights identity or disk schema. + std::array geometry{}; + ConversationCheckpoint live; + std::vector checkpoints; + std::vector kv; // main layers followed by the draft layer + bool cvec = true; + + size_t bytes() const { + size_t n = live.bytes() + checkpoints.capacity() * sizeof(ConversationCheckpoint) + + kv.capacity() * sizeof(ConversationKv); + for (const auto& c : checkpoints) n += c.bytes(); + for (const auto& k : kv) n += k.bytes(); + return n; + } +}; + +template +int64_t conversation_prefix(const ConversationCheckpoint& c, const std::vector& prompt, + const std::vector& images) { + const size_t n = c.ids.size(); + // The last prompt token always starts the next verify window. + if (n == 0 || n >= prompt.size() || !std::equal(c.ids.begin(), c.ids.end(), prompt.begin())) return 0; + size_t j = 0; + for (const auto& image : images) { + if (image.start >= (int64_t) n) continue; + if (j == c.imgs.size() || !(c.imgs[j++] == image)) return 0; + } + if (j != c.imgs.size()) return 0; + return (int64_t) n; +} + +class ConversationCache { +public: + struct Match { + size_t index = 0; + int64_t tokens = 0; + bool live = false; + }; + + ConversationCache(size_t budget, size_t slots) : budget_(budget), slots_(slots) {} + bool enabled() const { return budget_ != 0 && slots_ != 0; } + size_t bytes() const { return bytes_; } + size_t size() const { return entries_.size(); } + size_t evictions() const { return evictions_; } + + template + Match best(const std::vector& prompt, const std::vector& images, bool cvec) const { + Match best; + // Ties prefer the most recently parked branch. The caller prefers its + // already-active state when that offers the same prefix length. + for (size_t i = entries_.size(); i-- > 0;) { + const auto& e = entries_[i]; + if (e.cvec != cvec) continue; + auto consider = [&](const ConversationCheckpoint& c, bool live) { + const int64_t n = conversation_prefix(c, prompt, images); + if (n > best.tokens) best = {i, n, live}; + }; + consider(e.live, true); + for (const auto& c : e.checkpoints) consider(c, false); + } + return best; + } + + SavedConversation take(size_t index) { + SavedConversation out = std::move(entries_.at(index)); + bytes_ -= out.bytes(); + entries_.erase(entries_.begin() + (std::ptrdiff_t) index); + return out; + } + + // Reserve before allocating a snapshot. held is an incoming image removed + // with take() but still alive during the exchange; count it against RAM too. + bool make_room(size_t incoming, size_t held = 0) { + if (!enabled() || held > budget_ || incoming > budget_ - held) return false; + while (!entries_.empty() && (entries_.size() >= slots_ || bytes_ > budget_ - held - incoming)) { + bytes_ -= entries_.front().bytes(); + entries_.pop_front(); + ++evictions_; + } + return true; + } + + bool put(SavedConversation&& image, size_t held = 0) { + const size_t n = image.bytes(); + if (!make_room(n, held)) return false; + entries_.push_back(std::move(image)); + bytes_ += n; + return true; + } + +private: + size_t budget_ = 0, slots_ = 0, bytes_ = 0, evictions_ = 0; + std::deque entries_; // least recently active first +}; + +} // namespace strata::core diff --git a/include/strata/core/conversation_memory.hpp b/include/strata/core/conversation_memory.hpp new file mode 100644 index 00000000..0e908b40 --- /dev/null +++ b/include/strata/core/conversation_memory.hpp @@ -0,0 +1,19 @@ +#pragma once + +#include +#include +#include + +namespace strata::core { + +// Host physical memory, not swap/commit or a container/job memory reservation. +// Unknown telemetry is deliberately distinct from a measured zero. +std::optional conversation_available_memory(); +std::optional conversation_mem_available(std::istream& meminfo); + +inline bool conversation_memory_admit(std::optional available, + uint64_t allocation, uint64_t floor) { + return available && *available >= floor && allocation <= *available - floor; +} + +} // namespace strata::core diff --git a/include/strata/core/conversation_snapshot.hpp b/include/strata/core/conversation_snapshot.hpp new file mode 100644 index 00000000..a135e310 --- /dev/null +++ b/include/strata/core/conversation_snapshot.hpp @@ -0,0 +1,55 @@ +#pragma once + +#include "strata/core/conversation_cache.hpp" +#include "strata/core/layer.hpp" +#include "strata/core/session.hpp" + +#include + +namespace strata::core { + +// Caller synchronizes the device before saving, and after restoring all layers. +// include_index is false for the draft layer (its attention has no indexer). +size_t conversation_kv_bytes(const QsaState& state, const ModelGeometry& g, int64_t upto, bool include_index); +bool conversation_kv_save(ConversationKv& image, const QsaState& state, const ModelGeometry& g, + int64_t upto, bool include_index, std::string& error); +// No CUDA calls or destination writes. Used for whole-session prevalidation. +bool conversation_kv_validate(const ConversationKv& image, const QsaState& state, const ModelGeometry& g, + int64_t upto, bool include_index, std::string& error); +bool conversation_kv_restore(const ConversationKv& image, const QsaState& state, const ModelGeometry& g, + int64_t upto, bool include_index, std::string& error); + +struct ConversationStateSizes { + size_t gdn = 0, ple = 0, tail = 0, dead = 0, block_pos = 0; +}; +bool conversation_state_sizes(const ModelGeometry& g, ConversationStateSizes& sizes, std::string& error); +bool conversation_checkpoint_validate(const ConversationCheckpoint& checkpoint, const SessionState& session, + const ModelGeometry& g, std::string& error); +bool conversation_checkpoint_save(ConversationCheckpoint& checkpoint, const SessionState& session, + const ModelGeometry& g, std::string& error); +bool conversation_checkpoint_restore(const ConversationCheckpoint& checkpoint, SessionState& session, + const ModelGeometry& g, std::string& error); + +struct ConversationView { + const std::vector& ids; + const std::vector& images; + const std::vector& checkpoints; + bool cvec; +}; +bool conversation_snapshot_bytes(const ConversationView& view, const SessionState& session, + const ModelGeometry& g, const QsaState& draft, size_t& bytes, std::string& error); +// Caller admits the estimate before invoking capture. Allocation failures propagate +// to the RAM policy; the active session is never modified by capture. +bool conversation_snapshot_save(SavedConversation& image, const ConversationView& view, + const SessionState& session, const ModelGeometry& g, + const QsaState& draft, std::string& error); +bool conversation_snapshot_validate(const SavedConversation& image, const SessionState& session, + const ModelGeometry& g, const QsaState& draft, std::string& error); +enum class ConversationRestore { restored, invalid, transfer_failed }; +// Invalid images are rejected before any CUDA call/write. Transfer failure may +// leave partial state: caller MUST NOT continue inference from that session. +ConversationRestore conversation_snapshot_restore(const SavedConversation& image, SessionState& session, + const ModelGeometry& g, const QsaState& draft, + std::string& error); + +} // namespace strata::core diff --git a/src/core/conversation_cache_test.cpp b/src/core/conversation_cache_test.cpp new file mode 100644 index 00000000..f6346d90 --- /dev/null +++ b/src/core/conversation_cache_test.cpp @@ -0,0 +1,92 @@ +#include "strata/core/conversation_cache.hpp" + +#include +#include + +using namespace strata::core; + +namespace { +int checks = 0; +void check(bool value, const char* description) { + ++checks; + if (!value) { std::fprintf(stderr, "FAIL: %s\n", description); std::exit(1); } +} +SavedConversation image(std::initializer_list ids, bool cvec = true) { + SavedConversation s; + s.live.ids = ids; + s.live.gdn.resize(64, 7); + s.cvec = cvec; + return s; +} +} + +int main() { + const std::vector a = {1, 2, 3, 4}, b = {9, 8, 7, 6}; + { + ConversationCache cache(1024, 2); + check(cache.put(image({1, 2, 3})), "park A"); + check(cache.put(image({9, 8, 7})), "park B"); + auto match = cache.best(a, {}, true); + check(match.tokens == 3 && match.live, "A/B/A: recover A"); + auto restored = cache.take(match.index); + check(restored.live.ids == std::vector({1, 2, 3}), "taking selected A preserves identity"); + check(cache.size() == 1 && cache.best(b, {}, true).tokens == 3, "B remains parked"); + check(cache.bytes() == image({9,8,7}).bytes(), "byte accounting after take"); + check(cache.put(std::move(restored)), "park returned A as newest"); + check(cache.put(image({5, 6})), "evict oldest by slot limit"); + check(cache.best(b, {}, true).tokens == 0 && cache.best(a, {}, true).tokens == 3, "B evicted before A"); + check(cache.evictions() == 1, "eviction counter"); + } + { + auto s = image({1, 2, 3}); + ConversationCheckpoint cp; + cp.ids = {1, 2}; + s.checkpoints.push_back(cp); + ConversationCache cache(4096, 4); + cache.put(std::move(s)); + auto match = cache.best(std::vector{1, 2, 9, 4}, {}, true); + check(match.tokens == 2 && !match.live, "edited suffix falls back to parked checkpoint"); + check(cache.best(a, {}, true).tokens == 3, "live prefix beats shorter checkpoint"); + check(cache.best(a, {}, false).tokens == 0, "steering mode is isolated"); + check(cache.best(std::vector{1, 2}, {}, true).tokens == 0, "equal-length checkpoint cannot consume last token"); + check(cache.best(std::vector{1}, {}, true).tokens == 0, "short prompt cannot match"); + check(cache.best(std::vector{}, {}, true).tokens == 0, "empty prompt cannot match"); + cache.put(image({1, 2, 3})); + check(cache.best(a, {}, true).index == 1, "ties prefer most recently parked"); + } + { + auto s = image({1, 2, 3}); + s.live.imgs = {{1, 123}}; + ConversationCache cache(1024, 3); + cache.put(std::move(s)); + check(cache.best(a, {{1,123}}, true).tokens == 3, "same image can resume"); + check(cache.best(a, {{1,124}}, true).tokens == 0, "different image pixels invalidate same pad tokens"); + check(cache.best(a, {}, true).tokens == 0, "missing image invalidates prefix"); + check(cache.best(a, {{1,123},{2,45}}, true).tokens == 0, "additional image in cached prefix invalidates"); + check(cache.best(a, {{1,123},{3,45}}, true).tokens == 3, "image after cached prefix does not invalidate"); + } + { + const size_t one = image({1,2,3}).bytes(); + ConversationCache cache(one*2, 8); + cache.put(image({1,2,3})); cache.put(image({9,8,7})); + check(cache.bytes() == one*2, "budget holds two exact-sized images"); + auto held = cache.take(cache.best(a, {}, true).index); + check(cache.make_room(one, held.bytes()), "count in-flight image when reserving outgoing snapshot"); + check(cache.size() == 0, "in-flight reservation evicts otherwise fitting B"); + check(cache.put(image({5,6,7}), held.bytes()), "insert with in-flight accounting"); + check(cache.bytes()+held.bytes() <= one*2, "exchange obeys byte budget"); + check(!cache.make_room(one+1, one), "oversized exchange rejected"); + check(cache.size() == 1, "oversized snapshot does not evict useful entries"); + auto huge = image({1}); huge.live.gdn.resize(one*3); + check(!cache.put(std::move(huge)), "oversized image rejected"); + check(cache.size() == 1, "oversized put leaves cache unchanged"); + check(!cache.make_room(0, one*2+1), "held larger than budget cannot underflow"); + } + { + ConversationCache disabled(0,4), no_slots(1024,0); + check(!disabled.enabled() && !no_slots.enabled(), "both disable switches"); + check(!disabled.put(image({1,2,3})) && !no_slots.put(image({1,2,3})), "disabled cache stores nothing"); + check(disabled.best(a,{},true).tokens == 0, "disabled cache has no matches"); + } + std::printf("conversation_cache_test: %d checks passed\n", checks); +} diff --git a/src/core/conversation_checked.hpp b/src/core/conversation_checked.hpp new file mode 100644 index 00000000..4355dc4e --- /dev/null +++ b/src/core/conversation_checked.hpp @@ -0,0 +1,24 @@ +#pragma once + +#include +#include +#include +#include + +namespace strata::core::conversation_detail { +inline bool add(size_t& total, size_t n) { + if (n > std::numeric_limits::max() - total) return false; + total += n; + return true; +} +inline bool product(size_t& out, std::initializer_list factors) { + size_t value = 1; + for (uint64_t factor : factors) { + if (factor > std::numeric_limits::max() || + (factor && value > std::numeric_limits::max() / factor)) return false; + value *= (size_t) factor; + } + out = value; + return true; +} +} // namespace strata::core::conversation_detail diff --git a/src/core/conversation_memory.cpp b/src/core/conversation_memory.cpp new file mode 100644 index 00000000..bd5740f2 --- /dev/null +++ b/src/core/conversation_memory.cpp @@ -0,0 +1,51 @@ +#include "strata/core/conversation_memory.hpp" + +#include +#include +#include +#include +#include + +#if defined(_WIN32) +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#endif + +namespace strata::core { + +std::optional conversation_mem_available(std::istream& meminfo) { + std::optional result; + std::string line; + while (std::getline(meminfo, line)) { + std::istringstream fields(line); + std::string key, value, unit, extra; + if (!(fields >> key) || key != "MemAvailable:") continue; + if (result || !(fields >> value >> unit) || unit != "kB" || (fields >> extra)) return {}; + uint64_t kb = 0; + const auto parsed = std::from_chars(value.data(), value.data() + value.size(), kb); + if (parsed.ec != std::errc{} || parsed.ptr != value.data() + value.size() || + kb > std::numeric_limits::max() / 1024) return {}; + result = kb * 1024; + } + if (meminfo.bad() || (meminfo.fail() && !meminfo.eof())) return {}; + return result; +} + +std::optional conversation_available_memory() { +#if defined(_WIN32) + MEMORYSTATUSEX status{}; + status.dwLength = sizeof status; + if (GlobalMemoryStatusEx(&status)) return status.ullAvailPhys; + return {}; +#elif defined(__linux__) + std::ifstream meminfo("/proc/meminfo"); + if (!meminfo) return {}; + return conversation_mem_available(meminfo); +#else + return {}; +#endif +} + +} // namespace strata::core diff --git a/src/core/conversation_memory_test.cpp b/src/core/conversation_memory_test.cpp new file mode 100644 index 00000000..aec678f3 --- /dev/null +++ b/src/core/conversation_memory_test.cpp @@ -0,0 +1,49 @@ +#include "strata/core/conversation_memory.hpp" + +#include +#include +#include +#include + +using namespace strata::core; +namespace { +int checks = 0; +void check(bool ok, const char* label) { + ++checks; + if (!ok) { std::fprintf(stderr, "FAIL: %s\n", label); std::exit(1); } +} +} + +int main() { + for (const char* text : {"", "MemFree: 100 kB\n", "MemAvailable: -1 kB\n", + "MemAvailable: +1 kB\n", "MemAvailable: 1 MB\n", + "MemAvailable: 1\n", "MemAvailable: 1x kB\n", + "MemAvailable: 18446744073709551615 kB\n", + "MemAvailable: 18446744073709551616 kB\n", + "MemAvailable: 1 kB trailing\n", + "MemAvailable: 1 kB\nMemAvailable: 2 kB\n"}) { + std::istringstream input(text); + check(!conversation_mem_available(input), "missing/malformed telemetry is unknown"); + } + std::istringstream normal("MemTotal: 999999 kB\nMemAvailable: 12345 kB\nSwapFree: 777 kB\n"); + check(conversation_mem_available(normal) == 12345ULL * 1024, "only MemAvailable is counted"); + std::istringstream zero("MemAvailable: 0 kB"); + check(conversation_mem_available(zero) == 0, "zero available memory is known"); + std::istringstream broken("MemAvailable: 123 kB\n"); + broken.setstate(std::ios::badbit); + check(!conversation_mem_available(broken), "I/O failure declines admission"); + check(!conversation_memory_admit({}, 0, 0), "unknown fails closed even with zero floor"); + check(conversation_memory_admit(100, 40, 60), "exact allocation plus floor fits"); + check(!conversation_memory_admit(99, 40, 60), "one byte below required memory rejected"); + check(!conversation_memory_admit(59, 0, 60), "floor subtraction cannot underflow"); + check(conversation_memory_admit(60, 0, 60), "post-capture floor check"); + check(!conversation_memory_admit(100, std::numeric_limits::max(), 1), "allocation arithmetic cannot overflow"); + check(conversation_memory_admit(std::numeric_limits::max(), + std::numeric_limits::max(), 0), "maximal exact bound"); + check(!conversation_memory_admit(std::numeric_limits::max(), + std::numeric_limits::max(), 1), "maximal sum overflow rejected"); + // Test the real provider without assuming any particular amount of free RAM. + const auto available = conversation_available_memory(); + check(!available || conversation_memory_admit(available, 0, 0), "provider returns bytes or unknown"); + std::printf("conversation_memory_test: %d checks passed\n", checks); +} diff --git a/src/core/conversation_snapshot.cpp b/src/core/conversation_snapshot.cpp new file mode 100644 index 00000000..b085da83 --- /dev/null +++ b/src/core/conversation_snapshot.cpp @@ -0,0 +1,190 @@ +#include "strata/core/conversation_snapshot.hpp" +#include "strata/kernels/kv_q4.hpp" +#include "conversation_checked.hpp" +#include + +#include +#include + +namespace strata::core { +namespace { +struct Layout { + int format; + int64_t cells, pooled_rows, page_size; + size_t data, scales, pooled, value_data, value_scales; +}; + +bool valid_extent(const QsaState& st, int64_t upto, std::string& error) { + const int64_t page = strata::kernels::qsa_real_shapes().page_size; + if (upto < 0 || upto > st.max_cells || upto > std::numeric_limits::max() - (page - 1)) { + error = "conversation snapshot: invalid K/V extent"; + return false; + } + return true; +} + +bool layout(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index, Layout& l, std::string& error) { + if (!valid_extent(st, upto, error)) return false; + if (st.kv_hybrid && (st.kv_mode != 0 || st.kv_q4 || !st.kv_int8)) { + error = "conversation snapshot: hybrid K8V4 requires identity-layout INT8 K"; + return false; + } + const auto s = strata::kernels::qsa_real_shapes(); + if (g.n_head_kv <= 0 || g.head_dim <= 0 || g.head_dim > INT32_MAX || g.idx_key_dim <= 0 || + (st.kv_q4 && g.head_dim % 32) || (st.kv_int8 && !st.kv_q4 && g.head_dim % 64)) { + error = "conversation snapshot: invalid K/V geometry"; + return false; + } + const int64_t cells = ((upto + s.page_size - 1) / s.page_size) * s.page_size; + const size_t per = st.kv_q4 ? (size_t) strata::kernels::kv_q4_bytes_per_head((int) g.head_dim) + : (size_t) g.head_dim * (st.kv_int8 ? 1 : 2); + // Include the moving spare row, not only completed blocks. The checkpoint + // restore reconstructs that row when rewinding to an earlier prefix. + const int64_t pooled = index && upto > 0 ? upto / s.idx_block + 1 : 0; + // Format 3 identifies snapshot K8V4 only; never pass it to the block movers. + l = {st.kv_hybrid ? 3 : qsa_kv_format(st), cells, pooled, s.page_size, 0, 0, 0, 0, 0}; + using conversation_detail::product; + if (!product(l.data, {(uint64_t) cells, (uint64_t) g.n_head_kv, per}) || + !product(l.scales, {(uint64_t) cells, (uint64_t) g.n_head_kv, + st.kv_int8 && !st.kv_q4 ? (uint64_t) (g.head_dim / 64) * 2 : 0}) || + !product(l.pooled, {(uint64_t) pooled, (uint64_t) g.idx_key_dim, sizeof(float)})) { + error = "conversation snapshot: K/V byte count overflow"; + return false; + } + l.value_data = l.data; + l.value_scales = l.scales; + if (st.kv_hybrid) { + if (!product(l.value_data, {(uint64_t) cells, (uint64_t) g.n_head_kv, + (uint64_t) strata::kernels::kv_q4_bytes_per_head((int) g.head_dim)})) { + error = "conversation snapshot: hybrid V byte count overflow"; + return false; + } + l.value_scales = 0; + } + return true; +} + +std::array pools(const QsaState& st) { + const bool host = st.kv_mode != 0; + if (st.kv_hybrid) return {st.k_q, st.v_q4, st.k_scale, nullptr, st.idx_pooled}; + if (st.kv_q4) + return {host ? st.host.k_q4 : st.k_q4, host ? st.host.v_q4 : st.v_q4, nullptr, nullptr, st.idx_pooled}; + if (st.kv_int8) + return {host ? st.host.k_q : st.k_q, host ? st.host.v_q : st.v_q, + host ? st.host.k_scale : st.k_scale, host ? st.host.v_scale : st.v_scale, st.idx_pooled}; + return {host ? st.host.k_pool : st.k_pool, host ? st.host.v_pool : st.v_pool, nullptr, nullptr, st.idx_pooled}; +} + +bool valid(const QsaState& st, const Layout& l, int64_t upto, std::string& error) { + if (upto < 0 || upto > st.max_cells || st.n_pages < 0 || l.cells / l.page_size > st.n_pages || + st.kv_mode < 0 || st.kv_mode > 2 || st.n_slots <= 0 || + (st.kv_mode == 0 && st.n_slots < st.n_pages) || + l.pooled_rows > st.idx_pooled_rows || (st.kv_mode != 0 && !st.host.present())) { + error = "conversation snapshot: invalid K/V extent or missing authoritative host pool"; + return false; + } + if (st.kv_mode == 1) { + const auto& m = st.map; + if (m.n_blocks != st.n_pages || m.n_slots != st.n_slots || !m.page_table || !m.slot_block || + !m.slot_stamp || !m.slot_ref || !m.ctl || !m.miss_block || !m.miss_slot) { + error = "conversation snapshot: invalid streaming map"; + return false; + } + } + if (st.kv_mode == 2 && (!st.page_table || + (st.kv_q4 ? !st.k_q4 || !st.v_q4 : st.kv_int8 ? !st.k_q || !st.v_q || !st.k_scale || !st.v_scale + : !st.k_pool || !st.v_pool))) { + error = "conversation snapshot: invalid draft ring"; + return false; + } + return true; +} + +bool transfer(void* dst, const void* src, size_t n, std::string& error) { + if (!n) return true; + if (!src || !dst) { error = "conversation snapshot: missing state buffer"; return false; } + // Default handles both device allocations and device-mapped host pool aliases. + const cudaError_t e = cudaMemcpy(dst, src, n, cudaMemcpyDefault); + if (e == cudaSuccess) return true; + error = std::string("conversation snapshot copy: ") + cudaGetErrorString(e); + return false; +} +} // namespace + +size_t conversation_kv_bytes(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index) { + std::string error; + Layout l{}; + if (!layout(st, g, upto, index, l, error) || !valid(st, l, upto, error)) return 0; + size_t bytes = l.pooled; + for (size_t n : {l.data, l.value_data, l.scales, l.value_scales}) + if (!conversation_detail::add(bytes, n)) return 0; + return bytes; +} + +bool conversation_kv_save(ConversationKv& image, const QsaState& st, const ModelGeometry& g, + int64_t upto, bool index, std::string& error) { + Layout l{}; + if (!layout(st, g, upto, index, l, error)) return false; + if (!valid(st, l, upto, error)) return false; + image.format = l.format; + image.cells = l.cells; + image.heads = g.n_head_kv; + image.head_dim = g.head_dim; + image.page_size = l.page_size; + image.pooled_rows = l.pooled_rows; + image.idx_dim = g.idx_key_dim; + const auto src = pools(st); + const std::array sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled}; + const std::array*,5> dst = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; + for (size_t i = 0; i < dst.size(); ++i) { + dst[i]->resize(sizes[i]); + if (!transfer(dst[i]->data(), src[i], sizes[i], error)) return false; + } + return true; +} + +bool conversation_kv_validate(const ConversationKv& image, const QsaState& st, const ModelGeometry& g, + int64_t upto, bool index, std::string& error) { + Layout l{}; + if (!layout(st, g, upto, index, l, error)) return false; + if (!valid(st, l, upto, error)) return false; + const std::array sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled}; + const std::array*,5> src = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; + if (image.format != l.format || image.cells != l.cells || image.heads != g.n_head_kv || + image.head_dim != g.head_dim || image.page_size != l.page_size || image.pooled_rows != l.pooled_rows || + image.idx_dim != g.idx_key_dim) { + error = "conversation snapshot: incompatible K/V geometry"; + return false; + } + for (size_t i = 0; i < src.size(); ++i) + if (src[i]->size() != sizes[i]) { error = "conversation snapshot: invalid K/V payload size"; return false; } + const auto dst = pools(st); + for (size_t i = 0; i < src.size(); ++i) + if (sizes[i] && !dst[i]) { error = "conversation snapshot: missing target state buffer"; return false; } + return true; +} + +bool conversation_kv_restore(const ConversationKv& image, const QsaState& st, const ModelGeometry& g, + int64_t upto, bool index, std::string& error) { + if (!conversation_kv_validate(image, st, g, upto, index, error)) return false; + const std::array*,5> src = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; + const auto dst = pools(st); + for (size_t i = 0; i < src.size(); ++i) + if (!transfer(dst[i], src[i]->data(), src[i]->size(), error)) return false; + // VRAM slots still contain the outgoing conversation. Resolve must refill + // them from the restored authoritative pools before any attention reads. + if (st.kv_mode == 1) strata::kernels::kv_stream_reset(st.map, nullptr); + if (st.kv_mode == 2 && upto > 0) { + auto shapes = strata::kernels::qsa_real_shapes(); + shapes.n_head_kv = g.n_head_kv; shapes.head_dim = g.head_dim; + const int64_t end = (upto + shapes.page_size - 1) / shapes.page_size; + strata::kernels::kv_ring_restore(qsa_attn_pools(st), st.host, qsa_kv_format(st), + std::max(0, end - st.n_slots), end, st.n_slots, shapes, nullptr); + } + const auto status = cudaGetLastError(); + if (status == cudaSuccess) return true; + error = std::string("conversation snapshot residency restore: ") + cudaGetErrorString(status); + return false; +} + +} // namespace strata::core diff --git a/src/core/conversation_snapshot_test.cpp b/src/core/conversation_snapshot_test.cpp new file mode 100644 index 00000000..9a8c89a7 --- /dev/null +++ b/src/core/conversation_snapshot_test.cpp @@ -0,0 +1,232 @@ +#include "strata/core/conversation_snapshot.hpp" +#include "strata/kernels/kv_q4.hpp" +#include + +#include +#include +#include +#include +#include + +using namespace strata::core; +using namespace strata::kernels; + +namespace { +int checks = 0; +void check(bool ok, const char* label) { + ++checks; + if (!ok) { std::fprintf(stderr, "FAIL: %s\n", label); std::exit(1); } +} +void cuda_check(cudaError_t e) { + if (e != cudaSuccess) { std::fprintf(stderr, "CUDA: %s\n", cudaGetErrorString(e)); std::exit(1); } +} +struct Fixture { + ModelGeometry g; + QsaState state; + std::vector device, host; + std::array sources{}; + std::array sizes{}; + + template void alloc(T*& p, size_t n, bool pinned = false) { + if (!n) return; + void* raw = nullptr; + if (pinned) { + cuda_check(cudaHostAlloc(&raw, n, cudaHostAllocMapped)); + host.push_back(raw); + void* mapped = nullptr; + cuda_check(cudaHostGetDevicePointer(&mapped, raw, 0)); + p = static_cast(mapped); + } else { + cuda_check(cudaMalloc(&raw, n)); device.push_back(raw); p = static_cast(raw); + } + } + Fixture(int fmt, int mode) { + auto& st = state; + st.kv_mode = mode; st.kv_int8 = fmt==kKvInt8 || fmt==3; st.kv_q4 = fmt==kKvQ4; st.kv_hybrid = fmt==3; + st.n_pages = 24; st.n_slots = mode ? 4 : st.n_pages; + st.max_cells = st.n_pages * 4; st.idx_pooled_rows = mode==2 ? 2 : st.max_cells/4+2; + const size_t per = fmt==kKvQ4 ? kv_q4_bytes_per_head((int)g.head_dim) : g.head_dim*(st.kv_int8 ? 1:2); + const size_t rows = st.max_cells*g.n_head_kv, slot_rows = st.n_slots*4*g.n_head_kv; + sizes = {rows*per, rows*per, fmt==kKvInt8 ? rows*(g.head_dim/64)*2:0, + fmt==kKvInt8 ? rows*(g.head_dim/64)*2:0, (size_t)st.idx_pooled_rows*g.idx_key_dim*4}; + if (fmt==3) { + sizes = {rows*per, rows*kv_q4_bytes_per_head((int)g.head_dim), rows*(g.head_dim/64)*2, 0, + (size_t)st.idx_pooled_rows*g.idx_key_dim*4}; + alloc(st.k_q,sizes[0]); alloc(st.v_q4,sizes[1]); alloc(st.k_scale,sizes[2]); + sources[0]=st.k_q; sources[1]=st.v_q4; sources[2]=st.k_scale; + } else if (fmt==kKvQ4) { + alloc(st.k_q4,slot_rows*per); alloc(st.v_q4,slot_rows*per); + if (mode) {alloc(st.host.k_q4,sizes[0],true); alloc(st.host.v_q4,sizes[1],true);} + sources[0]=mode?st.host.k_q4:st.k_q4; sources[1]=mode?st.host.v_q4:st.v_q4; + } else if (fmt==kKvInt8) { + alloc(st.k_q,slot_rows*per); alloc(st.v_q,slot_rows*per); + alloc(st.k_scale,slot_rows*(g.head_dim/64)*2); alloc(st.v_scale,slot_rows*(g.head_dim/64)*2); + if (mode) { + alloc(st.host.k_q,sizes[0],true); alloc(st.host.v_q,sizes[1],true); + alloc(st.host.k_scale,sizes[2],true); alloc(st.host.v_scale,sizes[3],true); + } + sources[0]=mode?st.host.k_q:st.k_q; sources[1]=mode?st.host.v_q:st.v_q; + sources[2]=mode?st.host.k_scale:st.k_scale; sources[3]=mode?st.host.v_scale:st.v_scale; + } else { + alloc(st.k_pool,slot_rows*per); alloc(st.v_pool,slot_rows*per); + if (mode) {alloc(st.host.k_pool,sizes[0],true); alloc(st.host.v_pool,sizes[1],true);} + sources[0]=mode?st.host.k_pool:st.k_pool; sources[1]=mode?st.host.v_pool:st.v_pool; + } + alloc(st.idx_pooled,sizes[4]); sources[4]=st.idx_pooled; + alloc(st.page_table,st.n_pages*4); + if (mode==1) { + auto& m=st.map; + m.page_table=st.page_table; m.n_blocks=st.n_pages; m.n_slots=st.n_slots; + alloc(m.slot_block,st.n_slots*4); alloc(m.slot_stamp,st.n_slots*4); alloc(m.slot_ref,st.n_slots*4); + alloc(m.miss_block,st.n_slots*4); alloc(m.miss_slot,st.n_slots*4); alloc(m.ctl,kKvCtlInts*4); + } else if (mode==2) { + kv_ring_table(st.page_table,st.n_pages,st.n_slots,nullptr); + } + } + void fill(uint8_t salt) { + for (size_t i=0;i data(sizes[i]); + for (size_t j=0;j ids(65); + for (size_t i=0;i images; + std::vector checkpoints; + auto fill=[&](uint8_t salt) { + main.fill(salt); draft.fill(salt); + for (const auto& [p,n] : std::vector>{ + {ss.gdn_state,sizes.gdn},{ss.ple_hist,sizes.ple},{main.state.idx_tail,sizes.tail}, + {main.state.idx_dead,sizes.dead},{main.state.idx_block_pos,sizes.block_pos}}) + cuda_check(cudaMemset(p,salt,n)); + // A real indexer maintains its spare pooled row as a copy of idx_dead. + cuda_check(cudaMemcpy(main.state.idx_pooled+(ids.size()/4)*g.idx_key_dim, + main.state.idx_dead,sizes.dead,cudaMemcpyDeviceToDevice)); + cuda_check(cudaDeviceSynchronize()); + }; + fill(13); + ConversationCheckpoint checkpoint; + checkpoint.ids.assign(ids.begin(),ids.begin()+3); + check(conversation_checkpoint_save(checkpoint,ss,g,err),"save complete running checkpoint"); + checkpoint.used = 17; + checkpoints.push_back(std::move(checkpoint)); + const ConversationView view{ids,images,checkpoints,true}; + SavedConversation a,b,restored; + check(conversation_snapshot_save(a,view,ss,g,draft.state,err),"capture complete A"); + check(a.checkpoints[0].used == 17,"upstream checkpoint LRU stamp survives capture"); + fill(177); + check(conversation_snapshot_save(b,view,ss,g,draft.state,err),"capture complete B"); + check(a.live.dead!=b.live.dead,"different opening-state spare keys in regression fixture"); + auto bad=a; bad.kv.back().k.pop_back(); + check(conversation_snapshot_restore(bad,ss,g,draft.state,err)==ConversationRestore::invalid, + "reject invalid late draft before any main-layer write"); + check(conversation_snapshot_save(restored,view,ss,g,draft.state,err),"capture B after refused restore"); + check(restored.live.gdn==b.live.gdn && restored.live.dead==b.live.dead && + equal(restored.kv[0],b.kv[0]) && equal(restored.kv[1],b.kv[1]),"refusal preserves all tested state"); + check(conversation_snapshot_restore(a,ss,g,draft.state,err)==ConversationRestore::restored,"restore complete A"); + check(conversation_snapshot_save(restored,view,ss,g,draft.state,err),"capture restored A"); + check(restored.live.gdn==a.live.gdn && restored.live.ple==a.live.ple && restored.live.tails==a.live.tails && + restored.live.dead==a.live.dead && restored.live.block_pos==a.live.block_pos && + equal(restored.kv[0],a.kv[0]) && equal(restored.kv[1],a.kv[1]),"whole-session A/B/A exactness including spare key"); + check(ss.ple_prev[0]==64 && ss.ple_prev[1]==65,"PLE token window reconstructed"); + check(conversation_checkpoint_restore(a.checkpoints[0],ss,g,err),"restore early running checkpoint"); + std::vector spare(sizes.dead); + cuda_check(cudaMemcpy(spare.data(),main.state.idx_pooled,sizes.dead,cudaMemcpyDeviceToHost)); + check(spare==a.checkpoints[0].dead,"checkpoint rebuilds spare row over a later completed block"); + check(ss.ple_prev[0]==2 && ss.ple_prev[1]==3,"checkpoint PLE token window"); +} +} + +int main() { + int devices=0; + if (cudaGetDeviceCount(&devices)!=cudaSuccess || !devices) return 77; + for (int fmt : {kKvF16,kKvInt8,kKvQ4,3}) for (int mode : {0,1,2}) { + if (fmt==3 && mode!=0) continue; + Fixture f(fmt,mode); + if (fmt==3) { + std::string err; + ConversationKv invalid; + for (int unsupported : {1,2}) { + f.state.kv_mode=unsupported; + check(conversation_kv_bytes(f.state,f.g,9,true)==0,"hybrid streaming/ring rejected without block-mover abort"); + check(!conversation_kv_save(invalid,f.state,f.g,9,true,err),"hybrid streaming/ring capture fails closed"); + } + f.state.kv_mode=0; + } + { + std::string err; + ConversationKv invalid; + for (const int64_t bad : {-1LL, 97LL, (long long) std::numeric_limits::max()}) { + check(!conversation_kv_save(invalid,f.state,f.g,bad,mode!=2,err),"reject invalid save extent before allocation"); + check(!conversation_kv_restore(invalid,f.state,f.g,bad,mode!=2,err),"reject invalid restore extent before copying"); + check(conversation_kv_bytes(f.state,f.g,bad,mode!=2)==0,"invalid extent cannot overflow byte estimate"); + } + } + for (int64_t upto : {0,1,3,4,5,63,64,65,96}) { + const bool index=mode!=2; + std::string err; + f.fill(13); + ConversationKv a,b,restored; + cuda_check(cudaDeviceSynchronize()); + check(conversation_kv_save(a,f.state,f.g,upto,index,err),"save A"); + check(a.bytes()==conversation_kv_bytes(f.state,f.g,upto,index),"size estimate equals snapshot payload"); + f.fill(177); + check(conversation_kv_save(b,f.state,f.g,upto,index,err),"save B"); + check(upto==0 || !equal(a,b),"fixture changes state"); + check(conversation_kv_restore(a,f.state,f.g,upto,index,err),"restore A over B"); + cuda_check(cudaDeviceSynchronize()); + check(conversation_kv_save(restored,f.state,f.g,upto,index,err),"read back restored A"); + check(equal(a,restored),"A/B/A byte-exact K/V and indexer state"); + if (mode==1) { + std::vector table((size_t)f.state.n_pages); + cuda_check(cudaMemcpy(table.data(),f.state.page_table,table.size()*4,cudaMemcpyDeviceToHost)); + check(std::all_of(table.begin(),table.end(),[](int32_t x){return x==-1;}),"stale VRAM pages invalidated"); + } + if (mode==2 && upto>0) { + const auto s=qsa_real_shapes(); + const int64_t b1=(upto+s.page_size-1)/s.page_size,b0=std::max(0,b1-f.state.n_slots); + kv_ring_restore(qsa_attn_pools(f.state),f.state.host,fmt,b0,b1,f.state.n_slots,s,nullptr); + cuda_check(cudaDeviceSynchronize()); + const size_t block=kv_block_bytes(s,fmt)/2; + // Codes and scales are separate in INT8; check code bytes here. + const size_t code_block=fmt==kKvInt8 ? s.page_size*s.n_head_kv*s.head_dim : block; + const void* slots=fmt==kKvQ4?(void*)f.state.k_q4:fmt==kKvInt8?(void*)f.state.k_q:(void*)f.state.k_pool; + std::vector got(code_block); + for (int64_t page=b0;page +#include +#include + +namespace strata::core { +namespace { +using conversation_detail::add; +using conversation_detail::product; + +std::array geometry_key(const ModelGeometry& g) { + return {g.n_embd, g.n_layers, g.qsa_interval, g.ssm_state_size, g.ssm_k_heads, + g.ssm_v_heads, g.ssm_d_conv, g.ssm_conv_channels, g.ssm_value_dim, + g.n_head, g.n_head_kv, g.head_dim, g.idx_q_heads, g.idx_key_dim, + g.hc, g.hc_lr, g.n_expert, g.n_ff}; +} + +bool fail(std::string& error, const char* message) { + error = std::string("conversation snapshot: ") + message; + return false; +} + +bool sync(std::string& error) { + const auto status = cudaDeviceSynchronize(); + if (status == cudaSuccess) return true; + error = std::string("conversation snapshot synchronize: ") + cudaGetErrorString(status); + return false; +} + +bool copy(void* dst, const void* src, size_t bytes, std::string& error) { + if (!bytes) return true; + if (!dst || !src) return fail(error, "missing running-state buffer"); + const auto status = cudaMemcpy(dst, src, bytes, cudaMemcpyDefault); + if (status == cudaSuccess) return true; + error = std::string("conversation snapshot running-state copy: ") + cudaGetErrorString(status); + return false; +} + +bool image_keys(const std::vector& images, size_t tokens) { + int64_t previous = -1; + for (const auto& image : images) { + if (image.start <= previous || image.start < 0 || (uint64_t) image.start >= tokens) return false; + previous = image.start; + } + return true; +} + +bool checkpoint_targets(const SessionState& ss, const ModelGeometry& g, size_t tokens, + ConversationStateSizes& z, std::string& error) { + if (!conversation_state_sizes(g, z, error)) return false; + if (ss.max_cells < 0 || tokens > (uint64_t) ss.max_cells || (z.gdn && !ss.gdn_state) || + (g.n_qsa_layers() && !ss.qsa_states)) return fail(error, "invalid session running-state targets"); + for (int64_t i = 0; i < g.n_qsa_layers(); ++i) { + const auto& st = ss.qsa_states[i]; + const auto block = strata::kernels::qsa_real_shapes().idx_block; + size_t pooled_bytes = 0; + if (!st.idx_tail || !st.idx_dead || !st.idx_block_pos || !st.idx_pooled || + st.max_cells < 0 || tokens > (uint64_t) st.max_cells || + (tokens && tokens / (uint64_t) block >= (uint64_t) std::max(0, st.idx_pooled_rows)) || + !product(pooled_bytes, {tokens / (uint64_t) block + 1, (uint64_t) g.idx_key_dim, sizeof(float)})) + return fail(error, "invalid indexer running-state target"); + } + return true; +} + +bool view_validate(const ConversationView& view, const SessionState& ss, + const ModelGeometry& g, std::string& error) { + ConversationStateSizes z; + if (!checkpoint_targets(ss, g, view.ids.size(), z, error)) return false; + if (view.ids.empty() || !image_keys(view.images, view.ids.size()) || + std::any_of(view.ids.begin(), view.ids.end(), [](int32_t id) { return id < 0; })) + return fail(error, "invalid live token/image metadata"); + for (const auto& c : view.checkpoints) { + if (!c.stage_parts.empty() || c.ids.empty() || c.ids.size() > view.ids.size() || + !std::equal(c.ids.begin(), c.ids.end(), view.ids.begin())) + return fail(error, "checkpoint is not a live token prefix"); + if (!conversation_checkpoint_validate(c, ss, g, error)) return false; + size_t image = 0; + for (const auto& key : view.images) { + if ((uint64_t) key.start >= c.ids.size()) break; + if (image >= c.imgs.size() || !(c.imgs[image++] == key)) + return fail(error, "checkpoint image identity differs"); + } + if (image != c.imgs.size()) return fail(error, "checkpoint image prefix differs"); + } + return true; +} + +bool metadata_bytes(const ConversationCheckpoint& c, size_t& total) { + size_t ids = 0, images = 0; + if (!product(ids, {c.ids.size(), sizeof(int32_t)}) || + !product(images, {c.imgs.size(), sizeof(ConversationImageKey)})) return false; + for (size_t n : {ids, images, c.gdn.size(), c.ple.size(), c.tails.size(), c.dead.size(), c.block_pos.size()}) + if (!add(total, n)) return false; + return true; +} +} // namespace + +bool conversation_state_sizes(const ModelGeometry& g, ConversationStateSizes& z, std::string& error) { + z = {}; + const auto key = geometry_key(g); + for (size_t i = 0; i < key.size(); ++i) + if (key[i] < 0 || (i != 1 && key[i] == 0)) return fail(error, "invalid model geometry"); + size_t recurrence = 0, convolution = 0; + if (!product(recurrence, {(uint64_t) g.ssm_state_size, (uint64_t) g.ssm_v_heads, (uint64_t) g.ssm_state_size}) || + !product(convolution, {(uint64_t) g.ssm_conv_channels, (uint64_t) (g.ssm_d_conv - 1)}) || + !add(recurrence, convolution) || + !product(z.gdn, {(uint64_t) g.n_gdn_layers(), recurrence, sizeof(float)}) || + !product(z.ple, {strata::kernels::NG_HIST, strata::kernels::NG_HC_DIM, sizeof(float)}) || + !product(z.tail, {(uint64_t) (strata::kernels::qsa_real_shapes().idx_block - 1), + (uint64_t) g.idx_key_dim, sizeof(float)}) || + !product(z.dead, {(uint64_t) g.idx_key_dim, sizeof(float)})) + return fail(error, "running-state byte count overflow"); + z.block_pos = sizeof(int32_t); + size_t total = 0; + if (!product(total, {(uint64_t) g.n_qsa_layers(), z.tail}) || + !product(total, {(uint64_t) g.n_qsa_layers(), z.dead}) || + !product(total, {(uint64_t) g.n_qsa_layers(), z.block_pos})) + return fail(error, "indexer byte count overflow"); + return true; +} + +bool conversation_checkpoint_validate(const ConversationCheckpoint& c, const SessionState& ss, + const ModelGeometry& g, std::string& error) { + ConversationStateSizes z; + if (!checkpoint_targets(ss, g, c.ids.size(), z, error)) return false; + const size_t layers = (size_t) g.n_qsa_layers(); + if (c.gdn.size() != z.gdn || c.ple.size() != (ss.ple_hist ? z.ple : 0) || + c.tails.size() != layers * z.tail || c.dead.size() != layers * z.dead || + c.block_pos.size() != layers * z.block_pos || !image_keys(c.imgs, c.ids.size())) + return fail(error, "invalid checkpoint running-state payload"); + return true; +} + +bool conversation_checkpoint_save(ConversationCheckpoint& c, const SessionState& ss, + const ModelGeometry& g, std::string& error) { + ConversationStateSizes z; + if (!checkpoint_targets(ss, g, c.ids.size(), z, error)) return false; + const size_t layers = (size_t) g.n_qsa_layers(); + c.gdn.resize(z.gdn); c.ple.resize(ss.ple_hist ? z.ple : 0); + c.tails.resize(layers * z.tail); c.dead.resize(layers * z.dead); c.block_pos.resize(layers * z.block_pos); + if (!copy(c.gdn.data(), ss.gdn_state, c.gdn.size(), error) || + !copy(c.ple.data(), ss.ple_hist, c.ple.size(), error)) return false; + for (size_t i = 0; i < layers; ++i) { + const auto& st = ss.qsa_states[i]; + if (!copy(c.tails.data() + i * z.tail, st.idx_tail, z.tail, error) || + !copy(c.dead.data() + i * z.dead, st.idx_dead, z.dead, error) || + !copy(c.block_pos.data() + i * z.block_pos, st.idx_block_pos, z.block_pos, error)) return false; + } + return true; +} + +bool conversation_checkpoint_restore(const ConversationCheckpoint& c, SessionState& ss, + const ModelGeometry& g, std::string& error) { + if (!conversation_checkpoint_validate(c, ss, g, error)) return false; + ConversationStateSizes z; + if (!conversation_state_sizes(g, z, error)) return false; + if (!copy(ss.gdn_state, c.gdn.data(), c.gdn.size(), error) || + !copy(ss.ple_hist, c.ple.data(), c.ple.size(), error)) return false; + for (size_t i = 0; i < (size_t) g.n_qsa_layers(); ++i) { + const auto& st = ss.qsa_states[i]; + if (!copy(st.idx_tail, c.tails.data() + i * z.tail, z.tail, error) || + !copy(st.idx_dead, c.dead.data() + i * z.dead, z.dead, error) || + !copy(st.idx_block_pos, c.block_pos.data() + i * z.block_pos, z.block_pos, error)) return false; + if (!c.ids.empty()) { + const size_t row = c.ids.size() / strata::kernels::qsa_real_shapes().idx_block; + if (!copy(st.idx_pooled + row * g.idx_key_dim, c.dead.data() + i * z.dead, z.dead, error)) return false; + } + } + const size_t tokens = c.ids.size(); + ss.ple_prev[0] = tokens >= 2 ? c.ids[tokens - 2] : -1; + ss.ple_prev[1] = tokens >= 1 ? c.ids[tokens - 1] : -1; + return sync(error); +} + +bool conversation_snapshot_bytes(const ConversationView& view, const SessionState& ss, + const ModelGeometry& g, const QsaState& draft, size_t& bytes, std::string& error) { + bytes = 0; + if (!view_validate(view, ss, g, error)) return false; + ConversationStateSizes z; + if (!conversation_state_sizes(g, z, error)) return false; + size_t ids = 0, images = 0, checkpoints = 0, layers = 0, tails = 0, dead = 0, positions = 0; + const auto qsa = (uint64_t) g.n_qsa_layers(); + if (!product(ids, {view.ids.size(), sizeof(int32_t)}) || + !product(images, {view.images.size(), sizeof(ConversationImageKey)}) || + !product(checkpoints, {view.checkpoints.size(), sizeof(ConversationCheckpoint)}) || + !product(layers, {qsa + 1, sizeof(ConversationKv)}) || + !product(tails, {qsa, z.tail}) || !product(dead, {qsa, z.dead}) || + !product(positions, {qsa, z.block_pos})) return fail(error, "snapshot metadata byte count overflow"); + for (size_t n : {ids, images, checkpoints, layers, tails, dead, positions, z.gdn, ss.ple_hist ? z.ple : 0}) + if (!add(bytes, n)) return fail(error, "snapshot byte count overflow"); + for (const auto& c : view.checkpoints) + if (!metadata_bytes(c, bytes)) return fail(error, "checkpoint byte count overflow"); + const int64_t upto = (int64_t) view.ids.size(); // view_validate bounds this by signed max_cells + for (uint64_t i = 0; i <= qsa; ++i) { + const auto& st = i == qsa ? draft : ss.qsa_states[i]; + const size_t n = conversation_kv_bytes(st, g, upto, i != qsa); + if (!n || !add(bytes, n)) return fail(error, "invalid or overflowing K/V byte estimate"); + } + return true; +} + +bool conversation_snapshot_save(SavedConversation& image, const ConversationView& view, + const SessionState& ss, const ModelGeometry& g, + const QsaState& draft, std::string& error) { + size_t estimate = 0; + if (!conversation_snapshot_bytes(view, ss, g, draft, estimate, error) || !sync(error)) return false; + // Build into a new object so a failure cannot publish a partial snapshot. + SavedConversation captured; + captured.geometry = geometry_key(g); + captured.live.ids = view.ids; captured.live.imgs = view.images; + captured.cvec = view.cvec; captured.checkpoints = view.checkpoints; + captured.kv.resize((size_t) g.n_qsa_layers() + 1); + if (!conversation_checkpoint_save(captured.live, ss, g, error)) return false; + const int64_t upto = (int64_t) view.ids.size(); + for (int64_t i = 0; i < g.n_qsa_layers(); ++i) + if (!conversation_kv_save(captured.kv[(size_t) i], ss.qsa_states[i], g, upto, true, error)) return false; + if (!conversation_kv_save(captured.kv.back(), draft, g, upto, false, error)) return false; + image = std::move(captured); + return true; +} + +bool conversation_snapshot_validate(const SavedConversation& image, const SessionState& ss, + const ModelGeometry& g, const QsaState& draft, std::string& error) { + if (!image.live.stage_parts.empty()) return fail(error, "layer-split parking is not supported"); + if (image.geometry != geometry_key(g)) return fail(error, "incompatible runtime geometry"); + const ConversationView view{image.live.ids, image.live.imgs, image.checkpoints, image.cvec}; + if (!view_validate(view, ss, g, error) || !conversation_checkpoint_validate(image.live, ss, g, error)) return false; + if (image.kv.size() != (size_t) g.n_qsa_layers() + 1) return fail(error, "invalid K/V layer count"); + const int64_t upto = (int64_t) image.live.ids.size(); + for (int64_t i = 0; i < g.n_qsa_layers(); ++i) + if (!conversation_kv_validate(image.kv[(size_t) i], ss.qsa_states[i], g, upto, true, error)) return false; + return conversation_kv_validate(image.kv.back(), draft, g, upto, false, error); +} + +ConversationRestore conversation_snapshot_restore(const SavedConversation& image, SessionState& ss, + const ModelGeometry& g, const QsaState& draft, std::string& error) { + if (!conversation_snapshot_validate(image, ss, g, draft, error)) return ConversationRestore::invalid; + if (!sync(error)) return ConversationRestore::transfer_failed; + const int64_t upto = (int64_t) image.live.ids.size(); + for (int64_t i = 0; i < g.n_qsa_layers(); ++i) + if (!conversation_kv_restore(image.kv[(size_t) i], ss.qsa_states[i], g, upto, true, error)) + return ConversationRestore::transfer_failed; + if (!conversation_kv_restore(image.kv.back(), draft, g, upto, false, error) || + !conversation_checkpoint_restore(image.live, ss, g, error)) return ConversationRestore::transfer_failed; + return ConversationRestore::restored; +} +} // namespace strata::core diff --git a/src/core/conversation_validation_test.cpp b/src/core/conversation_validation_test.cpp new file mode 100644 index 00000000..13d9b7c4 --- /dev/null +++ b/src/core/conversation_validation_test.cpp @@ -0,0 +1,182 @@ +// Host-only validation fixtures. CUDA is linked but must never be initialized: +// invalid restores must return before the first CUDA call or destination write. +#include "strata/core/conversation_snapshot.hpp" +#include "strata/kernels/kv_q4.hpp" + +#include +#include +#include +#include +#include + +#if defined(CONVERSATION_TEST_TRANSFERS) +// GNU/ELF link wrapping exercises the actual restore control flow without +// initializing CUDA or deliberately poisoning a real device context. This is +// host-backend fault injection, not a claim of hardware-failure recovery. +namespace { +int copy_calls = 0, sync_calls = 0, fail_copy = 0, fail_sync = 0; +} +extern "C" cudaError_t __wrap_cudaMemcpy(void* dst, const void* src, size_t n, cudaMemcpyKind) { + if (++copy_calls == fail_copy) return cudaErrorInvalidValue; + std::memcpy(dst, src, n); + return cudaSuccess; +} +extern "C" cudaError_t __wrap_cudaDeviceSynchronize() { + return ++sync_calls == fail_sync ? cudaErrorUnknown : cudaSuccess; +} +extern "C" cudaError_t __wrap_cudaGetLastError() { return cudaSuccess; } +#endif + +using namespace strata::core; +namespace { +int checks = 0; +void check(bool ok, const char* label) { + ++checks; + if (!ok) { std::fprintf(stderr, "FAIL: %s\n", label); std::exit(1); } +} +struct Pools { + QsaState st; + std::array, 8> data; + Pools(const ModelGeometry& g, int format) { + st.max_cells = 96; st.n_pages = st.n_slots = 24; st.idx_pooled_rows = 26; + st.kv_int8 = format == 1; st.kv_q4 = format == 2; + const size_t per = format == 2 ? strata::kernels::kv_q4_bytes_per_head((int) g.head_dim) + : g.head_dim * (format == 1 ? 1 : 2); + data[0].resize(96 * g.n_head_kv * per, 0xa5); data[1] = data[0]; + data[2].resize(format == 1 ? 96 * g.n_head_kv * (g.head_dim / 64) * 2 : 0, 0xa5); data[3] = data[2]; + data[4].resize(26 * g.idx_key_dim * 4, 0xa5); + data[5].resize(3 * g.idx_key_dim * 4, 0xa5); + data[6].resize(g.idx_key_dim * 4, 0xa5); data[7].resize(4, 0xa5); + if (format == 2) { st.k_q4 = data[0].data(); st.v_q4 = data[1].data(); } + else if (format == 1) { + st.k_q = (int8_t*) data[0].data(); st.v_q = (int8_t*) data[1].data(); + st.k_scale = (uint16_t*) data[2].data(); st.v_scale = (uint16_t*) data[3].data(); + } else { st.k_pool = (uint16_t*) data[0].data(); st.v_pool = (uint16_t*) data[1].data(); } + st.idx_pooled = (float*) data[4].data(); st.idx_tail = (float*) data[5].data(); + st.idx_dead = (float*) data[6].data(); st.idx_block_pos = (int32_t*) data[7].data(); + } + ConversationKv image(const ModelGeometry& g, bool index) const { + ConversationKv k; + k.format = qsa_kv_format(st); k.cells = 12; k.page_size = 4; + k.heads = g.n_head_kv; k.head_dim = g.head_dim; k.idx_dim = g.idx_key_dim; + k.pooled_rows = index ? 3 : 0; + k.k.resize(data[0].size() / 8, 13); k.v = k.k; + k.k_scale.resize(data[2].size() / 8, 13); k.v_scale = k.k_scale; + k.pooled.resize(k.pooled_rows * g.idx_key_dim * 4, 13); + return k; + } +}; + +void fixture(int format, int experts, bool zero_qsa, bool ple) { + ModelGeometry g; + g.n_layers = zero_qsa ? 3 : 8; g.n_expert = experts; + g.ssm_state_size = 2; g.ssm_v_heads = 2; g.ssm_conv_channels = 8; + g.n_head_kv = 1; g.head_dim = 64; g.idx_key_dim = 8; + std::string error; + ConversationStateSizes z; + check(conversation_state_sizes(g, z, error), "checked canonical/pruned/zero-QSA sizing"); + Pools first(g, format), last(g, format), draft(g, format); + std::array layers{first.st, last.st}; + std::vector gdn(z.gdn, 0xa5), history(ple ? z.ple : 0, 0xa5); + SessionState ss; + ss.max_cells = 96; ss.gdn_state = (float*) gdn.data(); + ss.ple_hist = ple ? (float*) history.data() : nullptr; + ss.qsa_states = zero_qsa ? nullptr : layers.data(); + SavedConversation image; + image.geometry = {g.n_embd,g.n_layers,g.qsa_interval,g.ssm_state_size,g.ssm_k_heads,g.ssm_v_heads, + g.ssm_d_conv,g.ssm_conv_channels,g.ssm_value_dim,g.n_head,g.n_head_kv,g.head_dim, + g.idx_q_heads,g.idx_key_dim,g.hc,g.hc_lr,g.n_expert,g.n_ff}; + auto checkpoint = [&](size_t tokens) { + ConversationCheckpoint c; + c.ids.resize(tokens); + for (size_t i = 0; i < tokens; ++i) c.ids[i] = (int32_t) i + 1; + c.imgs = {{1, 44}}; + c.gdn.resize(z.gdn, 13); c.ple.resize(ple ? z.ple : 0, 13); + c.tails.resize(g.n_qsa_layers() * z.tail, 13); c.dead.resize(g.n_qsa_layers() * z.dead, 13); + c.block_pos.resize(g.n_qsa_layers() * z.block_pos, 13); + return c; + }; + image.live = checkpoint(9); image.checkpoints.push_back(checkpoint(5)); + image.kv.reserve((size_t) g.n_qsa_layers() + 1); + if (!zero_qsa) { image.kv.push_back(first.image(g, true)); image.kv.push_back(last.image(g, true)); } + image.kv.push_back(draft.image(g, false)); + check(conversation_snapshot_validate(image, ss, g, draft.st, error), "complete image validates without CUDA"); + size_t estimate = 0; + check(conversation_snapshot_bytes({image.live.ids,image.live.imgs,image.checkpoints,true},ss,g,draft.st,estimate,error), + "capture estimate works without CUDA"); + check(estimate == image.bytes(), "estimate covers checkpoint/indexer/spare payloads"); + auto unchanged = [&] { + auto pristine = [](const auto& bytes) { return std::all_of(bytes.begin(),bytes.end(),[](uint8_t b){return b==0xa5;}); }; + if (!pristine(gdn) || !pristine(history) || ss.ple_prev[0] != -1 || ss.ple_prev[1] != -1) return false; + for (const auto* p : {&first,&last,&draft}) for (const auto& bytes : p->data) if (!pristine(bytes)) return false; + return true; + }; + auto reject = [&](const std::function& mutate, const char* label) { + auto bad = image; mutate(bad); + check(conversation_snapshot_restore(bad,ss,g,draft.st,error) == ConversationRestore::invalid,label); + check(unchanged(), "invalid restore did not touch any layer or running-state buffer"); + }; + reject([](auto& s){s.kv.back().k.pop_back();}, "late draft corruption rejected before first layer write"); + reject([](auto& s){s.geometry[16] = 128;}, "different expert geometry rejected"); + reject([](auto& s){s.live.stage_parts.emplace_back();}, "layer-split live state rejected before writes"); + reject([](auto& s){s.checkpoints[0].stage_parts.emplace_back();}, "layer-split checkpoint rejected before writes"); + reject([](auto& s){s.kv.pop_back();}, "missing KV layer rejected"); + reject([](auto& s){s.live.gdn.pop_back();}, "bad live recurrence rejected"); + reject([](auto& s){s.checkpoints.back().gdn.pop_back();}, "bad retained checkpoint rejected"); + reject([](auto& s){s.checkpoints.back().ids[0] = 99;}, "foreign checkpoint prefix rejected"); + reject([](auto& s){s.checkpoints.back().imgs[0].hash++;}, "foreign checkpoint image rejected"); + reject([](auto& s){s.live.imgs[0].start = -1;}, "negative image position rejected"); + reject([](auto& s){s.live.ids[0] = -1;}, "negative live token rejected"); + reject([](auto& s){s.live.ple.push_back(0);}, "PLE size/enabled mismatch rejected"); + reject([](auto& s){s.live.tails.push_back(0);}, "tail size/zero-QSA mismatch rejected"); + if (!zero_qsa) { + reject([](auto& s){s.kv[1].pooled.pop_back();}, "late indexer spare row corruption rejected"); + reject([](auto& s){s.live.dead.pop_back();}, "missing indexer spare key rejected"); + reject([](auto& s){s.live.block_pos.pop_back();}, "missing indexer metadata rejected"); + ss.qsa_states = nullptr; + check(!conversation_snapshot_validate(image,ss,g,draft.st,error), "missing QSA targets rejected"); + ss.qsa_states = layers.data(); + } + auto bad_geometry = g; bad_geometry.ssm_state_size = std::numeric_limits::max(); + check(!conversation_state_sizes(bad_geometry,z,error), "running-state arithmetic overflow rejected"); + bad_geometry = g; bad_geometry.qsa_interval = 0; + check(!conversation_state_sizes(bad_geometry,z,error), "zero layer interval rejected before division"); + bad_geometry = g; bad_geometry.n_head_kv = std::numeric_limits::max(); + check(conversation_kv_bytes(draft.st,bad_geometry,9,false)==0, "KV byte overflow rejected"); +#if defined(CONVERSATION_TEST_TRANSFERS) + auto reset = [&] { + for (auto* p : {&first,&last,&draft}) for (auto& bytes : p->data) std::fill(bytes.begin(),bytes.end(),0xa5); + std::fill(gdn.begin(),gdn.end(),0xa5); std::fill(history.begin(),history.end(),0xa5); + ss.ple_prev[0] = ss.ple_prev[1] = -1; + copy_calls = sync_calls = fail_copy = fail_sync = 0; + }; + reset(); fail_sync = 1; + check(conversation_snapshot_restore(image,ss,g,draft.st,error)==ConversationRestore::transfer_failed, + "pre-transfer CUDA synchronization failure is fatal"); + check(copy_calls==0 && unchanged(), "pre-sync failure did not mutate state"); + reset(); fail_copy = 1; + check(conversation_snapshot_restore(image,ss,g,draft.st,error)==ConversationRestore::transfer_failed, + "first CUDA transfer failure is fatal"); + check(unchanged(), "first-copy failure did not mutate state"); + reset(); fail_copy = 2; + check(conversation_snapshot_restore(image,ss,g,draft.st,error)==ConversationRestore::transfer_failed, + "partial CUDA transfer failure is fatal, not an invalid-image fallback"); + check(!unchanged(), "fault fixture genuinely produced partial state"); + reset(); fail_sync = 2; + check(conversation_snapshot_restore(image,ss,g,draft.st,error)==ConversationRestore::transfer_failed, + "post-transfer CUDA synchronization failure is fatal"); + check(copy_calls>0 && !unchanged(), "post-sync failure occurred after state writes"); + reset(); + check(conversation_snapshot_restore(image,ss,g,draft.st,error)==ConversationRestore::restored, + "injected host transfer backend completes a valid restore"); + check(gdn==image.live.gdn && history==image.live.ple && ss.ple_prev[0]==8 && ss.ple_prev[1]==9, + "successful restore publishes correct running state and PLE window"); +#endif +} +} + +int main() { + for (int format : {0,1,2}) for (int experts : {256,512}) + for (bool zero_qsa : {false,true}) for (bool ple : {false,true}) fixture(format,experts,zero_qsa,ple); + std::printf("conversation_validation_test: %d host-only checks passed\n", checks); +} diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 60700870..a2bb0d13 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -15,6 +15,8 @@ // (`phase-2-correct-engine.md:5-9`). What it is FOR is the honest tok/s figure and the logit dump. #include "strata/core/expert_cache.hpp" +#include "strata/core/conversation_snapshot.hpp" +#include "strata/core/conversation_memory.hpp" #include "strata/core/expert_source.hpp" #include "strata/core/remote_experts.hpp" #include "strata/core/on_device.hpp" @@ -75,6 +77,8 @@ #include #include #include +#include +#include #include #include #include @@ -282,6 +286,9 @@ struct Options { /// prompt again, the v0.1.2 behaviour). One is the GDN recurrence of the 36 layers, the QSA indexer tails and /// the PLE history (~118 MB of host RAM); the KV cache itself is positional and stays where it is. int prompt_cache = 6; + int64_t conversation_cache_mib = 0; // opt-in host RAM for independent conversations + int conversation_cache_slots = 4; + int64_t conversation_cache_min_free_mib = 2560; /// --serve: also keep a checkpoint every N freshly read prompt tokens (0 = only at the last turn boundary) int64_t prompt_cache_every = 16384; /// --serve: a prompt read from token 0 is also checkpointed at its first turn boundary - the end of the system @@ -375,6 +382,9 @@ void usage() { " --vision --serve takes images too (GENI requests; embeddings from strata-vision)\n" " --prompt-cache N --serve: keep N conversation checkpoints between requests (default 6, ~118 MB\n" " of RAM each; 0 = read every prompt from the start)\n" + " --conversation-cache-mib N --serve: RAM budget for parked conversations (default 0 = off)\n" + " --conversation-cache-slots N --serve: at most N parked conversations (default 4)\n" + " --conversation-cache-min-free-mib N --serve: physical RAM floor when parking (default 2560)\n" " --prompt-cache-every N --serve: also checkpoint every N fresh prompt tokens (default 16384, 0 = off)\n" " --turn-token ID --serve: the token that opens a chat turn (default 248045, <|im_start|>)\n" " --short-read N --serve: read at most N fresh text tokens through the decode windows instead\n" @@ -708,19 +718,8 @@ int argmax(const std::vector& v) { // back rejected drafts. // A checkpoint is only valid while the positional cells below it still hold ITS tokens, so the serve loop keeps // just the checkpoints that are prefixes of the tokens the session holds now. -struct ImgKey { - int64_t start = 0; ///< the image's first <|image_pad|> position - uint64_t hash = 0; ///< its embeddings and grid: the pad tokens alone are the same for every picture - bool operator==(const ImgKey& o) const { return start == o.start && hash == o.hash; } -}; - -struct ConvCheckpoint { - std::vector ids; ///< the tokens this state has consumed - std::vector imgs; ///< the images among them - std::vector gdn, ple, tails; - uint64_t used = 0; ///< last-use stamp for the retention policy (conv_cache.hpp) - std::vector stage_parts; ///< a layer split's later stages: their sessions' running state -}; +using ImgKey = strata::core::ConversationImageKey; +using ConvCheckpoint = strata::core::ConversationCheckpoint; uint64_t fnv1a(const void* data, size_t n, uint64_t h = 1469598103934665603ull) { const uint8_t* p = (const uint8_t*) data; @@ -728,52 +727,25 @@ uint64_t fnv1a(const void* data, size_t n, uint64_t h = 1469598103934665603ull) return h; } -struct ConvStateSizes { - size_t gdn = 0, ple = 0, tail = 0; -}; +using ConvStateSizes = strata::core::ConversationStateSizes; ConvStateSizes conv_state_sizes(const strata::core::ModelGeometry& g) { ConvStateSizes z; - z.gdn = (size_t) g.n_gdn_layers() * - ((size_t) g.ssm_state_size * (size_t) g.ssm_v_heads * (size_t) g.ssm_state_size + - (size_t) g.ssm_conv_channels * (size_t) (g.ssm_d_conv - 1)) * sizeof(float); - z.ple = (size_t) strata::kernels::NG_HIST * (size_t) strata::kernels::NG_HC_DIM * sizeof(float); - z.tail = (size_t) (strata::kernels::qsa_real_shapes().idx_block - 1) * (size_t) g.idx_key_dim * sizeof(float); + std::string error; + strata::core::conversation_state_sizes(g, z, error); // geometry has already passed engine validation return z; } /// Copies the running state out. The caller has synchronized the device. bool checkpoint_save(ConvCheckpoint& c, const strata::core::SessionState& ss, const strata::core::ModelGeometry& g) { - const ConvStateSizes z = conv_state_sizes(g); - c.gdn.resize(z.gdn); - c.ple.resize(ss.ple_hist != nullptr ? z.ple : 0); - c.tails.resize(z.tail * (size_t) g.n_qsa_layers()); - if (cudaMemcpy(c.gdn.data(), ss.gdn_state, z.gdn, cudaMemcpyDeviceToHost) != cudaSuccess) return false; - if (!c.ple.empty() && cudaMemcpy(c.ple.data(), ss.ple_hist, z.ple, cudaMemcpyDeviceToHost) != cudaSuccess) - return false; - for (int64_t i = 0; i < g.n_qsa_layers(); ++i) - if (cudaMemcpy(c.tails.data() + (size_t) i * z.tail, ss.qsa_states[i].idx_tail, z.tail, cudaMemcpyDeviceToHost) != - cudaSuccess) - return false; - return true; + std::string error; + return strata::core::conversation_checkpoint_save(c, ss, g, error); } /// Puts a checkpoint's running state back; the positional cells below it are the caller's to guarantee. bool checkpoint_restore(const ConvCheckpoint& c, strata::core::SessionState& ss, const strata::core::ModelGeometry& g) { - const ConvStateSizes z = conv_state_sizes(g); - if (c.gdn.size() != z.gdn || c.tails.size() != z.tail * (size_t) g.n_qsa_layers()) return false; - if (cudaMemcpy(ss.gdn_state, c.gdn.data(), z.gdn, cudaMemcpyHostToDevice) != cudaSuccess) return false; - if (!c.ple.empty() && cudaMemcpy(ss.ple_hist, c.ple.data(), z.ple, cudaMemcpyHostToDevice) != cudaSuccess) - return false; - for (int64_t i = 0; i < g.n_qsa_layers(); ++i) - if (cudaMemcpy(ss.qsa_states[i].idx_tail, c.tails.data() + (size_t) i * z.tail, z.tail, cudaMemcpyHostToDevice) != - cudaSuccess) - return false; - // the PLE's token window is the last two tokens, OLDEST FIRST, -1 where there is none (as session_zero leaves it) - const size_t L = c.ids.size(); - ss.ple_prev[0] = L >= 2 ? c.ids[L - 2] : -1; - ss.ple_prev[1] = L >= 1 ? c.ids[L - 1] : -1; - return cudaDeviceSynchronize() == cudaSuccess; + std::string error; + return strata::core::conversation_checkpoint_restore(c, ss, g, error); } // --control-vector-scaled: llama.cpp's `common_control_vector_load` (every file's `direction.` times its scale, @@ -1020,6 +992,20 @@ int main(int argc, char** argv) { else if (a == "--serve") o.serve = true; else if (a == "--vision") o.vision = true; else if (a == "--prompt-cache") o.prompt_cache = std::max(0, std::atoi(next("--prompt-cache"))); + else if (a == "--conversation-cache-mib" || a == "--conversation-cache-slots" || + a == "--conversation-cache-min-free-mib") { + const std::string value = next(a.c_str()); + int64_t parsed = 0; + const auto result = std::from_chars(value.data(), value.data() + value.size(), parsed); + const int64_t limit = a == "--conversation-cache-slots" ? INT32_MAX : INT64_MAX / (1024 * 1024); + if (result.ec != std::errc{} || result.ptr != value.data() + value.size() || parsed < 0 || parsed > limit) { + std::fprintf(stderr, "%s needs a nonnegative integer within range\n", a.c_str()); + return 2; + } + if (a == "--conversation-cache-mib") o.conversation_cache_mib = parsed; + else if (a == "--conversation-cache-min-free-mib") o.conversation_cache_min_free_mib = parsed; + else o.conversation_cache_slots = (int) parsed; + } else if (a == "--prompt-cache-every") o.prompt_cache_every = std::max(0LL, std::atoll(next("--prompt-cache-every"))); else if (a == "--prompt-cache-root") o.prompt_cache_root = std::max(0LL, std::atoll(next("--prompt-cache-root"))); else if (a == "--turn-token") o.turn_token = std::atoll(next("--turn-token")); @@ -1089,6 +1075,13 @@ int main(int argc, char** argv) { return 2; } } + if (o.serve && o.conversation_cache_mib > 0 && (o.prompt_cache == 0 || o.conversation_cache_slots == 0)) + std::fprintf(stderr, "strata serve: warning: conversation caching is disabled by %s\n", + o.prompt_cache == 0 ? "--prompt-cache 0" : "--conversation-cache-slots 0"); + if (o.conversation_cache_mib > 0 && o.conversation_cache_slots > 0 && o.prompt_cache > 0 && !o.layer_split.empty()) { + std::fprintf(stderr, "strata serve: conversation parking does not yet support --layer-split; disable parking with --conversation-cache-mib 0\n"); + return 2; + } // Layer split (multi-GPU): the later stages run layers [K_i, K_i+1) on their own GPUs (--split-device, default // the next visible ones); "auto" places the K from each GPU's free VRAM once the weights are in (below). Across // GPUs, not yet: KV streaming, images, control vectors, the helper caches (--expert-cache-remote), and lending @@ -3263,6 +3256,50 @@ int main(int argc, char** argv) { std::vector checks; uint64_t check_clock = 0; // the checkpoints' LRU clock; creation and every use advance it bool cvec_cached = true; // the control vector's state the live session and the checkpoints were read with + strata::core::ConversationCache conversations( + o.prompt_cache > 0 ? (size_t) o.conversation_cache_mib * 1024 * 1024 : 0, + (size_t) o.conversation_cache_slots); + // Save only on a switch/rewind, not on each continuing request. No graph + // addresses change: all parked images live in ordinary host vectors. + auto park_current = [&](size_t held) -> bool { + if (!conversations.enabled() || !live_ok || live.empty()) return true; + const strata::core::ConversationView view{live, live_imgs, checks, cvec_cached}; + size_t estimate = 0; + if (!strata::core::conversation_snapshot_bytes(view, ss, g, mtp.kv_state(), estimate, err)) { + std::fprintf(stderr, "strata serve: conversation cache: skip parking (%s)\n", err.c_str()); + return true; + } + if (!conversations.make_room(estimate, held)) { + std::fprintf(stderr, "strata serve: conversation cache: skip parking (snapshot %zu MiB exceeds available budget)\n", + estimate >> 20); + return true; + } + const auto t0 = Clock::now(); + try { + const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib * 1024 * 1024; + if (!strata::core::conversation_memory_admit(strata::core::conversation_available_memory(), estimate, floor)) { + std::fprintf(stderr, "strata serve: conversation cache: skip parking (physical RAM admission; need %zu MiB plus %lld MiB floor, or telemetry unavailable)\n", + estimate >> 20, (long long) o.conversation_cache_min_free_mib); + return true; + } + strata::core::SavedConversation image; + if (!strata::core::conversation_snapshot_save(image, view, ss, g, mtp.kv_state(), err)) return false; + if (!strata::core::conversation_memory_admit(strata::core::conversation_available_memory(), 0, floor)) { + std::fprintf(stderr, "strata serve: conversation cache: skip parking (physical RAM floor after capture, or telemetry unavailable)\n"); + return true; + } + const bool stored = conversations.put(std::move(image), held); + std::fprintf(stderr, "strata serve: conversation cache: %s %zu tokens in %.1f ms; parked=%zu bytes=%zu evictions=%zu\n", + stored ? "parked" : "skipped", live.size(), + std::chrono::duration(Clock::now() - t0).count(), + conversations.size(), conversations.bytes(), conversations.evictions()); + } catch (const std::bad_alloc&) { + // The active state has not been touched. Continue with normal + // prompt processing rather than killing a serving process. + std::fprintf(stderr, "strata serve: conversation cache: allocation failed; skip parking\n"); + } + return true; + }; int64_t pp_total = 0, pp_from = 0, pp_next_check = 0; Clock::time_point pp_t0 = Clock::now(); auto imgs_below = [&](const std::vector& all, int64_t L) { @@ -3291,12 +3328,15 @@ int main(int argc, char** argv) { c.gdn = std::move((*parts)[0].gdn); c.ple = std::move((*parts)[0].ple); c.tails = std::move((*parts)[0].tails); + c.dead = std::move((*parts)[0].dead); + c.block_pos = std::move((*parts)[0].block_pos); for (size_t i = 1; i < parts->size(); ++i) c.stage_parts.push_back(std::move((*parts)[i])); } else { if (cudaDeviceSynchronize() != cudaSuccess || !checkpoint_save(c, ss, g)) return false; for (auto& st : stages) { // a layer split's later stages: their sessions' part const strata::core::OnDevice on(st->dev); ConvCheckpoint part; + part.ids = c.ids; if (cudaDeviceSynchronize() != cudaSuccess || !checkpoint_save(part, st->ss, g)) return false; c.stage_parts.push_back(std::move(part)); } @@ -3358,6 +3398,7 @@ int main(int argc, char** argv) { if (o.prompt_cache <= 0 || o.prompt_cache_every <= 0 || done < part_next[i]) return true; part_next[i] = done + o.prompt_cache_every; ConvCheckpoint part; // this stage's state at `done` (its stream is synchronized) + part.ids.assign(cur.begin(), cur.begin() + done); if (!checkpoint_save(part, stage_ss, g)) { e = "saving a checkpoint part failed"; return false; } std::lock_guard lk(part_mu); auto& v = part_at[done]; @@ -3542,14 +3583,16 @@ int main(int argc, char** argv) { cudaMemGetInfo(&free_b, &total_b); std::printf("INFO context=%lld kv=%s kv_resident=%lld expert_slots=%lld expert_cache_mib=%lld spec=%d " "mtp_max=%d lookup=%d vram_free_mib=%lld cvec=%s arena_mib=%lld pool_workers=%d pcie_frac=%.2f " - "spec_min_p=%.2f engine=" STRATA_VERSION "\n", + "spec_min_p=%.2f conversation_cache_mib=%lld conversation_cache_slots=%d " + "conversation_cache_min_free_mib=%lld engine=" STRATA_VERSION "\n", (long long) o.max_context, o.kv.c_str(), (long long) (g.n_qsa_layers() > 0 && ss.qsa_states[0].kv_mode == 1 ? ss.qsa_states[0].n_slots * 4 : 0), (long long) xcache.slots(), (long long) (xcache.bytes() >> 20), o.spec, o.mtp_max_t, o.suffix_draft, (long long) (free_b >> 20), cvec_summary.c_str(), (long long) (strata::kernels::cpu::expert_layout().total >> 20), pool.workers(), o.pcie_frac, - o.spec_min_p); + o.spec_min_p, (long long) o.conversation_cache_mib, o.conversation_cache_slots, + (long long) o.conversation_cache_min_free_mib); } // issue #29: a request whose heartbeat (tokens, prompt chunks, verify windows) stops for this long is stuck on // a flag nobody will raise - end the engine with where it was, so the server starts it again instead of the @@ -3784,20 +3827,10 @@ int main(int argc, char** argv) { if ((int32_t) ids[(size_t) i] != pre[(size_t) i]) return false; return imgs_below(req_imgs, L) == pre_imgs; }; - // the control vector for this request. The live session and the checkpoints were read one way, so a - // switch reads the prompt again from the start - if (strata::kernels::cvec().loaded()) { - const bool want = req_cvec != 0; - if (want != cvec_cached) { - live_ok = false; - checks.clear(); - cvec_cached = want; - } - strata::kernels::cvec_set_enabled(want); - } + const bool want_cvec = strata::kernels::cvec().loaded() ? req_cvec != 0 : true; int64_t resume = 0; bool from_live = false; - if (o.prompt_cache > 0) { + if (o.prompt_cache > 0 && want_cvec == cvec_cached) { if (live_ok && starts_with(live, live_imgs)) { resume = (int64_t) live.size(); from_live = true; } for (const ConvCheckpoint& c : checks) if ((int64_t) c.ids.size() > resume && starts_with(c.ids, c.imgs)) { @@ -3805,6 +3838,48 @@ int main(int argc, char** argv) { from_live = false; } } + const auto parked = conversations.best(ids, req_imgs, want_cvec); + std::optional incoming; + if (parked.tokens > resume) incoming.emplace(conversations.take(parked.index)); + // Reject the entire image before parking/overwriting the outgoing + // state. Invalid entries can safely fall back to its existing prefix. + if (incoming && !strata::core::conversation_snapshot_validate(*incoming, ss, g, mtp.kv_state(), err)) { + std::fprintf(stderr, "strata serve: conversation cache: discard invalid snapshot (%s)\n", err.c_str()); + incoming.reset(); + } + // Preserve the outgoing branch before any checkpoint rewind, reset, + // or incoming restore overwrites the positional state it requires. + if ((!from_live || incoming) && !park_current(incoming ? incoming->bytes() : 0)) { + std::printf("ERR %s\n", err.c_str()); + return 1; + } + if (incoming) { + const auto t0 = Clock::now(); + if (strata::core::conversation_snapshot_restore(*incoming, ss, g, mtp.kv_state(), err) != + strata::core::ConversationRestore::restored) { + // Already prevalidated above: a failure here is fatal, never + // permission to decode from a partially restored session. + std::printf("ERR restoring parked conversation: %s\n", err.c_str()); + return 1; + } + live = std::move(incoming->live.ids); + live_imgs = std::move(incoming->live.imgs); + checks = std::move(incoming->checkpoints); + cvec_cached = incoming->cvec; + resume = parked.tokens; + from_live = parked.live; + incoming.reset(); // release the transfer image before prompt processing + std::fprintf(stderr, "strata serve: conversation cache: restored %lld tokens (%s) in %.1f ms; parked=%zu bytes=%zu\n", + (long long) resume, from_live ? "live" : "checkpoint", + std::chrono::duration(Clock::now() - t0).count(), + conversations.size(), conversations.bytes()); + } + if (want_cvec != cvec_cached) { + live_ok = false; + checks.clear(); + cvec_cached = want_cvec; + } + if (strata::kernels::cvec().loaded()) strata::kernels::cvec_set_enabled(want_cvec); // this request rewrites every cell from `resume` on, so a checkpoint past it (or not on this prompt's // path) no longer has its cells; the ones kept are prefixes of both the old tokens and the new checks.erase(std::remove_if(checks.begin(), checks.end(), [&](const ConvCheckpoint& c) { @@ -4257,7 +4332,7 @@ int main(int argc, char** argv) { }; const ConvStateSizes z = conv_state_sizes(g); uint64_t h_gdn = hash_dev(ss.gdn_state, z.gdn, 1469598103934665603ull); - if (std::getenv("STRATA_STATE_HASH_GDN") != nullptr) { // per GDN layer: which one differs first + if (std::getenv("STRATA_STATE_HASH_GDN") != nullptr && g.n_gdn_layers() > 0) { // per GDN layer: which one differs first const size_t per = z.gdn / (size_t) g.n_gdn_layers(); std::string s; char b[8]; @@ -4267,8 +4342,9 @@ int main(int argc, char** argv) { } std::fprintf(stderr, "strata serve: STATE_HASH_GDN %s\n", s.c_str()); } - uint64_t h_ple = hash_dev(ss.ple_hist, z.ple, 1469598103934665603ull); + uint64_t h_ple = hash_dev(ss.ple_hist, ss.ple_hist ? z.ple : 0, 1469598103934665603ull); uint64_t h_tail = 1469598103934665603ull, h_pool = h_tail, h_kv = h_tail, h_stale = h_tail; + uint64_t h_dead = h_tail; const int64_t kvb = qs.head_dim, scb = (qs.head_dim / 64) * 2; // a state's K/V arrays and their bytes per (cell, head) row: the host copy when it has one auto kv_arrays = [&](const strata::core::QsaState& st) { @@ -4281,18 +4357,22 @@ int main(int argc, char** argv) { const int64_t q4b = (int64_t) strata::kernels::kv_q4_bytes_per_head((int) qs.head_dim); a = {{h ? st.host.k_q : st.k_q, kvb}, {h ? st.host.v_q4 : st.v_q4, q4b}, {h ? st.host.k_scale : st.k_scale, scb}}; - } else { + } else if (st.kv_int8) { a = {{h ? st.host.k_q : st.k_q, kvb}, {h ? st.host.v_q : st.v_q, kvb}, {h ? st.host.k_scale : st.k_scale, scb}, {h ? st.host.v_scale : st.v_scale, scb}}; + } else { + a = {{h ? st.host.k_pool : st.k_pool, qs.head_dim * 2}, + {h ? st.host.v_pool : st.v_pool, qs.head_dim * 2}}; } return a; }; const int64_t end_cell = std::min(((L + qs.page_size - 1) / qs.page_size) * qs.page_size, - ss.qsa_states[0].max_cells); + ss.max_cells); for (int64_t i = 0; i < g.n_qsa_layers(); ++i) { const strata::core::QsaState& st = ss.qsa_states[i]; h_tail = hash_dev(st.idx_tail, z.tail, h_tail); - h_pool = hash_dev(st.idx_pooled, (size_t) (L / qs.idx_block) * qs.idx_dim * 4, h_pool); + h_dead = hash_dev(st.idx_dead, z.dead, h_dead); + h_pool = hash_dev(st.idx_pooled, (size_t) (L > 0 ? L / qs.idx_block + 1 : 0) * qs.idx_dim * 4, h_pool); // KV streaming: the host copy is the identity layout and holds every cell for (const auto& [pool, w] : kv_arrays(st)) { h_kv = hash_cells(pool, w, 0, L, h_kv); @@ -4305,10 +4385,10 @@ int main(int argc, char** argv) { for (const auto& [pool, w] : kv_arrays(ms)) if (pool != nullptr) h_mtp = hash_cells(pool, w, 0, mL, h_mtp); std::fprintf(stderr, "strata serve: STATE_HASH L=%lld gdn=%016llx ple=%016llx tail=%016llx pooled=%016llx " - "kv=%016llx mtp=%016llx stale=%016llx ple_prev=%d,%d\n", (long long) L, + "kv=%016llx mtp=%016llx stale=%016llx dead=%016llx ple_prev=%d,%d\n", (long long) L, (unsigned long long) h_gdn, (unsigned long long) h_ple, (unsigned long long) h_tail, (unsigned long long) h_pool, (unsigned long long) h_kv, (unsigned long long) h_mtp, - (unsigned long long) h_stale, ss.ple_prev[0], ss.ple_prev[1]); + (unsigned long long) h_stale, (unsigned long long) h_dead, ss.ple_prev[0], ss.ple_prev[1]); } const int64_t req_hits = drive.d.cache_hits - decode_hits0; const int64_t req_look = (drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused) - decode_look0; diff --git a/tools/conversation_cache_http_smoke.py b/tools/conversation_cache_http_smoke.py new file mode 100644 index 00000000..bd1df98c --- /dev/null +++ b/tools/conversation_cache_http_smoke.py @@ -0,0 +1,137 @@ +"""Destructive-to-cache HTTP smoke test for an EXCLUSIVE, idle Strata test server. + +Sends synthetic conversations, deliberately evicts cached conversations, and +disconnects a streaming response. Never run while other clients are using it. +Dry-run by default; --run explicitly enables network traffic. Does not restart +or reconfigure the server. Use the private-engine parity gate for state hashes. +""" +import argparse +import json +from pathlib import Path +import time +import urllib.request +import uuid + + +def require(condition, message): + if not condition: + raise RuntimeError(message) + + +class Client: + def __init__(self, url): + self.url = url.rstrip('/') + + def metrics(self): + with urllib.request.urlopen(self.url + '/metrics', timeout=10) as response: + return json.load(response) + + def request(self, model, content, stream=False, count=8): + body = {'model': model, 'messages': [{'role': 'user', 'content': content}], + 'max_tokens': count, 'temperature': 0, 'stream': stream, + 'chat_template_kwargs': {'enable_thinking': False}} + request = urllib.request.Request(self.url + '/v1/chat/completions', + data=json.dumps(body).encode(), + headers={'Content-Type': 'application/json'}) + return urllib.request.urlopen(request, timeout=120) + + +def run(client): + initial = client.metrics() + require(initial['live']['state'] == 'idle' and initial['live']['queued'] == 0, 'server is busy') + info = initial['engine'] + slots = info.get('conversation_cache_slots', 0) + require(info.get('conversation_cache_mib', 0) > 0 and 1 <= slots <= 16, + 'requires an enabled cache with 1–16 slots') + require(not info.get('api_key'), 'use an unauthenticated private test endpoint') + marker = 'cache-smoke-' + uuid.uuid4().hex + records = [] + + def before(): + metrics = client.metrics() + require(metrics['live']['state'] == 'idle' and metrics['live']['queued'] == 0, + 'concurrent client detected') + return max((r['time'] for r in metrics['requests']), default=0) + + def after(stamp, label): + for _ in range(50): + metrics = client.metrics() + if metrics['live']['state'] == 'idle': + break + time.sleep(.2) + require(metrics['live']['state'] == 'idle', 'request did not drain') + fresh = [r for r in metrics['requests'] if r['time'] > stamp] + require(len(fresh) == 1 and metrics['live']['queued'] == 0, + 'missing request evidence or concurrent traffic') + record = {'name': label, **fresh[0]} + records.append(record) + return record + + def prompt(label): + return marker + ' ' + label + '\n' + '\n'.join( + f'Record {i}: blue square, green triangle, red circle.' for i in range(128) + ) + '\nName one color. Answer with one word.' + + def ask(label, content): + stamp = before() + with client.request(info['model'], content) as response: + result = json.load(response) + require(bool(result.get('choices')), 'missing completion') + record = after(stamp, label) + require(record['finish'] in ('length', 'stop'), 'request did not finish normally') + return result['choices'][0]['message'], record + + a, _ = ask('A', prompt('A')) + ask('B', prompt('B')) + restored, record = ask('A-restored', prompt('A')) + require(record['reused'] > 0 and a == restored, 'A/B/A reuse or output mismatch') + for i in range(slots + 1): + ask(f'evict-{i}', prompt(f'evict-{i}')) + _, record = ask('A-evicted', prompt('A')) + require(record['reused'] == 0, 'old A survived slot eviction') + + text = marker + ' cancel: ' + 'blue green red. ' * 256 + text += '\nCount from 1 to 1000, one number per line. Do not summarize.' + stamp = before() + with client.request(info['model'], text, stream=True, count=4096) as response: + for line in response: + if not line.startswith(b'data: ') or line.strip() == b'data: [DONE]': + continue + choices = json.loads(line[6:]).get('choices', []) + if choices and choices[0].get('delta', {}).get('content'): + break + else: + raise RuntimeError('no streamed content to cancel') + record = after(stamp, 'cancelled') + require(record['finish'] in ('disconnect', 'cancel') and 0 < record['output_tokens'] < 4096, + 'stream cancellation not observed') + ask('after-cancel-B', marker + ' Unrelated B: say hello.') + _, record = ask('cancelled-A-restored', text) + require(record['reused'] > 0, 'cancelled conversation was not restored') + return {'engine_info': info, 'records': records} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--url', default='http://127.0.0.1:11434') + parser.add_argument('--output', type=Path, required=True, help='new results file; existing paths refused') + parser.add_argument('--run', action='store_true') + args = parser.parse_args() + if not args.run: + print('Dry run: HTTP A/B/A, slot eviction, cancellation and recovery. No network traffic.') + return + # Refuse accidental overwrites before generating traffic. + with args.output.open('x', encoding='utf-8') as output: + try: + result = run(Client(args.url)) + except Exception as error: + json.dump({'passed': False, 'error': str(error)}, output, indent=2) + output.write('\n') + raise + json.dump({'passed': True, **result}, output, indent=2) + output.write('\n') + print(f'PASS: HTTP reuse, slot eviction, cancellation/recovery. Results: {args.output}') + + +if __name__ == '__main__': + main() diff --git a/tools/conversation_cache_isolation.py b/tools/conversation_cache_isolation.py new file mode 100644 index 00000000..8cfa5479 --- /dev/null +++ b/tools/conversation_cache_isolation.py @@ -0,0 +1,156 @@ +"""Private-engine image/steering cache isolation gate; dry-run unless --run. + +Synthetic image embeddings exercise GENI, image identity and M-RoPE without an +image encoder. Synthetic nonzero control vectors exercise actual add/project +kernels. This validates cache correctness, not vision or steering quality. +""" +import argparse +import json +from pathlib import Path +import re +import struct +import sys +import threading + +ROOT = Path(__file__).resolve().parents[1] +sys.path[:0] = [str(ROOT), str(ROOT / 'tools')] +from conversation_cache_parity import STATE_KEYS, engine_args, require +from gguf_reader import GGUFFile +from gguf_writer import GGUFWriter +from serve.server import StrataEngine, child_env +from serve.frontend import ChatTemplate +import strata_tokenizer as ST +import numpy as np + + +def fixtures(output, width): + vector = np.sin(np.arange(width, dtype=np.float32) * .17) + vector *= .25 / np.linalg.norm(vector) + writer = GGUFWriter() + writer.add('general.architecture', 'controlvector') + writer.add('controlvector.model_hint', 'qwen4exp') + writer.add_f32('direction.1', vector) + writer.add_f32('direction.20', vector) + writer.write(output / 'control.gguf') + rows = np.sin(np.arange(4 * width, dtype=np.float32) * .013).reshape(4, width) * .2 + for name, nx, ny, values in [('image-a', 2, 2, rows), ('image-b', 2, 2, -rows), + ('image-grid', 1, 4, rows)]: + with (output / (name + '.sve')).open('xb') as f: + f.write(struct.pack('<5i', 0x31455653, 4, nx, ny, width)) + f.write(values.astype(' 0 for i in hits), 'compatible parked state was not restored') + changed = 3 if scenario == 'image' else 1 + require(baseline[0]['state'] != baseline[changed]['state'], 'fixture did not change actual model state') + if scenario == 'image': + require(baseline[0]['state'] != baseline[5]['state'], 'grid fixture did not change M-RoPE state') + else: + require(results['engine_info']['candidate']['cvec'] != 0, 'control vector not loaded') + + +def main(): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument('--config', type=Path, required=True) + ap.add_argument('--engine', type=Path, required=True) + ap.add_argument('--output', type=Path, required=True) + ap.add_argument('--scenario', choices=('image', 'add', 'project'), required=True) + ap.add_argument('--run', action='store_true') + args = ap.parse_args() + if not args.run: + print(f'Dry run: {args.scenario} isolation; no model loaded or files created.') + return + cfg = json.loads(args.config.read_text()) + native = cfg['args'][cfg['args'].index('--native') + 1] + geometry = GGUFFile(native).metadata + width = geometry['qwen4exp.embedding_length'] + require(geometry['qwen4exp.block_count'] > 20, 'fixture requires layers 1 and 20') + p = Path(cfg['tokenizer']) + vocab = json.loads((p / 'vocab.json').read_text()) + tokens = [None] * len(vocab) + for token, i in vocab.items(): + tokens[i] = token + tok = ST.Tokenizer(tokens, (p / 'merges.txt').read_text().split('\n'), + json.loads((p / 'token_type.json').read_text())) + tpl = ChatTemplate(p / 'chat_template.jinja') + def encode(text): + return tok.encode(tpl.render([{'role': 'user', 'content': text}], enable_thinking=False), parse_special=True) + image_tokens = '<|vision_start|>' + '<|image_pad|>' * 4 + '<|vision_end|>' + tail = '\n'.join(f'Record {i}: blue square and green triangle.' for i in range(64)) + A = encode('Conversation A: ' + (image_tokens if args.scenario == 'image' else '') + '\n' + tail) + B = encode('Unrelated conversation B: name a color.\n' + tail) + args.output.mkdir(mode=0o700, parents=False, exist_ok=False) + fixtures(args.output, width) + env = child_env(cfg) + env['STRATA_STATE_HASH'] = '1' + results = {'engine_info': {}} + for label, budget in [('baseline', 0), ('candidate', 8192)]: + log = args.output / (label + '.log') + command = engine_args(cfg, budget, 1) + if args.scenario == 'image': + command += ['--vision'] + else: + command += ['--control-vector', str(args.output / 'control.gguf'), '--cvec-mode', args.scenario] + engine = StrataEngine(str(args.engine.resolve()), command, cwd=cfg.get('cwd'), log=str(log), env=env) + records = [] + results['engine_info'][label] = dict(engine.info) + def generate(name, ids, image=None, steering=True): + embeddings = str(args.output / (image + '.sve')) if image else None + out = [t for t in engine.generate(ids, 1, {'experimental_speed_projection': steering}, + threading.Event(), embeddings=embeddings) if t is not None] + records.append({'name': name, 'ids': out, **engine.last}) + try: + if args.scenario == 'image': + generate('image-A', A, 'image-a') + generate('text-B', B) + generate('image-A-return', A, 'image-a') + generate('image-B', A, 'image-b') + generate('image-A-again', A, 'image-a') + generate('grid-changed', A, 'image-grid') + generate('image-A-final', A, 'image-a') + else: + generate('off', A, steering=False) + generate('on', A) + generate('text-B', B) + generate('off-return', A, steering=False) + generate('on-return', A) + generate('off-again', A, steering=False) + finally: + engine.close() + hashes = [] + for line in log.read_text().splitlines(): + if 'STATE_HASH L=' in line: + fields = dict(re.findall(r'(\w+)=([0-9a-f,-]+)', line)) + hashes.append({k: fields[k] for k in STATE_KEYS}) + require(len(hashes) == len(records), 'missing isolation state hashes') + for record, state in zip(records, hashes): + record['state'] = state + results[label] = records + (args.output / 'results.json').write_text(json.dumps(results, indent=2) + '\n') + verify(results, args.scenario) + print(f'PASS: {args.scenario} identity isolation, output and main-model state parity') + print(f'Results: {args.output / "results.json"}') + + +if __name__ == '__main__': + main() diff --git a/tools/conversation_cache_parity.py b/tools/conversation_cache_parity.py new file mode 100644 index 00000000..710baee8 --- /dev/null +++ b/tools/conversation_cache_parity.py @@ -0,0 +1,219 @@ +"""Full-model A/B/A parity gate. Loads private engines sequentially, never uses an existing server. + +Dry-run by default. --run requires an available GPU/model-loading window. +""" +import argparse +import json +from pathlib import Path +import re +import sys +import threading + +ROOT = Path(__file__).resolve().parents[1] +sys.path[:0] = [str(ROOT), str(ROOT / 'tools')] +from serve.server import StrataEngine, child_env +from serve.frontend import ChatTemplate +import strata_tokenizer as ST + +STATE_KEYS = ('L', 'gdn', 'ple', 'tail', 'dead', 'pooled', 'kv', 'ple_prev') + +def require(condition, message): + if not condition: + raise AssertionError(message) + + +def engine_args(cfg, budget, spec): + # Native IQ packs require verifier capacity >= 2, even for one-token decode. + return list(cfg['args']) + [ + '--conversation-cache-mib', str(budget), '--conversation-cache-slots', '4', + '--prompt-cache', '6', '--adapt-swaps', '0', '--spec', str(max(2, spec)), + '--mtp-max-t', str(spec), '--suffix-draft', '0', '--spec-min-p', '0'] + + +def verify_pressure(results, budget_mib, oversized=False): + """Require actual byte-pressure evidence, not just correct output on misses.""" + baseline, candidate = results['baseline'], results['candidate'] + names = ['A', 'B', 'C', 'A-again'] + for records in (baseline, candidate): + require([r['name'] for r in records] == names, 'incomplete pressure sequence') + for before, after in zip(baseline, candidate): + require(len(before['ids']) == len(after['ids']) == 1, 'missing pressure output') + require(before['finish'] in ('length', 'stop') and after['finish'] in ('length', 'stop'), + 'pressure request did not finish normally') + require(before['reused'] == after['reused'] == 0, 'pressure did not force a cache miss') + require(before['ids'] == after['ids'], 'pressure output differs') + keys = set(STATE_KEYS) + require(keys <= before['state'].keys() and keys <= after['state'].keys(), 'missing pressure state') + require(before['state'] == after['state'], 'pressure state differs') + for key in ('expert_slots', 'kv', 'kv_resident', 'context', 'spec', 'mtp_max', 'lookup', 'cvec'): + require(results['engine_info']['baseline'][key] == results['engine_info']['candidate'][key], + f'pressure engine setting differs: {key}') + info = results['engine_info']['candidate'] + require(info['conversation_cache_mib'] == budget_mib and info['conversation_cache_slots'] == 4, + 'pressure cache configuration differs') + evidence = results['pressure'] + parks = evidence['parks'] + require(all(p['bytes'] <= budget_mib * 1024 * 1024 for p in parks), 'byte budget exceeded') + if oversized: + require(evidence['skips'] == 3 and not parks, 'oversized snapshots were not all skipped') + else: + require(evidence['skips'] == 0 and len(parks) == 3, 'snapshots must fit individually') + require(all(0 < p['parked'] < 4 for p in parks), 'slot pressure confounds byte-pressure test') + require(parks[-1]['evictions'] > 0, 'no byte-pressure eviction observed; reduce --cache-mib') + + +def verify_results(results, prompt_tokens, spec): + """Fail closed on incomplete evidence, even under python -O.""" + baseline, candidate = results['baseline'], results['candidate'] + require([r['name'] for r in baseline] == ['A', 'A+'], 'incomplete baseline') + require([r['name'] for r in candidate] == ['A', 'B', 'A+', 'B-again', 'A+-checkpoint'], 'incomplete candidate') + state_keys = set(STATE_KEYS) + for record in baseline + candidate: + require(bool(record['ids']), 'missing generated tokens') + require(record['finish'] in ('length', 'stop'), 'request did not finish normally') + require(state_keys <= record['state'].keys(), 'incomplete state fingerprint') + require(len(baseline[0]['ids']) == len(candidate[0]['ids']) == 1, 'invalid initial A output length') + require(baseline[0]['ids'] == candidate[0]['ids'], 'initial A output differs') + require(candidate[2]['reused'] >= prompt_tokens, 'A was not restored after B') + require(candidate[4]['reused'] > 0, 'parked checkpoint was not restored') + for key in ('expert_slots', 'kv', 'kv_resident', 'context', 'spec', 'mtp_max', 'lookup', 'cvec'): + require(results['engine_info']['baseline'][key] == results['engine_info']['candidate'][key], + f'baseline/candidate engine setting differs: {key}') + for record in (candidate[2], candidate[4]): + require(record['ids'] == baseline[1]['ids'], 'restored continuation output differs') + if spec == 1: + require(record['state'] == baseline[1]['state'], 'restored main-model state differs') + + +def verify_exchange(results, prompt_tokens, spec, budget_mib): + verify_results(results, prompt_tokens, spec) + require(results['engine_info']['candidate']['conversation_cache_mib'] == budget_mib, + 'exchange cache budget differs') + evidence = results['pressure'] + require(evidence['skips'] == 2 and len(evidence['parks']) == 2, + 'expected two parks and two outgoing skips while an incoming snapshot is held') + require(all(p['parked'] == 1 and 0 < p['bytes'] <= budget_mib * 1024 * 1024 + for p in evidence['parks']), 'invalid exchange snapshot budget') + + +def verify_admission(results, budget_mib, floor_mib): + evidence = results['pressure'] + require(evidence['memory_skips'] == 3 and evidence['skips'] == 0 and not evidence['parks'], + 'expected physical-memory denial, not oversized-budget fallback') + require(results['engine_info']['candidate']['conversation_cache_min_free_mib'] == floor_mib, + 'physical RAM floor differs') + # The same four cold requests must preserve output and complete state. Reuse + # the oversized gate's no-parking assertions after checking the actual cause. + equivalent = {**results, 'pressure': {**evidence, 'skips': evidence['memory_skips']}} + verify_pressure(equivalent, budget_mib, oversized=True) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument('--config', type=Path, required=True) + ap.add_argument('--engine', type=Path, required=True) + ap.add_argument('--output', type=Path, required=True, help='new private directory; existing paths refused') + ap.add_argument('--cache-mib', type=int, default=8192) + ap.add_argument('--paragraphs', type=int, default=128) + ap.add_argument('--scenario', choices=('reuse', 'pressure', 'oversized', 'exchange', 'admission'), default='reuse', + help='pressure requires snapshots fitting individually but not together; oversized requires none to fit') + ap.add_argument('--min-free-mib', type=int, default=2560, + help='physical RAM floor; for admission denial choose a value above available system RAM') + ap.add_argument('--spec', type=int, default=1, choices=range(1, 9), + help='decode window cap; 1 uses engine --spec 2 --mtp-max-t 1 for native IQ packs') + ap.add_argument('--run', action='store_true') + a = ap.parse_args() + if a.cache_mib <= 0 or a.paragraphs < 1 or not 0 <= a.min_free_mib <= (2**63 - 1) // (1024 * 1024): + ap.error('cache-mib/paragraphs must be positive and min-free-mib must fit the engine range') + if not a.run: + print(f'Dry run: {a.scenario}; paired baseline/candidate; fixed residency, greedy output.') + print('No model loaded. Use --run only with a separately available GPU/test window.') + return + cfg = json.loads(a.config.read_text()) + p = Path(cfg['tokenizer']) + vocab = json.loads((p / 'vocab.json').read_text()) + tokens = [None] * len(vocab) + for text, i in vocab.items(): + tokens[i] = text + tok = ST.Tokenizer(tokens, (p / 'merges.txt').read_text().split('\n'), + json.loads((p / 'token_type.json').read_text())) + tpl = ChatTemplate(p / 'chat_template.jinja') + def encode(text): + return tok.encode(text, parse_special=True) + def prompt(label): + text = label + ': remember this list.\n' + '\n'.join( + f'Record {i}: blue square, green triangle, red circle.' for i in range(a.paragraphs)) + return encode(tpl.render([{'role': 'user', 'content': text}], enable_thinking=False)) + A, B, C = prompt('Conversation A'), prompt('Unrelated conversation B'), prompt('Distinct conversation C') + suffix = encode('<|im_end|>\n<|im_start|>user\nName a color from the list.<|im_end|>\n' + '<|im_start|>assistant\n\n\n\n\n') + a.output.mkdir(mode=0o700, parents=False, exist_ok=False) + env = child_env(cfg) + env['STRATA_STATE_HASH'] = '1' + results = {'engine_info': {}} + for label, budget in [('baseline', 0), ('candidate', a.cache_mib)]: + log = a.output / f'{label}.log' + args = engine_args(cfg, budget, a.spec) + args += ['--conversation-cache-min-free-mib', str(a.min_free_mib)] + engine = StrataEngine(str(a.engine.resolve()), args, cwd=cfg.get('cwd'), log=str(log), env=env) + results['engine_info'][label] = dict(engine.info) + records = [] + def generate(ids, count, name): + out = [t for t in engine.generate(ids, count, {'temperature': 0}, threading.Event()) if t is not None] + records.append({'name': name, 'ids': out, **engine.last}) + return out + try: + # One output token leaves exactly A's prompt as the live prefix, + # avoiding the pre-existing accepted-draft output-cap overshoot. + if a.scenario in ('pressure', 'oversized', 'admission'): + generate(A, 1, 'A') + generate(B, 1, 'B') + generate(C, 1, 'C') + generate(A, 1, 'A-again') + else: + head = generate(A, 1, 'A') + continuation = A + head + suffix + if budget: + generate(B, 1, 'B') + generate(continuation, 8, 'A+') + if budget: + generate(B, 1, 'B-again') + generate(continuation, 8, 'A+-checkpoint') + finally: + engine.close() + hashes = [] + for line in log.read_text().splitlines(): + if 'STATE_HASH L=' in line: + fields = dict(re.findall(r'(\w+)=([0-9a-f,-]+)', line)) + # Padding and the drafter's final uncomputed cell aren't used + # main-model state; do not gate on their diagnostic hashes. + hashes.append({k: fields[k] for k in STATE_KEYS}) + require(len(hashes) == len(records), 'missing state hashes') + for record, fingerprint in zip(records, hashes): + record['state'] = fingerprint + results[label] = records + if label == 'candidate' and a.scenario != 'reuse': + log_text = log.read_text() + parks = re.findall(r'conversation cache: parked \d+ tokens .*?parked=(\d+) bytes=(\d+) evictions=(\d+)', log_text) + results['pressure'] = { + 'parks': [dict(zip(('parked', 'bytes', 'evictions'), map(int, p))) for p in parks], + 'skips': log_text.count('conversation cache: skip parking (snapshot '), + 'memory_skips': log_text.count('conversation cache: skip parking (physical RAM admission;')} + (a.output / 'results.json').write_text(json.dumps(results, indent=2) + '\n') + if a.scenario == 'admission': + verify_admission(results, a.cache_mib, a.min_free_mib) + print('PASS: physical-memory admission denial, output and byte-exact main-model state') + elif a.scenario == 'exchange': + verify_exchange(results, len(A), a.spec, a.cache_mib) + print('PASS: bounded incoming/outgoing exchange, A/B/A output and checkpoint reuse') + elif a.scenario == 'reuse': + verify_results(results, len(A), a.spec) + print('PASS: A/B/A output and checkpoint reuse' + (', byte-exact main-model state' if a.spec == 1 else '')) + else: + verify_pressure(results, a.cache_mib, a.scenario == 'oversized') + print(f'PASS: {a.scenario} fallback, output and byte-exact main-model state') + print(f'Results: {a.output / "results.json"}') + + +if __name__ == '__main__': + main() diff --git a/tools/conversation_cache_soak.py b/tools/conversation_cache_soak.py new file mode 100644 index 00000000..ae910c00 --- /dev/null +++ b/tools/conversation_cache_soak.py @@ -0,0 +1,176 @@ +"""Private-engine known-answer A/B/A soak; dry-run by default. + +Loads paired engines sequentially. Requires an exclusive model/GPU window, not +an existing HTTP server. This is a synthetic cache gate, not a real-agent benchmark. +""" +import argparse +import json +from pathlib import Path +import re +import sys +import threading + +ROOT = Path(__file__).resolve().parents[1] +sys.path[:0] = [str(ROOT), str(ROOT / 'tools')] +from conversation_cache_parity import STATE_KEYS, engine_args, require +from serve.server import StrataEngine, child_env +from serve.frontend import ChatTemplate +import strata_tokenizer as ST + + +def answer_text(text): + return text.replace('<|im_end|>', '').replace('<|endoftext|>', '').strip().casefold() + + +def verify(results): + contexts, cycles = results['contexts'], results['cycles'] + count = results['requested_cycles'] + require(count >= 30 and len(cycles) == count, 'incomplete 30-cycle soak') + require(len(contexts) >= 3, 'need at least three context lengths') + require(len({c['prompt_tokens'] for c in contexts}) == len(contexts), 'context lengths are not distinct') + baseline, candidate = results['engine_info']['baseline'], results['engine_info']['candidate'] + for key in ('expert_slots', 'kv', 'kv_resident', 'context', 'spec', 'mtp_max', 'lookup', 'cvec'): + require(baseline[key] == candidate[key], f'engine setting differs: {key}') + require(baseline['conversation_cache_mib'] == 0 and candidate['conversation_cache_mib'] > 0, + 'invalid baseline/candidate cache configuration') + lengths = [c['prompt_tokens'] for c in contexts] + require(candidate['kv_resident'] > 0 and max(lengths) > candidate['kv_resident'], 'no streamed-KV coverage') + require(max(lengths) >= .9 * candidate['context'], 'longest prompt is not near the context limit') + budget = candidate['conversation_cache_mib'] * 1024 * 1024 + for c in contexts: + require(c['baseline']['ids'] and set(STATE_KEYS) <= c['baseline']['state'].keys(), 'incomplete baseline') + require(c['baseline']['finish'] in ('length', 'stop'), 'baseline did not finish normally') + require(answer_text(c['baseline']['text']) == c['expected'].casefold(), 'baseline known answer is wrong') + for i, record in enumerate(cycles): + require(record['cycle'] == i and record['context'] == i % len(contexts), 'missing or reordered cycle') + c = contexts[record['context']] + require(record['finish'] in ('length', 'stop') and record['ids'], 'soak request failed') + require(answer_text(record['text']) == c['expected'].casefold(), 'restored known answer is wrong') + require(record['ids'] == c['baseline']['ids'], 'continuation token parity failed') + require(record['reused'] >= c['prompt_tokens'], 'return did not restore the long prefix') + require(set(STATE_KEYS) <= record['state'].keys() and record['state'] == c['baseline']['state'], + 'restored main-model state differs') + require(0 <= record['cache_bytes'] <= budget, 'parked byte budget exceeded') + # Compare steady-state retained snapshot payload, not allocator RSS or VRAM. + # Sampled RSS is diagnostic: allocator high-water marks need not shrink, + # and request-end samples do not establish a transient peak bound. + for index in range(len(contexts)): + tail = [r['cache_bytes'] for r in cycles if r['context'] == index][-3:] + require(len(tail) == 3 and len(set(tail)) == 1, 'retained payload did not reach a stable plateau') + + +def main(): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument('--config', type=Path, required=True) + ap.add_argument('--engine', type=Path, required=True) + ap.add_argument('--output', type=Path, required=True, help='new directory; existing paths refused') + ap.add_argument('--prompt-tokens', default='2048,40000,120000', help='three increasing approximate prompt lengths') + ap.add_argument('--cycles', type=int, default=30) + ap.add_argument('--cache-mib', type=int, default=8192) + ap.add_argument('--run', action='store_true') + args = ap.parse_args() + try: + lengths = [int(n) for n in args.prompt_tokens.split(',')] + except ValueError: + ap.error('prompt-tokens must contain three integers') + if len(lengths) != 3 or lengths != sorted(set(lengths)) or min(lengths) < 256 or args.cycles < 30 or args.cache_mib <= 0: + ap.error('need three distinct increasing lengths >= 256, cycles >= 30 and cache-mib > 0') + if not args.run: + print(f'Dry run: {args.cycles} known-answer A/B/A cycles; approximate lengths {lengths}.') + print('No model loaded or files created. Use --run only in an exclusive GPU test window.') + return + cfg = json.loads(args.config.read_text()) + path = Path(cfg['tokenizer']) + vocab = json.loads((path / 'vocab.json').read_text()) + tokens = [None] * len(vocab) + for token, index in vocab.items(): + tokens[index] = token + tok = ST.Tokenizer(tokens, (path / 'merges.txt').read_text().split('\n'), + json.loads((path / 'token_type.json').read_text())) + template = ChatTemplate(path / 'chat_template.jinja') + def encode(text): + return tok.encode(text, parse_special=True) + def prompt(text): + return encode(template.render([{'role': 'user', 'content': text}], enable_thinking=False)) + def long_prompt(target, secret, index): + paragraphs = max(1, target // 17) + for _ in range(6): + lines = [f'Record {i}: blue square, green triangle, red circle.' for i in range(paragraphs)] + lines[paragraphs // 3] = f'The secret access code for conversation {index} is {secret}.' + ids = prompt(f'Conversation {index}. Remember its secret access code for my next question.\n' + '\n'.join(lines)) + delta = target - len(ids) + if abs(delta) < 64: + return ids + paragraphs = max(1, paragraphs + delta // 17) + return ids + secrets = ['MANGO', 'CEDAR', 'RAVEN'] + prompts = [long_prompt(n, secret, i) for i, (n, secret) in enumerate(zip(lengths, secrets))] + suffix = encode('<|im_end|>\n<|im_start|>user\nWhat is this conversation\'s secret access code? ' + 'Reply with only that one word, no punctuation.<|im_end|>\n' + '<|im_start|>assistant\n\n\n\n\n') + other = prompt('Unrelated worker conversation. Reply with HELLO and nothing else.') + args.output.mkdir(mode=0o700, parents=False, exist_ok=False) + env = child_env(cfg) + env['STRATA_STATE_HASH'] = '1' + results = {'requested_cycles': args.cycles, 'engine_info': {}, 'contexts': [], 'cycles': []} + heads, continuations = [], [] + for label, budget in [('baseline', 0), ('candidate', args.cache_mib)]: + log = args.output / f'{label}.log' + engine = StrataEngine(str(args.engine.resolve()), engine_args(cfg, budget, 1), + cwd=cfg.get('cwd'), log=str(log), env=env) + results['engine_info'][label] = dict(engine.info) + hash_count = 0 + def generate(ids, count): + nonlocal hash_count + output = [t for t in engine.generate(ids, count, {'temperature': 0}, threading.Event()) if t is not None] + text = log.read_text() + hashes = [dict(re.findall(r'(\w+)=([0-9a-f,-]+)', line)) + for line in text.splitlines() if 'STATE_HASH L=' in line] + require(len(hashes) == hash_count + 1 and int(hashes[-1]['L']) >= len(ids), 'missing current state fingerprint') + hash_count += 1 + state = {k: hashes[-1][k] for k in STATE_KEYS} + occupancy = re.findall(r'parked=\d+ bytes=(\d+)', text) + rss = None + try: + match = re.search(r'^VmRSS:\s+(\d+) kB', Path(f'/proc/{engine.proc.pid}/status').read_text(), re.M) + if match: + rss = int(match[1]) * 1024 + except OSError: + pass + return {'ids': output, 'text': tok.decode(output), **engine.last, 'state': state, + 'cache_bytes': int(occupancy[-1]) if occupancy else 0, 'sampled_rss_bytes': rss} + try: + require(max(map(len, prompts)) + len(suffix) + 64 < engine.max_context, 'test prompt exceeds context') + if label == 'baseline': + for i, ids in enumerate(prompts): + head = generate(ids, 1) + require(len(head['ids']) == 1, 'baseline initial output is missing') + heads.append(head['ids']) + continuations.append(ids + head['ids'] + suffix) + answer = generate(continuations[-1], 16) + results['contexts'].append({'expected': secrets[i], 'prompt_tokens': len(ids), 'baseline': answer}) + require(answer_text(answer['text']) == secrets[i].casefold(), 'baseline known answer is wrong') + print(f'baseline length={len(ids)} answer={answer_text(answer["text"])}', flush=True) + else: + primed = set() + for cycle in range(args.cycles): + index = cycle % len(prompts) + if index not in primed: + head = generate(prompts[index], 1) + require(head['ids'] == heads[index], 'initial candidate output differs') + primed.add(index) + generate(other, 1) + answer = generate(continuations[index], 16) + results['cycles'].append({'cycle': cycle, 'context': index, **answer}) + print(f'cycle={cycle + 1}/{args.cycles} length={len(prompts[index])} ' + f'reused={answer["reused"]} answer={answer_text(answer["text"])}', flush=True) + finally: + engine.close() + # Keep partial evidence on failure; verify rejects incomplete runs. + (args.output / 'results.json').write_text(json.dumps(results, indent=2) + '\n') + verify(results) + print('PASS: 30+ known-answer A/B/A cycles, streamed/near-limit KV, exact state/output, stable retained payload') + + +if __name__ == '__main__': + main() diff --git a/tools/test_conversation_cache_http_smoke.py b/tools/test_conversation_cache_http_smoke.py new file mode 100644 index 00000000..fd0a79d2 --- /dev/null +++ b/tools/test_conversation_cache_http_smoke.py @@ -0,0 +1,71 @@ +"""Offline tests of HTTP smoke-test orchestration and safety defaults.""" +from collections import OrderedDict +import io +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import Mock + +from tools.conversation_cache_http_smoke import run + + +class FakeClient: + def __init__(self): + self.history = [] + self.cache = OrderedDict() + + def metrics(self): + return {'live': {'state': 'idle', 'queued': 0}, + 'engine': {'model': 'fake', 'conversation_cache_slots': 4, 'conversation_cache_mib': 8192}, + 'requests': self.history[::-1]} + + def request(self, model, content, stream=False, count=8): + reused = 100 if content in self.cache else 0 + self.cache.pop(content, None) + self.cache[content] = True + while len(self.cache) > 5: # active plus four parked entries + self.cache.popitem(last=False) + self.history.append({'time': len(self.history) + 1, 'reused': reused, 'output_tokens': 5, + 'finish': 'disconnect' if stream else 'stop'}) + data = {'choices': [{'delta': {'content': '1'}}]} if stream else { + 'choices': [{'message': {'role': 'assistant', 'content': 'blue'}}]} + return io.BytesIO((('data: ' if stream else '') + json.dumps(data) + '\n').encode()) + + +class HttpSmoke(unittest.TestCase): + def test_orchestration_offline(self): + result = run(FakeClient()) + self.assertEqual(len(result['records']), 12) + self.assertEqual(result['records'][-1]['name'], 'cancelled-A-restored') + self.assertGreater(result['records'][-1]['reused'], 0) + + def test_busy_server_receives_no_requests(self): + client = Mock() + client.metrics.return_value = {'live': {'state': 'generating', 'queued': 0}} + with self.assertRaisesRegex(RuntimeError, 'busy'): + run(client) + client.request.assert_not_called() + + def test_disabled_cache_receives_no_requests(self): + client = Mock() + client.metrics.return_value = {'live': {'state': 'idle', 'queued': 0}, 'engine': {}} + with self.assertRaisesRegex(RuntimeError, 'enabled cache'): + run(client) + client.request.assert_not_called() + + def test_dry_run_does_not_connect_or_create_output(self): + with tempfile.TemporaryDirectory(prefix='strata-http-dry-') as directory: + output = Path(directory) / 'not-created.json' + result = subprocess.run([sys.executable, str(Path(__file__).with_name('conversation_cache_http_smoke.py')), + '--url', 'invalid://not-a-server', '--output', str(output)], + capture_output=True, text=True, timeout=10) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn('No network traffic', result.stdout) + self.assertFalse(output.exists()) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/test_conversation_cache_isolation.py b/tools/test_conversation_cache_isolation.py new file mode 100644 index 00000000..7205d4d4 --- /dev/null +++ b/tools/test_conversation_cache_isolation.py @@ -0,0 +1,82 @@ +"""Offline checks for image/steering isolation evidence and generated fixtures.""" +import copy +from pathlib import Path +import struct +import subprocess +import sys +import tempfile +import unittest + +from tools.conversation_cache_isolation import STATE_KEYS, fixtures, verify +from tools.gguf_reader import GGUFFile + + +def evidence(scenario): + image = scenario == 'image' + names = (['image-A', 'text-B', 'image-A-return', 'image-B', 'image-A-again', 'grid-changed', 'image-A-final'] + if image else ['off', 'on', 'text-B', 'off-return', 'on-return', 'off-again']) + hits = [2, 4, 6] if image else [3, 4, 5] + records = [{'name': name, 'ids': [123], 'finish': 'length', 'reused': 0, + 'state': {k: str(i) for k in STATE_KEYS}} for i, name in enumerate(names)] + candidate = copy.deepcopy(records) + for i in hits: + candidate[i]['reused'] = 100 + info = dict(expert_slots=8000, kv='int8', kv_resident=32768, context=262144, + spec=2, mtp_max=1, lookup=0, cvec=0 if image else 'add:1-47') + return {'baseline': records, 'candidate': candidate, + 'engine_info': {'baseline': dict(info), 'candidate': dict(info)}} + + +class IsolationGate(unittest.TestCase): + def test_complete_evidence(self): + for scenario in ('image', 'add', 'project'): + verify(evidence(scenario), scenario) + + def test_incomplete_or_wrong_evidence_rejected(self): + for scenario in ('image', 'add'): + cases = { + 'incompatible reuse': lambda d: d['candidate'][1].update(reused=5), + 'no parked hit': lambda d: d['candidate'][-1].update(reused=0), + 'state mismatch': lambda d: d['candidate'][-1]['state'].update(gdn='ffff'), + 'missing state': lambda d: d['candidate'][-1]['state'].clear(), + 'empty output': lambda d: d['candidate'][-1]['ids'].clear(), + 'missing request': lambda d: d['candidate'].pop(), + 'different residency': lambda d: d['engine_info']['candidate'].update(expert_slots=1), + } + for name, mutate in cases.items(): + with self.subTest(scenario=scenario, case=name): + data = evidence(scenario) + mutate(data) + with self.assertRaises(AssertionError): + verify(data, scenario) + + def test_generated_fixtures(self): + with tempfile.TemporaryDirectory(prefix='strata-isolation-') as directory: + p = Path(directory) + fixtures(p, 2560) + cv = GGUFFile(p / 'control.gguf') + self.assertEqual(cv.metadata['general.architecture'], 'controlvector') + self.assertEqual([t.name for t in cv.tensors], ['direction.1', 'direction.20']) + self.assertTrue(all(t.elements == 2560 for t in cv.tensors)) + a, b, grid = [(p / (name + '.sve')).read_bytes() for name in ('image-a', 'image-b', 'image-grid')] + self.assertEqual(struct.unpack('<5i', a[:20]), (0x31455653, 4, 2, 2, 2560)) + self.assertEqual(len(a), 20 + 4 * 2560 * 4) + self.assertEqual(a[:20], b[:20]) + self.assertNotEqual(a[20:], b[20:]) + self.assertNotEqual(a[:20], grid[:20]) + self.assertEqual(a[20:], grid[20:]) + + def test_dry_run_does_not_read_missing_config(self): + with tempfile.TemporaryDirectory(prefix='strata-isolation-dry-') as directory: + p = Path(directory) + result = subprocess.run([sys.executable, str(Path(__file__).with_name('conversation_cache_isolation.py')), + '--config', str(p / 'missing.json'), '--engine', str(p / 'missing'), + '--output', str(p / 'not-created'), '--scenario', 'image'], + capture_output=True, text=True, timeout=10) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn('no model loaded', result.stdout) + self.assertFalse((p / 'not-created').exists()) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/test_conversation_cache_parity.py b/tools/test_conversation_cache_parity.py new file mode 100644 index 00000000..15c9cc40 --- /dev/null +++ b/tools/test_conversation_cache_parity.py @@ -0,0 +1,154 @@ +"""CPU-only checks that the model-level gate cannot pass with incomplete evidence.""" +import copy +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +from tools.conversation_cache_parity import STATE_KEYS, engine_args, verify_admission, verify_exchange, verify_pressure, verify_results + + +def fixture(): + state = {k: '1234' for k in STATE_KEYS} + def record(name): + return {'name': name, 'ids': [123], 'finish': 'length', 'state': dict(state), 'reused': 100} + info = {'expert_slots': 100, 'kv': 'int8', 'kv_resident': 32768, 'context': 65536, + 'spec': 1, 'mtp_max': 0, 'lookup': 0, 'cvec': '0'} + return {'baseline': [record('A'), record('A+')], + 'candidate': [record(n) for n in ('A', 'B', 'A+', 'B-again', 'A+-checkpoint')], + 'engine_info': {'baseline': dict(info), 'candidate': dict(info)}} + + +class ParityGate(unittest.TestCase): + def test_native_iq_single_token_arguments(self): + cfg = {'args': ['--spec', '4', '--mtp-max-t', '4']} + args = engine_args(cfg, 400, 1) + values = {args[i]: args[i + 1] for i in range(0, len(args), 2)} + self.assertEqual(values['--spec'], '2') + self.assertEqual(values['--mtp-max-t'], '1') + self.assertEqual(values['--suffix-draft'], '0') + self.assertEqual(values['--adapt-swaps'], '0') + self.assertEqual(values['--conversation-cache-mib'], '400') + self.assertEqual(cfg['args'], ['--spec', '4', '--mtp-max-t', '4']) + + def test_complete_evidence(self): + verify_results(fixture(), 100, 1) + + def test_incomplete_or_different_evidence_fails(self): + cases = { + 'missing state': lambda d: d['candidate'][2]['state'].clear(), + 'missing spare key': lambda d: d['candidate'][2]['state'].pop('dead'), + 'empty output': lambda d: d['candidate'][2]['ids'].clear(), + 'missing request': lambda d: d['candidate'].pop(), + 'state differs': lambda d: d['candidate'][2]['state'].update(gdn='ffff'), + 'output differs': lambda d: d['candidate'][2].update(ids=[456]), + 'live not restored': lambda d: d['candidate'][2].update(reused=0), + 'checkpoint not restored': lambda d: d['candidate'][4].update(reused=0), + 'different residency': lambda d: d['engine_info']['candidate'].update(expert_slots=99), + 'cancellation': lambda d: d['candidate'][2].update(finish='cancel'), + 'initial output differs': lambda d: d['candidate'][0].update(ids=[789]), + } + for name, mutate in cases.items(): + with self.subTest(name=name): + data = copy.deepcopy(fixture()) + mutate(data) + with self.assertRaises(AssertionError): + verify_results(data, 100, 1) + + def test_speculative_gate_still_requires_output_parity(self): + data = fixture() + data['candidate'][2]['state']['gdn'] = 'ffff' + verify_results(data, 100, 4) + data['candidate'][2]['ids'] = [456] + with self.assertRaises(AssertionError): + verify_results(data, 100, 4) + + def test_dry_run_does_not_read_config_or_start_engine(self): + with tempfile.TemporaryDirectory(prefix='strata-parity-dry-') as directory: + output = Path(directory) / 'not-created' + result = subprocess.run([sys.executable, str(Path(__file__).with_name('conversation_cache_parity.py')), + '--config', str(Path(directory) / 'missing.json'), + '--engine', str(Path(directory) / 'missing-engine'), '--output', str(output)], + capture_output=True, text=True, timeout=10) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn('No model loaded', result.stdout) + self.assertFalse(output.exists()) + + +def pressure_fixture(): + data = fixture() + record = data['baseline'][0] + for key in ('baseline', 'candidate'): + data[key] = [{**copy.deepcopy(record), 'name': name, 'reused': 0} + for name in ('A', 'B', 'C', 'A-again')] + data['engine_info']['candidate'].update(conversation_cache_mib=400, conversation_cache_slots=4) + data['pressure'] = {'skips': 0, 'parks': [ + {'parked': 1, 'bytes': 266000000, 'evictions': n} for n in range(3)]} + return data + + +class PressureGate(unittest.TestCase): + def test_physical_memory_admission_evidence(self): + data = pressure_fixture() + data['pressure'] = {'memory_skips': 3, 'skips': 0, 'parks': []} + data['engine_info']['candidate']['conversation_cache_min_free_mib'] = 999999 + verify_admission(data, 400, 999999) + for mutate in ( + lambda d: d['pressure'].update(memory_skips=0, skips=3), + lambda d: d['pressure'].update(memory_skips=2), + lambda d: d['engine_info']['candidate'].update(conversation_cache_min_free_mib=2560), + lambda d: d['candidate'][3].update(reused=10), + ): + broken = copy.deepcopy(data) + mutate(broken) + with self.assertRaises(AssertionError): + verify_admission(broken, 400, 999999) + + def test_incoming_exchange_evidence(self): + data = fixture() + data['engine_info']['candidate']['conversation_cache_mib'] = 400 + data['pressure'] = {'skips': 2, 'parks': [ + {'parked': 1, 'bytes': 266000000, 'evictions': 0}, + {'parked': 1, 'bytes': 384000000, 'evictions': 0}]} + verify_exchange(data, 100, 1, 400) + for skips in (0, 1, 3): + data['pressure']['skips'] = skips + with self.assertRaises(AssertionError): + verify_exchange(data, 100, 1, 400) + + def test_byte_eviction_evidence(self): + verify_pressure(pressure_fixture(), 400) + + def test_oversized_evidence(self): + data = pressure_fixture() + data['engine_info']['candidate']['conversation_cache_mib'] = 1 + data['pressure'] = {'skips': 3, 'parks': []} + verify_pressure(data, 1, oversized=True) + data['pressure']['skips'] = 2 + with self.assertRaises(AssertionError): + verify_pressure(data, 1, oversized=True) + + def test_insufficient_pressure_evidence_rejected(self): + cases = { + 'slot pressure': lambda d: d['pressure']['parks'][1].update(parked=4), + 'no eviction': lambda d: d['pressure']['parks'][-1].update(evictions=0), + 'too large individually': lambda d: d['pressure'].update(skips=1), + 'missing snapshots': lambda d: d['pressure']['parks'].pop(), + 'over budget': lambda d: d['pressure']['parks'][0].update(bytes=500 * 1024 * 1024), + 'cache hit': lambda d: d['candidate'][-1].update(reused=100), + 'state mismatch': lambda d: d['candidate'][-1]['state'].update(gdn='ffff'), + 'empty state': lambda d: d['candidate'][-1]['state'].clear(), + 'wrong output': lambda d: d['candidate'][-1].update(ids=[456]), + 'wrong budget': lambda d: d['engine_info']['candidate'].update(conversation_cache_mib=8192), + } + for name, mutate in cases.items(): + with self.subTest(name=name): + data = pressure_fixture() + mutate(data) + with self.assertRaises(AssertionError): + verify_pressure(data, 400) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/test_conversation_cache_soak.py b/tools/test_conversation_cache_soak.py new file mode 100644 index 00000000..7d815890 --- /dev/null +++ b/tools/test_conversation_cache_soak.py @@ -0,0 +1,73 @@ +"""Offline checks for the synthetic known-answer soak acceptance gate.""" +import copy +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +from tools.conversation_cache_soak import STATE_KEYS, answer_text, verify + + +def evidence(): + lengths = [2048, 40000, 120000] + def record(index): + return {'ids': [100 + index], 'text': ['MANGO', 'CEDAR', 'RAVEN'][index], + 'finish': 'stop', 'reused': lengths[index], 'cache_bytes': 100000, + 'state': {key: str(index) for key in STATE_KEYS}} + info = dict(expert_slots=8000, kv='int8', kv_resident=32768, context=131072, + spec=2, mtp_max=1, lookup=0, cvec=0, conversation_cache_mib=8192) + return {'requested_cycles': 30, 'engine_info': {'baseline': {**info, 'conversation_cache_mib': 0}, 'candidate': info}, + 'contexts': [{'expected': record(i)['text'], 'prompt_tokens': lengths[i], 'baseline': record(i)} for i in range(3)], + 'cycles': [{'cycle': i, 'context': i % 3, **record(i % 3)} for i in range(30)]} + + +class SoakGate(unittest.TestCase): + def test_complete_evidence(self): + verify(evidence()) + + def test_bad_or_incomplete_evidence(self): + cases = { + 'missing cycle': lambda r: r['cycles'].pop(), + 'too few requested': lambda r: r.update(requested_cycles=29), + 'missing context': lambda r: r['contexts'].pop(), + 'duplicate lengths': lambda r: r['contexts'][0].update(prompt_tokens=40000), + 'reordered cycle': lambda r: r['cycles'][2].update(context=0), + 'no streaming': lambda r: r['engine_info']['candidate'].update(kv_resident=0), + 'not near context limit': lambda r: (r['engine_info']['baseline'].update(context=262144), + r['engine_info']['candidate'].update(context=262144)), + 'different GPU residency': lambda r: r['engine_info']['candidate'].update(expert_slots=7999), + 'no restore': lambda r: r['cycles'][9].update(reused=0), + 'wrong answer despite parity': lambda r: (r['contexts'][0]['baseline'].update(text='WRONG'), + r['cycles'][0].update(text='WRONG')), + 'wrong token output': lambda r: r['cycles'][5].update(ids=[999]), + 'missing spare fingerprint': lambda r: r['cycles'][4]['state'].pop('dead'), + 'different state': lambda r: r['cycles'][4]['state'].update(gdn='bad'), + 'cancelled': lambda r: r['cycles'][3].update(finish='cancel'), + 'over budget': lambda r: r['cycles'][3].update(cache_bytes=2**40), + 'retained allocation grows': lambda r: r['cycles'][-1].update(cache_bytes=200000), + } + for name, mutate in cases.items(): + with self.subTest(name=name): + results = copy.deepcopy(evidence()) + mutate(results) + with self.assertRaises(AssertionError): + verify(results) + + def test_answer_normalization_does_not_hide_extra_text(self): + self.assertEqual(answer_text(' MANGO<|im_end|>\n'), 'mango') + self.assertNotEqual(answer_text('The code is MANGO.'), 'mango') + + def test_dry_run_never_reads_config_or_starts_model(self): + with tempfile.TemporaryDirectory(prefix='strata-soak-dry-') as directory: + root = Path(directory) + result = subprocess.run([sys.executable, str(Path(__file__).with_name('conversation_cache_soak.py')), + '--config', str(root / 'missing.json'), '--engine', str(root / 'missing'), + '--output', str(root / 'output')], capture_output=True, text=True, timeout=10) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn('No model loaded', result.stdout) + self.assertFalse((root / 'output').exists()) + + +if __name__ == '__main__': + unittest.main() From 6adb2e5ac4709ff5b59599288788d0952cc01a02 Mon Sep 17 00:00:00 2001 From: midhatn <35053211+midhatn@users.noreply.github.com> Date: Tue, 29 Sep 2026 05:29:32 +0300 Subject: [PATCH 02/22] test: require a real physical-memory sample on Windows --- src/core/conversation_memory_test.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/core/conversation_memory_test.cpp b/src/core/conversation_memory_test.cpp index aec678f3..a8cb25d4 100644 --- a/src/core/conversation_memory_test.cpp +++ b/src/core/conversation_memory_test.cpp @@ -5,6 +5,13 @@ #include #include +#if defined(_WIN32) +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#endif + using namespace strata::core; namespace { int checks = 0; @@ -45,5 +52,15 @@ int main() { // Test the real provider without assuming any particular amount of free RAM. const auto available = conversation_available_memory(); check(!available || conversation_memory_admit(available, 0, 0), "provider returns bytes or unknown"); +#if defined(_WIN32) + // Unknown must fail closed in production, but must not let a broken Windows provider pass this test. + // Compare with total physical memory, not a second available reading: other processes can allocate + // between calls. No pressure allocation or fixed free-memory assumption is needed. + MEMORYSTATUSEX physical{}; + physical.dwLength = sizeof physical; + check(GlobalMemoryStatusEx(&physical) != 0, "Windows physical-memory API is available"); + check(available.has_value() && *available <= physical.ullTotalPhys, + "Windows provider returns a known, physically bounded sample"); +#endif std::printf("conversation_memory_test: %d checks passed\n", checks); } From e0feb8530c07c71ddcc288571cff0034b25defe2 Mon Sep 17 00:00:00 2001 From: Jeremiah Ritchey <44681828+jeremiahritchey@users.noreply.github.com> Date: Tue, 29 Sep 2026 18:51:15 +0000 Subject: [PATCH 03/22] Add reproducible Pi cache comparison and document current integration --- CMakeLists.txt | 2 + docs/DETAILS.md | 6 + docs/plans/agent-cache-benchmark.md | 50 ++++++ docs/plans/shared-conversation-snapshots.md | 18 +- src/core/conversation_snapshot_test.cpp | 2 +- tools/agent_cache_benchmark.py | 183 ++++++++++++++++++++ tools/agent_cache_task.mjs | 106 ++++++++++++ 7 files changed, 362 insertions(+), 5 deletions(-) create mode 100644 docs/plans/agent-cache-benchmark.md create mode 100644 tools/agent_cache_benchmark.py create mode 100644 tools/agent_cache_task.mjs diff --git a/CMakeLists.txt b/CMakeLists.txt index 9f05042a..7631dbe7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -625,6 +625,8 @@ if(STRATA_BUILD_TESTS) add_executable(draft_policy_test src/spec/draft_policy_test.cpp) target_link_libraries(draft_policy_test PRIVATE strata_spec) add_test(NAME draft_policy_test COMMAND draft_policy_test) +endif() +if(STRATA_BUILD_TESTS OR STRATA_BUILD_CONVERSATION_TESTS) # the serve loop's conversation-cache retention policy (header-only, no library to link) add_executable(conv_cache_test src/program/conv_cache_test.cpp) target_include_directories(conv_cache_test PRIVATE include) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index d8a7765d..5e97ffee 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -377,6 +377,12 @@ in a bounded 8 GiB host-RAM cache. This preserves controller/worker histories wh their requests alternate; it does not execute requests concurrently. No client session ID is required: only exact token/image prefixes with matching steering mode are reused. The default budget is 0 (disabled); `--prompt-cache 0` also disables parking. +The initial shared-core integration supports a single session GPU: combining +enabled parking with `--layer-split` is rejected before model loading. Ordinary +upstream layer-split checkpoints remain available with parking disabled. FP16, +INT8, Q4_0 and identity-layout K8V4 snapshots are supported; the K8V4 draft ring +remains INT8, as in upstream. Windows/HIP and multi-GPU runtime coverage must be +reported separately from Linux/CUDA evidence. Snapshots contain running state, checkpoints, used K/V pages, and draft-layer K/V. They add host RAM, not another model or VRAM allocation. The byte budget also counts diff --git a/docs/plans/agent-cache-benchmark.md b/docs/plans/agent-cache-benchmark.md new file mode 100644 index 00000000..ffd40d75 --- /dev/null +++ b/docs/plans/agent-cache-benchmark.md @@ -0,0 +1,50 @@ +# Controlled local Pi cache comparison + +`tools/agent_cache_benchmark.py` runs a bounded real coding task through the Pi +SDK with parking disabled and enabled. It defaults to a dry run and never uses +an existing server. `--run` requires an exclusive GPU window, the configured +model assets, Node.js, and an installed `@earendil-works/pi-coding-agent` package. + +Both runs start from identical files and use the same working-directory path, +prompts, model configuration and tool limits. Each loads a fresh private server. +The workflow is controller A implementing a CSV-report library, worker B adding +its CLI, then A returning to verify/fix the integration. This exercises real file +edits and shell checks rather than replaying prerecorded model responses. The +input corpus is generated public test data, not a user conversation. + +The task uses the Python standard library. Ten independent checks cover UTC +date grouping, decimal sums, sorting, invalid input, last-valid duplicate IDs, +quoted commas, file/stdin CLI behavior and missing-file status. These validators +run outside the agent workspace after the workflow finishes. A model's assertion +that the task succeeded is not accepted as validation. + +Each phase allows 12 executed tools, 16 model turns and 240 seconds. Bash calls +are limited to 15 seconds and returned text to 16,000 characters per tool result. +Requests use greedy sampling, disabled thinking, and at most 2,048 output tokens. +No compaction, skills, discovered extensions, inherited context files or remote +model catalogs are loaded. Generated event logs remain local; review them before +publishing any benchmark artifact. + +Example (paths to the local model configuration and Pi installation are supplied +by the operator): + +```sh +python tools/agent_cache_benchmark.py \ + --config /path/to/engine-config.json --engine build-validation/strata \ + --pi-package /path/to/node_modules/@earendil-works/pi-coding-agent \ + --output /path/to/new-results --run +``` + +Use a fixed expert allocation small enough that neither engine trims it for +VRAM headroom. The harness rejects mismatched engine settings. `--order on,off` +supports a reverse-order repetition; changing the order is not a substitute for +reporting repeat variability. + +Results include task wall time (excluding model startup), per-phase/tool times, +prompt/decode times, token reuse and generation volume, engine configuration, +independent success status, generated files, and the engine's Linux kernel +high-water RSS. RSS includes startup and model mappings; it is not a system-wide +or GPU peak-memory measurement. Normal speculative inference can produce +different tool paths, so report output/task differences and do not infer a +general speedup from a single pair. This local workload does not reproduce the +earlier remote Windows game-building workflow. diff --git a/docs/plans/shared-conversation-snapshots.md b/docs/plans/shared-conversation-snapshots.md index e692c303..07e33177 100644 --- a/docs/plans/shared-conversation-snapshots.md +++ b/docs/plans/shared-conversation-snapshots.md @@ -1,9 +1,19 @@ # Shared conversation snapshots: convergence proposal -Status: proposed interface and development work for issues/PRs #41, #52 and #57. -This is not an agreed integration-owner assignment, a merged upstream feature, -or a claim that the disk tier already uses this core. Development starts at -upstream `b38c183` (0.1.18); the deployed/tested 0.1.15 branch remains separate. +Status: shared-core development for issues/PRs #41, #52 and #57. In the issue's +September 28 follow-up the maintainer asked @jeremiahritchey to own the unified +PR, @midhatn to review Windows admission/acceptance, and @maedoc to layer optional +NVMe persistence on the core. The September 29 follow-up permits the single-GPU +core to land first. This is not a merged upstream feature or acceptance of the +separate disk implementation. + +The original evidence targets upstream `b38c183` (0.1.18). Current integration +is based on `8fc40dd` (0.1.25), fetched September 29 after main advanced beyond +the requested 0.1.22. The earlier branches and their evidence remain separate. +Parking rejects `--layer-split` while ordinary upstream multi-device checkpoint +handling is retained. Checkpoint LRU stamps and system-prompt/root retention are +preserved. K8V4 snapshots store separate INT8 K/scales and Q4 V payloads; hybrid +streaming/ring layouts are rejected before calling upstream's block movers. ## Boundaries diff --git a/src/core/conversation_snapshot_test.cpp b/src/core/conversation_snapshot_test.cpp index 9a8c89a7..f6b8e6fb 100644 --- a/src/core/conversation_snapshot_test.cpp +++ b/src/core/conversation_snapshot_test.cpp @@ -160,7 +160,7 @@ void full_session(int fmt, int mode, int experts) { int main() { int devices=0; if (cudaGetDeviceCount(&devices)!=cudaSuccess || !devices) return 77; - for (int fmt : {kKvF16,kKvInt8,kKvQ4,3}) for (int mode : {0,1,2}) { + for (int fmt : std::array{kKvF16,kKvInt8,kKvQ4,3}) for (int mode : {0,1,2}) { if (fmt==3 && mode!=0) continue; Fixture f(fmt,mode); if (fmt==3) { diff --git a/tools/agent_cache_benchmark.py b/tools/agent_cache_benchmark.py new file mode 100644 index 00000000..74fa3838 --- /dev/null +++ b/tools/agent_cache_benchmark.py @@ -0,0 +1,183 @@ +"""Controlled local Pi coding task with cache off/on; private server, dry-run by default. + +Requires an installed Pi SDK (--pi-package). Never contacts an existing server. +Only --run creates files or loads a model. Retains generated code, private agent +events, exact inputs, timings, engine metrics and independent validator results. +""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import shutil +import signal +import subprocess +import sys +import time +import urllib.request + +ROOT = Path(__file__).resolve().parents[1] +SPEC = '''Implement a Python 3 standard-library expense report. +report.py exports summarize(text: str) -> list[dict]. Input is CSV with headers +id,timestamp,team,amount. Strip surrounding whitespace in values. A valid row has +a nonempty id and team, an ISO timestamp WITH timezone (Z or explicit offset), +and a finite decimal amount with at most two fractional digits. Ignore invalid +rows. Among valid rows with the same id, the last valid row wins (a later invalid +row must not erase a valid row). Normalize timestamps to UTC and group by UTC +date and team. Return groups sorted by (day, team), each with exactly the keys +day (YYYY-MM-DD), team, count (int), total (decimal string with two places). +Negative amounts and zero are valid. Use decimal arithmetic, not binary floats. +Empty input and header-only input return []. Correctly parse quoted commas. +cli.py accepts exactly one argument, a CSV filename or - for stdin. Print the +JSON list and exit 0. An unreadable filename prints a concise message to stderr +and exits 2 without a traceback. Do not add third-party dependencies. +''' +VALIDATOR = r''' +import importlib.util, json, subprocess, sys +from pathlib import Path +root=Path(sys.argv[1]); spec=importlib.util.spec_from_file_location('report',root/'report.py') +m=importlib.util.module_from_spec(spec); spec.loader.exec_module(m) +header='id,timestamp,team,amount\n' +cases=[('',[]),(header,[]), + (header+'a,2026-01-02T00:30:00+02:00,"Blue, East",0.10\nb,2026-01-01T12:00:00Z,"Blue, East",0.20\n', + [{'day':'2026-01-01','team':'Blue, East','count':2,'total':'0.30'}]), + (header+'a,2026-01-01T00:00:00Z,X,1.00\na,2026-01-02T00:00:00Z,Y,2.00\na,bad,X,9.00\n', + [{'day':'2026-01-02','team':'Y','count':1,'total':'2.00'}]), + (header+' a ,2026-01-01T00:00:00Z, X ,-2.10\nb,2026-01-01T00:00:00Z,X,0\n', + [{'day':'2026-01-01','team':'X','count':2,'total':'-2.10'}]), + (header+'a,2026-01-01T00:00:00,X,1\nb,2026-01-01T00:00:00Z,X,NaN\nc,2026-01-01T00:00:00Z,X,1.001\n,2026-01-01T00:00:00Z,X,2\nd,2026-01-01T00:00:00Z,,2\n',[]), + (header+'a,2026-01-02T00:00:00Z,B,1\nb,2026-01-01T00:00:00Z,Z,2\nc,2026-01-02T00:00:00Z,A,3\n', + [{'day':'2026-01-01','team':'Z','count':1,'total':'2.00'}, + {'day':'2026-01-02','team':'A','count':1,'total':'3.00'}, + {'day':'2026-01-02','team':'B','count':1,'total':'1.00'}])] +checks=[] +for i,(text,want) in enumerate(cases): + got=m.summarize(text); assert got==want,(i,got,want); checks.append('library-'+str(i)) +text,want=cases[2] +p=subprocess.run([sys.executable,str(root/'cli.py'),'-'],input=text,text=True,capture_output=True,timeout=10) +assert p.returncode==0 and json.loads(p.stdout)==want,p; checks.append('stdin') +f=root/'validator-input.csv';f.write_text(text) +p=subprocess.run([sys.executable,str(root/'cli.py'),str(f)],text=True,capture_output=True,timeout=10) +assert p.returncode==0 and json.loads(p.stdout)==want,p;checks.append('file');f.unlink() +p=subprocess.run([sys.executable,str(root/'cli.py'),str(root/'does-not-exist.csv')],text=True,capture_output=True,timeout=10) +assert p.returncode==2 and p.stderr and 'Traceback' not in p.stderr,p;checks.append('missing-file') +print(json.dumps({'passed':checks})) +''' + + +def get_json(url): + with urllib.request.urlopen(url, timeout=5) as response: + return json.load(response) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument('--config', type=Path, required=True) + ap.add_argument('--engine', type=Path, required=True) + ap.add_argument('--pi-package', type=Path, required=True) + ap.add_argument('--output', type=Path, required=True) + ap.add_argument('--port', type=int, default=11436) + ap.add_argument('--order', default='off,on', choices=('off,on', 'on,off')) + ap.add_argument('--run', action='store_true') + args = ap.parse_args() + if not args.run: + print('Dry run: private server, identical Pi A/B/A coding tasks, cache off/on, independent validators.') + return + args.output = args.output.resolve() + args.output.mkdir(parents=False, exist_ok=False) + cfg = json.loads(args.config.read_text()) + cfg.update(exe=str(args.engine.resolve()), cwd=str(ROOT), host='127.0.0.1', port=args.port) + work = args.output / 'workspace' + agent = args.output / 'agent' + agent.mkdir() + model = cfg['model_name'] + if model != 'qwen3.8-flash-next-iq3_s': + raise ValueError('This task is currently validated for qwen3.8-flash-next-iq3_s') + (agent/'models.json').write_text(json.dumps({'providers': {'strata-benchmark': { + 'baseUrl': f'http://127.0.0.1:{args.port}/v1', 'api': 'openai-completions', 'apiKey': 'local', + 'models': [{'id': model, 'reasoning': False, 'input': ['text'], 'contextWindow': 131072, + 'maxTokens': 2048, 'cost': {'input': 0, 'output': 0, 'cacheRead': 0, 'cacheWrite': 0}}], + 'compat': {'supportsStore': False, 'supportsDeveloperRole': False, 'supportsReasoningEffort': False} + }}})) + corpus = 'id,timestamp,team,amount\n' + ''.join( + f'r{i},2026-01-{i%28+1:02d}T12:00:00Z,Team{i%7},{i%100}.{i%97:02d}\n' for i in range(280)) + initial = {'SPEC.md': SPEC, 'sample.csv': corpus, + 'report.py': 'def summarize(text):\n raise NotImplementedError\n', 'cli.py': ''} + manifest = {name: hashlib.sha256(text.encode()).hexdigest() for name, text in initial.items()} + (args.output/'inputs.json').write_text(json.dumps(initial, indent=2)) + validator = args.output/'validate.py' + validator.write_text(VALIDATOR) + results = [] + for label in args.order.split(','): + run = args.output/label + run.mkdir() + if work.exists(): + shutil.rmtree(work) # only this harness's new, disposable task workspace + work.mkdir() + for name, text in initial.items(): + (work/name).write_text(text) + run_cfg = dict(cfg, args=list(cfg['args']), log=str(run/'engine.log')) + run_cfg['args'] += ['--conversation-cache-mib', '8192' if label=='on' else '0'] + config = run/'config.json' + config.write_text(json.dumps(run_cfg, indent=2)) + config.with_name('config.shared-settings.json').write_text(json.dumps({ + 'reasoning_effort': 'none', 'temperature': 0, 'max_tokens': 2048})) + record = {'mode': label, 'inputs_sha256': manifest} + with (run/'server.log').open('w') as log: + server = subprocess.Popen([sys.executable, '-m', 'serve.server', '--engine', 'strata', + '--config', str(config), '--host', '127.0.0.1', '--port', str(args.port)], + cwd=ROOT, stdout=log, stderr=subprocess.STDOUT, start_new_session=True) + try: + base = f'http://127.0.0.1:{args.port}' + for _ in range(180): + if server.poll() is not None: + raise RuntimeError('Private server exited; inspect server.log') + try: + get_json(base+'/health') + break + except OSError: + time.sleep(1) + else: + raise TimeoutError('Private server did not become ready') + started = time.monotonic() + with (run/'agent.log').open('w') as agent_log: + task = subprocess.run(['node', str(ROOT/'tools/agent_cache_task.mjs'), + str(args.pi_package.resolve()), str(work), str(agent), str(run/'task.json')], + cwd=work, stdout=agent_log, stderr=subprocess.STDOUT, timeout=750, + env={**os.environ, 'PI_OFFLINE': '1'}) + record.update(wall_s=time.monotonic()-started, agent_exit=task.returncode) + check = subprocess.run([sys.executable, str(validator), str(work)], + text=True, capture_output=True, timeout=30) + (run/'validation.txt').write_text(check.stdout+check.stderr) + record.update(validator_exit=check.returncode, success=task.returncode==check.returncode==0) + metrics = get_json(base+'/metrics?requests=all') + (run/'metrics.json').write_text(json.dumps(metrics, indent=2)) + record.update(totals=metrics['totals'], engine=metrics['engine']) + # Kernel high-water RSS for the engine, unlike periodic request-end samples. + children = Path(f'/proc/{server.pid}/task/{server.pid}/children').read_text().split() + record['child_memory_kib'] = {} + for pid in children: + status = Path(f'/proc/{pid}/status').read_text().splitlines() + record['child_memory_kib'][pid] = {s.split(':')[0]: int(s.split()[1]) + for s in status if s.startswith(('VmHWM:', 'VmRSS:'))} + shutil.copytree(work, run/'artifacts') + finally: + if server.poll() is None: + os.killpg(server.pid, signal.SIGINT) + try: + server.wait(timeout=30) + except subprocess.TimeoutExpired: + os.killpg(server.pid, signal.SIGTERM) + server.wait(timeout=10) + results.append(record) + (args.output/'results.json').write_text(json.dumps(results, indent=2)+'\n') + print(json.dumps(record), flush=True) + for key in ('expert_slots', 'context', 'kv', 'kv_resident', 'spec', 'mtp_max', 'lookup', 'pool_workers', 'pcie_frac'): + if results[0]['engine'][key] != results[1]['engine'][key]: + raise AssertionError(f'Unmatched engine configuration: {key}') + if not all(r['success'] for r in results): + raise SystemExit('Agent task or independent validation failed; no successful-task speedup claim') + + +if __name__ == '__main__': + main() diff --git a/tools/agent_cache_task.mjs b/tools/agent_cache_task.mjs new file mode 100644 index 00000000..75d1690c --- /dev/null +++ b/tools/agent_cache_task.mjs @@ -0,0 +1,106 @@ +// Bounded real Pi A -> B -> A coding workflow, used by agent_cache_benchmark.py. +import fs from 'node:fs'; +import path from 'node:path'; +import {pathToFileURL} from 'node:url'; + +const [packageDir, cwd, agentDir, output] = process.argv.slice(2); +const {createAgentSession, DefaultResourceLoader, ModelRuntime, SessionManager, SettingsManager} = + await import(pathToFileURL(path.join(packageDir, 'dist/index.js'))); +const runtime = await ModelRuntime.create({authPath: path.join(agentDir, 'auth.json'), + modelsPath: path.join(agentDir, 'models.json'), allowModelNetwork: false}); +const model = runtime.getModel('strata-benchmark', 'qwen3.8-flash-next-iq3_s'); +if (!model) throw new Error('Benchmark model unavailable'); +const events = fs.createWriteStream(output + '.events.jsonl'); +const sessions = []; +const phases = []; +const budgets = new WeakMap(); +const system = 'You are implementing a small Python standard-library project. Work only in the current directory. ' + + 'Do not access the network, install dependencies, or read parent directories. Use at most 12 tool calls per task. ' + + 'Keep tool outputs below 16000 characters and shell commands below 15 seconds. Implement the requested files, ' + + 'run focused checks, then give a short result. Do not build unrelated features.'; +async function makeSession() { + const budget = {calls: 0, limited: false}; + const settingsManager = SettingsManager.inMemory({compaction: {enabled: false}, retry: {enabled: false}}); + const loader = new DefaultResourceLoader({cwd, agentDir, settingsManager, noExtensions: true, + noSkills: true, noPromptTemplates: true, noThemes: true, noContextFiles: true, + extensionFactories: [pi => { + pi.on('tool_call', event => { + if (++budget.calls > 12) { + budget.limited = true; + return {block: true, terminate: true, reason: 'Benchmark tool-call limit'}; + } + if (event.toolName === 'bash') event.input.timeout = Math.min(event.input.timeout || 15, 15); + }); + pi.on('tool_result', event => { + let left = 16000; + return {content: event.content.map(part => { + if (part.type !== 'text') return part; + const text = part.text.slice(0, left); + left -= text.length; + return {...part, text: text + (text.length < part.text.length ? '\n[benchmark output limit]' : '')}; + })}; + }); + }], + systemPromptOverride: () => system}); + await loader.reload(); + const {session} = await createAgentSession({cwd, agentDir, model, modelRuntime: runtime, + thinkingLevel: 'off', tools: ['read', 'write', 'edit', 'bash'], resourceLoader: loader, + sessionManager: SessionManager.inMemory(), settingsManager}); + sessions.push(session); + budgets.set(session, budget); + return session; +} +async function phase(session, name, prompt) { + const budget = budgets.get(session); + budget.calls = 0; budget.limited = false; + const record = {name, tool_calls: 0, tool_ms: 0, turns: 0, limited: false}; + const activeTools = new Map(); + const started = performance.now(); + const unsubscribe = session.subscribe(event => { + events.write(JSON.stringify({phase: name, elapsed_ms: performance.now() - started, event}) + '\n'); + if (event.type === 'turn_start') record.turns++; + if (event.type === 'tool_execution_start') { + record.tool_calls++; + activeTools.set(event.toolCallId, performance.now()); + } + if (event.type === 'tool_execution_end') { + record.tool_ms += performance.now() - (activeTools.get(event.toolCallId) ?? performance.now()); + } + if (record.tool_calls > 12 || record.turns > 16) { + record.limited = true; + void session.abort(); + } + }); + const timeout = setTimeout(() => { record.limited = true; void session.abort(); }, 240000); + try { + await session.prompt(prompt); + const last = session.messages.filter(m => m.role === 'assistant').at(-1); + if (record.limited || budget.limited || !last || ['error', 'aborted'].includes(last.stopReason)) { + throw new Error(`Phase ${name} failed: ${last?.errorMessage ?? last?.stopReason ?? 'limit'}`); + } + record.answer = last.content; + } finally { + clearTimeout(timeout); unsubscribe(); record.wall_ms = performance.now() - started; + phases.push(record); + fs.writeFileSync(output, JSON.stringify({phases}, null, 2) + '\n'); + } +} +try { + const controller = await makeSession(); + const worker = await makeSession(); + await phase(controller, 'controller-implement', + 'Implement report.py summarize(text) using SPEC.md. Read the complete sample.csv (a realistic input corpus) ' + + 'before implementing. Implement only the library for now; another developer will implement cli.py. ' + + 'You may add small tests. Summarize what you implemented.'); + await phase(worker, 'worker-cli', + 'You are responsible for cli.py. Read SPEC.md and report.py, implement the specified CLI, and verify both ' + + 'file and stdin inputs. Do not modify report.py. Keep your answer brief.'); + await phase(controller, 'controller-integrate', + 'The CLI developer has finished. Read cli.py and verify the integrated project against SPEC.md, especially ' + + 'quoted commas, timezone-to-UTC day conversion, last-valid duplicate IDs, invalid rows, empty input, ' + + 'Decimal totals, stdin, and missing-file exit status. Fix any problems in report.py or cli.py. ' + + 'Run focused checks and report the result.'); +} finally { + for (const session of sessions) session.dispose(); + events.end(); +} From 089d4442789ac06c662af3c53d9f0328e89456c9 Mon Sep 17 00:00:00 2001 From: Jeremiah Ritchey <44681828+jeremiahritchey@users.noreply.github.com> Date: Tue, 29 Sep 2026 19:01:13 +0000 Subject: [PATCH 04/22] Enforce Pi benchmark request limits and engine memory evidence --- tools/agent_cache_benchmark.py | 9 ++++++++- tools/agent_cache_task.mjs | 6 ++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/tools/agent_cache_benchmark.py b/tools/agent_cache_benchmark.py index 74fa3838..8f817a54 100644 --- a/tools/agent_cache_benchmark.py +++ b/tools/agent_cache_benchmark.py @@ -157,9 +157,16 @@ def main(): children = Path(f'/proc/{server.pid}/task/{server.pid}/children').read_text().split() record['child_memory_kib'] = {} for pid in children: - status = Path(f'/proc/{pid}/status').read_text().splitlines() + try: + if Path(f'/proc/{pid}/comm').read_text().strip() != 'strata': + continue + status = Path(f'/proc/{pid}/status').read_text().splitlines() + except FileNotFoundError: + continue record['child_memory_kib'][pid] = {s.split(':')[0]: int(s.split()[1]) for s in status if s.startswith(('VmHWM:', 'VmRSS:'))} + if not record['child_memory_kib']: + raise RuntimeError('Missing engine high-water memory sample') shutil.copytree(work, run/'artifacts') finally: if server.poll() is None: diff --git a/tools/agent_cache_task.mjs b/tools/agent_cache_task.mjs index 75d1690c..13f6676c 100644 --- a/tools/agent_cache_task.mjs +++ b/tools/agent_cache_task.mjs @@ -24,6 +24,12 @@ async function makeSession() { const loader = new DefaultResourceLoader({cwd, agentDir, settingsManager, noExtensions: true, noSkills: true, noPromptTemplates: true, noThemes: true, noContextFiles: true, extensionFactories: [pi => { + pi.on('before_provider_request', event => { + const payload = {...event.payload, temperature: 0, max_tokens: 2048, + chat_template_kwargs: {enable_thinking: false}}; + delete payload.max_completion_tokens; + return payload; + }); pi.on('tool_call', event => { if (++budget.calls > 12) { budget.limited = true; From 055bc16e2ace5edc5aa1f5c3d09ce11d5eae93e9 Mon Sep 17 00:00:00 2001 From: Jeremiah Ritchey <44681828+jeremiahritchey@users.noreply.github.com> Date: Tue, 29 Sep 2026 19:18:37 +0000 Subject: [PATCH 05/22] Match upstream K8V4 flags when sizing conversation snapshots --- src/core/conversation_snapshot.cpp | 11 ++++++----- src/core/conversation_snapshot_test.cpp | 4 ++-- tools/agent_cache_task.mjs | 6 ++++-- 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/src/core/conversation_snapshot.cpp b/src/core/conversation_snapshot.cpp index b085da83..796d5c8b 100644 --- a/src/core/conversation_snapshot.cpp +++ b/src/core/conversation_snapshot.cpp @@ -25,19 +25,20 @@ bool valid_extent(const QsaState& st, int64_t upto, std::string& error) { bool layout(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index, Layout& l, std::string& error) { if (!valid_extent(st, upto, error)) return false; - if (st.kv_hybrid && (st.kv_mode != 0 || st.kv_q4 || !st.kv_int8)) { - error = "conversation snapshot: hybrid K8V4 requires identity-layout INT8 K"; + if (st.kv_hybrid && (st.kv_mode != 0 || st.kv_q4 || st.kv_int8)) { + error = "conversation snapshot: hybrid K8V4 requires an identity layout and distinct format flags"; return false; } const auto s = strata::kernels::qsa_real_shapes(); + const bool int8_keys = st.kv_int8 || st.kv_hybrid; if (g.n_head_kv <= 0 || g.head_dim <= 0 || g.head_dim > INT32_MAX || g.idx_key_dim <= 0 || - (st.kv_q4 && g.head_dim % 32) || (st.kv_int8 && !st.kv_q4 && g.head_dim % 64)) { + (st.kv_q4 && g.head_dim % 32) || (int8_keys && !st.kv_q4 && g.head_dim % 64)) { error = "conversation snapshot: invalid K/V geometry"; return false; } const int64_t cells = ((upto + s.page_size - 1) / s.page_size) * s.page_size; const size_t per = st.kv_q4 ? (size_t) strata::kernels::kv_q4_bytes_per_head((int) g.head_dim) - : (size_t) g.head_dim * (st.kv_int8 ? 1 : 2); + : (size_t) g.head_dim * (int8_keys ? 1 : 2); // Include the moving spare row, not only completed blocks. The checkpoint // restore reconstructs that row when rewinding to an earlier prefix. const int64_t pooled = index && upto > 0 ? upto / s.idx_block + 1 : 0; @@ -46,7 +47,7 @@ bool layout(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index using conversation_detail::product; if (!product(l.data, {(uint64_t) cells, (uint64_t) g.n_head_kv, per}) || !product(l.scales, {(uint64_t) cells, (uint64_t) g.n_head_kv, - st.kv_int8 && !st.kv_q4 ? (uint64_t) (g.head_dim / 64) * 2 : 0}) || + int8_keys && !st.kv_q4 ? (uint64_t) (g.head_dim / 64) * 2 : 0}) || !product(l.pooled, {(uint64_t) pooled, (uint64_t) g.idx_key_dim, sizeof(float)})) { error = "conversation snapshot: K/V byte count overflow"; return false; diff --git a/src/core/conversation_snapshot_test.cpp b/src/core/conversation_snapshot_test.cpp index f6b8e6fb..5b0343bd 100644 --- a/src/core/conversation_snapshot_test.cpp +++ b/src/core/conversation_snapshot_test.cpp @@ -42,10 +42,10 @@ struct Fixture { } Fixture(int fmt, int mode) { auto& st = state; - st.kv_mode = mode; st.kv_int8 = fmt==kKvInt8 || fmt==3; st.kv_q4 = fmt==kKvQ4; st.kv_hybrid = fmt==3; + st.kv_mode = mode; st.kv_int8 = fmt==kKvInt8; st.kv_q4 = fmt==kKvQ4; st.kv_hybrid = fmt==3; st.n_pages = 24; st.n_slots = mode ? 4 : st.n_pages; st.max_cells = st.n_pages * 4; st.idx_pooled_rows = mode==2 ? 2 : st.max_cells/4+2; - const size_t per = fmt==kKvQ4 ? kv_q4_bytes_per_head((int)g.head_dim) : g.head_dim*(st.kv_int8 ? 1:2); + const size_t per = fmt==kKvQ4 ? kv_q4_bytes_per_head((int)g.head_dim) : g.head_dim*((st.kv_int8 || st.kv_hybrid) ? 1:2); const size_t rows = st.max_cells*g.n_head_kv, slot_rows = st.n_slots*4*g.n_head_kv; sizes = {rows*per, rows*per, fmt==kKvInt8 ? rows*(g.head_dim/64)*2:0, fmt==kKvInt8 ? rows*(g.head_dim/64)*2:0, (size_t)st.idx_pooled_rows*g.idx_key_dim*4}; diff --git a/tools/agent_cache_task.mjs b/tools/agent_cache_task.mjs index 13f6676c..e48c7a78 100644 --- a/tools/agent_cache_task.mjs +++ b/tools/agent_cache_task.mjs @@ -41,9 +41,11 @@ async function makeSession() { let left = 16000; return {content: event.content.map(part => { if (part.type !== 'text') return part; - const text = part.text.slice(0, left); + const marker = '\n[benchmark output limit]'; + const text = part.text.length <= left ? part.text + : left >= marker.length ? part.text.slice(0, left - marker.length) + marker : ''; left -= text.length; - return {...part, text: text + (text.length < part.text.length ? '\n[benchmark output limit]' : '')}; + return {...part, text}; })}; }); }], From 717519d3451d4723c0d9b9f3fa2a3cda79ed6b98 Mon Sep 17 00:00:00 2001 From: Jeremiah Ritchey <44681828+jeremiahritchey@users.noreply.github.com> Date: Tue, 29 Sep 2026 19:28:37 +0000 Subject: [PATCH 06/22] Allow bounded Pi task completion and record benchmark provenance --- docs/plans/agent-cache-benchmark.md | 2 +- tools/agent_cache_benchmark.py | 4 +++- tools/agent_cache_task.mjs | 6 +++--- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/docs/plans/agent-cache-benchmark.md b/docs/plans/agent-cache-benchmark.md index ffd40d75..74789136 100644 --- a/docs/plans/agent-cache-benchmark.md +++ b/docs/plans/agent-cache-benchmark.md @@ -18,7 +18,7 @@ quoted commas, file/stdin CLI behavior and missing-file status. These validators run outside the agent workspace after the workflow finishes. A model's assertion that the task succeeded is not accepted as validation. -Each phase allows 12 executed tools, 16 model turns and 240 seconds. Bash calls +Each phase allows 24 executed tools, 32 model turns and 240 seconds. Bash calls are limited to 15 seconds and returned text to 16,000 characters per tool result. Requests use greedy sampling, disabled thinking, and at most 2,048 output tokens. No compaction, skills, discovered extensions, inherited context files or remote diff --git a/tools/agent_cache_benchmark.py b/tools/agent_cache_benchmark.py index 8f817a54..a36dc8fa 100644 --- a/tools/agent_cache_benchmark.py +++ b/tools/agent_cache_benchmark.py @@ -122,7 +122,9 @@ def main(): config.write_text(json.dumps(run_cfg, indent=2)) config.with_name('config.shared-settings.json').write_text(json.dumps({ 'reasoning_effort': 'none', 'temperature': 0, 'max_tokens': 2048})) - record = {'mode': label, 'inputs_sha256': manifest} + record = {'mode': label, 'inputs_sha256': manifest, + 'task_script_sha256': hashlib.sha256((ROOT/'tools/agent_cache_task.mjs').read_bytes()).hexdigest(), + 'engine_sha256': hashlib.sha256(args.engine.read_bytes()).hexdigest()} with (run/'server.log').open('w') as log: server = subprocess.Popen([sys.executable, '-m', 'serve.server', '--engine', 'strata', '--config', str(config), '--host', '127.0.0.1', '--port', str(args.port)], diff --git a/tools/agent_cache_task.mjs b/tools/agent_cache_task.mjs index e48c7a78..93a6df3e 100644 --- a/tools/agent_cache_task.mjs +++ b/tools/agent_cache_task.mjs @@ -15,7 +15,7 @@ const sessions = []; const phases = []; const budgets = new WeakMap(); const system = 'You are implementing a small Python standard-library project. Work only in the current directory. ' - + 'Do not access the network, install dependencies, or read parent directories. Use at most 12 tool calls per task. ' + + 'Do not access the network, install dependencies, or read parent directories. Use at most 24 tool calls per task. ' + 'Keep tool outputs below 16000 characters and shell commands below 15 seconds. Implement the requested files, ' + 'run focused checks, then give a short result. Do not build unrelated features.'; async function makeSession() { @@ -31,7 +31,7 @@ async function makeSession() { return payload; }); pi.on('tool_call', event => { - if (++budget.calls > 12) { + if (++budget.calls > 24) { budget.limited = true; return {block: true, terminate: true, reason: 'Benchmark tool-call limit'}; } @@ -74,7 +74,7 @@ async function phase(session, name, prompt) { if (event.type === 'tool_execution_end') { record.tool_ms += performance.now() - (activeTools.get(event.toolCallId) ?? performance.now()); } - if (record.tool_calls > 12 || record.turns > 16) { + if (record.tool_calls > 24 || record.turns > 32) { record.limited = true; void session.abort(); } From 28d07f8a1a8eaa1a6375e3e67660736143ccb159 Mon Sep 17 00:00:00 2001 From: Jeremiah Ritchey <44681828+jeremiahritchey@users.noreply.github.com> Date: Tue, 29 Sep 2026 19:38:45 +0000 Subject: [PATCH 07/22] Record upstream integration, Linux acceptance and controlled Pi results --- docs/plans/shared-conversation-snapshots.md | 2 + ...shared-conversation-upstream-validation.md | 171 ++++++++++++++++++ docs/plans/shared-conversation-validation.md | 3 + 3 files changed, 176 insertions(+) create mode 100644 docs/plans/shared-conversation-upstream-validation.md diff --git a/docs/plans/shared-conversation-snapshots.md b/docs/plans/shared-conversation-snapshots.md index 07e33177..0b4699e3 100644 --- a/docs/plans/shared-conversation-snapshots.md +++ b/docs/plans/shared-conversation-snapshots.md @@ -14,6 +14,8 @@ Parking rejects `--layer-split` while ordinary upstream multi-device checkpoint handling is retained. Checkpoint LRU stamps and system-prompt/root retention are preserved. K8V4 snapshots store separate INT8 K/scales and Q4 V payloads; hybrid streaming/ring layouts are rejected before calling upstream's block movers. +See the [current integration and validation record](shared-conversation-upstream-validation.md) +for revision-specific evidence and platform limits. ## Boundaries diff --git a/docs/plans/shared-conversation-upstream-validation.md b/docs/plans/shared-conversation-upstream-validation.md new file mode 100644 index 00000000..0910f9f0 --- /dev/null +++ b/docs/plans/shared-conversation-upstream-validation.md @@ -0,0 +1,171 @@ +# Shared-core integration onto upstream 0.1.25 + +Integration base: upstream `8fc40dd`, fetched 2026-09-29. Implementation starts +at `cabd50c`; Windows test contribution is preserved as `b319d43` (original +`32cf918`, by @midhatn). The earlier 0.1.18 validation record describes a different +revision and remains historical evidence. + +Issue #57 references: [unified PR ownership](https://github.com/Niko1221/Strata/issues/57#issuecomment-5875083621), +[current upstream/single-GPU scope](https://github.com/Niko1221/Strata/issues/57#issuecomment-5887959836), +and the [Windows test contribution](https://github.com/jeremiahritchey/Strata/pull/1). +Upstream had advanced from the requested 0.1.22 to 0.1.25 when fetched; this +record pins the exact revision rather than referring to a moving main branch. + +## Integration decisions + +- Preserve upstream's root-pinned/LRU checkpoint policy and retain last-use + stamps when parking a conversation. +- Preserve the existing layer-split checkpoint representation. Whole-session + parking with `--layer-split` is explicitly rejected before loading the model; + multi-GPU parking is deferred as permitted in issue #57. +- Retain chunked indexer processing and restore the per-sequence spare key, + block-position metadata and spare pooled row at checkpoint resume. +- Add K8V4 snapshot layout support: independently size/copy INT8 K, K scales and + Q4 V; the draft ring remains plain INT8. Reject hybrid streaming/ring layouts. +- Use the selected CUDA/HIP runtime target in CMake; CUDA linker-wrap fault + tests are not registered for HIP. No HIP runtime validation is claimed. + +## Windows review + +The contributed change modifies only `conversation_memory_test.cpp`. Under +Windows it checks that `GlobalMemoryStatusEx` succeeds and that the helper's +sample is known and no larger than total physical RAM. Comparing against total +RAM avoids a race between two available-memory samples. It neither allocates +pressure memory nor changes admission behavior. No review defect was found. + +This machine cannot run Windows/MSVC tests. The contributor reported 25 passing +MSVC checks in their PR; those are their results, not locally reproduced results. +Local Linux compilation runs the existing 23 admission checks. Full Windows +restore, memory-pressure and agent acceptance remain outstanding. + +## Local environment and evidence + +Linux, EPYC 7532, RTX 4090; GCC 15.2, CUDA 13.4, Release build, SM89, portable +AVX2. IQ3_S model; INT8 KV, 131,072 context and 32,768 GPU-resident KV cells for +the primary full-model gates. Engines run sequentially on the exclusive GPU. + +The private evidence directory is `logs/upstream-20260929/`. For paired model +tests, `--expert-cache 6000` yields 7,846 variable-sized expert slots; the PCIe +share is fixed to 0.55. Both engines must report matching residency and other +inference settings. The first attempt requested 8,700 uniform slots, was trimmed +to different residency by VRAM availability, and failed the comparison guard. +That attempt is retained under `spec1/` and excluded from accepted evidence. + +The entire optional upstream test build cannot configure because +`bench/micro/native_mmvq_multi.cpp` and `bench/micro/hit_cpu_order_parity.cu` are +absent at this revision. Focused conversation, checkpoint-retention and sampler +targets are built instead. Do not report this as a full upstream test-suite pass. + +The controlled local Pi task is documented in [agent-cache-benchmark.md](agent-cache-benchmark.md). +Results below must remain tied to the actual tested executable/configuration; +synthetic reuse timings are not version-to-version performance comparisons. + +## Results + +Completed checks: + +- Seven focused CTest targets: RAM policy, admission, GPU snapshot round trips, + whole-image validation, injected transfer failures, upstream root/LRU retention, + and sampler parity. K8V4 and checkpoint-stamp fixtures are included. +- 65 server Python tests (three skipped) and 47 tool tests passed; the 22 cache + harness tests also passed with Python assertions disabled (`-O`). +- ASan/UBSan: 35 RAM-policy checks, 23 admission checks, and 1,116 host validation/ + transfer-failure checks passed. The latter compiles snapshot/state code with + sanitizers and uses wrapped copies/synchronization, not CUDA hardware failures. +- Ten CLI checks: malformed/negative/overflowing options rejected and enabled + layer-split parking refused before loading a model. +- Nine full-model paired gates passed: single-token and long speculative A/B/A, + checkpoint recovery, byte pressure, oversized entries, incoming/outgoing + exchange budget, deliberate RAM-admission denial, synthetic image identity, + and add/project steering isolation. + +In the long speculative run, returning to the 55,009-token A reused all 55,009 +and processed 22 new tokens in 1.2559 seconds including snapshot work. Checkpoint +return reused 55,024 tokens and processed seven in 0.5746 seconds. Both output +and main-model fingerprints matched the uninterrupted baseline. This is an +intra-revision cache test, not a comparison against 0.1.18. + +The 30-cycle soak passed at approximately 2k, 40k and 120k tokens. Every output +and main-model fingerprint matched its uninterrupted baseline. Cache payload +plateaued for each repeated context rather than growing each cycle. + +The nine INT8 gates and soak above used executable SHA-256 +`0d8cbca38ce27153cea516cf6454df4653196ae875e0224fd3dd3c51e1d27ea0`. +A subsequent full-model K8V4 gate exposed a format-flag mismatch: upstream uses +`kv_hybrid=true` with `kv_int8=false`, while the initial fixture incorrectly set +both. Parking was skipped; the gate failed its reuse assertion. The layout and +fixture now reflect upstream's distinct flags. The failed attempt is retained +in `k8v4/`; final checks use `k8v4-fixed/` and executable SHA-256 +`4e174e8a4b602f1f8efe846cf19570478fcc7d2b50f3c48373c799d39b3610c7`. + +On the corrected executable, K8V4 and INT8 full-model A/B/A plus checkpoint +parity both passed (including byte-exact main-model fingerprints). The three +snapshot/validation/transfer CTest targets and 1,116 ASan/UBSan transfer checks +were rerun successfully. The twelve-request HTTP smoke passed reuse, slot +eviction, disconnect cancellation and recovery with the same engine process. + +The initial Pi pair (`pi-off-on/`) used a 12-tool/16-turn cap. Cache-off hit the +tool cap while correcting its own sample-data test expectations and did not +reach the CLI phase; cache-on completed all ten independent checks in 108.7 s. +This incomplete pair does not support a speedup claim. Both modes were repeated +with the same revised allowance of 24 tools/32 turns per phase; the 240-second +phase timeout, fixed task inputs and independent validators remain unchanged. + +Both revised pairs passed all ten independent checks in all four runs: + +| Order | Parking | Task seconds | Requests | Output tokens | Prompt seconds | Decode seconds | Engine peak RSS GiB | +| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | +| off → on | off | 91.59 | 20 | 6,319 | 23.259 | 64.865 | 49.734 | +| off → on | on | 108.37 | 28 | 7,361 | 25.750 | 78.780 | 53.433 | +| on → off | on | 104.57 | 23 | 7,274 | 22.823 | 78.350 | 53.433 | +| on → off | off | 111.39 | 26 | 7,525 | 27.948 | 79.471 | 51.979 | + +The controller's first return request took 4.334 s with parking off (15,431 +prompt tokens, zero reused), versus 1.503 s with parking on (16,333 prompt +tokens, 15,810 reused). Total task time increased in this pair while the +agent followed a different tool path and generated more output. This is not +evidence of an end-to-end speedup. RSS is Linux VmHWM for the engine, including +startup and model mappings, not cache payload or GPU memory. + +In reverse order, the return request took 5.777 s with parking off (17,113 +prompt tokens, zero reused), versus 1.522 s with parking on (16,165 prompt +tokens, 15,620 reused). Whole-task timing favored cache-on in this repetition +(104.57 vs 111.39 s), reversing the first pair. With different generated output +and tool paths, two pairs do not establish an overall speedup or regression. +The consistent finding is reduced return-prefill work: approximately 2.9–3.8× +faster for these observed requests, with higher engine peak RSS. Prompt lengths +are similar but not identical, so this is a workload observation, not a matched +microbenchmark ratio. + +Task wall time excludes server/model startup. All runs used 7,846 expert slots, +INT8 KV, 131,072 context, 32,768 resident cells and the same speculative settings. +The runner verified matching engine settings within each pair. It records +executable/task-script hashes and identical initial-file hashes for each mode; +per-run tool execution totaled 0.96–1.15 s. Private detail is retained in +`pi-bounded-off-on/`, `pi-bounded-on-off/`, and `pi-comparison.json`. + +## Scope and remaining validation + +These results cover this Linux/RTX 4090 host and the local IQ3_S model. Windows +runtime acceptance, HIP execution, multi-GPU parking, real vision-encoder +integration, and the larger Coder model remain untested here. Synthetic image +identity and model-geometry fixtures do not replace those runtime checks. +The NVMe backend remains a separate integration; this work validates the RAM +backend and shared snapshot representation. No upstream PR or issue comment +was posted as part of this local validation. + +This benchmark compares conversation parking on/off within the integrated +0.1.25 executable. It cannot establish whether 0.1.25 is faster or slower than +the earlier 0.1.15/0.1.18 branches, nor reproduce the previous Windows workload. + +## Local deployment + +The tested executable is running from `Strata-conversation-cache-upstream`, +branch `feat/conversation-cache-upstream`, in tmux pane `%15` on port 11434. +The runtime configuration is `logs/runtime-20260929-191116/engine-config.json`. +It preserves the user's automatic expert allocation, 131,072 context, INT8 KV, +32,768 resident cells, 8 GiB conversation budget, four slots and 2,560 MiB RAM +floor. Automatic allocation selected 8,814 expert slots; this differs from the +fixed 7,846-slot benchmark allocation and is not included in its timing claims. +Health and a non-streaming generation request passed (`OK`), with the server +idle and zero queued requests afterward. Earlier worktrees remain intact. diff --git a/docs/plans/shared-conversation-validation.md b/docs/plans/shared-conversation-validation.md index 0f549c23..18f27c75 100644 --- a/docs/plans/shared-conversation-validation.md +++ b/docs/plans/shared-conversation-validation.md @@ -1,5 +1,8 @@ # Shared snapshot core: validation record +Historical 0.1.18 evidence. The later integration is documented separately in +[the upstream 0.1.25 validation record](shared-conversation-upstream-validation.md). + Date: 2026-09-28. Engine source: `3657b8f`, based on upstream `b38c183` (0.1.18). This is development-branch evidence for the RAM tier/shared core, not acceptance of a combined RAM/NVMe implementation or a deployment report. From 4ac028522e40ef9b86dde7a64f34316db4927f5c Mon Sep 17 00:00:00 2001 From: Jeremiah Ritchey <44681828+jeremiahritchey@users.noreply.github.com> Date: Tue, 29 Sep 2026 21:50:38 +0000 Subject: [PATCH 08/22] Focus shared-core patch on runtime, regression tests and current documentation --- docs/DETAILS.md | 2 +- docs/plans/agent-cache-benchmark.md | 50 ---- docs/plans/multi-conversation-cache.md | 240 ------------------ docs/plans/shared-conversation-snapshots.md | 206 +++++---------- ...shared-conversation-upstream-validation.md | 217 +++++----------- docs/plans/shared-conversation-validation.md | 138 ---------- tools/agent_cache_benchmark.py | 192 -------------- tools/agent_cache_task.mjs | 114 --------- tools/conversation_cache_isolation.py | 17 +- tools/conversation_cache_parity.py | 34 ++- tools/conversation_cache_soak.py | 15 +- 11 files changed, 149 insertions(+), 1076 deletions(-) delete mode 100644 docs/plans/agent-cache-benchmark.md delete mode 100644 docs/plans/multi-conversation-cache.md delete mode 100644 docs/plans/shared-conversation-validation.md delete mode 100644 tools/agent_cache_benchmark.py delete mode 100644 tools/agent_cache_task.mjs diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 5e97ffee..0d043b75 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -402,7 +402,7 @@ moving spare row are preserved, including checkpoint rewinds. These development changes and the optional disk-tier boundary are described in the [shared-core proposal](plans/shared-conversation-snapshots.md). The engine log reports parking, restoration, bytes and evictions. Snapshots are not -persisted across restarts. See [the design and validation gates](plans/multi-conversation-cache.md). +persisted across restarts. See [the design and validation gates](plans/shared-conversation-snapshots.md). **Current limits (v1):** one request at a time, and one conversation cached at a time (switching between two chats re-reads the other one unless the opt-in cache above is enabled); images only when set up with them (below); no video. **Temperature / top_p / top_k / min_p / diff --git a/docs/plans/agent-cache-benchmark.md b/docs/plans/agent-cache-benchmark.md deleted file mode 100644 index 74789136..00000000 --- a/docs/plans/agent-cache-benchmark.md +++ /dev/null @@ -1,50 +0,0 @@ -# Controlled local Pi cache comparison - -`tools/agent_cache_benchmark.py` runs a bounded real coding task through the Pi -SDK with parking disabled and enabled. It defaults to a dry run and never uses -an existing server. `--run` requires an exclusive GPU window, the configured -model assets, Node.js, and an installed `@earendil-works/pi-coding-agent` package. - -Both runs start from identical files and use the same working-directory path, -prompts, model configuration and tool limits. Each loads a fresh private server. -The workflow is controller A implementing a CSV-report library, worker B adding -its CLI, then A returning to verify/fix the integration. This exercises real file -edits and shell checks rather than replaying prerecorded model responses. The -input corpus is generated public test data, not a user conversation. - -The task uses the Python standard library. Ten independent checks cover UTC -date grouping, decimal sums, sorting, invalid input, last-valid duplicate IDs, -quoted commas, file/stdin CLI behavior and missing-file status. These validators -run outside the agent workspace after the workflow finishes. A model's assertion -that the task succeeded is not accepted as validation. - -Each phase allows 24 executed tools, 32 model turns and 240 seconds. Bash calls -are limited to 15 seconds and returned text to 16,000 characters per tool result. -Requests use greedy sampling, disabled thinking, and at most 2,048 output tokens. -No compaction, skills, discovered extensions, inherited context files or remote -model catalogs are loaded. Generated event logs remain local; review them before -publishing any benchmark artifact. - -Example (paths to the local model configuration and Pi installation are supplied -by the operator): - -```sh -python tools/agent_cache_benchmark.py \ - --config /path/to/engine-config.json --engine build-validation/strata \ - --pi-package /path/to/node_modules/@earendil-works/pi-coding-agent \ - --output /path/to/new-results --run -``` - -Use a fixed expert allocation small enough that neither engine trims it for -VRAM headroom. The harness rejects mismatched engine settings. `--order on,off` -supports a reverse-order repetition; changing the order is not a substitute for -reporting repeat variability. - -Results include task wall time (excluding model startup), per-phase/tool times, -prompt/decode times, token reuse and generation volume, engine configuration, -independent success status, generated files, and the engine's Linux kernel -high-water RSS. RSS includes startup and model mappings; it is not a system-wide -or GPU peak-memory measurement. Normal speculative inference can produce -different tool paths, so report output/task differences and do not infer a -general speedup from a single pair. This local workload does not reproduce the -earlier remote Windows game-building workflow. diff --git a/docs/plans/multi-conversation-cache.md b/docs/plans/multi-conversation-cache.md deleted file mode 100644 index 0a2cb070..00000000 --- a/docs/plans/multi-conversation-cache.md +++ /dev/null @@ -1,240 +0,0 @@ -# Multi-conversation caching - -## Objective and evidence - -Keep Pi controller and worker conversations warm when their requests interleave, -without requiring a Pi-specific session ID or changing the generated prompt. -The existing server caches one conversation. Observed controller requests reread -46,856, 46,974, and 47,644 tokens after worker requests, spending 143 seconds in -prompt processing. A subsequent packet capture verified 21 continuing turns with -unchanged history and reasoning: do not modify Pi's reasoning serialization. - -This feature does not shorten tool results or fix the separate, unproven cause of -one historical within-conversation 12,038-token replay. - -## Design - -- Opt-in engine flags: `--conversation-cache-mib N` (default 0/off) and - `--conversation-cache-slots N` (default 4 parked conversations). -- Keep existing single-conversation behavior and fast-path cost when disabled. -- Search the active state and parked states for the longest exact token prefix. - Images and control-vector mode must also match. Prefer active state on ties. -- Before overwriting an eligible active state, snapshot its running state, - checkpoints, main-layer K/V, completed indexer rows, and draft-layer K/V. -- Park in ordinary host RAM, not additional VRAM. Preserve graph-bound addresses - by copying back into existing allocations. Streamed K/V snapshots use the - authoritative host pools; restore invalidates main-layer residency maps and - refills the draft ring before reuse. -- Save only used pages, not the full maximum context allocation. Full pages - preserve the page/head/cell layout, including partially filled final pages. -- Evict least-recently-active parked entries to satisfy slot and byte limits. - Count an incoming restore image against the byte budget during an exchange. - An oversized snapshot or allocation failure skips parking, not inference. -- Cache misses retain normal prompt processing; image or steering changes cannot - reuse incompatible state. No persistence to disk and no raw conversation logs. -- Keep checkpoint fallback available inside each parked conversation. - -The budget covers snapshot payload allocations, including retained checkpoint -buffers. It is additional to the active engine's normal state/checkpoint memory; -allocator bookkeeping and small container overhead are not exact RSS accounting. - -## Correctness gates - -1. CPU policy tests: A/B/A reuse, checkpoint fallback, image identity, steering - isolation, longest prefix and ties, byte/slot eviction, oversized entries, - disabled cache, short/equal prompts, and in-flight restore accounting. -2. Snapshot tests: byte-exact save/restore across FP16, INT8 and Q4 K/V, resident - and streamed layouts, draft rings, partial pages, and indexer boundaries. -3. Full engine builds; disabled option retains existing behavior. -4. Controlled A/B/A serving parity versus an uninterrupted A baseline, including - returning through a checkpoint, with fixed expert residency and deterministic - sampling. Verify restore tokens and compare running/KV state hashes. -5. Measure long-context switching time and memory bounds; test budget eviction - and cancellation. Do not claim end-to-end speedups from component tests. - -## Operational constraints - -Full-model tests load private engines and require an available GPU. Run them in -a maintenance window or on separate hardware; do not load a second model beside -a production engine unless there is sufficient GPU and host memory. - -## Status - -This document's historical results describe the original prototype and its -0.1.15 integration. The separate 0.1.18 development branch now has a -[shared-core proposal and acceptance checklist](shared-conversation-snapshots.md). -Its audit found that the original snapshots/fingerprints omitted `idx_dead` and -the moving indexer spare row; the new core preserves these and the new harnesses -require the expanded fingerprint. Earlier parity results remain valid only for -the fields and fixtures actually measured, not those previously omitted fields. - -Feature implemented; all five correctness gates above have passing evidence for -the original feature revision `9d154ed`, before the upstream integration below. -Verified on 2026-09-28: - -- Full CUDA 13.4 / SM89 portable-AVX2 engine build and help smoke test pass. -- CPU policy: 35 checks pass, also under AddressSanitizer/UBSan. -- GPU snapshots: 891 checks pass across FP16/INT8/Q4, resident/streamed/ring - storage, zero/full/partial pages, indexer boundaries, malformed payloads, and - incompatible geometry, and invalid/overflowing extents. GPU fixtures are small - and do not load a model. -- All 17 existing Python server tests pass using mock engines. -- 12 CLI parsing checks pass; new C++ modules pass `-Wall -Wextra -Werror`. -- Seventeen harness unit tests pass normally and under Python `-O`, including - rejection of incomplete evidence, native-IQ window configuration, byte-pressure - evidence validation, offline HTTP orchestration, and no-traffic dry-run checks. - -Full-model IQ3_S gates passed in an isolated test window, using a 262144-token -context, INT8 K/V with 32768 -resident cells, and the same 8000 expert slots in each paired run: - -- Single-token decoding: A/B/A and parked-checkpoint recovery reproduce both - output tokens and byte-exact main-model state fingerprints. -- Speculative decoding (`--spec 4`, suffix drafting off, fixed expert residency): - the same checks pass with 49909-token A and 49911-token B. Main-model state - fingerprints also match, although this gate only requires output parity. -- Initial A prompt read: 48.809 seconds. Returning to A after B: 49909 tokens - reused, 22 new tokens read, 1.961 seconds of prompt processing including - parking/restoring. This is a synthetic switching result, not a general decode - speedup or a matched uncached A/B/A replay benchmark. -- Returning through A's checkpoint: 49924 tokens reused, 7 read, 1.101 seconds. - Parking A used 1352930652 bytes; parking the continued A used 1471553864 bytes. - Restoring a parked state took 182–201 ms in this long-context run. -- HTTP checks on the candidate with normal production speculative/adaptive - settings: A/B/A returns the same text, reusing 1957 of 1964 prompt tokens. - Five intervening distinct conversations evict A; requesting it again reads - from zero. Logs show four parked slots and increasing eviction counts. -- HTTP streaming disconnect after five output tokens: the engine stays alive, - serves an unrelated B, then restores 1054 of the cancelled A's 1061 tokens. - The frontend and engine remained running without a restart throughout these checks. -- Byte pressure: a 400 MiB cache holds each ~254 MiB snapshot individually, but - not two. A/B/C/A produced two byte-driven evictions with only one parked slot - occupied. Output and main-model state match the cache-disabled sequence. -- Oversized snapshots: with a 1 MiB budget, all three attempted parks are skipped; - ordinary inference continues with output and state matching the baseline. -- In-flight budget: A/B/A and checkpoint recovery also pass at 400 MiB. Two - outgoing parks are skipped while the incoming snapshot is held, preserving the - restore and keeping allocated parked/transfer payload within the budget. -- Image isolation: real `GENI` requests with synthetic embeddings reject reuse - when embedding values or image-grid geometry change. Returning to the original - image restores 773 of 780 tokens with exact output/main-model state parity. -- Steering isolation: nonzero synthetic control vectors in both add and project - modes change actual model state. Switching on/off never reuses incompatible - state; returning to each mode restores 766 of 773 tokens with exact output and - main-model state parity. These are cache tests, not steering-quality tests. -- The packaged HTTP smoke test also passes against the restored service: - A/B/A, four-slot eviction, disconnect cancellation and cached recovery. Engine - and frontend remained running without a restart throughout that test. - -Raw synthetic test evidence is retained locally in the ignored -`logs/conversation-validation-2026-09-28/`: `spec1-supported`, `spec4-long`, -`pressure`, `oversized`, `exchange`, `image`, `steering-add`, and `steering-project` -(each contains engine logs and `results.json`), plus `http-smoke.json` for the -packaged HTTP check. -The original `spec1` attempt failed at startup because native IQ packs require -engine `--spec >= 2`; the harness now uses the supported configuration below. - -`tools/conversation_cache_parity.py` prepares the controlled runtime gate. It -defaults to a dry run and requires `--run` to launch private model processes. -Provide `--config`, `--engine`, and a new `--output` directory. Run first with -`--spec 1` for byte-exact main-model state, then `--spec 4` for speculative output -parity. The single-token gate configures engine `--spec 2 --mtp-max-t 1` because -native IQ packs require a speculative-capable engine even with one-token decode -windows. It compares an uninterrupted A/A+ baseline against A/B/A+, then exercises -a parked checkpoint by switching away and repeating A+. It never connects to an -existing HTTP server. Use only in a separately authorized GPU test window. - -The image tests exercise the serving engine's embedding-input and M-RoPE paths, -not a vision encoder or image-recognition quality. The live Pi configuration -remains text-only with no control vector loaded. - -### Reproducible checks - -The parity script now accepts `--scenario pressure` and `--scenario oversized`. -Both run A/B/C/A with one output token per request, compare against the same -cache-disabled sequence, and require output and main-model state parity. For -this IQ3_S model at the default 128 paragraphs, use `--cache-mib 400` for byte -pressure (one snapshot fits, two do not) and `--cache-mib 1` for oversized skips. -The byte-pressure gate rejects slot-limit eviction as insufficient evidence; -the oversized gate requires all three attempted parks to be skipped. Both gates -passed in the full-model test window. - -`--scenario exchange --cache-mib 400` instead runs the A/B/A continuation and -checkpoint sequence while requiring two outgoing parks to be skipped because an -incoming snapshot is still held. This specifically tests the temporary byte -budget during restoration, in addition to ordinary byte-driven eviction. This -gate also passed. - -`tools/conversation_cache_isolation.py` takes the same `--config`, `--engine`, -`--output`, and explicit `--run` arguments. Run `--scenario image`, `--scenario add`, -and `--scenario project` in separate new output directories. All three gates -passed. They generate small deterministic embedding/control-vector fixtures and -load baseline/candidate engines sequentially. Do not run any model gate beside -the production engine unless sufficient GPU capacity is separately available. - -For standalone component tests, configure with -`-DSTRATA_BUILD_CONVERSATION_TESTS=ON`; build `conversation_cache_test` and, with -CUDA enabled, `conversation_snapshot_test`. Run: - -```sh -ctest --test-dir build-conversations -R '^conversation_(cache|snapshot)_test$' --output-on-failure -python -m unittest tools.test_conversation_cache_parity tools.test_conversation_cache_isolation tools.test_conversation_cache_http_smoke -``` - -`tools/conversation_cache_http_smoke.py --output NEW_RESULTS.json` defaults to -no traffic. Adding `--run` targets `http://127.0.0.1:11434` (override with `--url`) -and exercises A/B/A, slot eviction, streaming cancellation, and recovery. Use -only with an exclusive idle test endpoint: it intentionally displaces cached -conversations. An idle check cannot lock out new clients, so pause other clients -first. Both the one-off sequence and the packaged script have passed against the -real cache-enabled HTTP server. - -### Upstream integration (2026-09-28) - -Merged upstream `main` at `d551edf` (engine 0.1.15). The serving INFO-line -conflict was resolved by retaining both engine-version reporting and the -conversation-cache settings. Upstream prefill/MMQ and AVX2 changes are retained. - -The merged tree passes a separate CUDA 13.4 / SM89 portable-AVX2 engine build, -35 CPU cache-policy checks, 891 GPU snapshot checks, 12 CLI parsing/help checks, -and 35 Python tests (17 cache-harness tests and 18 server tests). - -The merge itself did not restart or reconfigure the running engine. In a -subsequently authorized maintenance window, all eight full-model gates passed -on merged revision `eb6a392`: single-token reuse/checkpoint state parity, long -speculative reuse/checkpoint parity, byte-pressure eviction, oversized snapshots, -incoming/outgoing exchange budgeting, image identity, and control-vector -isolation in add/project modes. The 12-request HTTP smoke test also passed on -an exclusive localhost endpoint with normal adaptive settings, including slot -eviction, streaming cancellation, and cached recovery without a process restart. - -The merged long-context test used 51133-token A and 51135-token B, fixed 8700 -expert slots, INT8 KV with 32768 resident cells, spec 4, and suffix drafting off. -Initial A read took 46.558 seconds. Returning after B reused 51133 tokens and -read 22 in 1.363 seconds including parking/restoring; checkpoint recovery reused -51148 tokens and read 7 in 0.580 seconds. Both restored outputs and main-model -state fingerprints match the uninterrupted baseline. This synthetic switch test -is not a matched performance comparison against the original feature binary. - -Evidence is retained locally under the ignored -`logs/upstream-merge-validation-20260928-F1emt1/` directory, including paired -engine logs/results and `http-smoke.json`. The earlier measurements above remain -specific to the original feature revision. - -## Deployment and rollback - -The original Pi trial used an 8192 MiB host-RAM budget and four parked slots, with -the existing text-only model configuration otherwise unchanged. HTTP health -and generation checks pass; image/steering tests ran in separate private engines. - -After the upstream-integration gates passed, the merged engine was deployed -with the same 8192 MiB/four-slot cache settings. The normal launch configuration -selects the merged binary; the prior binary and configuration are preserved for -rollback. Final HTTP generation and idle/empty-queue health checks passed. - -To try this feature, preserve the original binary and configuration, then add -the two opt-in flags to the engine arguments and restart in a maintenance window. -To disable parking, remove the flags or set `--conversation-cache-mib 0` and -restart. To roll back the binary, gracefully stop the candidate, verify its engine -exited, then start the original binary with the original configuration. Never -start both model processes on the same GPU without sufficient free memory. diff --git a/docs/plans/shared-conversation-snapshots.md b/docs/plans/shared-conversation-snapshots.md index 0b4699e3..f7cfc4d0 100644 --- a/docs/plans/shared-conversation-snapshots.md +++ b/docs/plans/shared-conversation-snapshots.md @@ -1,159 +1,73 @@ -# Shared conversation snapshots: convergence proposal +# Conversation snapshots and RAM cache -Status: shared-core development for issues/PRs #41, #52 and #57. In the issue's -September 28 follow-up the maintainer asked @jeremiahritchey to own the unified -PR, @midhatn to review Windows admission/acceptance, and @maedoc to layer optional -NVMe persistence on the core. The September 29 follow-up permits the single-GPU -core to land first. This is not a merged upstream feature or acceptance of the -separate disk implementation. +[Issue #57](https://github.com/Niko1221/Strata/issues/57) preserves reusable state +when independent agent conversations alternate on one server. Requests remain +serial, require no client session markers, and restore into existing allocations. +The shared core and RAM policy land first; the optional NVMe tier is a dependent +integration, following the [maintainer's requested order](https://github.com/Niko1221/Strata/pull/52#issuecomment-5898176448). -The original evidence targets upstream `b38c183` (0.1.18). Current integration -is based on `8fc40dd` (0.1.25), fetched September 29 after main advanced beyond -the requested 0.1.22. The earlier branches and their evidence remain separate. -Parking rejects `--layer-split` while ordinary upstream multi-device checkpoint -handling is retained. Checkpoint LRU stamps and system-prompt/root retention are -preserved. K8V4 snapshots store separate INT8 K/scales and Q4 V payloads; hybrid -streaming/ring layouts are rejected before calling upstream's block movers. -See the [current integration and validation record](shared-conversation-upstream-validation.md) -for revision-specific evidence and platform limits. +## Ownership and matching -## Boundaries +- `conversation_snapshot.hpp`, `conversation_snapshot.cpp`, and + `conversation_state.cpp` define complete capture, validation and restoration. + They contain no retention policy or filesystem operations. +- `ConversationCache` owns inactive snapshots, selects the longest exact token + prefix with matching image/grid identity and steering state, and evicts the + least recently active entries. Active state wins ties. +- The serve loop parks before a switch or checkpoint rewind overwrites state. + A continuing request does not trigger a snapshot. Checkpoint root/LRU behavior + from upstream is retained inside each conversation. -1. **Snapshot core:** own the in-memory representation, checked sizing, - capture, complete non-mutating validation, and restore into existing session - allocations. Validate all layers, running state and checkpoints before the - first destination write. No cache policy, filesystem I/O or client markers. -2. **RAM policy:** longest compatible exact prefix, active wins ties, bounded - payload bytes and slots, LRU eviction. Incoming/outgoing exchange payloads - count together. Off by default. A failed admission is a normal cache miss. -3. **Disk adapter (separate contribution):** use the same state representation, - but do not serialize C++ structs, pointers or native vector layouts. Define a - versioned envelope and bounded streaming/staging explicitly before integration. +Snapshots include live and checkpoint GDN/PLE state, page-rounded used main KV, +indexer pooled rows/tail/spare key/block position, and used draft KV. They exclude +scratch recomputed before use. Restoring an early checkpoint reconstructs the +spare pooled row and PLE token history. Streamed KV uses authoritative host pools; +restore invalidates replaceable VRAM maps and refills the draft ring. Device +addresses remain stable for captured graphs. -The serve loop selects a resume point and publishes new token/image/checkpoint -metadata only after successful restore. It must not infer that a failed transfer -left the old session usable. +FP16, INT8, Q4 and identity-layout K8V4 are represented explicitly. K8V4 stores +INT8 K/scales separately from Q4 V; it does not use the block movers' format enum. +Hybrid streaming/ring layouts and whole-conversation layer-split parking are +rejected. Ordinary upstream layer-split checkpoints remain available. -## State checklist +## Capacity and failure handling -| State | Representation or reconstruction | -|---|---| -| Token/image identity and steering | Exact IDs, image identity/grid hashes, immutable engine steering configuration plus per-request enabled state | -| GDN | Recurrences and convolution history, in live state and every retained checkpoint | -| PLE | Normalized history; previous token window reconstructed from the checkpoint IDs | -| QSA KV | Used, page-rounded identity-layout cells, all codes/scales for FP16/INT8/Q4; authoritative host pools for streamed layers | -| Indexer | Completed pooled rows, raw tail, per-sequence spare key (`idx_dead`), and block-position metadata; rebuild the spare pooled row at the selected resume point | -| MTP | Used authoritative draft KV; refill its resident ring at the selected resume point | -| Residency | Invalidate replaceable streamed maps; keep graph-bound addresses stable; do not treat outgoing VRAM slots as authoritative | -| Compatibility | Runtime geometry, layout and buffer extents; persistent identity additionally binds exact weights/tokenizer/steering/schema | +`--conversation-cache-mib` defaults to zero (disabled), +`--conversation-cache-slots` to four, and `--conversation-cache-min-free-mib` to +2560. `--prompt-cache 0` disables parking and produces a warning when requested. -The first #57 implementation omitted `idx_dead` and block-position metadata; -fixtures with identical opening tokens can mask the spare-key omission. Include -distinct spare keys in the component regression and different opening prefixes -in future model gates. Do not describe earlier state hashes as coverage of these -previously unmeasured fields. Scratch recomputed before use (attention scores, -step/position uploads, graph intermediates) is not part of the persisted state. +The byte budget counts vector capacity, retained checkpoints, and incoming +snapshots held during an exchange; it is additional to the active session and +is not an exact RSS limit. Estimate before allocation, then check physical RAM +using Linux `MemAvailable` or Windows `GlobalMemoryStatusEx`. Unknown telemetry +rejects admission. Check the free-RAM floor again after capture. These samples +are not reservations or cgroup/job-limit enforcement. -## Failure contract +Oversized entries and allocation/admission failures skip parking. Validate the +entire incoming image before modifying the outgoing session; invalid images +are discarded and ordinary prefix selection/prefill remains available. Transfer +or synchronization failures may leave partial GPU state, so the engine reports +an error and exits rather than continuing inference. Publish resume metadata +only after successful restore. Validation is not a transactional GPU rollback. -- Invalid snapshot: reject before CUDA synchronization/copies or destination - writes; discard that entry and retain a valid active prefix or perform normal - clean prefill. Do not discard the outgoing state before validating the incoming - candidate. -- Allocation/admission failure: skip parking, preserving active inference. -- Transfer/synchronization failure: return a distinct fatal outcome. The caller - reports an error and exits so the server can restart on the next request. A - future clean-reset recovery needs its own proof that the CUDA context remains - usable; validation does **not** make GPU failures transactional. -- Resume metadata is committed only after successful state application. +## NVMe integration contract -## Memory admission +The disk adapter must consume this representation and restore through this core, +without another state-copy implementation. Spill immutable snapshots on RAM +eviction; disabled persistence performs no filesystem operations. A disk hit +competes with active/RAM prefixes and must reserve an explicit bounded staging +allocation plus physical RAM headroom before reading. -Keep logical byte/slot capacity separate from physical-memory headroom. Proposed -flag: `--conversation-cache-min-free-mib` (default 2560, matching #41's starting -floor). Before allocating, require known available physical memory sufficient -for the estimated new payload plus that floor. Check again after capture; if the -floor is no longer met, discard the temporary image. Telemetry already includes -incoming images and parked allocations: do not subtract them a second time. +Persist a versioned portable envelope, not native C++ objects. Bind exact weights, +tokenizer, steering configuration, geometry, KV format (including K8V4) and state +schema. Read, integrity-check and validate the same staged bytes before applying +them. Atomic publication must reject interrupted, truncated, corrupt and foreign +entries. A failed spill may drop the already-evicted entry; it must not exceed +RAM limits or stop inference. Eviction-only persistence does not promise that +the latest active turn survives a crash. Files contain conversation content. -Use `GlobalMemoryStatusEx` on Windows and `MemAvailable` on Linux. Unknown or -malformed telemetry declines parking. These are instantaneous admission samples, -not a reservation against other processes. Host telemetry alone does not enforce -cgroup/job limits; container-aware limits and Windows runtime verification need -review. Disabled caching must not sample telemetry or allocate snapshots. - -## Disk interface questions for review - -- A spill consumes an evicted immutable snapshot. If persistence fails, should - eviction still drop it, or may policy retain it within the existing bound? -- A promoted snapshot must reserve its staging bytes before reading. Either use - an explicitly bounded whole-image reservation or a validated streaming format; - a digest pass alone is not safe if the file can change before the apply pass. -- Bind model/weights, tokenizer, all geometry/KV layout, control vectors and - scales, image identity, and schema. The current RAM-only steering boolean is - not a persistent model identity. -- Use atomic publication and reject truncated/corrupt/foreign snapshots. Specify - local permissions, retention/deletion and privacy: disk contains conversation - tokens and model state, unlike the current RAM-only feature. -- Eviction-only spilling does not promise that the latest active turn survives - a crash. Decide whether shutdown/periodic persistence is a separate opt-in. - -## Acceptance and remaining work - -Use #57's existing component/parity harnesses as a starting point, not a complete -acceptance contract. Add CPU tests for unknown/low memory, arithmetic boundaries, -late-layer and checkpoint rejection before mutation, PLE mismatch, zero-QSA and -256/512-expert geometries; GPU round trips with distinct indexer spare keys; -transfer-failure tests; and a dry-run-by-default known-answer 30-cycle soak. - -Full-model testing must cover histories beyond resident KV at several lengths, -including near the configured limit, and compare exact answers plus the restored -state. Add real-encoder image smoke separately from synthetic embeddings. -Persistence/restart/corruption/staging tests belong with the disk adapter. -A controlled real Pi/Hermes task comparison still needs reproducible task inputs, -independent success validation, timings and peak memory. No existing synthetic -benchmark substitutes for that evidence. - -No unified PR should claim the whole contract until these gates and the -collaborators' interface/ownership review are complete. - -## Development checks - -Revision-specific results and coverage limits are in the -[validation record](shared-conversation-validation.md). - -The first development pass implements the RAM-side shared core and host-memory -admission; it does not connect the NVMe tier or define a stable disk ABI. Configure -with `-DSTRATA_BUILD_CONVERSATION_TESTS=ON` and build/run these targets: - -```sh -cmake --build build --target conversation_cache_test conversation_memory_test conversation_snapshot_test conversation_validation_test -ctest --test-dir build -R '^conversation_(cache|memory|snapshot|validation)_test$' --output-on-failure -python -m unittest tools.test_conversation_cache_parity tools.test_conversation_cache_isolation tools.test_conversation_cache_http_smoke tools.test_conversation_cache_soak -``` - -`conversation_validation_test` links CUDA but runs with devices hidden and checks -invalid-image rejection without CUDA initialization. On GNU/Clang ELF platforms, -also build `conversation_transfer_test`: link-wrapped host copies/synchronization -inject first-copy, partial-copy and final-sync failures into the real restore -control flow. This demonstrates fail-closed outcomes, not hardware-context recovery. -Run that target with `ctest --test-dir build -R '^conversation_transfer_test$' --output-on-failure`. -`conversation_snapshot_test` uses small real-GPU fixtures, including distinct spare -keys, early checkpoint rewinds and both expert-count metadata variants. Geometry -fixtures are not a full-model Coder run. - -The private parity script's `--scenario admission --min-free-mib N` gate requires -three physical-memory admission skips, no budget-related skips, and unchanged -output/state. Choose an `N` above the machine's available physical RAM to test -denial without actually exhausting memory. - -`tools/conversation_cache_soak.py` defaults to no I/O or model loading. With -`--config CONFIG --engine ENGINE --output NEW_DIRECTORY --run`, it runs at least -30 A/B/A cycles across three approximate lengths (`--prompt-tokens 2048,40000,120000`). -Select lengths for the test configuration: the largest must cross resident KV and -reach at least 90% of maximum context, while leaving room for the continuation. -It checks known secret-code answers, token/state parity against uninterrupted -baselines, cache reuse and a steady-state retained-payload plateau. Request-end RSS -samples are diagnostics, not a transient peak-memory bound. This is a synthetic -soak, not the requested real Pi/Hermes task benchmark. Run all model gates only in -an exclusive GPU window; no existing HTTP service is contacted by these scripts. +The adapter is being integrated from @maedoc's #52; disk restart/corruption, +staging-budget, compatibility and eviction/promotion tests remain required. +Windows admission coverage includes @midhatn's contribution, preserved with its +original authorship. See the [validation record](shared-conversation-upstream-validation.md) +for results, commands, and hardware limits. diff --git a/docs/plans/shared-conversation-upstream-validation.md b/docs/plans/shared-conversation-upstream-validation.md index 0910f9f0..5aa0ac79 100644 --- a/docs/plans/shared-conversation-upstream-validation.md +++ b/docs/plans/shared-conversation-upstream-validation.md @@ -1,171 +1,74 @@ -# Shared-core integration onto upstream 0.1.25 +# Conversation cache validation -Integration base: upstream `8fc40dd`, fetched 2026-09-29. Implementation starts -at `cabd50c`; Windows test contribution is preserved as `b319d43` (original -`32cf918`, by @midhatn). The earlier 0.1.18 validation record describes a different -revision and remains historical evidence. +The core review branch is being brought onto upstream 0.1.26 (`4c68013`). Results +below belong to the earlier 0.1.25 implementation (`cabd50c` through `1d9e4e7`), +not the new base. The Windows admission test is @midhatn's `32cf918`, retained as +`b319d43`. Historical records and the general Pi benchmark remain on local branch +`feat/conversation-cache-upstream` at `cb8d90c`; they are outside the core patch. -Issue #57 references: [unified PR ownership](https://github.com/Niko1221/Strata/issues/57#issuecomment-5875083621), -[current upstream/single-GPU scope](https://github.com/Niko1221/Strata/issues/57#issuecomment-5887959836), -and the [Windows test contribution](https://github.com/jeremiahritchey/Strata/pull/1). -Upstream had advanced from the requested 0.1.22 to 0.1.25 when fetched; this -record pins the exact revision rather than referring to a moving main branch. +## Recorded Linux evidence (2026-09-29) -## Integration decisions +EPYC 7532, RTX 4090, GCC 15.2, CUDA 13.4, SM89, portable AVX2, IQ3_S. Paired +engines used 131,072 context, INT8 KV, 32,768 resident cells, 7,846 expert slots, +and PCIe share 0.55. Evidence remains in that worktree's `logs/upstream-20260929/`. -- Preserve upstream's root-pinned/LRU checkpoint policy and retain last-use - stamps when parking a conversation. -- Preserve the existing layer-split checkpoint representation. Whole-session - parking with `--layer-split` is explicitly rejected before loading the model; - multi-GPU parking is deferred as permitted in issue #57. -- Retain chunked indexer processing and restore the per-sequence spare key, - block-position metadata and spare pooled row at checkpoint resume. -- Add K8V4 snapshot layout support: independently size/copy INT8 K, K scales and - Q4 V; the draft ring remains plain INT8. Reject hybrid streaming/ring layouts. -- Use the selected CUDA/HIP runtime target in CMake; CUDA linker-wrap fault - tests are not registered for HIP. No HIP runtime validation is claimed. +| Gate | Result and scope | +| --- | --- | +| Components | Seven CTest targets passed: cache policy, admission, GPU round trips, host validation, injected transfers, checkpoint retention, sampler parity | +| Python | 65 server tests (three skipped), 47 tool tests, 22 harness tests under `-O` | +| ASan/UBSan | 35 policy, 23 admission, 1,116 host validation/transfer checks passed | +| CLI | Ten malformed/range/layer-split checks passed | +| Full model | Nine paired gates: reuse/checkpoints, long speculation, pressure, oversize, exchange, admission denial, synthetic image/grid and add/project steering isolation | +| Soak | 30 known-answer returns at 2,026 / 39,985 / 119,987 tokens; exact outputs/main-state fingerprints and stable retained payload | +| HTTP | Twelve requests passed reuse, eviction, disconnect and recovery without an engine restart | -## Windows review - -The contributed change modifies only `conversation_memory_test.cpp`. Under -Windows it checks that `GlobalMemoryStatusEx` succeeds and that the helper's -sample is known and no larger than total physical RAM. Comparing against total -RAM avoids a race between two available-memory samples. It neither allocates -pressure memory nor changes admission behavior. No review defect was found. - -This machine cannot run Windows/MSVC tests. The contributor reported 25 passing -MSVC checks in their PR; those are their results, not locally reproduced results. -Local Linux compilation runs the existing 23 admission checks. Full Windows -restore, memory-pressure and agent acceptance remain outstanding. - -## Local environment and evidence - -Linux, EPYC 7532, RTX 4090; GCC 15.2, CUDA 13.4, Release build, SM89, portable -AVX2. IQ3_S model; INT8 KV, 131,072 context and 32,768 GPU-resident KV cells for -the primary full-model gates. Engines run sequentially on the exclusive GPU. - -The private evidence directory is `logs/upstream-20260929/`. For paired model -tests, `--expert-cache 6000` yields 7,846 variable-sized expert slots; the PCIe -share is fixed to 0.55. Both engines must report matching residency and other -inference settings. The first attempt requested 8,700 uniform slots, was trimmed -to different residency by VRAM availability, and failed the comparison guard. -That attempt is retained under `spec1/` and excluded from accepted evidence. - -The entire optional upstream test build cannot configure because -`bench/micro/native_mmvq_multi.cpp` and `bench/micro/hit_cpu_order_parity.cu` are -absent at this revision. Focused conversation, checkpoint-retention and sampler -targets are built instead. Do not report this as a full upstream test-suite pass. - -The controlled local Pi task is documented in [agent-cache-benchmark.md](agent-cache-benchmark.md). -Results below must remain tied to the actual tested executable/configuration; -synthetic reuse timings are not version-to-version performance comparisons. - -## Results - -Completed checks: - -- Seven focused CTest targets: RAM policy, admission, GPU snapshot round trips, - whole-image validation, injected transfer failures, upstream root/LRU retention, - and sampler parity. K8V4 and checkpoint-stamp fixtures are included. -- 65 server Python tests (three skipped) and 47 tool tests passed; the 22 cache - harness tests also passed with Python assertions disabled (`-O`). -- ASan/UBSan: 35 RAM-policy checks, 23 admission checks, and 1,116 host validation/ - transfer-failure checks passed. The latter compiles snapshot/state code with - sanitizers and uses wrapped copies/synchronization, not CUDA hardware failures. -- Ten CLI checks: malformed/negative/overflowing options rejected and enabled - layer-split parking refused before loading a model. -- Nine full-model paired gates passed: single-token and long speculative A/B/A, - checkpoint recovery, byte pressure, oversized entries, incoming/outgoing - exchange budget, deliberate RAM-admission denial, synthetic image identity, - and add/project steering isolation. - -In the long speculative run, returning to the 55,009-token A reused all 55,009 -and processed 22 new tokens in 1.2559 seconds including snapshot work. Checkpoint -return reused 55,024 tokens and processed seven in 0.5746 seconds. Both output -and main-model fingerprints matched the uninterrupted baseline. This is an -intra-revision cache test, not a comparison against 0.1.18. - -The 30-cycle soak passed at approximately 2k, 40k and 120k tokens. Every output -and main-model fingerprint matched its uninterrupted baseline. Cache payload -plateaued for each repeated context rather than growing each cycle. - -The nine INT8 gates and soak above used executable SHA-256 +The nine INT8 gates and soak used executable SHA-256 `0d8cbca38ce27153cea516cf6454df4653196ae875e0224fd3dd3c51e1d27ea0`. -A subsequent full-model K8V4 gate exposed a format-flag mismatch: upstream uses -`kv_hybrid=true` with `kv_int8=false`, while the initial fixture incorrectly set -both. Parking was skipped; the gate failed its reuse assertion. The layout and -fixture now reflect upstream's distinct flags. The failed attempt is retained -in `k8v4/`; final checks use `k8v4-fixed/` and executable SHA-256 -`4e174e8a4b602f1f8efe846cf19570478fcc7d2b50f3c48373c799d39b3610c7`. +K8V4 then exposed incorrect hybrid-format flags. After correction, executable +`4e174e8a4b602f1f8efe846cf19570478fcc7d2b50f3c48373c799d39b3610c7` +passed K8V4/INT8 model parity, the three affected CTest targets, the 1,116 sanitizer +checks, and HTTP recovery. The full nine-gate suite was not repeated on that fix. +An initial unequal-expert-residency comparison was rejected, not counted as a pass. -On the corrected executable, K8V4 and INT8 full-model A/B/A plus checkpoint -parity both passed (including byte-exact main-model fingerprints). The three -snapshot/validation/transfer CTest targets and 1,116 ASan/UBSan transfer checks -were rerun successfully. The twelve-request HTTP smoke passed reuse, slot -eviction, disconnect cancellation and recovery with the same engine process. +Four bounded Pi coding runs passed ten independent checks each. Return prompt +processing took 4.33–5.78 s with parking off and 1.50–1.52 s with it on, with +similar but unequal prompts. Whole-task timing favored opposite modes in the two +pairs, so there is no demonstrated overall speedup/regression. The benchmark +harness, detailed results and failed preliminary tool-budget trial are separate +from the core patch. These are not version-to-version or Windows measurements. -The initial Pi pair (`pi-off-on/`) used a 12-tool/16-turn cap. Cache-off hit the -tool cap while correcting its own sample-data test expectations and did not -reach the CLI phase; cache-on completed all ten independent checks in 108.7 s. -This incomplete pair does not support a speedup claim. Both modes were repeated -with the same revised allowance of 24 tools/32 turns per phase; the 240-second -phase timeout, fixed task inputs and independent validators remain unchanged. +## Reproduction -Both revised pairs passed all ten independent checks in all four runs: +Configure the engine normally with `-DSTRATA_BUILD_CONVERSATION_TESTS=ON`, then: -| Order | Parking | Task seconds | Requests | Output tokens | Prompt seconds | Decode seconds | Engine peak RSS GiB | -| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | -| off → on | off | 91.59 | 20 | 6,319 | 23.259 | 64.865 | 49.734 | -| off → on | on | 108.37 | 28 | 7,361 | 25.750 | 78.780 | 53.433 | -| on → off | on | 104.57 | 23 | 7,274 | 22.823 | 78.350 | 53.433 | -| on → off | off | 111.39 | 26 | 7,525 | 27.948 | 79.471 | 51.979 | +```sh +cmake --build build --target conversation_cache_test conversation_memory_test conversation_snapshot_test conversation_validation_test conv_cache_test sampler_parity +ctest --test-dir build -R '^(conversation_.*|conv_cache_test|sampler_parity)$' --output-on-failure +python -m unittest tools.test_conversation_cache_parity tools.test_conversation_cache_isolation tools.test_conversation_cache_soak tools.test_conversation_cache_http_smoke +``` -The controller's first return request took 4.334 s with parking off (15,431 -prompt tokens, zero reused), versus 1.503 s with parking on (16,333 prompt -tokens, 15,810 reused). Total task time increased in this pair while the -agent followed a different tool path and generated more output. This is not -evidence of an end-to-end speedup. RSS is Linux VmHWM for the engine, including -startup and model mappings, not cache payload or GPU memory. +On GNU/Clang ELF CUDA builds also build `conversation_transfer_test`; it wraps +copies and synchronization for host fault injection. It does not simulate recovery +of a broken CUDA context. GPU fixtures cover partial pages, distinct indexer spare +keys, early checkpoints, zero-QSA and 256/512-expert metadata. -In reverse order, the return request took 5.777 s with parking off (17,113 -prompt tokens, zero reused), versus 1.522 s with parking on (16,165 prompt -tokens, 15,620 reused). Whole-task timing favored cache-on in this repetition -(104.57 vs 111.39 s), reversing the first pair. With different generated output -and tool paths, two pairs do not establish an overall speedup or regression. -The consistent finding is reduced return-prefill work: approximately 2.9–3.8× -faster for these observed requests, with higher engine peak RSS. Prompt lengths -are similar but not identical, so this is a workload observation, not a matched -microbenchmark ratio. +Model tools default to a dry run. With `--config CONFIG --engine ENGINE --output +NEW_DIRECTORY --run`, run parity at `--spec 1` and `--spec 4`, then scenarios +`pressure`, `oversized`, `exchange` and `admission`. Select byte budgets that +actually force the named condition; use a RAM floor above available memory for +denial. Isolation scenarios are `image`, `add`, and `project`. The soak requires +at least 30 cycles and three lengths crossing resident KV and approaching the +configured context limit. HTTP smoke requires an exclusive idle test endpoint. +Run model/GPU gates only in an exclusive test window. -Task wall time excludes server/model startup. All runs used 7,846 expert slots, -INT8 KV, 131,072 context, 32,768 resident cells and the same speculative settings. -The runner verified matching engine settings within each pair. It records -executable/task-script hashes and identical initial-file hashes for each mode; -per-run tool execution totaled 0.96–1.15 s. Private detail is retained in -`pi-bounded-off-on/`, `pi-bounded-on-off/`, and `pi-comparison.json`. +## Outstanding evidence -## Scope and remaining validation - -These results cover this Linux/RTX 4090 host and the local IQ3_S model. Windows -runtime acceptance, HIP execution, multi-GPU parking, real vision-encoder -integration, and the larger Coder model remain untested here. Synthetic image -identity and model-geometry fixtures do not replace those runtime checks. -The NVMe backend remains a separate integration; this work validates the RAM -backend and shared snapshot representation. No upstream PR or issue comment -was posted as part of this local validation. - -This benchmark compares conversation parking on/off within the integrated -0.1.25 executable. It cannot establish whether 0.1.25 is faster or slower than -the earlier 0.1.15/0.1.18 branches, nor reproduce the previous Windows workload. - -## Local deployment - -The tested executable is running from `Strata-conversation-cache-upstream`, -branch `feat/conversation-cache-upstream`, in tmux pane `%15` on port 11434. -The runtime configuration is `logs/runtime-20260929-191116/engine-config.json`. -It preserves the user's automatic expert allocation, 131,072 context, INT8 KV, -32,768 resident cells, 8 GiB conversation budget, four slots and 2,560 MiB RAM -floor. Automatic allocation selected 8,814 expert slots; this differs from the -fixed 7,846-slot benchmark allocation and is not included in its timing claims. -Health and a non-streaming generation request passed (`OK`), with the server -idle and zero queued requests afterward. Earlier worktrees remain intact. +- Repeat affected build/model gates on 0.1.26, including batched draft prompt KV + and its fingerprint. Previous main-model hashes excluded draft scratch/state. +- NVMe restart, corruption, foreign identity, eviction/promotion and explicit + staging bounds; no disk acceptance is claimed yet. +- Windows runtime: only contributor-reported 25 MSVC admission checks, not locally + reproduced. HIP execution, multi-GPU parking, real vision encoder and full + Coder-model runs are untested; synthetic fixtures do not substitute for them. +- Full optional upstream test configuration was blocked on 0.1.25 by missing + `native_mmvq_multi.cpp` and `hit_cpu_order_parity.cu`; focused tests were used. diff --git a/docs/plans/shared-conversation-validation.md b/docs/plans/shared-conversation-validation.md deleted file mode 100644 index 18f27c75..00000000 --- a/docs/plans/shared-conversation-validation.md +++ /dev/null @@ -1,138 +0,0 @@ -# Shared snapshot core: validation record - -Historical 0.1.18 evidence. The later integration is documented separately in -[the upstream 0.1.25 validation record](shared-conversation-upstream-validation.md). - -Date: 2026-09-28. Engine source: `3657b8f`, based on upstream `b38c183` -(0.1.18). This is development-branch evidence for the RAM tier/shared core, -not acceptance of a combined RAM/NVMe implementation or a deployment report. - -## Configuration and provenance - -- Linux, AMD EPYC 7532, approximately 247 GiB physical RAM, NVIDIA RTX 4090. -- GCC 15.2, CUDA 13.4, SM 89, portable/AVX2 CPU kernels. -- Qwen3.8-Flash-Next-GSQ-RCO IQ3_S; INT8 KV, 131,072-token maximum context, - 32,768 resident KV cells, automatic prefill sizing, 8,817 expert slots. -- Paired engines run sequentially with fixed expert residency. Baseline has - conversation caching disabled; candidate normally has an 8,192 MiB budget, - four parked slots and a 2,560 MiB physical-memory floor. Pressure/oversize/ - exchange/admission gates explicitly change the relevant limit. -- Tested executable SHA-256: - `f31d1fe2eecf7d27f440ea1ddfdb39133a16f471c70c1869491582614a16c2f9`. - -Do not infer a speedup over the earlier 0.1.15 results: maximum context, -expert residency and prefill configuration differ. These tests compare cache -behavior within this revision, not engine versions. - -## Component and offline checks - -| Gate | Result | -|---|---| -| CPU RAM ownership/prefix/budget policy | 35 checks passed | -| Available-memory parsing/admission boundaries | 23 checks passed | -| Real-GPU KV and complete-session fixtures | 1,071 checks passed | -| Whole-image rejection before mutation, devices hidden | 780 checks passed | -| Wrapped transfer/synchronization failure control flow | 1,020 checks passed (includes the 780 validation checks) | -| CPU policy/memory and host validation/transfer tests under ASan/UBSan | Passed | -| Python server tests plus cache-harness tests | 45 tests passed | -| Cache-harness tests under Python `-O` | 22 tests passed | -| CLI parsing, help, disabled-feature warnings | 20 checks passed | - -GPU fixtures cover FP16/INT8/Q4 KV, resident/streamed layouts, distinct indexer -spare keys, checkpoint rewind, and 256/512-expert geometry metadata. Host fixtures -also cover zero-QSA and PLE-present/absent layouts. Small geometry fixtures do not -constitute a full Coder/pruned-model run. Link-wrapped host failures exercise the -real restore control flow, not actual CUDA hardware-context recovery. - -## Full-model private-engine gates - -All nine gates below passed with this executable: - -1. Single-token A/B/A and checkpoint output/main-model state parity. -2. Long speculative A/B/A and checkpoint recovery beyond resident KV. -3. Byte-pressure eviction and correct cold fallback. -4. Oversized-entry rejection without disrupting inference. -5. Incoming/outgoing exchange-budget enforcement. -6. Image-content/grid identity isolation using synthetic embeddings. -7. Add-mode control-vector identity isolation. -8. Project-mode control-vector identity isolation. -9. Physical-memory admission denied by a 1 TiB floor: three admission skips, - no budget skips or parked entries, and output/state parity for A/B/C/A. - -State comparisons include GDN, PLE, indexer tail, `idx_dead`, pooled rows -including the spare row, main KV, previous PLE tokens and consumed length. -Unused draft cells are not part of the main-model fingerprint; draft snapshot -copies are covered by the component fixtures. Earlier prototype fingerprints -did not include `idx_dead` and must not be treated as equivalent coverage. - -In the long speculative gate (`spec=4`, `mtp_max=4`, lookup disabled): - -| Candidate request | Prompt tokens | Reused | Prompt-path time | -|---|---:|---:|---:| -| Initial A | 51,133 | 0 | 23.3721 s | -| Initial B | 51,135 | 0 | 22.3445 s | -| A continuation after B | 51,155 | 51,133 | 1.2371 s | -| A checkpoint continuation | 51,155 | 51,148 | 0.5659 s | - -Return-path times include parking/restoration and the remaining new prompt -tokens, but not decoding. Both A continuations matched uninterrupted baseline -outputs and the complete main-model fingerprints listed above. These synthetic -requests are not a controlled real-agent task benchmark. - -## Known-answer soak - -`tools/conversation_cache_soak.py --prompt-tokens 2048,40000,120000 --cycles 30` -passed against the same executable. Actual prompt lengths were 2,026, 39,985 and -119,987 tokens (the largest is 91.5% of maximum context). Single-token decode -was enforced with `spec=2`, `mtp_max=1` and lookup disabled. - -Each conversation contains a distinct secret word inside its history. After an -unrelated worker request, all 30 returns produced the expected word and exactly -matched uninterrupted baseline output tokens and main-model state fingerprints. -Each size was restored ten times; the final three retained-payload samples per -size were identical: - -| Active conversation length | Parked payload after its answer | -|---|---:| -| 2,026 tokens | 4,099,851,588 bytes | -| 39,985 tokens | 3,283,651,392 bytes | -| 119,987 tokens | 1,824,199,544 bytes | - -Occupancy differs because the active conversation is not parked; these figures -are not the snapshot sizes of the active conversations. Maximum logged parked -payload was 4,249,016,776 bytes, below the 8 GiB budget. The policy also accounts -for an incoming image held during exchange; the logged parked count alone does -not measure that transient total. Request-end RSS was sampled as a diagnostic, -not as a peak-memory bound or a proof against every allocator leak. Thirty cycles -establish this finite regression gate, not indefinite stability. - -## Private HTTP smoke - -All 12 requests in `tools/conversation_cache_http_smoke.py` passed on a separate -localhost-only endpoint using the same executable and normal adaptive settings -(reported `spec=6`, `mtp_max=4`, lookup 3, 8,816 expert slots). This was not the -fixed-residency/single-token configuration used for deterministic state parity. - -- A/B/A preserved the answer and reused 1,987 of 1,994 prompt tokens. -- Exceeding the four-slot limit evicted A; its next request correctly reused zero. -- A streaming disconnect cancelled after five output tokens; an unrelated - request then succeeded, and returning to the cancelled conversation reused - 1,085 of 1,092 prompt tokens. -- Frontend and engine process identities remained unchanged throughout the - smoke. The private test instance was then stopped; no production endpoint or - configuration was replaced. - -## Remaining acceptance work - -- Real vision encoder/image-recognition smoke (current image gate uses synthetic - embeddings); full-model 256-expert/Coder coverage. -- Windows runtime/memory-pressure review, including constrained-memory hardware; - Linux container/job-limit-aware admission is not implemented. -- Controlled real Pi/Hermes task with fixed initial files, tool limits, - independent success checks, wall-time breakdown and peak memory. -- Agreed ownership/interface for the unified PR, NVMe adapter, bounded staging, - persistent compatibility identity, corruption/restart/durability tests. - -No private conversations, raw request captures, local configuration files or -machine-specific paths are needed to reproduce these synthetic fixtures. -See [the design and test commands](shared-conversation-snapshots.md). diff --git a/tools/agent_cache_benchmark.py b/tools/agent_cache_benchmark.py deleted file mode 100644 index a36dc8fa..00000000 --- a/tools/agent_cache_benchmark.py +++ /dev/null @@ -1,192 +0,0 @@ -"""Controlled local Pi coding task with cache off/on; private server, dry-run by default. - -Requires an installed Pi SDK (--pi-package). Never contacts an existing server. -Only --run creates files or loads a model. Retains generated code, private agent -events, exact inputs, timings, engine metrics and independent validator results. -""" -import argparse -import hashlib -import json -import os -from pathlib import Path -import shutil -import signal -import subprocess -import sys -import time -import urllib.request - -ROOT = Path(__file__).resolve().parents[1] -SPEC = '''Implement a Python 3 standard-library expense report. -report.py exports summarize(text: str) -> list[dict]. Input is CSV with headers -id,timestamp,team,amount. Strip surrounding whitespace in values. A valid row has -a nonempty id and team, an ISO timestamp WITH timezone (Z or explicit offset), -and a finite decimal amount with at most two fractional digits. Ignore invalid -rows. Among valid rows with the same id, the last valid row wins (a later invalid -row must not erase a valid row). Normalize timestamps to UTC and group by UTC -date and team. Return groups sorted by (day, team), each with exactly the keys -day (YYYY-MM-DD), team, count (int), total (decimal string with two places). -Negative amounts and zero are valid. Use decimal arithmetic, not binary floats. -Empty input and header-only input return []. Correctly parse quoted commas. -cli.py accepts exactly one argument, a CSV filename or - for stdin. Print the -JSON list and exit 0. An unreadable filename prints a concise message to stderr -and exits 2 without a traceback. Do not add third-party dependencies. -''' -VALIDATOR = r''' -import importlib.util, json, subprocess, sys -from pathlib import Path -root=Path(sys.argv[1]); spec=importlib.util.spec_from_file_location('report',root/'report.py') -m=importlib.util.module_from_spec(spec); spec.loader.exec_module(m) -header='id,timestamp,team,amount\n' -cases=[('',[]),(header,[]), - (header+'a,2026-01-02T00:30:00+02:00,"Blue, East",0.10\nb,2026-01-01T12:00:00Z,"Blue, East",0.20\n', - [{'day':'2026-01-01','team':'Blue, East','count':2,'total':'0.30'}]), - (header+'a,2026-01-01T00:00:00Z,X,1.00\na,2026-01-02T00:00:00Z,Y,2.00\na,bad,X,9.00\n', - [{'day':'2026-01-02','team':'Y','count':1,'total':'2.00'}]), - (header+' a ,2026-01-01T00:00:00Z, X ,-2.10\nb,2026-01-01T00:00:00Z,X,0\n', - [{'day':'2026-01-01','team':'X','count':2,'total':'-2.10'}]), - (header+'a,2026-01-01T00:00:00,X,1\nb,2026-01-01T00:00:00Z,X,NaN\nc,2026-01-01T00:00:00Z,X,1.001\n,2026-01-01T00:00:00Z,X,2\nd,2026-01-01T00:00:00Z,,2\n',[]), - (header+'a,2026-01-02T00:00:00Z,B,1\nb,2026-01-01T00:00:00Z,Z,2\nc,2026-01-02T00:00:00Z,A,3\n', - [{'day':'2026-01-01','team':'Z','count':1,'total':'2.00'}, - {'day':'2026-01-02','team':'A','count':1,'total':'3.00'}, - {'day':'2026-01-02','team':'B','count':1,'total':'1.00'}])] -checks=[] -for i,(text,want) in enumerate(cases): - got=m.summarize(text); assert got==want,(i,got,want); checks.append('library-'+str(i)) -text,want=cases[2] -p=subprocess.run([sys.executable,str(root/'cli.py'),'-'],input=text,text=True,capture_output=True,timeout=10) -assert p.returncode==0 and json.loads(p.stdout)==want,p; checks.append('stdin') -f=root/'validator-input.csv';f.write_text(text) -p=subprocess.run([sys.executable,str(root/'cli.py'),str(f)],text=True,capture_output=True,timeout=10) -assert p.returncode==0 and json.loads(p.stdout)==want,p;checks.append('file');f.unlink() -p=subprocess.run([sys.executable,str(root/'cli.py'),str(root/'does-not-exist.csv')],text=True,capture_output=True,timeout=10) -assert p.returncode==2 and p.stderr and 'Traceback' not in p.stderr,p;checks.append('missing-file') -print(json.dumps({'passed':checks})) -''' - - -def get_json(url): - with urllib.request.urlopen(url, timeout=5) as response: - return json.load(response) - - -def main(): - ap = argparse.ArgumentParser(description=__doc__) - ap.add_argument('--config', type=Path, required=True) - ap.add_argument('--engine', type=Path, required=True) - ap.add_argument('--pi-package', type=Path, required=True) - ap.add_argument('--output', type=Path, required=True) - ap.add_argument('--port', type=int, default=11436) - ap.add_argument('--order', default='off,on', choices=('off,on', 'on,off')) - ap.add_argument('--run', action='store_true') - args = ap.parse_args() - if not args.run: - print('Dry run: private server, identical Pi A/B/A coding tasks, cache off/on, independent validators.') - return - args.output = args.output.resolve() - args.output.mkdir(parents=False, exist_ok=False) - cfg = json.loads(args.config.read_text()) - cfg.update(exe=str(args.engine.resolve()), cwd=str(ROOT), host='127.0.0.1', port=args.port) - work = args.output / 'workspace' - agent = args.output / 'agent' - agent.mkdir() - model = cfg['model_name'] - if model != 'qwen3.8-flash-next-iq3_s': - raise ValueError('This task is currently validated for qwen3.8-flash-next-iq3_s') - (agent/'models.json').write_text(json.dumps({'providers': {'strata-benchmark': { - 'baseUrl': f'http://127.0.0.1:{args.port}/v1', 'api': 'openai-completions', 'apiKey': 'local', - 'models': [{'id': model, 'reasoning': False, 'input': ['text'], 'contextWindow': 131072, - 'maxTokens': 2048, 'cost': {'input': 0, 'output': 0, 'cacheRead': 0, 'cacheWrite': 0}}], - 'compat': {'supportsStore': False, 'supportsDeveloperRole': False, 'supportsReasoningEffort': False} - }}})) - corpus = 'id,timestamp,team,amount\n' + ''.join( - f'r{i},2026-01-{i%28+1:02d}T12:00:00Z,Team{i%7},{i%100}.{i%97:02d}\n' for i in range(280)) - initial = {'SPEC.md': SPEC, 'sample.csv': corpus, - 'report.py': 'def summarize(text):\n raise NotImplementedError\n', 'cli.py': ''} - manifest = {name: hashlib.sha256(text.encode()).hexdigest() for name, text in initial.items()} - (args.output/'inputs.json').write_text(json.dumps(initial, indent=2)) - validator = args.output/'validate.py' - validator.write_text(VALIDATOR) - results = [] - for label in args.order.split(','): - run = args.output/label - run.mkdir() - if work.exists(): - shutil.rmtree(work) # only this harness's new, disposable task workspace - work.mkdir() - for name, text in initial.items(): - (work/name).write_text(text) - run_cfg = dict(cfg, args=list(cfg['args']), log=str(run/'engine.log')) - run_cfg['args'] += ['--conversation-cache-mib', '8192' if label=='on' else '0'] - config = run/'config.json' - config.write_text(json.dumps(run_cfg, indent=2)) - config.with_name('config.shared-settings.json').write_text(json.dumps({ - 'reasoning_effort': 'none', 'temperature': 0, 'max_tokens': 2048})) - record = {'mode': label, 'inputs_sha256': manifest, - 'task_script_sha256': hashlib.sha256((ROOT/'tools/agent_cache_task.mjs').read_bytes()).hexdigest(), - 'engine_sha256': hashlib.sha256(args.engine.read_bytes()).hexdigest()} - with (run/'server.log').open('w') as log: - server = subprocess.Popen([sys.executable, '-m', 'serve.server', '--engine', 'strata', - '--config', str(config), '--host', '127.0.0.1', '--port', str(args.port)], - cwd=ROOT, stdout=log, stderr=subprocess.STDOUT, start_new_session=True) - try: - base = f'http://127.0.0.1:{args.port}' - for _ in range(180): - if server.poll() is not None: - raise RuntimeError('Private server exited; inspect server.log') - try: - get_json(base+'/health') - break - except OSError: - time.sleep(1) - else: - raise TimeoutError('Private server did not become ready') - started = time.monotonic() - with (run/'agent.log').open('w') as agent_log: - task = subprocess.run(['node', str(ROOT/'tools/agent_cache_task.mjs'), - str(args.pi_package.resolve()), str(work), str(agent), str(run/'task.json')], - cwd=work, stdout=agent_log, stderr=subprocess.STDOUT, timeout=750, - env={**os.environ, 'PI_OFFLINE': '1'}) - record.update(wall_s=time.monotonic()-started, agent_exit=task.returncode) - check = subprocess.run([sys.executable, str(validator), str(work)], - text=True, capture_output=True, timeout=30) - (run/'validation.txt').write_text(check.stdout+check.stderr) - record.update(validator_exit=check.returncode, success=task.returncode==check.returncode==0) - metrics = get_json(base+'/metrics?requests=all') - (run/'metrics.json').write_text(json.dumps(metrics, indent=2)) - record.update(totals=metrics['totals'], engine=metrics['engine']) - # Kernel high-water RSS for the engine, unlike periodic request-end samples. - children = Path(f'/proc/{server.pid}/task/{server.pid}/children').read_text().split() - record['child_memory_kib'] = {} - for pid in children: - try: - if Path(f'/proc/{pid}/comm').read_text().strip() != 'strata': - continue - status = Path(f'/proc/{pid}/status').read_text().splitlines() - except FileNotFoundError: - continue - record['child_memory_kib'][pid] = {s.split(':')[0]: int(s.split()[1]) - for s in status if s.startswith(('VmHWM:', 'VmRSS:'))} - if not record['child_memory_kib']: - raise RuntimeError('Missing engine high-water memory sample') - shutil.copytree(work, run/'artifacts') - finally: - if server.poll() is None: - os.killpg(server.pid, signal.SIGINT) - try: - server.wait(timeout=30) - except subprocess.TimeoutExpired: - os.killpg(server.pid, signal.SIGTERM) - server.wait(timeout=10) - results.append(record) - (args.output/'results.json').write_text(json.dumps(results, indent=2)+'\n') - print(json.dumps(record), flush=True) - for key in ('expert_slots', 'context', 'kv', 'kv_resident', 'spec', 'mtp_max', 'lookup', 'pool_workers', 'pcie_frac'): - if results[0]['engine'][key] != results[1]['engine'][key]: - raise AssertionError(f'Unmatched engine configuration: {key}') - if not all(r['success'] for r in results): - raise SystemExit('Agent task or independent validation failed; no successful-task speedup claim') - - -if __name__ == '__main__': - main() diff --git a/tools/agent_cache_task.mjs b/tools/agent_cache_task.mjs deleted file mode 100644 index 93a6df3e..00000000 --- a/tools/agent_cache_task.mjs +++ /dev/null @@ -1,114 +0,0 @@ -// Bounded real Pi A -> B -> A coding workflow, used by agent_cache_benchmark.py. -import fs from 'node:fs'; -import path from 'node:path'; -import {pathToFileURL} from 'node:url'; - -const [packageDir, cwd, agentDir, output] = process.argv.slice(2); -const {createAgentSession, DefaultResourceLoader, ModelRuntime, SessionManager, SettingsManager} = - await import(pathToFileURL(path.join(packageDir, 'dist/index.js'))); -const runtime = await ModelRuntime.create({authPath: path.join(agentDir, 'auth.json'), - modelsPath: path.join(agentDir, 'models.json'), allowModelNetwork: false}); -const model = runtime.getModel('strata-benchmark', 'qwen3.8-flash-next-iq3_s'); -if (!model) throw new Error('Benchmark model unavailable'); -const events = fs.createWriteStream(output + '.events.jsonl'); -const sessions = []; -const phases = []; -const budgets = new WeakMap(); -const system = 'You are implementing a small Python standard-library project. Work only in the current directory. ' - + 'Do not access the network, install dependencies, or read parent directories. Use at most 24 tool calls per task. ' - + 'Keep tool outputs below 16000 characters and shell commands below 15 seconds. Implement the requested files, ' - + 'run focused checks, then give a short result. Do not build unrelated features.'; -async function makeSession() { - const budget = {calls: 0, limited: false}; - const settingsManager = SettingsManager.inMemory({compaction: {enabled: false}, retry: {enabled: false}}); - const loader = new DefaultResourceLoader({cwd, agentDir, settingsManager, noExtensions: true, - noSkills: true, noPromptTemplates: true, noThemes: true, noContextFiles: true, - extensionFactories: [pi => { - pi.on('before_provider_request', event => { - const payload = {...event.payload, temperature: 0, max_tokens: 2048, - chat_template_kwargs: {enable_thinking: false}}; - delete payload.max_completion_tokens; - return payload; - }); - pi.on('tool_call', event => { - if (++budget.calls > 24) { - budget.limited = true; - return {block: true, terminate: true, reason: 'Benchmark tool-call limit'}; - } - if (event.toolName === 'bash') event.input.timeout = Math.min(event.input.timeout || 15, 15); - }); - pi.on('tool_result', event => { - let left = 16000; - return {content: event.content.map(part => { - if (part.type !== 'text') return part; - const marker = '\n[benchmark output limit]'; - const text = part.text.length <= left ? part.text - : left >= marker.length ? part.text.slice(0, left - marker.length) + marker : ''; - left -= text.length; - return {...part, text}; - })}; - }); - }], - systemPromptOverride: () => system}); - await loader.reload(); - const {session} = await createAgentSession({cwd, agentDir, model, modelRuntime: runtime, - thinkingLevel: 'off', tools: ['read', 'write', 'edit', 'bash'], resourceLoader: loader, - sessionManager: SessionManager.inMemory(), settingsManager}); - sessions.push(session); - budgets.set(session, budget); - return session; -} -async function phase(session, name, prompt) { - const budget = budgets.get(session); - budget.calls = 0; budget.limited = false; - const record = {name, tool_calls: 0, tool_ms: 0, turns: 0, limited: false}; - const activeTools = new Map(); - const started = performance.now(); - const unsubscribe = session.subscribe(event => { - events.write(JSON.stringify({phase: name, elapsed_ms: performance.now() - started, event}) + '\n'); - if (event.type === 'turn_start') record.turns++; - if (event.type === 'tool_execution_start') { - record.tool_calls++; - activeTools.set(event.toolCallId, performance.now()); - } - if (event.type === 'tool_execution_end') { - record.tool_ms += performance.now() - (activeTools.get(event.toolCallId) ?? performance.now()); - } - if (record.tool_calls > 24 || record.turns > 32) { - record.limited = true; - void session.abort(); - } - }); - const timeout = setTimeout(() => { record.limited = true; void session.abort(); }, 240000); - try { - await session.prompt(prompt); - const last = session.messages.filter(m => m.role === 'assistant').at(-1); - if (record.limited || budget.limited || !last || ['error', 'aborted'].includes(last.stopReason)) { - throw new Error(`Phase ${name} failed: ${last?.errorMessage ?? last?.stopReason ?? 'limit'}`); - } - record.answer = last.content; - } finally { - clearTimeout(timeout); unsubscribe(); record.wall_ms = performance.now() - started; - phases.push(record); - fs.writeFileSync(output, JSON.stringify({phases}, null, 2) + '\n'); - } -} -try { - const controller = await makeSession(); - const worker = await makeSession(); - await phase(controller, 'controller-implement', - 'Implement report.py summarize(text) using SPEC.md. Read the complete sample.csv (a realistic input corpus) ' - + 'before implementing. Implement only the library for now; another developer will implement cli.py. ' - + 'You may add small tests. Summarize what you implemented.'); - await phase(worker, 'worker-cli', - 'You are responsible for cli.py. Read SPEC.md and report.py, implement the specified CLI, and verify both ' - + 'file and stdin inputs. Do not modify report.py. Keep your answer brief.'); - await phase(controller, 'controller-integrate', - 'The CLI developer has finished. Read cli.py and verify the integrated project against SPEC.md, especially ' - + 'quoted commas, timezone-to-UTC day conversion, last-valid duplicate IDs, invalid rows, empty input, ' - + 'Decimal totals, stdin, and missing-file exit status. Fix any problems in report.py or cli.py. ' - + 'Run focused checks and report the result.'); -} finally { - for (const session of sessions) session.dispose(); - events.end(); -} diff --git a/tools/conversation_cache_isolation.py b/tools/conversation_cache_isolation.py index 8cfa5479..5c201300 100644 --- a/tools/conversation_cache_isolation.py +++ b/tools/conversation_cache_isolation.py @@ -7,19 +7,17 @@ kernels. This validates cache correctness, not vision or steering quality. import argparse import json from pathlib import Path -import re import struct import sys import threading ROOT = Path(__file__).resolve().parents[1] sys.path[:0] = [str(ROOT), str(ROOT / 'tools')] -from conversation_cache_parity import STATE_KEYS, engine_args, require +from conversation_cache_parity import STATE_KEYS, engine_args, load_tokenizer, require, state_hashes from gguf_reader import GGUFFile from gguf_writer import GGUFWriter from serve.server import StrataEngine, child_env from serve.frontend import ChatTemplate -import strata_tokenizer as ST import numpy as np @@ -86,12 +84,7 @@ def main(): width = geometry['qwen4exp.embedding_length'] require(geometry['qwen4exp.block_count'] > 20, 'fixture requires layers 1 and 20') p = Path(cfg['tokenizer']) - vocab = json.loads((p / 'vocab.json').read_text()) - tokens = [None] * len(vocab) - for token, i in vocab.items(): - tokens[i] = token - tok = ST.Tokenizer(tokens, (p / 'merges.txt').read_text().split('\n'), - json.loads((p / 'token_type.json').read_text())) + tok = load_tokenizer(p) tpl = ChatTemplate(p / 'chat_template.jinja') def encode(text): return tok.encode(tpl.render([{'role': 'user', 'content': text}], enable_thinking=False), parse_special=True) @@ -137,11 +130,7 @@ def main(): generate('off-again', A, steering=False) finally: engine.close() - hashes = [] - for line in log.read_text().splitlines(): - if 'STATE_HASH L=' in line: - fields = dict(re.findall(r'(\w+)=([0-9a-f,-]+)', line)) - hashes.append({k: fields[k] for k in STATE_KEYS}) + hashes = state_hashes(log.read_text()) require(len(hashes) == len(records), 'missing isolation state hashes') for record, state in zip(records, hashes): record['state'] = state diff --git a/tools/conversation_cache_parity.py b/tools/conversation_cache_parity.py index 710baee8..80c467d2 100644 --- a/tools/conversation_cache_parity.py +++ b/tools/conversation_cache_parity.py @@ -22,6 +22,25 @@ def require(condition, message): raise AssertionError(message) +def load_tokenizer(path): + vocab = json.loads((path / 'vocab.json').read_text()) + tokens = [None] * len(vocab) + for token, index in vocab.items(): + tokens[index] = token + return ST.Tokenizer(tokens, (path / 'merges.txt').read_text().split('\n'), + json.loads((path / 'token_type.json').read_text())) + + +def state_hashes(text): + # Padding and the drafter's final uncomputed cell aren't main-model state. + hashes = [] + for line in text.splitlines(): + if 'STATE_HASH L=' in line: + fields = dict(re.findall(r'(\w+)=([0-9a-f,-]+)', line)) + hashes.append({key: fields[key] for key in STATE_KEYS}) + return hashes + + def engine_args(cfg, budget, spec): # Native IQ packs require verifier capacity >= 2, even for one-token decode. return list(cfg['args']) + [ @@ -131,12 +150,7 @@ def main(): return cfg = json.loads(a.config.read_text()) p = Path(cfg['tokenizer']) - vocab = json.loads((p / 'vocab.json').read_text()) - tokens = [None] * len(vocab) - for text, i in vocab.items(): - tokens[i] = text - tok = ST.Tokenizer(tokens, (p / 'merges.txt').read_text().split('\n'), - json.loads((p / 'token_type.json').read_text())) + tok = load_tokenizer(p) tpl = ChatTemplate(p / 'chat_template.jinja') def encode(text): return tok.encode(text, parse_special=True) @@ -181,13 +195,7 @@ def main(): generate(continuation, 8, 'A+-checkpoint') finally: engine.close() - hashes = [] - for line in log.read_text().splitlines(): - if 'STATE_HASH L=' in line: - fields = dict(re.findall(r'(\w+)=([0-9a-f,-]+)', line)) - # Padding and the drafter's final uncomputed cell aren't used - # main-model state; do not gate on their diagnostic hashes. - hashes.append({k: fields[k] for k in STATE_KEYS}) + hashes = state_hashes(log.read_text()) require(len(hashes) == len(records), 'missing state hashes') for record, fingerprint in zip(records, hashes): record['state'] = fingerprint diff --git a/tools/conversation_cache_soak.py b/tools/conversation_cache_soak.py index ae910c00..a7c95fdd 100644 --- a/tools/conversation_cache_soak.py +++ b/tools/conversation_cache_soak.py @@ -12,10 +12,9 @@ import threading ROOT = Path(__file__).resolve().parents[1] sys.path[:0] = [str(ROOT), str(ROOT / 'tools')] -from conversation_cache_parity import STATE_KEYS, engine_args, require +from conversation_cache_parity import STATE_KEYS, engine_args, load_tokenizer, require, state_hashes from serve.server import StrataEngine, child_env from serve.frontend import ChatTemplate -import strata_tokenizer as ST def answer_text(text): @@ -81,12 +80,7 @@ def main(): return cfg = json.loads(args.config.read_text()) path = Path(cfg['tokenizer']) - vocab = json.loads((path / 'vocab.json').read_text()) - tokens = [None] * len(vocab) - for token, index in vocab.items(): - tokens[index] = token - tok = ST.Tokenizer(tokens, (path / 'merges.txt').read_text().split('\n'), - json.loads((path / 'token_type.json').read_text())) + tok = load_tokenizer(path) template = ChatTemplate(path / 'chat_template.jinja') def encode(text): return tok.encode(text, parse_special=True) @@ -124,11 +118,10 @@ def main(): nonlocal hash_count output = [t for t in engine.generate(ids, count, {'temperature': 0}, threading.Event()) if t is not None] text = log.read_text() - hashes = [dict(re.findall(r'(\w+)=([0-9a-f,-]+)', line)) - for line in text.splitlines() if 'STATE_HASH L=' in line] + hashes = state_hashes(text) require(len(hashes) == hash_count + 1 and int(hashes[-1]['L']) >= len(ids), 'missing current state fingerprint') hash_count += 1 - state = {k: hashes[-1][k] for k in STATE_KEYS} + state = hashes[-1] occupancy = re.findall(r'parked=\d+ bytes=(\d+)', text) rss = None try: From f3072a95e61a29c16c9470646074ebb4c5202418 Mon Sep 17 00:00:00 2001 From: Jeremiah Ritchey <44681828+jeremiahritchey@users.noreply.github.com> Date: Tue, 29 Sep 2026 21:53:45 +0000 Subject: [PATCH 09/22] Clear recoverable snapshot errors before batched draft prefill --- .../shared-conversation-upstream-validation.md | 13 +++++++++++-- src/program/generate.cpp | 2 ++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/docs/plans/shared-conversation-upstream-validation.md b/docs/plans/shared-conversation-upstream-validation.md index 5aa0ac79..6ae00dab 100644 --- a/docs/plans/shared-conversation-upstream-validation.md +++ b/docs/plans/shared-conversation-upstream-validation.md @@ -1,11 +1,20 @@ # Conversation cache validation -The core review branch is being brought onto upstream 0.1.26 (`4c68013`). Results -below belong to the earlier 0.1.25 implementation (`cabd50c` through `1d9e4e7`), +The core review branch is based on upstream 0.1.26 (`4c68013`). Recorded model +results below belong to the earlier 0.1.25 implementation (`cabd50c` through `1d9e4e7`), not the new base. The Windows admission test is @midhatn's `32cf918`, retained as `b319d43`. Historical records and the general Pi benchmark remain on local branch `feat/conversation-cache-upstream` at `cb8d90c`; they are outside the core patch. +## Current offline checks + +After separating the general benchmark tooling and merging 0.1.26, all 47 tool +tests and the 22 cache-harness tests under Python `-O` pass. Recoverable snapshot +rejection now clears its diagnostic error before the new batched draft-prefill +path runs. That C++ integration change still needs an engine build and model +validation; these Python passes do not establish it. No benchmark server or GPU +was used for these checks. + ## Recorded Linux evidence (2026-09-29) EPYC 7532, RTX 4090, GCC 15.2, CUDA 13.4, SM89, portable AVX2, IQ3_S. Paired diff --git a/src/program/generate.cpp b/src/program/generate.cpp index a2bb0d13..7ee627be 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -3267,6 +3267,7 @@ int main(int argc, char** argv) { size_t estimate = 0; if (!strata::core::conversation_snapshot_bytes(view, ss, g, mtp.kv_state(), estimate, err)) { std::fprintf(stderr, "strata serve: conversation cache: skip parking (%s)\n", err.c_str()); + err.clear(); // A recoverable miss must not poison the batched draft prefill's error channel. return true; } if (!conversations.make_room(estimate, held)) { @@ -3846,6 +3847,7 @@ int main(int argc, char** argv) { if (incoming && !strata::core::conversation_snapshot_validate(*incoming, ss, g, mtp.kv_state(), err)) { std::fprintf(stderr, "strata serve: conversation cache: discard invalid snapshot (%s)\n", err.c_str()); incoming.reset(); + err.clear(); } // Preserve the outgoing branch before any checkpoint rewind, reset, // or incoming restore overwrites the positional state it requires. From 13fd32a227d3aa80083ab368d9cd23c10aa0e8c8 Mon Sep 17 00:00:00 2001 From: Jeremiah Ritchey <44681828+jeremiahritchey@users.noreply.github.com> Date: Tue, 29 Sep 2026 23:04:26 +0000 Subject: [PATCH 10/22] Verify restored draft KV and fail incomplete state fingerprints Move core diagnostics from the dependent NVMe work (4d73bb3) into the shared-core review branch. Read back authoritative bytes and resident ring pages without rewriting state; remove a redundant GPU fixture refill that could mask restore failures. Bound hash workspace and check synchronization/copy errors. Opt-in diagnostics record batched versus token draft prefill. Validation: current core translation units pass C++ syntax checks; 1188 host transfer checks pass with ASan/UBSan. Real GPU and full-model validation remain pending the benchmark window. --- include/strata/core/conversation_snapshot.hpp | 5 +++ src/core/conversation_snapshot.cpp | 43 ++++++++++++++++++- src/core/conversation_snapshot_test.cpp | 4 +- src/core/conversation_validation_test.cpp | 7 +++ src/program/generate.cpp | 39 +++++++++++++++-- 5 files changed, 90 insertions(+), 8 deletions(-) diff --git a/include/strata/core/conversation_snapshot.hpp b/include/strata/core/conversation_snapshot.hpp index a135e310..550e373a 100644 --- a/include/strata/core/conversation_snapshot.hpp +++ b/include/strata/core/conversation_snapshot.hpp @@ -18,6 +18,11 @@ bool conversation_kv_validate(const ConversationKv& image, const QsaState& state int64_t upto, bool include_index, std::string& error); bool conversation_kv_restore(const ConversationKv& image, const QsaState& state, const ModelGeometry& g, int64_t upto, bool include_index, std::string& error); +// Diagnostic read-back after a synchronized restore. Uses 64 KiB of stack +// workspace, compares authoritative bytes and resident draft-ring pages, and +// fingerprints the authoritative payload only. Never changes model state. +bool conversation_kv_verify(const ConversationKv& image, const QsaState& state, const ModelGeometry& g, + int64_t upto, bool include_index, uint64_t& fingerprint, std::string& error); struct ConversationStateSizes { size_t gdn = 0, ple = 0, tail = 0, dead = 0, block_pos = 0; diff --git a/src/core/conversation_snapshot.cpp b/src/core/conversation_snapshot.cpp index 796d5c8b..3e1254a5 100644 --- a/src/core/conversation_snapshot.cpp +++ b/src/core/conversation_snapshot.cpp @@ -4,6 +4,7 @@ #include #include +#include #include namespace strata::core { @@ -65,8 +66,8 @@ bool layout(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index return true; } -std::array pools(const QsaState& st) { - const bool host = st.kv_mode != 0; +std::array pools(const QsaState& st, bool resident = false) { + const bool host = st.kv_mode != 0 && !resident; if (st.kv_hybrid) return {st.k_q, st.v_q4, st.k_scale, nullptr, st.idx_pooled}; if (st.kv_q4) return {host ? st.host.k_q4 : st.k_q4, host ? st.host.v_q4 : st.v_q4, nullptr, nullptr, st.idx_pooled}; @@ -188,4 +189,42 @@ bool conversation_kv_restore(const ConversationKv& image, const QsaState& st, co return false; } +bool conversation_kv_verify(const ConversationKv& image, const QsaState& st, const ModelGeometry& g, + int64_t upto, bool index, uint64_t& fingerprint, std::string& error) { + if (!conversation_kv_validate(image, st, g, upto, index, error)) return false; + std::array buffer; + uint64_t hash = 1469598103934665603ull; + auto compare = [&](const void* device, const uint8_t* expected, size_t bytes, bool include_hash) { + for (size_t offset = 0; offset < bytes;) { + const size_t n = std::min(buffer.size(), bytes - offset); + if (!transfer(buffer.data(), static_cast(device) + offset, n, error)) return false; + if (std::memcmp(buffer.data(), expected + offset, n) != 0) { + error = "conversation snapshot: restored K/V bytes differ"; + return false; + } + if (include_hash) for (size_t i = 0; i < n; ++i) { hash ^= buffer[i]; hash *= 1099511628211ull; } + offset += n; + } + return true; + }; + const std::array*, 5> saved = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; + const auto authoritative = pools(st); + for (size_t i = 0; i < saved.size(); ++i) + if (!compare(authoritative[i], saved[i]->data(), saved[i]->size(), true)) return false; + if (st.kv_mode == 2 && image.cells > 0) { + const auto resident = pools(st, true); + const int64_t end = image.cells / image.page_size; + const int64_t begin = std::max(0, end - st.n_slots); + for (size_t i = 0; i < 4; ++i) { + if (saved[i]->empty()) continue; + const size_t page_bytes = saved[i]->size() / size_t(end); + for (int64_t page = begin; page < end; ++page) + if (!compare(static_cast(resident[i]) + size_t(page % st.n_slots) * page_bytes, + saved[i]->data() + size_t(page) * page_bytes, page_bytes, false)) return false; + } + } + fingerprint = hash; + return true; +} + } // namespace strata::core diff --git a/src/core/conversation_snapshot_test.cpp b/src/core/conversation_snapshot_test.cpp index 5b0343bd..515a6408 100644 --- a/src/core/conversation_snapshot_test.cpp +++ b/src/core/conversation_snapshot_test.cpp @@ -197,6 +197,8 @@ int main() { cuda_check(cudaDeviceSynchronize()); check(conversation_kv_save(restored,f.state,f.g,upto,index,err),"read back restored A"); check(equal(a,restored),"A/B/A byte-exact K/V and indexer state"); + uint64_t fingerprint = 0; + check(conversation_kv_verify(a,f.state,f.g,upto,index,fingerprint,err),"verify restored authoritative and resident bytes without rewriting them"); if (mode==1) { std::vector table((size_t)f.state.n_pages); cuda_check(cudaMemcpy(table.data(),f.state.page_table,table.size()*4,cudaMemcpyDeviceToHost)); @@ -205,8 +207,6 @@ int main() { if (mode==2 && upto>0) { const auto s=qsa_real_shapes(); const int64_t b1=(upto+s.page_size-1)/s.page_size,b0=std::max(0,b1-f.state.n_slots); - kv_ring_restore(qsa_attn_pools(f.state),f.state.host,fmt,b0,b1,f.state.n_slots,s,nullptr); - cuda_check(cudaDeviceSynchronize()); const size_t block=kv_block_bytes(s,fmt)/2; // Codes and scales are separate in INT8; check code bytes here. const size_t code_block=fmt==kKvInt8 ? s.page_size*s.n_head_kv*s.head_dim : block; diff --git a/src/core/conversation_validation_test.cpp b/src/core/conversation_validation_test.cpp index 13d9b7c4..3676b93d 100644 --- a/src/core/conversation_validation_test.cpp +++ b/src/core/conversation_validation_test.cpp @@ -171,6 +171,13 @@ void fixture(int format, int experts, bool zero_qsa, bool ple) { "injected host transfer backend completes a valid restore"); check(gdn==image.live.gdn && history==image.live.ple && ss.ple_prev[0]==8 && ss.ple_prev[1]==9, "successful restore publishes correct running state and PLE window"); + uint64_t fingerprint = 0; + check(conversation_kv_verify(image.kv.back(),draft.st,g,9,false,fingerprint,error), "read-back verifies complete draft payload"); + draft.data[0][0] ^= 1; + check(!conversation_kv_verify(image.kv.back(),draft.st,g,9,false,fingerprint,error), "read-back detects corrupted draft byte"); + draft.data[0][0] ^= 1; + fail_copy = copy_calls + 1; + check(!conversation_kv_verify(image.kv.back(),draft.st,g,9,false,fingerprint,error), "read-back transfer failure is not a successful fingerprint"); #endif } } diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 7ee627be..d98d43f4 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -3360,6 +3360,9 @@ int main(int argc, char** argv) { // E-9: batched through the prompt path when it can (one GPU: a layer split's drafter is on the last stage) const bool batched = !multi_gpu && sp.draft_kv(mtp, R_rows, nxt.data(), T, p0, e); if (!e.empty() || (!batched && !mtp.prefill(R_rows, nxt.data(), T, p0, e))) return false; + if (std::getenv("STRATA_SNAPSHOT_VERIFY") != nullptr) + std::fprintf(stderr, "strata serve: DRAFT_PREFILL path=%s mode=%d cells=%lld\n", + batched ? "batched" : "token", mtp.kv_state().kv_mode, (long long) T); // progress for the server window: PP const int64_t done = p0 + T; const double ms = std::chrono::duration(Clock::now() - pp_t0).count(); @@ -3864,6 +3867,17 @@ int main(int argc, char** argv) { std::printf("ERR restoring parked conversation: %s\n", err.c_str()); return 1; } + if (std::getenv("STRATA_SNAPSHOT_VERIFY") != nullptr) { + uint64_t draft_hash = 0; + if (!strata::core::conversation_kv_verify(incoming->kv.back(), mtp.kv_state(), g, + int64_t(incoming->live.ids.size()), false, draft_hash, err)) { + std::printf("ERR verifying restored draft KV: %s\n", err.c_str()); + return 1; + } + std::fprintf(stderr, "strata serve: SNAPSHOT_VERIFY draft=%016llx cells=%lld mode=%d source=%s\n", + (unsigned long long) draft_hash, (long long) incoming->kv.back().cells, + mtp.kv_state().kv_mode, "ram"); + } live = std::move(incoming->live.ids); live_imgs = std::move(incoming->live.imgs); checks = std::move(incoming->checkpoints); @@ -4309,17 +4323,30 @@ int main(int argc, char** argv) { if (state_hash && live_ok) { // DEBUG: a fingerprint of every part of the session over the positions it holds ([0, L)), and // separately of what lies past them in the last KV page (stale cells, fine unless something reads them) - cudaDeviceSynchronize(); + if (cudaDeviceSynchronize() != cudaSuccess) { + std::printf("ERR synchronizing state fingerprint\n"); + return 1; + } const int64_t L = (int64_t) live.size(); const strata::kernels::QsaShapes qs = [&] { strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_dim = g.idx_key_dim; return s; }(); + bool hash_ok = true; + std::array hash_buffer; auto hash_dev = [&](const void* p, size_t bytes, uint64_t h) { - std::vector b(bytes); - if (bytes) cudaMemcpy(b.data(), p, bytes, cudaMemcpyDefault); // VRAM or a streamed host copy - return fnv1a(b.data(), b.size(), h); + for (size_t offset = 0; hash_ok && offset < bytes;) { + const size_t n = std::min(hash_buffer.size(), bytes - offset); + // VRAM or a streamed host copy, with fixed diagnostic workspace. + if (cudaMemcpy(hash_buffer.data(), static_cast(p) + offset, n, cudaMemcpyDefault) != cudaSuccess) { + hash_ok = false; + break; + } + h = fnv1a(hash_buffer.data(), n, h); + offset += n; + } + return h; }; // the cells [c0, c1) of one int8 K or V pool ([page][kv_head][page_size][head_dim]), bytes per value `w` auto hash_cells = [&](const void* pool, int64_t per_cell, int64_t c0, int64_t c1, uint64_t h) { @@ -4386,6 +4413,10 @@ int main(int argc, char** argv) { const int64_t mL = std::min(L, ms.max_cells); for (const auto& [pool, w] : kv_arrays(ms)) if (pool != nullptr) h_mtp = hash_cells(pool, w, 0, mL, h_mtp); + if (!hash_ok) { + std::printf("ERR reading state fingerprint\n"); + return 1; + } std::fprintf(stderr, "strata serve: STATE_HASH L=%lld gdn=%016llx ple=%016llx tail=%016llx pooled=%016llx " "kv=%016llx mtp=%016llx stale=%016llx dead=%016llx ple_prev=%d,%d\n", (long long) L, (unsigned long long) h_gdn, (unsigned long long) h_ple, (unsigned long long) h_tail, From 75fce92c93fe77041611732f4bf7427b7d87ac80 Mon Sep 17 00:00:00 2001 From: Jeremiah Ritchey <44681828+jeremiahritchey@users.noreply.github.com> Date: Tue, 29 Sep 2026 23:08:51 +0000 Subject: [PATCH 11/22] Refresh core validation record for upstream 0.1.27 --- docs/plans/shared-conversation-snapshots.md | 5 +++++ .../shared-conversation-upstream-validation.md | 17 +++++++++++++---- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/docs/plans/shared-conversation-snapshots.md b/docs/plans/shared-conversation-snapshots.md index f7cfc4d0..a0ad89d4 100644 --- a/docs/plans/shared-conversation-snapshots.md +++ b/docs/plans/shared-conversation-snapshots.md @@ -71,3 +71,8 @@ staging-budget, compatibility and eviction/promotion tests remain required. Windows admission coverage includes @midhatn's contribution, preserved with its original authorship. See the [validation record](shared-conversation-upstream-validation.md) for results, commands, and hardware limits. + +For model validation, `STRATA_SNAPSHOT_VERIFY=1` records the draft-prefill path and +compares restored draft KV with saved bytes, including resident ring pages. The +read-back uses 64 KiB of workspace and emits a fingerprint only on success. +A mismatch or read-back failure stops the test engine. It is off by default. diff --git a/docs/plans/shared-conversation-upstream-validation.md b/docs/plans/shared-conversation-upstream-validation.md index 6ae00dab..6493d50b 100644 --- a/docs/plans/shared-conversation-upstream-validation.md +++ b/docs/plans/shared-conversation-upstream-validation.md @@ -1,6 +1,6 @@ # Conversation cache validation -The core review branch is based on upstream 0.1.26 (`4c68013`). Recorded model +The core review branch is based on upstream 0.1.27 (`a790805`). Recorded model results below belong to the earlier 0.1.25 implementation (`cabd50c` through `1d9e4e7`), not the new base. The Windows admission test is @midhatn's `32cf918`, retained as `b319d43`. Historical records and the general Pi benchmark remain on local branch @@ -8,12 +8,14 @@ not the new base. The Windows admission test is @midhatn's `32cf918`, retained a ## Current offline checks -After separating the general benchmark tooling and merging 0.1.26, all 47 tool +After separating the general benchmark tooling and merging 0.1.27, all 47 tool tests and the 22 cache-harness tests under Python `-O` pass. Recoverable snapshot rejection now clears its diagnostic error before the new batched draft-prefill path runs. That C++ integration change still needs an engine build and model validation; these Python passes do not establish it. No benchmark server or GPU -was used for these checks. +was used for these checks. The core frontend suite passes 66 tests (three skipped) +on 0.1.27. Upstream changes include a HIP-only compilation fix and a changed draft +vocabulary; the latter requires new model evidence with its exact loaded assets. ## Recorded Linux evidence (2026-09-29) @@ -72,7 +74,7 @@ Run model/GPU gates only in an exclusive test window. ## Outstanding evidence -- Repeat affected build/model gates on 0.1.26, including batched draft prompt KV +- Repeat affected build/model gates on 0.1.27, including batched draft prompt KV and its fingerprint. Previous main-model hashes excluded draft scratch/state. - NVMe restart, corruption, foreign identity, eviction/promotion and explicit staging bounds; no disk acceptance is claimed yet. @@ -81,3 +83,10 @@ Run model/GPU gates only in an exclusive test window. Coder-model runs are untested; synthetic fixtures do not substitute for them. - Full optional upstream test configuration was blocked on 0.1.25 by missing `native_mmvq_multi.cpp` and `hit_cpu_order_parity.cu`; focused tests were used. + +The opt-in draft read-back diagnostic is part of the core branch. It verifies +restored authoritative and resident-ring bytes before emitting a draft fingerprint. +The GPU fixture no longer refills the ring itself, which could hide a restore bug. +On the 0.1.26 core, 1,188 ASan/UBSan host transfer checks passed, including corrupted +bytes and failed copies, and affected translation units passed syntax checks. +The actual GPU fixture and final 0.1.27 engine/model tests remain pending. From 876f254c7895df916784e332988062765d5f9bd1 Mon Sep 17 00:00:00 2001 From: Jeremiah Ritchey <44681828+jeremiahritchey@users.noreply.github.com> Date: Tue, 29 Sep 2026 23:14:24 +0000 Subject: [PATCH 12/22] Report actual draft residency in snapshot verification --- src/program/generate.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index d98d43f4..7cadca36 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -3874,9 +3874,10 @@ int main(int argc, char** argv) { std::printf("ERR verifying restored draft KV: %s\n", err.c_str()); return 1; } - std::fprintf(stderr, "strata serve: SNAPSHOT_VERIFY draft=%016llx cells=%lld mode=%d source=%s\n", + std::fprintf(stderr, "strata serve: SNAPSHOT_VERIFY draft=%016llx cells=%lld mode=%d source=%s resident=%lld\n", (unsigned long long) draft_hash, (long long) incoming->kv.back().cells, - mtp.kv_state().kv_mode, "ram"); + mtp.kv_state().kv_mode, "ram", + (long long) (mtp.kv_state().n_slots * strata::kernels::qsa_real_shapes().page_size)); } live = std::move(incoming->live.ids); live_imgs = std::move(incoming->live.imgs); From 8d46e95ff52beedf65dabc39956f3cfcdfb5a89c Mon Sep 17 00:00:00 2001 From: Jeremiah Ritchey <44681828+jeremiahritchey@users.noreply.github.com> Date: Tue, 29 Sep 2026 23:20:13 +0000 Subject: [PATCH 13/22] Record linked 0.1.27 core build and host validation --- docs/plans/shared-conversation-upstream-validation.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/plans/shared-conversation-upstream-validation.md b/docs/plans/shared-conversation-upstream-validation.md index 6493d50b..90bb4d6e 100644 --- a/docs/plans/shared-conversation-upstream-validation.md +++ b/docs/plans/shared-conversation-upstream-validation.md @@ -11,8 +11,10 @@ not the new base. The Windows admission test is @midhatn's `32cf918`, retained a After separating the general benchmark tooling and merging 0.1.27, all 47 tool tests and the 22 cache-harness tests under Python `-O` pass. Recoverable snapshot rejection now clears its diagnostic error before the new batched draft-prefill -path runs. That C++ integration change still needs an engine build and model -validation; these Python passes do not establish it. No benchmark server or GPU +path runs. The final core engine and snapshot test binaries build with GCC 15.2, +CUDA 13.4, SM89 and portable AVX2. Five host CTests pass with GPU visibility +disabled: policy, admission, checkpoint retention, validation and injected +transfers. Model correctness remains unverified on this base. No benchmark server or GPU was used for these checks. The core frontend suite passes 66 tests (three skipped) on 0.1.27. Upstream changes include a HIP-only compilation fix and a changed draft vocabulary; the latter requires new model evidence with its exact loaded assets. @@ -89,4 +91,6 @@ restored authoritative and resident-ring bytes before emitting a draft fingerpri The GPU fixture no longer refills the ring itself, which could hide a restore bug. On the 0.1.26 core, 1,188 ASan/UBSan host transfer checks passed, including corrupted bytes and failed copies, and affected translation units passed syntax checks. -The actual GPU fixture and final 0.1.27 engine/model tests remain pending. +The actual GPU fixture and final 0.1.27 model tests remain pending. The linked +engine SHA-256 is `f3eda68ad0dce9a1604345743ba5432ed73f2efeaf6b4f84f435317d7f2ba9ff`; +build and host-test records are in `logs/review-0.1.27/`. From 3a5b090014f1561a9f36412e30a91c4f835abc2f Mon Sep 17 00:00:00 2001 From: Jeremiah Ritchey <44681828+jeremiahritchey@users.noreply.github.com> Date: Wed, 30 Sep 2026 01:16:12 +0000 Subject: [PATCH 14/22] Record final Linux snapshot and RAM cache acceptance --- docs/plans/shared-conversation-snapshots.md | 4 +- ...shared-conversation-upstream-validation.md | 131 ++++++++---------- 2 files changed, 60 insertions(+), 75 deletions(-) diff --git a/docs/plans/shared-conversation-snapshots.md b/docs/plans/shared-conversation-snapshots.md index a0ad89d4..b93bf91e 100644 --- a/docs/plans/shared-conversation-snapshots.md +++ b/docs/plans/shared-conversation-snapshots.md @@ -66,8 +66,8 @@ entries. A failed spill may drop the already-evicted entry; it must not exceed RAM limits or stop inference. Eviction-only persistence does not promise that the latest active turn survives a crash. Files contain conversation content. -The adapter is being integrated from @maedoc's #52; disk restart/corruption, -staging-budget, compatibility and eviction/promotion tests remain required. +The dependent adapter follows @maedoc's #52 streaming-envelope approach; its +implementation and disk acceptance evidence belong to that dependent branch. Windows admission coverage includes @midhatn's contribution, preserved with its original authorship. See the [validation record](shared-conversation-upstream-validation.md) for results, commands, and hardware limits. diff --git a/docs/plans/shared-conversation-upstream-validation.md b/docs/plans/shared-conversation-upstream-validation.md index 90bb4d6e..abbd680e 100644 --- a/docs/plans/shared-conversation-upstream-validation.md +++ b/docs/plans/shared-conversation-upstream-validation.md @@ -1,58 +1,49 @@ # Conversation cache validation -The core review branch is based on upstream 0.1.27 (`a790805`). Recorded model -results below belong to the earlier 0.1.25 implementation (`cabd50c` through `1d9e4e7`), -not the new base. The Windows admission test is @midhatn's `32cf918`, retained as -`b319d43`. Historical records and the general Pi benchmark remain on local branch -`feat/conversation-cache-upstream` at `cb8d90c`; they are outside the core patch. +The focused core branch includes upstream 0.1.27 (`a790805`). Final Linux checks +ran on 2026-09-30 after the user's Pi benchmark completed. This record describes +the review binaries, not the original server restored after the test window. +Windows admission coverage retains @midhatn's original authorship in `b319d43`. -## Current offline checks +## Hardware and artifacts -After separating the general benchmark tooling and merging 0.1.27, all 47 tool -tests and the 22 cache-harness tests under Python `-O` pass. Recoverable snapshot -rejection now clears its diagnostic error before the new batched draft-prefill -path runs. The final core engine and snapshot test binaries build with GCC 15.2, -CUDA 13.4, SM89 and portable AVX2. Five host CTests pass with GPU visibility -disabled: policy, admission, checkpoint retention, validation and injected -transfers. Model correctness remains unverified on this base. No benchmark server or GPU -was used for these checks. The core frontend suite passes 66 tests (three skipped) -on 0.1.27. Upstream changes include a HIP-only compilation fix and a changed draft -vocabulary; the latter requires new model evidence with its exact loaded assets. +EPYC 7532, RTX 4090, GCC 15.2, CUDA 13.4, SM89, portable AVX2, IQ3_S. +All model engines used `numactl --interleave=all --physcpubind=0-31` and matched +expert residency (7,846 slots, PCIe share 0.55). INT8 streamed/ring tests used +131,072 context and 32,768 main resident cells; batched INT8/K8V4 tests used +16,384 context with full device KV. These are correctness gates, not a Pi speed +comparison or measurements at the production server's 262,144 context limit. -## Recorded Linux evidence (2026-09-29) +Core executable SHA-256: +`f3eda68ad0dce9a1604345743ba5432ed73f2efeaf6b4f84f435317d7f2ba9ff`. +Local commands, configs, raw logs and result JSON are under +`logs/review-0.1.27/`; full-model artifacts are in its `model-window/` directory. +Documentation-only commits after this build do not change the tested code. -EPYC 7532, RTX 4090, GCC 15.2, CUDA 13.4, SM89, portable AVX2, IQ3_S. Paired -engines used 131,072 context, INT8 KV, 32,768 resident cells, 7,846 expert slots, -and PCIe share 0.55. Evidence remains in that worktree's `logs/upstream-20260929/`. +## Passed gates -| Gate | Result and scope | +| Gate | Evidence | | --- | --- | -| Components | Seven CTest targets passed: cache policy, admission, GPU round trips, host validation, injected transfers, checkpoint retention, sampler parity | -| Python | 65 server tests (three skipped), 47 tool tests, 22 harness tests under `-O` | -| ASan/UBSan | 35 policy, 23 admission, 1,116 host validation/transfer checks passed | -| CLI | Ten malformed/range/layer-split checks passed | -| Full model | Nine paired gates: reuse/checkpoints, long speculation, pressure, oversize, exchange, admission denial, synthetic image/grid and add/project steering isolation | -| Soak | 30 known-answer returns at 2,026 / 39,985 / 119,987 tokens; exact outputs/main-state fingerprints and stable retained payload | -| HTTP | Twelve requests passed reuse, eviction, disconnect and recovery without an engine restart | +| Components | Policy, admission, checkpoint retention, validation, injected transfers and sampler parity CTests | +| GPU snapshot fixture | 1,298 checks; FP16/INT8/Q4/K8V4 supported layouts, partial pages, indexer spare keys, early checkpoints, zero-QSA, 256/512-expert metadata and draft ring read-back | +| Python | 66 frontend tests (three skipped), 47 tool tests, 22 cache-harness tests under Python `-O` | +| Transfer diagnostics | 1,188 ASan/UBSan host checks, including corrupted bytes and failed copies | +| RAM model reuse | Streamed INT8; batched INT8 and K8V4; known answers, exact output tokens and main-state parity | +| Long speculation | Speculation width four beyond resident KV, with output/state parity | +| Capacity/fallback | 400 MiB pressure and exchange, 1 MiB oversized entry, impossible RAM-floor rejection in ring and batched paths | +| Isolation | Synthetic image/grid identity and add/project steering isolation | +| Soak | 30 returns at 2,026 / 39,985 / 119,987 tokens; exact output/state parity and bounded retention | +| HTTP | Twelve requests passed reuse, slot eviction, disconnect and recovery on a private endpoint | -The nine INT8 gates and soak used executable SHA-256 -`0d8cbca38ce27153cea516cf6454df4653196ae875e0224fd3dd3c51e1d27ea0`. -K8V4 then exposed incorrect hybrid-format flags. After correction, executable -`4e174e8a4b602f1f8efe846cf19570478fcc7d2b50f3c48373c799d39b3610c7` -passed K8V4/INT8 model parity, the three affected CTest targets, the 1,116 sanitizer -checks, and HTTP recovery. The full nine-gate suite was not repeated on that fix. -An initial unequal-expert-residency comparison was rejected, not counted as a pass. - -Four bounded Pi coding runs passed ten independent checks each. Return prompt -processing took 4.33–5.78 s with parking off and 1.50–1.52 s with it on, with -similar but unequal prompts. Whole-task timing favored opposite modes in the two -pairs, so there is no demonstrated overall speedup/regression. The benchmark -harness, detailed results and failed preliminary tool-budget trial are separate -from the core patch. These are not version-to-version or Windows measurements. +The opt-in `STRATA_SNAPSHOT_VERIFY=1` diagnostic records the actual draft-prefill +path and verifies restored authoritative bytes and resident ring pages before +emitting a fingerprint. Main-model state hashes alone do not cover draft state. +The GPU fixture checks the ring produced by restore without refilling it first. +Host fault injection does not simulate recovery of a broken CUDA context. ## Reproduction -Configure the engine normally with `-DSTRATA_BUILD_CONVERSATION_TESTS=ON`, then: +Configure the normal engine with `-DSTRATA_BUILD_CONVERSATION_TESTS=ON`, then: ```sh cmake --build build --target conversation_cache_test conversation_memory_test conversation_snapshot_test conversation_validation_test conv_cache_test sampler_parity @@ -60,37 +51,31 @@ ctest --test-dir build -R '^(conversation_.*|conv_cache_test|sampler_parity)$' - python -m unittest tools.test_conversation_cache_parity tools.test_conversation_cache_isolation tools.test_conversation_cache_soak tools.test_conversation_cache_http_smoke ``` -On GNU/Clang ELF CUDA builds also build `conversation_transfer_test`; it wraps -copies and synchronization for host fault injection. It does not simulate recovery -of a broken CUDA context. GPU fixtures cover partial pages, distinct indexer spare -keys, early checkpoints, zero-QSA and 256/512-expert metadata. +On GNU/Clang ELF CUDA builds also build `conversation_transfer_test` for wrapped +copy/synchronization fault injection. Focused targets were used; this record does +not claim the full optional upstream test configuration passes. -Model tools default to a dry run. With `--config CONFIG --engine ENGINE --output -NEW_DIRECTORY --run`, run parity at `--spec 1` and `--spec 4`, then scenarios -`pressure`, `oversized`, `exchange` and `admission`. Select byte budgets that -actually force the named condition; use a RAM floor above available memory for -denial. Isolation scenarios are `image`, `add`, and `project`. The soak requires -at least 30 cycles and three lengths crossing resident KV and approaching the -configured context limit. HTTP smoke requires an exclusive idle test endpoint. -Run model/GPU gates only in an exclusive test window. +Model tools default to dry runs. Supply `--config CONFIG --engine ENGINE --output +NEW_DIRECTORY --run` to parity at `--spec 1` and `--spec 4`, then scenarios +`pressure`, `oversized`, `exchange` and `admission`. Budgets must force the named +condition. Isolation scenarios are `image`, `add` and `project`. The soak requires +at least 30 cycles and three lengths crossing residency and approaching context. +Use `STRATA_SNAPSHOT_VERIFY=1` and verify actual batched-prefill evidence when +claiming that path. HTTP smoke needs an exclusive idle test endpoint. Run model +and GPU checks only in an exclusive test window. -## Outstanding evidence +## Limits and separate work -- Repeat affected build/model gates on 0.1.27, including batched draft prompt KV - and its fingerprint. Previous main-model hashes excluded draft scratch/state. -- NVMe restart, corruption, foreign identity, eviction/promotion and explicit - staging bounds; no disk acceptance is claimed yet. -- Windows runtime: only contributor-reported 25 MSVC admission checks, not locally - reproduced. HIP execution, multi-GPU parking, real vision encoder and full - Coder-model runs are untested; synthetic fixtures do not substitute for them. -- Full optional upstream test configuration was blocked on 0.1.25 by missing - `native_mmvq_multi.cpp` and `hit_cpu_order_parity.cu`; focused tests were used. +- Windows implementation reviewed, not locally executed. Contributor reports + concern separate Windows work and do not validate this branch. +- HIP execution, real vision encoding and the full Coder model are untested. + Synthetic image inputs test cache identity, not the vision encoder. +- Whole-conversation multi-GPU parking and hybrid K8V4 streaming/rings are + unsupported; ordinary upstream stage checkpoints remain available. +- Optional disk persistence is a dependent change with its own acceptance record. -The opt-in draft read-back diagnostic is part of the core branch. It verifies -restored authoritative and resident-ring bytes before emitting a draft fingerprint. -The GPU fixture no longer refills the ring itself, which could hide a restore bug. -On the 0.1.26 core, 1,188 ASan/UBSan host transfer checks passed, including corrupted -bytes and failed copies, and affected translation units passed syntax checks. -The actual GPU fixture and final 0.1.27 model tests remain pending. The linked -engine SHA-256 is `f3eda68ad0dce9a1604345743ba5432ed73f2efeaf6b4f84f435317d7f2ba9ff`; -build and host-test records are in `logs/review-0.1.27/`. +Historical 0.1.25 evidence remains on local `feat/conversation-cache-upstream` +at `cb8d90c`. General Pi tooling is isolated on +`tools/conversation-cache-benchmark`. Four historical bounded Pi trials passed +correctness, but overall timing favored opposite modes in the two pairs; no +whole-task speedup or version-to-version performance claim follows from them. From 3782659274922a497a842ae02b08b1426381b930 Mon Sep 17 00:00:00 2001 From: Jeremiah Ritchey <44681828+jeremiahritchey@users.noreply.github.com> Date: Wed, 30 Sep 2026 02:00:12 +0000 Subject: [PATCH 15/22] Ignore llama.cpp dependency directories and symlinks --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index cb227e32..26885bfe 100644 --- a/.gitignore +++ b/.gitignore @@ -28,7 +28,7 @@ td.log # created by setup.py on the user's machine /.venv/ /build/ -/third_party/llama.cpp/ +/third_party/llama.cpp /models/ /packs/ /mtp/ From 0fca77bfe02e828ac4951915ce8345e6d64471fd Mon Sep 17 00:00:00 2001 From: Jeremiah Ritchey <44681828+jeremiahritchey@users.noreply.github.com> Date: Wed, 30 Sep 2026 03:30:58 +0000 Subject: [PATCH 16/22] Remove planning documents from the core PR --- docs/DETAILS.md | 6 +- docs/plans/shared-conversation-snapshots.md | 78 ------------------ ...shared-conversation-upstream-validation.md | 81 ------------------- 3 files changed, 2 insertions(+), 163 deletions(-) delete mode 100644 docs/plans/shared-conversation-snapshots.md delete mode 100644 docs/plans/shared-conversation-upstream-validation.md diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 0d043b75..b21652cf 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -398,11 +398,9 @@ is a cap, not a recommendation for every machine. The shared snapshot core validates all layers and checkpoints before applying any state. Invalid entries are discarded; transfer/synchronization failure is fatal rather than permission to continue with partial state. Indexer spare keys and the -moving spare row are preserved, including checkpoint rewinds. These development -changes and the optional disk-tier boundary are described in the -[shared-core proposal](plans/shared-conversation-snapshots.md). +moving spare row are preserved, including checkpoint rewinds. The engine log reports parking, restoration, bytes and evictions. Snapshots are not -persisted across restarts. See [the design and validation gates](plans/shared-conversation-snapshots.md). +persisted across restarts. **Current limits (v1):** one request at a time, and one conversation cached at a time (switching between two chats re-reads the other one unless the opt-in cache above is enabled); images only when set up with them (below); no video. **Temperature / top_p / top_k / min_p / diff --git a/docs/plans/shared-conversation-snapshots.md b/docs/plans/shared-conversation-snapshots.md deleted file mode 100644 index b93bf91e..00000000 --- a/docs/plans/shared-conversation-snapshots.md +++ /dev/null @@ -1,78 +0,0 @@ -# Conversation snapshots and RAM cache - -[Issue #57](https://github.com/Niko1221/Strata/issues/57) preserves reusable state -when independent agent conversations alternate on one server. Requests remain -serial, require no client session markers, and restore into existing allocations. -The shared core and RAM policy land first; the optional NVMe tier is a dependent -integration, following the [maintainer's requested order](https://github.com/Niko1221/Strata/pull/52#issuecomment-5898176448). - -## Ownership and matching - -- `conversation_snapshot.hpp`, `conversation_snapshot.cpp`, and - `conversation_state.cpp` define complete capture, validation and restoration. - They contain no retention policy or filesystem operations. -- `ConversationCache` owns inactive snapshots, selects the longest exact token - prefix with matching image/grid identity and steering state, and evicts the - least recently active entries. Active state wins ties. -- The serve loop parks before a switch or checkpoint rewind overwrites state. - A continuing request does not trigger a snapshot. Checkpoint root/LRU behavior - from upstream is retained inside each conversation. - -Snapshots include live and checkpoint GDN/PLE state, page-rounded used main KV, -indexer pooled rows/tail/spare key/block position, and used draft KV. They exclude -scratch recomputed before use. Restoring an early checkpoint reconstructs the -spare pooled row and PLE token history. Streamed KV uses authoritative host pools; -restore invalidates replaceable VRAM maps and refills the draft ring. Device -addresses remain stable for captured graphs. - -FP16, INT8, Q4 and identity-layout K8V4 are represented explicitly. K8V4 stores -INT8 K/scales separately from Q4 V; it does not use the block movers' format enum. -Hybrid streaming/ring layouts and whole-conversation layer-split parking are -rejected. Ordinary upstream layer-split checkpoints remain available. - -## Capacity and failure handling - -`--conversation-cache-mib` defaults to zero (disabled), -`--conversation-cache-slots` to four, and `--conversation-cache-min-free-mib` to -2560. `--prompt-cache 0` disables parking and produces a warning when requested. - -The byte budget counts vector capacity, retained checkpoints, and incoming -snapshots held during an exchange; it is additional to the active session and -is not an exact RSS limit. Estimate before allocation, then check physical RAM -using Linux `MemAvailable` or Windows `GlobalMemoryStatusEx`. Unknown telemetry -rejects admission. Check the free-RAM floor again after capture. These samples -are not reservations or cgroup/job-limit enforcement. - -Oversized entries and allocation/admission failures skip parking. Validate the -entire incoming image before modifying the outgoing session; invalid images -are discarded and ordinary prefix selection/prefill remains available. Transfer -or synchronization failures may leave partial GPU state, so the engine reports -an error and exits rather than continuing inference. Publish resume metadata -only after successful restore. Validation is not a transactional GPU rollback. - -## NVMe integration contract - -The disk adapter must consume this representation and restore through this core, -without another state-copy implementation. Spill immutable snapshots on RAM -eviction; disabled persistence performs no filesystem operations. A disk hit -competes with active/RAM prefixes and must reserve an explicit bounded staging -allocation plus physical RAM headroom before reading. - -Persist a versioned portable envelope, not native C++ objects. Bind exact weights, -tokenizer, steering configuration, geometry, KV format (including K8V4) and state -schema. Read, integrity-check and validate the same staged bytes before applying -them. Atomic publication must reject interrupted, truncated, corrupt and foreign -entries. A failed spill may drop the already-evicted entry; it must not exceed -RAM limits or stop inference. Eviction-only persistence does not promise that -the latest active turn survives a crash. Files contain conversation content. - -The dependent adapter follows @maedoc's #52 streaming-envelope approach; its -implementation and disk acceptance evidence belong to that dependent branch. -Windows admission coverage includes @midhatn's contribution, preserved with its -original authorship. See the [validation record](shared-conversation-upstream-validation.md) -for results, commands, and hardware limits. - -For model validation, `STRATA_SNAPSHOT_VERIFY=1` records the draft-prefill path and -compares restored draft KV with saved bytes, including resident ring pages. The -read-back uses 64 KiB of workspace and emits a fingerprint only on success. -A mismatch or read-back failure stops the test engine. It is off by default. diff --git a/docs/plans/shared-conversation-upstream-validation.md b/docs/plans/shared-conversation-upstream-validation.md deleted file mode 100644 index abbd680e..00000000 --- a/docs/plans/shared-conversation-upstream-validation.md +++ /dev/null @@ -1,81 +0,0 @@ -# Conversation cache validation - -The focused core branch includes upstream 0.1.27 (`a790805`). Final Linux checks -ran on 2026-09-30 after the user's Pi benchmark completed. This record describes -the review binaries, not the original server restored after the test window. -Windows admission coverage retains @midhatn's original authorship in `b319d43`. - -## Hardware and artifacts - -EPYC 7532, RTX 4090, GCC 15.2, CUDA 13.4, SM89, portable AVX2, IQ3_S. -All model engines used `numactl --interleave=all --physcpubind=0-31` and matched -expert residency (7,846 slots, PCIe share 0.55). INT8 streamed/ring tests used -131,072 context and 32,768 main resident cells; batched INT8/K8V4 tests used -16,384 context with full device KV. These are correctness gates, not a Pi speed -comparison or measurements at the production server's 262,144 context limit. - -Core executable SHA-256: -`f3eda68ad0dce9a1604345743ba5432ed73f2efeaf6b4f84f435317d7f2ba9ff`. -Local commands, configs, raw logs and result JSON are under -`logs/review-0.1.27/`; full-model artifacts are in its `model-window/` directory. -Documentation-only commits after this build do not change the tested code. - -## Passed gates - -| Gate | Evidence | -| --- | --- | -| Components | Policy, admission, checkpoint retention, validation, injected transfers and sampler parity CTests | -| GPU snapshot fixture | 1,298 checks; FP16/INT8/Q4/K8V4 supported layouts, partial pages, indexer spare keys, early checkpoints, zero-QSA, 256/512-expert metadata and draft ring read-back | -| Python | 66 frontend tests (three skipped), 47 tool tests, 22 cache-harness tests under Python `-O` | -| Transfer diagnostics | 1,188 ASan/UBSan host checks, including corrupted bytes and failed copies | -| RAM model reuse | Streamed INT8; batched INT8 and K8V4; known answers, exact output tokens and main-state parity | -| Long speculation | Speculation width four beyond resident KV, with output/state parity | -| Capacity/fallback | 400 MiB pressure and exchange, 1 MiB oversized entry, impossible RAM-floor rejection in ring and batched paths | -| Isolation | Synthetic image/grid identity and add/project steering isolation | -| Soak | 30 returns at 2,026 / 39,985 / 119,987 tokens; exact output/state parity and bounded retention | -| HTTP | Twelve requests passed reuse, slot eviction, disconnect and recovery on a private endpoint | - -The opt-in `STRATA_SNAPSHOT_VERIFY=1` diagnostic records the actual draft-prefill -path and verifies restored authoritative bytes and resident ring pages before -emitting a fingerprint. Main-model state hashes alone do not cover draft state. -The GPU fixture checks the ring produced by restore without refilling it first. -Host fault injection does not simulate recovery of a broken CUDA context. - -## Reproduction - -Configure the normal engine with `-DSTRATA_BUILD_CONVERSATION_TESTS=ON`, then: - -```sh -cmake --build build --target conversation_cache_test conversation_memory_test conversation_snapshot_test conversation_validation_test conv_cache_test sampler_parity -ctest --test-dir build -R '^(conversation_.*|conv_cache_test|sampler_parity)$' --output-on-failure -python -m unittest tools.test_conversation_cache_parity tools.test_conversation_cache_isolation tools.test_conversation_cache_soak tools.test_conversation_cache_http_smoke -``` - -On GNU/Clang ELF CUDA builds also build `conversation_transfer_test` for wrapped -copy/synchronization fault injection. Focused targets were used; this record does -not claim the full optional upstream test configuration passes. - -Model tools default to dry runs. Supply `--config CONFIG --engine ENGINE --output -NEW_DIRECTORY --run` to parity at `--spec 1` and `--spec 4`, then scenarios -`pressure`, `oversized`, `exchange` and `admission`. Budgets must force the named -condition. Isolation scenarios are `image`, `add` and `project`. The soak requires -at least 30 cycles and three lengths crossing residency and approaching context. -Use `STRATA_SNAPSHOT_VERIFY=1` and verify actual batched-prefill evidence when -claiming that path. HTTP smoke needs an exclusive idle test endpoint. Run model -and GPU checks only in an exclusive test window. - -## Limits and separate work - -- Windows implementation reviewed, not locally executed. Contributor reports - concern separate Windows work and do not validate this branch. -- HIP execution, real vision encoding and the full Coder model are untested. - Synthetic image inputs test cache identity, not the vision encoder. -- Whole-conversation multi-GPU parking and hybrid K8V4 streaming/rings are - unsupported; ordinary upstream stage checkpoints remain available. -- Optional disk persistence is a dependent change with its own acceptance record. - -Historical 0.1.25 evidence remains on local `feat/conversation-cache-upstream` -at `cb8d90c`. General Pi tooling is isolated on -`tools/conversation-cache-benchmark`. Four historical bounded Pi trials passed -correctness, but overall timing favored opposite modes in the two pairs; no -whole-task speedup or version-to-version performance claim follows from them. From 573bb36baa91a242484eaf51a75ce50437fc4061 Mon Sep 17 00:00:00 2001 From: Jeremiah Ritchey <44681828+jeremiahritchey@users.noreply.github.com> Date: Wed, 30 Sep 2026 04:06:08 +0000 Subject: [PATCH 17/22] Compare cache-disabled engines against untouched upstream Replay identical requests and require token, known-answer, reuse, resolved-setting and comparable main-state parity. Retain the complete pooled-state diagnostic and add a completed-row fingerprint matching upstream. Add negative controls that remain active under optimized Python. --- src/program/generate.cpp | 7 +- tools/conversation_cache_disabled.py | 195 ++++++++++++++++++++++ tools/test_conversation_cache_disabled.py | 102 +++++++++++ 3 files changed, 302 insertions(+), 2 deletions(-) create mode 100644 tools/conversation_cache_disabled.py create mode 100644 tools/test_conversation_cache_disabled.py diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 7cadca36..7e79f840 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -4375,6 +4375,7 @@ int main(int argc, char** argv) { uint64_t h_ple = hash_dev(ss.ple_hist, ss.ple_hist ? z.ple : 0, 1469598103934665603ull); uint64_t h_tail = 1469598103934665603ull, h_pool = h_tail, h_kv = h_tail, h_stale = h_tail; uint64_t h_dead = h_tail; + uint64_t h_pool_complete = h_tail; // upstream's extent, without the moving spare row const int64_t kvb = qs.head_dim, scb = (qs.head_dim / 64) * 2; // a state's K/V arrays and their bytes per (cell, head) row: the host copy when it has one auto kv_arrays = [&](const strata::core::QsaState& st) { @@ -4402,6 +4403,7 @@ int main(int argc, char** argv) { const strata::core::QsaState& st = ss.qsa_states[i]; h_tail = hash_dev(st.idx_tail, z.tail, h_tail); h_dead = hash_dev(st.idx_dead, z.dead, h_dead); + h_pool_complete = hash_dev(st.idx_pooled, (size_t) (L / qs.idx_block) * qs.idx_dim * 4, h_pool_complete); h_pool = hash_dev(st.idx_pooled, (size_t) (L > 0 ? L / qs.idx_block + 1 : 0) * qs.idx_dim * 4, h_pool); // KV streaming: the host copy is the identity layout and holds every cell for (const auto& [pool, w] : kv_arrays(st)) { @@ -4419,10 +4421,11 @@ int main(int argc, char** argv) { return 1; } std::fprintf(stderr, "strata serve: STATE_HASH L=%lld gdn=%016llx ple=%016llx tail=%016llx pooled=%016llx " - "kv=%016llx mtp=%016llx stale=%016llx dead=%016llx ple_prev=%d,%d\n", (long long) L, + "kv=%016llx mtp=%016llx stale=%016llx dead=%016llx pooled_complete=%016llx ple_prev=%d,%d\n", (long long) L, (unsigned long long) h_gdn, (unsigned long long) h_ple, (unsigned long long) h_tail, (unsigned long long) h_pool, (unsigned long long) h_kv, (unsigned long long) h_mtp, - (unsigned long long) h_stale, (unsigned long long) h_dead, ss.ple_prev[0], ss.ple_prev[1]); + (unsigned long long) h_stale, (unsigned long long) h_dead, + (unsigned long long) h_pool_complete, ss.ple_prev[0], ss.ple_prev[1]); } const int64_t req_hits = drive.d.cache_hits - decode_hits0; const int64_t req_look = (drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused) - decode_look0; diff --git a/tools/conversation_cache_disabled.py b/tools/conversation_cache_disabled.py new file mode 100644 index 00000000..db3c05f2 --- /dev/null +++ b/tools/conversation_cache_disabled.py @@ -0,0 +1,195 @@ +"""Compare untouched upstream with cache-disabled engines; dry-run by default. + +Private engines run sequentially in an exclusive GPU window. This is a correctness +gate, not a throughput benchmark: state fingerprinting adds diagnostic overhead. +""" +import argparse +import hashlib +import json +from pathlib import Path +import re +import sys +import threading +import time + +ROOT = Path(__file__).resolve().parents[1] +sys.path[:0] = [str(ROOT), str(ROOT / 'tools')] +from conversation_cache_parity import load_tokenizer, require +from conversation_cache_soak import answer_text +from serve.frontend import ChatTemplate +from serve.server import StrataEngine, child_env + +NAMES = ('short', 'A', 'A-live', 'A-checkpoint', 'B', 'A-return', 'B-return', 'A-return-again') +SETTINGS = ('version', 'context', 'kv', 'kv_resident', 'expert_slots', 'spec', + 'mtp_max', 'lookup', 'cvec', 'pcie_frac', 'spec_min_p', 'pool_workers') +# Untouched 0.1.27 does not emit the indexer `dead` field added by this PR. +# Draft scratch and unused page padding are not comparable authoritative state. +STATE_KEYS = ('L', 'gdn', 'ple', 'tail', 'pooled', 'kv', 'ple_prev') + + +def state_hashes(text, *, candidate=False): + hashes = [] + for line in text.splitlines(): + if 'STATE_HASH L=' in line: + fields = dict(re.findall(r'(\w+)=([0-9a-f,-]+)', line)) + require(set(STATE_KEYS) <= fields.keys(), 'missing upstream-compatible state fields') + if candidate: + # The PR's pooled hash includes the spare row. Require the + # separately emitted upstream extent instead of comparing unlike bytes. + require('pooled_complete' in fields, 'candidate lacks completed-row fingerprint') + fields['pooled'] = fields['pooled_complete'] + hashes.append({key: fields[key] for key in STATE_KEYS}) + return hashes + + +def common_args(cfg, spec): + # Upstream has no conversation-cache options. Omit them from EVERY arm so + # the candidates exercise their disabled default with identical arguments. + args, i = [], 0 + while i < len(cfg['args']): + arg = cfg['args'][i] + if arg.startswith('--conversation-cache-'): + require(i + 1 < len(cfg['args']), 'cache option lacks a value') + i += 2 + else: + args.append(arg) + i += 1 + return args + ['--prompt-cache', '6', '--adapt-swaps', '0', '--spec', str(max(2, spec)), + '--mtp-max-t', str(spec), '--suffix-draft', '0', '--spec-min-p', '0'] + + +def verify(results): + arms = results['arms'] + require(len(arms) >= 2 and arms[0]['name'] == 'upstream', 'missing comparison arms') + baseline = arms[0] + requests = results['requests'] + require([r['name'] for r in requests] == list(NAMES), 'incomplete request sequence') + require(all(r['ids'] and r['max_new'] > 0 for r in requests), 'empty request') + digest = hashlib.sha256(json.dumps(requests, sort_keys=True).encode()).hexdigest() + require(digest == results['request_digest'], 'request evidence changed') + for arm in arms: + require(arm['args'] == baseline['args'], 'engine arguments differ') + require(arm['request_digest'] == results['request_digest'], 'input requests differ') + require([r['name'] for r in arm['records']] == list(NAMES), 'incomplete output sequence') + require(not arm['cache_events'], 'disabled cache performed snapshot operations') + for key in SETTINGS: + require(key in arm['info'] and arm['info'][key] == baseline['info'][key], + f'{arm["name"]}: resolved setting differs: {key}') + if arm['name'] != 'upstream': + require(arm['info'].get('conversation_cache_mib') == 0, 'RAM cache not disabled') + require(arm['info'].get('conversation_disk_mib', 0) == 0, 'disk cache not disabled') + for request, reference, record in zip(requests, baseline['records'], arm['records']): + require(record['ids'] and record['finish'] in ('stop', 'length'), 'incomplete generation') + require(set(STATE_KEYS) <= record['state'].keys(), 'incomplete state fingerprint') + require(record['ids'] == reference['ids'], f'{arm["name"]}/{record["name"]}: output differs') + require(record['state'] == reference['state'], f'{arm["name"]}/{record["name"]}: state differs') + require(record['reused'] == reference['reused'], 'prefix reuse differs') + require(record['prompt_tokens'] == len(request['ids']), 'wrong prompt length') + if request.get('expected'): + require(answer_text(record['text']) == request['expected'].casefold(), 'known answer is wrong') + records = {r['name']: r for r in arm['records']} + require(records['A-live']['reused'] > 0 and records['A-checkpoint']['reused'] > 0, + 'continuation/checkpoint path not exercised') + require(records['A-return']['reused'] == records['A-return-again']['reused'] == 0, + 'conversation switching did not force cold fallback') + + +def main(): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument('--config', type=Path, required=True) + ap.add_argument('--upstream', type=Path, required=True) + ap.add_argument('--candidate', type=Path, action='append', required=True) + ap.add_argument('--output', type=Path, required=True, help='new directory; existing paths refused') + ap.add_argument('--paragraphs', type=int, default=128) + ap.add_argument('--spec', type=int, choices=(1, 4), default=1) + ap.add_argument('--run', action='store_true') + a = ap.parse_args() + if a.paragraphs < 1: + ap.error('paragraphs must be positive') + if not a.run: + print('Dry run: upstream and disabled candidates; identical inputs/settings, known answers and state parity.') + return + cfg = json.loads(a.config.read_text()) + tok_path = Path(cfg['tokenizer']) + tok = load_tokenizer(tok_path) + tpl_path = tok_path / 'chat_template.jinja' + tpl = ChatTemplate(tpl_path if tpl_path.exists() else ROOT / 'serve/chat_template.jinja') + def encode(text): + return tok.encode(text, parse_special=True) + def prompt(text): + return encode(tpl.render([{'role': 'user', 'content': text}], enable_thinking=False)) + text = 'Conversation A. Remember the exact code AZURE-314159.\n' + text += '\n'.join(f'Record {i}: blue square, green triangle, red circle.' for i in range(a.paragraphs)) + A = prompt(text + '\nThe exact code to remember is AZURE-314159. Reply OK.') + B = prompt('Unrelated conversation B. Remember BRONZE-271828. Reply OK.') + suffix = encode('<|im_end|>\n<|im_start|>user\nWhat exact code did I ask you to remember? ' + 'Reply with only that code.<|im_end|>\n<|im_start|>assistant\n\n\n\n\n') + args = common_args(cfg, a.spec) + env = child_env(cfg) + env.pop('STRATA_SNAPSHOT_VERIFY', None) + env['STRATA_STATE_HASH'] = '1' + env['STRATA_MTP_BATCH'] = '1' + a.output.mkdir(mode=0o700, parents=False, exist_ok=False) + results = {'config': cfg, 'paragraphs': a.paragraphs, 'spec': a.spec, 'arms': [], 'requests': [], + 'compared_state_fields': STATE_KEYS, + 'environment': {k: v for k, v in env.items() if k.startswith('STRATA_')}} + for index, exe in enumerate([a.upstream, *a.candidate]): + name = 'upstream' if index == 0 else f'candidate-{index}' + log = a.output / f'{name}.log' + print(f'START {name}: {exe}', flush=True) + started = time.monotonic() + engine = StrataEngine(str(exe.resolve()), args, cwd=cfg.get('cwd'), log=str(log), env=env) + arm = {'name': name, 'exe': str(exe.resolve()), 'args': args, 'info': dict(engine.info), + 'startup_seconds': time.monotonic() - started, 'records': []} + with exe.open('rb') as source: + arm['exe_sha256'] = hashlib.file_digest(source, 'sha256').hexdigest() + def generate(request): + ids = [t for t in engine.generate(request['ids'], request['max_new'], {'temperature': 0}, + threading.Event()) if t is not None] + arm['records'].append({'name': request['name'], 'ids': ids, **engine.last, + 'text': tok.decode(ids)}) + return ids + try: + if index == 0: + def add(name, ids, max_new, expected=None): + request = dict(name=name, ids=ids, max_new=max_new, expected=expected) + results['requests'].append(request) + return generate(request) + add('short', prompt('What is 2 + 2? Reply with only the number.'), 16, '4') + head = add('A', A, 1) + require(len(head) == 1, 'A must produce one token') + continuation = A + head + suffix + add('A-live', continuation, 32, 'AZURE-314159') + add('A-checkpoint', continuation, 32, 'AZURE-314159') + add('B', B, 1) + add('A-return', continuation, 32, 'AZURE-314159') + add('B-return', B, 1) + add('A-return-again', continuation, 32, 'AZURE-314159') + payload = json.dumps(results['requests'], sort_keys=True).encode() + results['request_digest'] = hashlib.sha256(payload).hexdigest() + (a.output / 'requests.json').write_bytes(payload) + else: + for request in results['requests']: + generate(request) + finally: + engine.close() + engine.proc.wait(timeout=30) + engine.log.close() + arm['request_digest'] = hashlib.sha256(json.dumps(results['requests'], sort_keys=True).encode()).hexdigest() + log_text = log.read_text() + hashes = state_hashes(log_text, candidate=index != 0) + require(len(hashes) == len(arm['records']), f'{name}: missing state hashes') + for record, fingerprint in zip(arm['records'], hashes): + record['state'] = fingerprint + arm['cache_events'] = [line for line in log_text.splitlines() if any(mark in line for mark in + ('conversation cache: parked', 'disk cache: spilled', 'SNAPSHOT_VERIFY'))] + results['arms'].append(arm) + (a.output / 'results.json').write_text(json.dumps(results, indent=2) + '\n') + print(f'DONE {name}', flush=True) + verify(results) + (a.output / 'passed.json').write_text(json.dumps({'passed': True, 'request_digest': results['request_digest']}) + '\n') + print('PASS: untouched upstream versus disabled engines; identical tokens, main state, reuse and known answers') + + +if __name__ == '__main__': + main() diff --git a/tools/test_conversation_cache_disabled.py b/tools/test_conversation_cache_disabled.py new file mode 100644 index 00000000..3eec19b2 --- /dev/null +++ b/tools/test_conversation_cache_disabled.py @@ -0,0 +1,102 @@ +"""The upstream comparison must reject mismatches and incomplete evidence.""" +import copy +import hashlib +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +from tools.conversation_cache_disabled import NAMES, SETTINGS, STATE_KEYS, common_args, state_hashes, verify + + +def fixture(): + requests = [dict(name=n, ids=[1, 2], max_new=16, expected='4' if n == 'short' else None) for n in NAMES] + digest = hashlib.sha256(json.dumps(requests, sort_keys=True).encode()).hexdigest() + baseline = dict(name='upstream', args=['--kv', 'int8'], info={key: 1 for key in SETTINGS}, + request_digest=digest, cache_events=[], records=[]) + for name in NAMES: + baseline['records'].append(dict(name=name, ids=[4], text='4', finish='stop', prompt_tokens=2, + reused=2 if name in ('A-live', 'A-checkpoint') else 0, + state={key: 'abc' for key in STATE_KEYS})) + candidate = copy.deepcopy(baseline) + candidate['name'] = 'candidate-1' + candidate['info']['conversation_cache_mib'] = 0 + candidate['info']['conversation_disk_mib'] = 0 + return dict(arms=[baseline, candidate], requests=requests, request_digest=digest) + + +class DisabledCacheGateTest(unittest.TestCase): + def test_reference_fixture(self): + verify(fixture()) + + def test_upstream_hash_schema(self): + line = 'strata serve: STATE_HASH L=2 gdn=ab ple=cd tail=ef pooled=12 kv=34 mtp=56 stale=78 ple_prev=1,2' + self.assertEqual(set(state_hashes(line)[0]), set(STATE_KEYS)) + self.assertEqual(state_hashes(line), state_hashes(line + ' dead=99')) + self.assertEqual(state_hashes(line), state_hashes(line.replace('pooled=12', 'pooled=ff') + + ' pooled_complete=12', candidate=True)) + with self.assertRaises(AssertionError): + state_hashes(line, candidate=True) + with self.assertRaises(AssertionError): + state_hashes(line.replace('kv=34 ', '')) + + def test_rejects_bad_evidence(self): + mutations = [ + lambda r: r['arms'].pop(), + lambda r: r['requests'].pop(), + lambda r: r['requests'][0]['ids'].append(3), + lambda r: r['arms'][1]['args'].append('--different'), + lambda r: r['arms'][1].update(request_digest='different'), + lambda r: r['arms'][1]['records'].pop(), + lambda r: r['arms'][1]['info'].update(expert_slots=2), + lambda r: r['arms'][1]['info'].pop('kv'), + lambda r: r['arms'][1]['info'].update(conversation_cache_mib=8192), + lambda r: r['arms'][1]['info'].pop('conversation_cache_mib'), + lambda r: r['arms'][1]['info'].update(conversation_disk_mib=16384), + lambda r: r['arms'][1]['cache_events'].append('disk cache: spilled'), + lambda r: r['arms'][1]['records'][0].update(ids=[]), + lambda r: r['arms'][1]['records'][0].update(ids=[5]), + lambda r: r['arms'][1]['records'][0].update(finish='disconnect'), + lambda r: r['arms'][1]['records'][0].update(prompt_tokens=1), + lambda r: r['arms'][1]['records'][0]['state'].pop('gdn'), + lambda r: r['arms'][1]['records'][0]['state'].update(kv='bad'), + lambda r: r['arms'][1]['records'][0].update(reused=1), + lambda r: [a['records'][0].update(text='5') for a in r['arms']], + lambda r: [a['records'][2].update(reused=0) for a in r['arms']], + lambda r: [a['records'][5].update(reused=2) for a in r['arms']], + ] + for mutation in mutations: + with self.subTest(mutation=mutations.index(mutation)): + result = fixture() + mutation(result) + with self.assertRaises(AssertionError): + verify(result) + + def test_optimized_python_still_rejects(self): + code = ('from tools.test_conversation_cache_disabled import fixture, verify; ' + 'r=fixture(); r["arms"][1]["records"][0]["ids"]=[5]; verify(r)') + p = subprocess.run([sys.executable, '-O', '-c', code], capture_output=True, text=True) + self.assertNotEqual(p.returncode, 0) + self.assertIn('output differs', p.stderr) + + def test_cache_options_omitted_from_shared_arguments(self): + cfg = {'args': ['--pack', '/model', '--conversation-cache-mib', '8192', + '--conversation-cache-disk', '/cache', '--kv', 'int8']} + args = common_args(cfg, 4) + self.assertEqual(args[:4], ['--pack', '/model', '--kv', 'int8']) + self.assertFalse(any(x.startswith('--conversation-cache-') for x in args)) + + def test_dry_run_does_not_load_or_create_output(self): + with tempfile.TemporaryDirectory() as tmp: + out = Path(tmp) / 'absent' + p = subprocess.run([sys.executable, 'tools/conversation_cache_disabled.py', '--config', '/absent', + '--upstream', '/absent', '--candidate', '/absent', '--output', str(out)], + capture_output=True, text=True) + self.assertEqual(p.returncode, 0, p.stderr) + self.assertFalse(out.exists()) + + +if __name__ == '__main__': + unittest.main() From 7f7f88688685d57e088fdd1f994ad3097d051ee4 Mon Sep 17 00:00:00 2001 From: Jeremiah Ritchey <44681828+jeremiahritchey@users.noreply.github.com> Date: Wed, 30 Sep 2026 04:38:41 +0000 Subject: [PATCH 18/22] Retain unchanged KV storage across repeated conversation parking Grow snapshot buffers in segments, track the first rewritten token, and charge retained active storage to the existing RAM budget. Refresh running state, partial pages and draft boundary state. Add full-capture versus incremental growth/rewind checks and report snapshot sizes with usable pressure-test budget ranges. --- docs/DETAILS.md | 11 +- include/strata/core/conversation_buffer.hpp | 132 ++++++++++++++ include/strata/core/conversation_cache.hpp | 34 +++- include/strata/core/conversation_snapshot.hpp | 11 +- src/core/conversation_cache_test.cpp | 45 +++++ src/core/conversation_snapshot.cpp | 68 +++++-- src/core/conversation_snapshot_test.cpp | 41 ++++- src/core/conversation_state.cpp | 40 ++++- src/core/conversation_validation_test.cpp | 30 ++++ src/program/generate.cpp | 29 ++- tools/conversation_cache_growth.py | 168 ++++++++++++++++++ tools/conversation_cache_parity.py | 33 +++- tools/test_conversation_cache_growth.py | 77 ++++++++ tools/test_conversation_cache_parity.py | 18 +- 14 files changed, 698 insertions(+), 39 deletions(-) create mode 100644 include/strata/core/conversation_buffer.hpp create mode 100644 tools/conversation_cache_growth.py create mode 100644 tools/test_conversation_cache_growth.py diff --git a/docs/DETAILS.md b/docs/DETAILS.md index b21652cf..45bc63aa 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -386,7 +386,12 @@ reported separately from Linux/CUDA evidence. Snapshots contain running state, checkpoints, used K/V pages, and draft-layer K/V. They add host RAM, not another model or VRAM allocation. The byte budget also counts -an incoming snapshot during a switch; oldest parked entries are evicted first. +an incoming snapshot during a switch. After a restore, unchanged K/V pages can be +retained for the next parking operation; growth appends storage without copying +the existing pages. Rewinds refresh the affected pages, and running state and +checkpoints are captured again. Retained active K/V counts against the same byte +budget and is discarded before evicting parked entries under memory pressure. +Oldest parked entries are evicted first. Oversized snapshots or host allocation failures fall back to ordinary prompt processing. `--conversation-cache-min-free-mib N` (default 2560) additionally requires that physical-RAM headroom remain available: the engine checks before allocation and @@ -399,7 +404,9 @@ The shared snapshot core validates all layers and checkpoints before applying an state. Invalid entries are discarded; transfer/synchronization failure is fatal rather than permission to continue with partial state. Indexer spare keys and the moving spare row are preserved, including checkpoint rewinds. -The engine log reports parking, restoration, bytes and evictions. Snapshots are not +The engine log reports parking, restoration, bytes, evictions, individual snapshot +sizes and K/V bytes reused during capture. `STRATA_SNAPSHOT_FULL_CAPTURE=1` disables +retention for diagnostic comparisons. Snapshots are not persisted across restarts. **Current limits (v1):** one request at a time, and one conversation cached at a time (switching between two chats diff --git a/include/strata/core/conversation_buffer.hpp b/include/strata/core/conversation_buffer.hpp new file mode 100644 index 00000000..a58a38bf --- /dev/null +++ b/include/strata/core/conversation_buffer.hpp @@ -0,0 +1,132 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace strata::core { + +// Snapshot-owned host storage. Appending never relocates existing payloads; +// only the small segment directory can move. No sharing or copy-on-write is +// needed because a parked image and its retained active buffers have one owner. +class ConversationBuffer { +public: + static constexpr size_t segment_bytes = 16 * 1024 * 1024; + ConversationBuffer() = default; + ConversationBuffer(std::initializer_list values) { + resize(values.size()); + visit(0, size(), [&](uint8_t* p, size_t n, size_t at) { + std::memcpy(p, values.begin() + at, n); + return true; + }); + } + ConversationBuffer(const ConversationBuffer&) = default; + ConversationBuffer& operator=(const ConversationBuffer&) = default; + ConversationBuffer(ConversationBuffer&& other) noexcept + : segments_(std::move(other.segments_)), size_(std::exchange(other.size_, 0)) {} + ConversationBuffer& operator=(ConversationBuffer&& other) noexcept { + if (this == &other) return *this; + segments_ = std::move(other.segments_); + size_ = std::exchange(other.size_, 0); + return *this; + } + + size_t size() const { return size_; } + bool empty() const { return size_ == 0; } + size_t bytes() const { + size_t n = segments_.capacity() * sizeof(Segment); + for (const auto& segment : segments_) n += segment.capacity(); + return n; + } + // Includes the old directory while reserve allocates its replacement. + // Saturation makes an overflowing estimate fail admission before resize. + size_t allocation_peak(size_t n) const { + size_t total = bytes(); + if (n <= size_) return total; + const size_t extra = n - size_; + if (!add(total, extra)) return SIZE_MAX; + size_t count = segments_.size(); + if (!add(count, extra / segment_bytes + (extra % segment_bytes != 0))) return SIZE_MAX; + if (count > segments_.capacity() && + (count > SIZE_MAX / sizeof(Segment) || !add(total, count * sizeof(Segment)))) return SIZE_MAX; + return total; + } + void resize(size_t n, uint8_t value = 0) { + if (n > size_) { + const size_t extra = n - size_; + segments_.reserve(segments_.size() + extra / segment_bytes + (extra % segment_bytes != 0)); + while (size_ < n) { + const size_t count = std::min(segment_bytes, n - size_); + segments_.emplace_back(count, value); + size_ += count; + } + } else { + while (!segments_.empty() && size_ - segments_.back().size() >= n) { + size_ -= segments_.back().size(); + segments_.pop_back(); + } + if (size_ > n) segments_.back().resize(segments_.back().size() - (size_ - n)); + size_ = n; + } + } + void pop_back() { resize(size_ - 1); } + + // fn(pointer, count, absolute_offset); false aborts a transfer immediately. + template bool visit(size_t offset, size_t count, Fn fn) { + return visit_impl(*this, offset, count, fn); + } + template bool visit(size_t offset, size_t count, Fn fn) const { + return visit_impl(*this, offset, count, fn); + } + bool read(void* target, size_t offset, size_t count) const { + return visit(offset, count, [&](const uint8_t* p, size_t n, size_t at) { + std::memcpy(static_cast(target) + at - offset, p, n); + return true; + }); + } + bool operator==(const ConversationBuffer& other) const { + if (size_ != other.size_) return false; + size_t a = 0, b = 0, x = 0, y = 0; + while (a < segments_.size() && b < other.segments_.size()) { + const auto& left = segments_[a]; + const auto& right = other.segments_[b]; + const size_t n = std::min(left.size() - x, right.size() - y); + if (std::memcmp(left.data() + x, right.data() + y, n)) return false; + x += n; y += n; + if (x == left.size()) { ++a; x = 0; } + if (y == right.size()) { ++b; y = 0; } + } + return true; + } + +private: + using Segment = std::vector; + static bool add(size_t& n, size_t extra) { + if (extra > SIZE_MAX - n) return false; + n += extra; + return true; + } + template static bool visit_impl(Self& self, size_t offset, size_t count, Fn fn) { + if (offset > self.size_ || count > self.size_ - offset) return false; + size_t begin = 0; + for (auto& segment : self.segments_) { + if (!count) break; + const size_t end = begin + segment.size(); + if (offset < end) { + const size_t n = std::min(count, end - offset); + if (!fn(segment.data() + offset - begin, n, offset)) return false; + offset += n; count -= n; + } + begin = end; + } + return count == 0; + } + std::vector segments_; + size_t size_ = 0; +}; + +} // namespace strata::core diff --git a/include/strata/core/conversation_cache.hpp b/include/strata/core/conversation_cache.hpp index 42409d3d..c1506c91 100644 --- a/include/strata/core/conversation_cache.hpp +++ b/include/strata/core/conversation_cache.hpp @@ -2,6 +2,8 @@ // Token equality, image identity, and steering mode are all required for reuse. #pragma once +#include "strata/core/conversation_buffer.hpp" + #include #include #include @@ -41,9 +43,19 @@ struct ConversationCheckpoint { struct ConversationKv { int format = 0; int64_t cells = 0, heads = 0, head_dim = 0, page_size = 0, pooled_rows = 0, idx_dim = 0; - std::vector k, v, k_scale, v_scale, pooled; + ConversationBuffer k, v, k_scale, v_scale, pooled; size_t bytes() const { - return k.capacity() + v.capacity() + k_scale.capacity() + v_scale.capacity() + pooled.capacity(); + return k.bytes() + v.bytes() + k_scale.bytes() + v_scale.bytes() + pooled.bytes(); + } +}; + +struct ConversationKvReuse { + std::vector kv; + int64_t captured_tokens = 0, unchanged_tokens = 0; + size_t bytes() const { + size_t n = kv.capacity() * sizeof(ConversationKv); + for (const auto& layer : kv) n += layer.bytes(); + return n; } }; @@ -89,10 +101,24 @@ public: ConversationCache(size_t budget, size_t slots) : budget_(budget), slots_(slots) {} bool enabled() const { return budget_ != 0 && slots_ != 0; } - size_t bytes() const { return bytes_; } + size_t bytes() const { return bytes_ + reuse_.bytes(); } size_t size() const { return entries_.size(); } size_t evictions() const { return evictions_; } + // Retain only the restored K/V buffers, not duplicate running checkpoints. + // This optimization never evicts a parked conversation to make itself fit. + void retain(std::vector&& kv, int64_t tokens) { + reuse_ = {}; + ConversationKvReuse candidate{std::move(kv), tokens, tokens}; + if (enabled() && candidate.bytes() <= budget_ - bytes_) reuse_ = std::move(candidate); + } + void limit_reuse(int64_t first_dirty) { + reuse_.unchanged_tokens = std::min(reuse_.unchanged_tokens, first_dirty); + if (reuse_.unchanged_tokens <= 0) reuse_ = {}; + } + ConversationKvReuse take_reuse() { return std::exchange(reuse_, {}); } + size_t retained_bytes() const { return reuse_.bytes(); } + template Match best(const std::vector& prompt, const std::vector& images, bool cvec) const { Match best; @@ -122,6 +148,7 @@ public: // with take() but still alive during the exchange; count it against RAM too. bool make_room(size_t incoming, size_t held = 0) { if (!enabled() || held > budget_ || incoming > budget_ - held) return false; + if (bytes() > budget_ - held - incoming) reuse_ = {}; while (!entries_.empty() && (entries_.size() >= slots_ || bytes_ > budget_ - held - incoming)) { bytes_ -= entries_.front().bytes(); entries_.pop_front(); @@ -141,6 +168,7 @@ public: private: size_t budget_ = 0, slots_ = 0, bytes_ = 0, evictions_ = 0; std::deque entries_; // least recently active first + ConversationKvReuse reuse_; }; } // namespace strata::core diff --git a/include/strata/core/conversation_snapshot.hpp b/include/strata/core/conversation_snapshot.hpp index 550e373a..d75a017b 100644 --- a/include/strata/core/conversation_snapshot.hpp +++ b/include/strata/core/conversation_snapshot.hpp @@ -12,7 +12,10 @@ namespace strata::core { // include_index is false for the draft layer (its attention has no indexer). size_t conversation_kv_bytes(const QsaState& state, const ModelGeometry& g, int64_t upto, bool include_index); bool conversation_kv_save(ConversationKv& image, const QsaState& state, const ModelGeometry& g, - int64_t upto, bool include_index, std::string& error); + int64_t upto, bool include_index, std::string& error, + int64_t unchanged_tokens = 0, size_t* reused_bytes = nullptr); +bool conversation_kv_capture_bytes(const ConversationKv& image, const QsaState& state, const ModelGeometry& g, + int64_t upto, bool include_index, size_t& bytes, std::string& error); // No CUDA calls or destination writes. Used for whole-session prevalidation. bool conversation_kv_validate(const ConversationKv& image, const QsaState& state, const ModelGeometry& g, int64_t upto, bool include_index, std::string& error); @@ -43,11 +46,15 @@ struct ConversationView { }; bool conversation_snapshot_bytes(const ConversationView& view, const SessionState& session, const ModelGeometry& g, const QsaState& draft, size_t& bytes, std::string& error); +bool conversation_snapshot_capture_bytes(const ConversationKvReuse& reuse, const ConversationView& view, + const SessionState& session, const ModelGeometry& g, + const QsaState& draft, size_t& bytes, std::string& error); // Caller admits the estimate before invoking capture. Allocation failures propagate // to the RAM policy; the active session is never modified by capture. bool conversation_snapshot_save(SavedConversation& image, const ConversationView& view, const SessionState& session, const ModelGeometry& g, - const QsaState& draft, std::string& error); + const QsaState& draft, std::string& error, + ConversationKvReuse reuse = {}, size_t* reused_bytes = nullptr); bool conversation_snapshot_validate(const SavedConversation& image, const SessionState& session, const ModelGeometry& g, const QsaState& draft, std::string& error); enum class ConversationRestore { restored, invalid, transfer_failed }; diff --git a/src/core/conversation_cache_test.cpp b/src/core/conversation_cache_test.cpp index f6346d90..6b002005 100644 --- a/src/core/conversation_cache_test.cpp +++ b/src/core/conversation_cache_test.cpp @@ -21,6 +21,51 @@ SavedConversation image(std::initializer_list ids, bool cvec = true) { } int main() { + { + ConversationBuffer bytes; + const size_t first = ConversationBuffer::segment_bytes + 17; + const size_t peak = bytes.allocation_peak(first); + bytes.resize(first, 7); + check(bytes.bytes() <= peak, "segmented payload and directory fit admitted bytes"); + uint8_t* original = nullptr; + bytes.visit(0, 1, [&](uint8_t* p, size_t, size_t) { original = p; return true; }); + const size_t grown_peak = bytes.allocation_peak(first + 99); + bytes.resize(first + 99, 9); + bytes.visit(0, 1, [&](uint8_t* p, size_t, size_t) { + check(p == original, "appending preserves existing payload addresses"); return true; + }); + check(bytes.bytes() <= grown_peak, "growth including transient directory fits admission"); + std::vector tail(116); + check(bytes.read(tail.data(), ConversationBuffer::segment_bytes, tail.size()), "read spans segment boundaries"); + check(std::all_of(tail.begin(), tail.begin()+17, [](auto v){return v==7;}) && + std::all_of(tail.begin()+17, tail.end(), [](auto v){return v==9;}), "growth preserves prefix and initializes only suffix"); + auto copy = bytes; + bytes.resize(ConversationBuffer::segment_bytes + 10); + bytes.resize(first, 7); bytes.resize(first + 99, 9); + check(bytes == copy, "equality ignores differing segmentation after rewind and regrowth"); + check(!bytes.read(tail.data(), bytes.size()-1, 2), "range check rejects a truncated payload"); + check(bytes.allocation_peak(SIZE_MAX) == SIZE_MAX, "allocation estimate rejects overflow"); + } + { + ConversationKv layer; + layer.k.resize(400); + std::vector layers; + layers.push_back(std::move(layer)); + const size_t retained = layers.capacity()*sizeof(ConversationKv) + layers[0].bytes(); + const size_t parked = image({1,2,3}).bytes(); + ConversationCache cache(retained + parked, 4); + check(cache.put(image({1,2,3})), "park before retaining active storage"); + cache.retain(std::move(layers), 16); + check(cache.bytes() == retained + parked && cache.size() == 1, "active retained storage consumes bytes but no parked slot"); + cache.limit_reuse(9); cache.limit_reuse(12); + auto reuse = cache.take_reuse(); + check(reuse.unchanged_tokens == 9, "a later continuation cannot undo a rewind's dirty boundary"); + check(cache.bytes() == parked, "taking retained buffers releases their budget accounting"); + cache.retain(std::move(reuse.kv), 16); + check(cache.make_room(parked), "reservation can discard optional active buffers"); + check(cache.retained_bytes() == 0 && cache.size() == 1 && cache.evictions() == 0, + "pressure drops retained storage before evicting parked conversations"); + } const std::vector a = {1, 2, 3, 4}, b = {9, 8, 7, 6}; { ConversationCache cache(1024, 2); diff --git a/src/core/conversation_snapshot.cpp b/src/core/conversation_snapshot.cpp index 3e1254a5..f7bc0988 100644 --- a/src/core/conversation_snapshot.cpp +++ b/src/core/conversation_snapshot.cpp @@ -113,21 +113,40 @@ bool transfer(void* dst, const void* src, size_t n, std::string& error) { } } // namespace -size_t conversation_kv_bytes(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index) { - std::string error; +bool conversation_kv_capture_bytes(const ConversationKv& image, const QsaState& st, const ModelGeometry& g, + int64_t upto, bool index, size_t& bytes, std::string& error) { Layout l{}; - if (!layout(st, g, upto, index, l, error) || !valid(st, l, upto, error)) return 0; - size_t bytes = l.pooled; - for (size_t n : {l.data, l.value_data, l.scales, l.value_scales}) - if (!conversation_detail::add(bytes, n)) return 0; - return bytes; + if (!layout(st, g, upto, index, l, error) || !valid(st, l, upto, error)) return false; + const std::array sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled}; + const std::array buffers = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; + bytes = 0; + for (size_t i = 0; i < buffers.size(); ++i) { + const size_t n = buffers[i]->allocation_peak(sizes[i]); + if (n == SIZE_MAX || !conversation_detail::add(bytes, n)) { + error = "conversation snapshot: segmented K/V allocation overflow"; + return false; + } + } + return true; +} + +size_t conversation_kv_bytes(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index) { + size_t bytes = 0; + std::string error; + return conversation_kv_capture_bytes({}, st, g, upto, index, bytes, error) ? bytes : 0; } bool conversation_kv_save(ConversationKv& image, const QsaState& st, const ModelGeometry& g, - int64_t upto, bool index, std::string& error) { + int64_t upto, bool index, std::string& error, + int64_t unchanged_tokens, size_t* reused_bytes) { Layout l{}; if (!layout(st, g, upto, index, l, error)) return false; if (!valid(st, l, upto, error)) return false; + if (unchanged_tokens < 0 || unchanged_tokens > upto || unchanged_tokens > image.cells) { + error = "conversation snapshot: invalid unchanged prefix"; + return false; + } + const int64_t whole_cells = (unchanged_tokens / l.page_size) * l.page_size; image.format = l.format; image.cells = l.cells; image.heads = g.n_head_kv; @@ -137,10 +156,18 @@ bool conversation_kv_save(ConversationKv& image, const QsaState& st, const Model image.idx_dim = g.idx_key_dim; const auto src = pools(st); const std::array sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled}; - const std::array*,5> dst = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; + const std::array dst = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; for (size_t i = 0; i < dst.size(); ++i) { + // Recopy the partial page and the indexer's moving spare row. Completed + // pages/rows strictly before the first rewritten token remain identical. + const size_t keep = i == 4 ? (index ? size_t(unchanged_tokens / strata::kernels::qsa_real_shapes().idx_block) * g.idx_key_dim * 4 : 0) + : l.cells ? (sizes[i] / size_t(l.cells)) * size_t(whole_cells) : 0; + if (keep > dst[i]->size()) { error = "conversation snapshot: missing reusable prefix"; return false; } dst[i]->resize(sizes[i]); - if (!transfer(dst[i]->data(), src[i], sizes[i], error)) return false; + if (!dst[i]->visit(keep, sizes[i] - keep, [&](uint8_t* p, size_t n, size_t at) { + return transfer(p, src[i] ? static_cast(src[i]) + at : nullptr, n, error); + })) return false; + if (reused_bytes) *reused_bytes += keep; } return true; } @@ -151,7 +178,7 @@ bool conversation_kv_validate(const ConversationKv& image, const QsaState& st, c if (!layout(st, g, upto, index, l, error)) return false; if (!valid(st, l, upto, error)) return false; const std::array sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled}; - const std::array*,5> src = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; + const std::array src = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; if (image.format != l.format || image.cells != l.cells || image.heads != g.n_head_kv || image.head_dim != g.head_dim || image.page_size != l.page_size || image.pooled_rows != l.pooled_rows || image.idx_dim != g.idx_key_dim) { @@ -169,10 +196,12 @@ bool conversation_kv_validate(const ConversationKv& image, const QsaState& st, c bool conversation_kv_restore(const ConversationKv& image, const QsaState& st, const ModelGeometry& g, int64_t upto, bool index, std::string& error) { if (!conversation_kv_validate(image, st, g, upto, index, error)) return false; - const std::array*,5> src = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; + const std::array src = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; const auto dst = pools(st); for (size_t i = 0; i < src.size(); ++i) - if (!transfer(dst[i], src[i]->data(), src[i]->size(), error)) return false; + if (!src[i]->visit(0, src[i]->size(), [&](const uint8_t* p, size_t n, size_t at) { + return transfer(static_cast(dst[i]) + at, p, n, error); + })) return false; // VRAM slots still contain the outgoing conversation. Resolve must refill // them from the restored authoritative pools before any attention reads. if (st.kv_mode == 1) strata::kernels::kv_stream_reset(st.map, nullptr); @@ -207,10 +236,12 @@ bool conversation_kv_verify(const ConversationKv& image, const QsaState& st, con } return true; }; - const std::array*, 5> saved = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; + const std::array saved = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; const auto authoritative = pools(st); for (size_t i = 0; i < saved.size(); ++i) - if (!compare(authoritative[i], saved[i]->data(), saved[i]->size(), true)) return false; + if (!saved[i]->visit(0, saved[i]->size(), [&](const uint8_t* p, size_t n, size_t at) { + return compare(static_cast(authoritative[i]) + at, p, n, true); + })) return false; if (st.kv_mode == 2 && image.cells > 0) { const auto resident = pools(st, true); const int64_t end = image.cells / image.page_size; @@ -219,8 +250,11 @@ bool conversation_kv_verify(const ConversationKv& image, const QsaState& st, con if (saved[i]->empty()) continue; const size_t page_bytes = saved[i]->size() / size_t(end); for (int64_t page = begin; page < end; ++page) - if (!compare(static_cast(resident[i]) + size_t(page % st.n_slots) * page_bytes, - saved[i]->data() + size_t(page) * page_bytes, page_bytes, false)) return false; + if (!saved[i]->visit(size_t(page) * page_bytes, page_bytes, + [&](const uint8_t* p, size_t n, size_t at) { + const size_t offset = size_t(page % st.n_slots) * page_bytes + at - size_t(page) * page_bytes; + return compare(static_cast(resident[i]) + offset, p, n, false); + })) return false; } } fingerprint = hash; diff --git a/src/core/conversation_snapshot_test.cpp b/src/core/conversation_snapshot_test.cpp index 515a6408..f298978d 100644 --- a/src/core/conversation_snapshot_test.cpp +++ b/src/core/conversation_snapshot_test.cpp @@ -90,6 +90,14 @@ struct Fixture { if (!data.empty()) cuda_check(cudaMemcpy(sources[i],data.data(),data.size(),cudaMemcpyDefault)); } } + void fill_after(uint8_t salt, int64_t first_dirty) { + for (size_t i=0;i offset) + cuda_check(cudaMemset(static_cast(sources[i])+offset, salt, sizes[i]-offset)); + } + } ~Fixture() { for (void* p:device) cudaFree(p); for (void* p:host) cudaFreeHost(p); } }; bool equal(const ConversationKv& a,const ConversationKv& b) { @@ -149,6 +157,35 @@ void full_session(int fmt, int mode, int experts) { restored.live.dead==a.live.dead && restored.live.block_pos==a.live.block_pos && equal(restored.kv[0],a.kv[0]) && equal(restored.kv[1],a.kv[1]),"whole-session A/B/A exactness including spare key"); check(ss.ple_prev[0]==64 && ss.ple_prev[1]==65,"PLE token window reconstructed"); + for (int64_t dirty : {65, 3, 0}) { + check(conversation_snapshot_restore(a,ss,g,draft.state,err)==ConversationRestore::restored,"restore growth fixture base"); + ConversationKvReuse reuse{a.kv,65,dirty}; + const uint8_t* original = nullptr; + reuse.kv[0].k.visit(0,1,[&](const uint8_t* p,size_t,size_t){original=p;return true;}); + main.fill_after(91,dirty); draft.fill_after(91,std::max(0,dirty-1)); + cuda_check(cudaMemset(ss.gdn_state,91,sizes.gdn)); + ids.resize(70); + for (size_t i=65;i=4)==(reused>0),"only complete unchanged pages or rows are retained"); + incremental.kv[0].k.visit(0,1,[&](const uint8_t* p,size_t,size_t){ + check(p==original,"growth never reallocates the retained payload");return true; + }); + check(conversation_snapshot_restore(incremental,ss,g,draft.state,err)==ConversationRestore::restored,"restore segmented incremental snapshot"); + uint64_t fingerprint=0; + check(conversation_kv_verify(incremental.kv.back(),draft.state,g,70,false,fingerprint,err),"incremental draft authoritative and ring read-back"); + ids.resize(65); + } check(conversation_checkpoint_restore(a.checkpoints[0],ss,g,err),"restore early running checkpoint"); std::vector spare(sizes.dead); cuda_check(cudaMemcpy(spare.data(),main.state.idx_pooled,sizes.dead,cudaMemcpyDeviceToHost)); @@ -214,7 +251,9 @@ int main() { std::vector got(code_block); for (int64_t page=b0;page expected(code_block); + check(a.k.read(expected.data(), page*code_block, code_block),"read segmented expected draft page"); + check(got == expected,"draft ring contains restored pages"); } } auto bad=a; bad.head_dim++; diff --git a/src/core/conversation_state.cpp b/src/core/conversation_state.cpp index 4841d8ed..b819acca 100644 --- a/src/core/conversation_state.cpp +++ b/src/core/conversation_state.cpp @@ -202,22 +202,54 @@ bool conversation_snapshot_bytes(const ConversationView& view, const SessionStat return true; } +bool conversation_snapshot_capture_bytes(const ConversationKvReuse& reuse, const ConversationView& view, + const SessionState& ss, const ModelGeometry& g, + const QsaState& draft, size_t& bytes, std::string& error) { + if (!conversation_snapshot_bytes(view, ss, g, draft, bytes, error)) return false; + if (reuse.kv.empty()) return true; + const size_t layers = size_t(g.n_qsa_layers()) + 1; + if (reuse.kv.size() != layers || reuse.unchanged_tokens < 0 || + reuse.unchanged_tokens > reuse.captured_tokens || reuse.unchanged_tokens > int64_t(view.ids.size())) + return fail(error, "invalid retained K/V prefix"); + for (size_t i = 0; i < layers; ++i) { + const bool index = i + 1 != layers; + const auto& st = index ? ss.qsa_states[i] : draft; + if (!conversation_kv_validate(reuse.kv[i], st, g, reuse.captured_tokens, index, error)) return false; + const size_t fresh = conversation_kv_bytes(st, g, int64_t(view.ids.size()), index); + size_t retained = 0; + if (!conversation_kv_capture_bytes(reuse.kv[i], st, g, int64_t(view.ids.size()), index, retained, error)) return false; + bytes -= fresh; + if (!add(bytes, retained)) return fail(error, "retained K/V allocation overflow"); + } + size_t directory = 0; + if (!product(directory, {reuse.kv.capacity() - layers, sizeof(ConversationKv)}) || !add(bytes, directory)) + return fail(error, "retained K/V directory overflow"); + return true; +} + bool conversation_snapshot_save(SavedConversation& image, const ConversationView& view, const SessionState& ss, const ModelGeometry& g, - const QsaState& draft, std::string& error) { + const QsaState& draft, std::string& error, + ConversationKvReuse reuse, size_t* reused_bytes) { size_t estimate = 0; - if (!conversation_snapshot_bytes(view, ss, g, draft, estimate, error) || !sync(error)) return false; + if (!conversation_snapshot_capture_bytes(reuse, view, ss, g, draft, estimate, error) || !sync(error)) return false; // Build into a new object so a failure cannot publish a partial snapshot. SavedConversation captured; captured.geometry = geometry_key(g); captured.live.ids = view.ids; captured.live.imgs = view.images; captured.cvec = view.cvec; captured.checkpoints = view.checkpoints; + const int64_t unchanged = reuse.kv.empty() ? 0 : reuse.unchanged_tokens; + captured.kv = std::move(reuse.kv); captured.kv.resize((size_t) g.n_qsa_layers() + 1); if (!conversation_checkpoint_save(captured.live, ss, g, error)) return false; const int64_t upto = (int64_t) view.ids.size(); for (int64_t i = 0; i < g.n_qsa_layers(); ++i) - if (!conversation_kv_save(captured.kv[(size_t) i], ss.qsa_states[i], g, upto, true, error)) return false; - if (!conversation_kv_save(captured.kv.back(), draft, g, upto, false, error)) return false; + if (!conversation_kv_save(captured.kv[(size_t) i], ss.qsa_states[i], g, upto, true, error, + unchanged, reused_bytes)) return false; + // The draft's final cell may not have been computed when the output cap was + // reached. Refresh that page even when the main prefix continued unchanged. + if (!conversation_kv_save(captured.kv.back(), draft, g, upto, false, error, + std::max(0, unchanged - 1), reused_bytes)) return false; image = std::move(captured); return true; } diff --git a/src/core/conversation_validation_test.cpp b/src/core/conversation_validation_test.cpp index 3676b93d..5e4bb83e 100644 --- a/src/core/conversation_validation_test.cpp +++ b/src/core/conversation_validation_test.cpp @@ -15,9 +15,11 @@ // host-backend fault injection, not a claim of hardware-failure recovery. namespace { int copy_calls = 0, sync_calls = 0, fail_copy = 0, fail_sync = 0; +size_t copied_bytes = 0; } extern "C" cudaError_t __wrap_cudaMemcpy(void* dst, const void* src, size_t n, cudaMemcpyKind) { if (++copy_calls == fail_copy) return cudaErrorInvalidValue; + copied_bytes += n; std::memcpy(dst, src, n); return cudaSuccess; } @@ -178,6 +180,34 @@ void fixture(int format, int experts, bool zero_qsa, bool ple) { draft.data[0][0] ^= 1; fail_copy = copy_calls + 1; check(!conversation_kv_verify(image.kv.back(),draft.st,g,9,false,fingerprint,error), "read-back transfer failure is not a successful fingerprint"); + reset(); copied_bytes = 0; + const ConversationView view{image.live.ids,image.live.imgs,image.checkpoints,true}; + SavedConversation full,incremental; + check(conversation_snapshot_save(full,view,ss,g,draft.st,error), "full capture through host transfer backend"); + const size_t full_copies = copied_bytes; + ConversationKvReuse reuse{full.kv,9,9}; + size_t peak = 0, reused = 0; + check(conversation_snapshot_capture_bytes(reuse,view,ss,g,draft.st,peak,error), "incremental capture admission without transfers"); + copied_bytes = 0; + const bool saved_incrementally = conversation_snapshot_save(incremental,view,ss,g,draft.st,error,std::move(reuse),&reused); + if (!saved_incrementally) std::fprintf(stderr,"capture error: %s\n",error.c_str()); + check(saved_incrementally, "incremental capture through host backend"); + check(reused > 0 && copied_bytes + reused == full_copies, "reused byte count measures transfers actually omitted"); + check(incremental.bytes() <= peak && incremental.live.gdn == full.live.gdn, "running state refreshed within admitted allocation"); + for (size_t i=0;i bool { if (!conversations.enabled() || !live_ok || live.empty()) return true; const strata::core::ConversationView view{live, live_imgs, checks, cvec_cached}; + auto reuse = conversations.take_reuse(); size_t estimate = 0; if (!strata::core::conversation_snapshot_bytes(view, ss, g, mtp.kv_state(), estimate, err)) { std::fprintf(stderr, "strata serve: conversation cache: skip parking (%s)\n", err.c_str()); err.clear(); // A recoverable miss must not poison the batched draft prefill's error channel. return true; } + const size_t fresh_estimate = estimate; + if (!reuse.kv.empty() && !strata::core::conversation_snapshot_capture_bytes( + reuse, view, ss, g, mtp.kv_state(), estimate, err)) { + reuse = {}; + estimate = fresh_estimate; + err.clear(); + } + if (!conversations.make_room(estimate, held) && !reuse.kv.empty()) { + reuse = {}; // Optional retained storage must not prevent a full capture. + estimate = fresh_estimate; + } if (!conversations.make_room(estimate, held)) { std::fprintf(stderr, "strata serve: conversation cache: skip parking (snapshot %zu MiB exceeds available budget)\n", estimate >> 20); @@ -3278,22 +3290,26 @@ int main(int argc, char** argv) { const auto t0 = Clock::now(); try { const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib * 1024 * 1024; - if (!strata::core::conversation_memory_admit(strata::core::conversation_available_memory(), estimate, floor)) { + if (!strata::core::conversation_memory_admit(strata::core::conversation_available_memory(), + estimate - reuse.bytes(), floor)) { std::fprintf(stderr, "strata serve: conversation cache: skip parking (physical RAM admission; need %zu MiB plus %lld MiB floor, or telemetry unavailable)\n", estimate >> 20, (long long) o.conversation_cache_min_free_mib); return true; } strata::core::SavedConversation image; - if (!strata::core::conversation_snapshot_save(image, view, ss, g, mtp.kv_state(), err)) return false; + size_t reused_bytes = 0; + if (!strata::core::conversation_snapshot_save(image, view, ss, g, mtp.kv_state(), err, + std::move(reuse), &reused_bytes)) return false; if (!strata::core::conversation_memory_admit(strata::core::conversation_available_memory(), 0, floor)) { std::fprintf(stderr, "strata serve: conversation cache: skip parking (physical RAM floor after capture, or telemetry unavailable)\n"); return true; } + const size_t snapshot_bytes = image.bytes(); const bool stored = conversations.put(std::move(image), held); - std::fprintf(stderr, "strata serve: conversation cache: %s %zu tokens in %.1f ms; parked=%zu bytes=%zu evictions=%zu\n", + std::fprintf(stderr, "strata serve: conversation cache: %s %zu tokens in %.1f ms; parked=%zu bytes=%zu evictions=%zu snapshot_bytes=%zu reused_kv_bytes=%zu\n", stored ? "parked" : "skipped", live.size(), std::chrono::duration(Clock::now() - t0).count(), - conversations.size(), conversations.bytes(), conversations.evictions()); + conversations.size(), conversations.bytes(), conversations.evictions(), snapshot_bytes, reused_bytes); } catch (const std::bad_alloc&) { // The active state has not been touched. Continue with normal // prompt processing rather than killing a serving process. @@ -3885,7 +3901,9 @@ int main(int argc, char** argv) { cvec_cached = incoming->cvec; resume = parked.tokens; from_live = parked.live; - incoming.reset(); // release the transfer image before prompt processing + if (std::getenv("STRATA_SNAPSHOT_FULL_CAPTURE") == nullptr) + conversations.retain(std::move(incoming->kv), int64_t(live.size())); + incoming.reset(); // Running-state/checkpoint copies are no longer needed. std::fprintf(stderr, "strata serve: conversation cache: restored %lld tokens (%s) in %.1f ms; parked=%zu bytes=%zu\n", (long long) resume, from_live ? "live" : "checkpoint", std::chrono::duration(Clock::now() - t0).count(), @@ -3952,6 +3970,7 @@ int main(int argc, char** argv) { tr("request", n, geni ? 1 : 0); mtp.set_prompt_len(n); const int64_t read_from = reread_to > 0 ? 0 : resume; + conversations.limit_reuse(read_from); pp_total = n; pp_from = read_from; pp_t0 = r0; diff --git a/tools/conversation_cache_growth.py b/tools/conversation_cache_growth.py new file mode 100644 index 00000000..9a455d4a --- /dev/null +++ b/tools/conversation_cache_growth.py @@ -0,0 +1,168 @@ +"""Compare full and incremental snapshot capture during growth and rewind. + +Private engines run sequentially; dry-run is the default. Both arms enable the +same conversation cache. The reference forces full capture for every parking. +""" +import argparse +import hashlib +import json +from pathlib import Path +import re +import sys +import threading + +ROOT = Path(__file__).resolve().parents[1] +sys.path[:0] = [str(ROOT), str(ROOT / 'tools')] +from conversation_cache_parity import STATE_KEYS, load_tokenizer, require, state_hashes +from conversation_cache_disabled import SETTINGS, common_args +from conversation_cache_soak import answer_text +from serve.frontend import ChatTemplate +from serve.server import StrataEngine, child_env + +NAMES = ['A', 'B-0', 'A-grow-0', 'B-1', 'A-grow-1', 'B-2', 'A-grow-2', + 'B-rewind', 'A-rewind', 'B-branch', 'A-branch', 'B-final'] +SECRET = 'SAPPHIRE' + + +def verify(results): + full, incremental = results['arms'] + require(full['name'] == 'full' and incremental['name'] == 'incremental', 'incorrect comparison arms') + requests = results['requests'] + require([r['name'] for r in requests] == NAMES, 'incomplete growth/rewind requests') + digest = hashlib.sha256(json.dumps(requests, sort_keys=True).encode()).hexdigest() + require(digest == results['request_digest'], 'request evidence changed') + for arm in (full, incremental): + require(arm['request_digest'] == digest and arm['args'] == full['args'], 'inputs or arguments differ') + require([r['name'] for r in arm['records']] == NAMES, 'incomplete growth/rewind outputs') + for key in (*SETTINGS, 'conversation_cache_mib', 'conversation_cache_slots'): + require(key in arm['info'] and arm['info'][key] == full['info'][key], f'engine setting differs: {key}') + require(arm['info']['conversation_cache_mib'] > 0, 'cache is not enabled') + budget = arm['info']['conversation_cache_mib'] * 1024 * 1024 + require(arm['parks'] and all(0 < p['snapshot_bytes'] <= p['bytes'] <= budget and + 0 <= p['reused_kv_bytes'] <= p['snapshot_bytes'] for p in arm['parks']), 'invalid allocation/reuse evidence') + require(arm['draft_verifications'] >= 4, 'missing restored draft read-back') + for request, reference, record in zip(requests, full['records'], arm['records']): + require(record['ids'] and record['finish'] in ('stop', 'length'), 'incomplete generation') + require(record['ids'] == reference['ids'], f'{record["name"]}: output differs') + require(set(STATE_KEYS) <= record['state'].keys() and record['state'] == reference['state'], + f'{record["name"]}: state differs or is incomplete') + require(record['reused'] == reference['reused'], 'prefix reuse differs') + require(record['prompt_tokens'] == len(request['ids']), 'prompt length differs') + if record['name'].startswith('A-'): + require(answer_text(record['text']) == SECRET.casefold(), 'known answer differs') + require(record['reused'] > 0, 'conversation was not restored') + require(all(p['reused_kv_bytes'] == 0 for p in full['parks']), 'reference did not force full captures') + require(sum(p['reused_kv_bytes'] > 0 for p in incremental['parks']) >= 3, 'repeated parking did not reuse KV bytes') + sizes = {r['name']: len(r['ids']) for r in requests} + require(sizes['A'] < sizes['A-grow-0'] < sizes['A-grow-1'] < sizes['A-grow-2'], 'conversation did not grow') + require(sizes['A-rewind'] == sizes['A-grow-0'] < sizes['A-grow-2'], 'missing rewind') + require(sizes['A-branch'] > sizes['A-rewind'], 'missing growth after rewind') + + +def main(): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument('--config', type=Path, required=True) + ap.add_argument('--engine', type=Path, required=True) + ap.add_argument('--output', type=Path, required=True, help='new output directory') + ap.add_argument('--paragraphs', type=int, default=128) + ap.add_argument('--spec', type=int, choices=(1, 4), default=1) + ap.add_argument('--cache-mib', type=int, default=8192) + ap.add_argument('--run', action='store_true') + a = ap.parse_args() + if a.paragraphs < 1 or a.cache_mib < 1: + ap.error('paragraphs and cache-mib must be positive') + if not a.run: + print('Dry run: paired full/incremental captures; growth, interruption, rewind and branch; no model loaded.') + return + cfg = json.loads(a.config.read_text()) + tok_path = Path(cfg['tokenizer']) + tok = load_tokenizer(tok_path) + template = ChatTemplate(tok_path / 'chat_template.jinja') + def encode(text): + return tok.encode(text, parse_special=True) + def prompt(text): + return encode(template.render([{'role': 'user', 'content': text}], enable_thinking=False)) + text = f'Remember the secret code {SECRET}.\n' + text += '\n'.join(f'Record {i}: blue square, green triangle, red circle.' for i in range(a.paragraphs)) + initial = prompt(text + f'\nThe secret code is {SECRET}. Reply OK.') + other = prompt('Unrelated worker. Reply HELLO.') + end = encode('<|im_end|>') + def continuation(ids, output, step): + close = [] if output[-len(end):] == end else end + filler = '\n'.join(f'Additional record {step}-{i}: blue square and green triangle.' for i in range(24)) + return ids + output + close + encode('\n<|im_start|>user\n' + filler + + '\nWhat is the secret code? Reply with only that word.<|im_end|>\n' + '<|im_start|>assistant\n\n\n\n\n') + args = common_args(cfg, a.spec) + ['--conversation-cache-mib', str(a.cache_mib), '--conversation-cache-slots', '4'] + env = child_env(cfg) + env['STRATA_STATE_HASH'] = '1' + env['STRATA_SNAPSHOT_VERIFY'] = '1' + env['STRATA_MTP_BATCH'] = '1' + a.output.mkdir(mode=0o700, parents=False, exist_ok=False) + results = {'requests': [], 'arms': [], 'spec': a.spec, 'paragraphs': a.paragraphs} + for name in ('full', 'incremental'): + current_env = dict(env) + if name == 'full': + current_env['STRATA_SNAPSHOT_FULL_CAPTURE'] = '1' + else: + current_env.pop('STRATA_SNAPSHOT_FULL_CAPTURE', None) + print('START', name, flush=True) + log = a.output / (name + '.log') + engine = StrataEngine(str(a.engine.resolve()), args, cwd=cfg.get('cwd'), log=str(log), env=current_env) + arm = {'name': name, 'args': args, 'info': dict(engine.info), 'records': []} + with a.engine.open('rb') as source: + arm['exe_sha256'] = hashlib.file_digest(source, 'sha256').hexdigest() + def generate(request): + ids = [x for x in engine.generate(request['ids'], request['max_new'], {'temperature': 0}, + threading.Event()) if x is not None] + arm['records'].append({'name': request['name'], 'ids': ids, 'text': tok.decode(ids), **engine.last}) + return ids + try: + if name == 'full': + def add(label, ids, count, expected=False): + request = {'name': label, 'ids': ids, 'max_new': count, 'expected': expected} + results['requests'].append(request) + return generate(request) + ids = initial + output = add('A', ids, 1) + first_growth = None + for step in range(3): + add(f'B-{step}', other, 1) + ids = continuation(ids, output, step) + if step == 0: + first_growth = list(ids) + output = add(f'A-grow-{step}', ids, 16, True) + add('B-rewind', other, 1) + output = add('A-rewind', first_growth, 16, True) + add('B-branch', other, 1) + add('A-branch', continuation(first_growth, output, 'branch'), 16, True) + add('B-final', other, 1) + results['request_digest'] = hashlib.sha256(json.dumps(results['requests'], sort_keys=True).encode()).hexdigest() + else: + for request in results['requests']: + generate(request) + finally: + engine.close() + engine.proc.wait(timeout=30) + engine.log.close() + log_text = log.read_text() + hashes = state_hashes(log_text) + require(len(hashes) == len(arm['records']), 'missing state fingerprints') + for record, state in zip(arm['records'], hashes): + record['state'] = state + parks = re.findall(r'conversation cache: parked (\d+) tokens in ([\d.]+) ms; parked=\d+ bytes=(\d+) ' + r'evictions=\d+ snapshot_bytes=(\d+) reused_kv_bytes=(\d+)', log_text) + arm['parks'] = [dict(tokens=int(p[0]), ms=float(p[1]), bytes=int(p[2]), snapshot_bytes=int(p[3]), + reused_kv_bytes=int(p[4])) for p in parks] + arm['draft_verifications'] = log_text.count('SNAPSHOT_VERIFY draft=') + arm['request_digest'] = hashlib.sha256(json.dumps(results['requests'], sort_keys=True).encode()).hexdigest() + results['arms'].append(arm) + (a.output / 'results.json').write_text(json.dumps(results, indent=2) + '\n') + print('DONE', name, flush=True) + verify(results) + (a.output / 'passed.json').write_text(json.dumps({'passed': True, 'request_digest': results['request_digest']}) + '\n') + print('PASS: growth and rewind preserve output/state; repeated captures reuse unchanged KV bytes') + + +if __name__ == '__main__': + main() diff --git a/tools/conversation_cache_parity.py b/tools/conversation_cache_parity.py index 80c467d2..cea5fc59 100644 --- a/tools/conversation_cache_parity.py +++ b/tools/conversation_cache_parity.py @@ -49,6 +49,25 @@ def engine_args(cfg, budget, spec): '--mtp-max-t', str(spec), '--suffix-draft', '0', '--spec-min-p', '0'] +def pressure_budget_hint(results, budget_mib): + sizes = [p['snapshot_bytes'] for p in results['pressure']['parks'] if p.get('snapshot_bytes', 0) > 0] + message = f'Configured --cache-mib {budget_mib}.' + if not sizes: + return message + ' No snapshot sizes recorded; use an engine that reports snapshot_bytes.' + mib = 1024 * 1024 + message += ' Observed snapshots: ' + ', '.join(f'{n / mib:.2f} MiB ({n} bytes)' for n in sizes) + '.' + if len(sizes) < 2: + return message + ' Need at least two captured snapshots to determine a pressure budget.' + # Fit every individual image but no adjacent pair in the A/B/C sequence. + low = (max(sizes) + mib - 1) // mib + high = (min(a + b for a, b in zip(sizes, sizes[1:])) - 1) // mib + if low <= high: + message += f' Use --cache-mib {low}..{high} to fit each snapshot but not two adjacent snapshots.' + else: + message += ' No whole-MiB budget fits every snapshot while excluding each adjacent pair; use similarly sized prompts.' + return message + + def verify_pressure(results, budget_mib, oversized=False): """Require actual byte-pressure evidence, not just correct output on misses.""" baseline, candidate = results['baseline'], results['candidate'] @@ -59,7 +78,9 @@ def verify_pressure(results, budget_mib, oversized=False): require(len(before['ids']) == len(after['ids']) == 1, 'missing pressure output') require(before['finish'] in ('length', 'stop') and after['finish'] in ('length', 'stop'), 'pressure request did not finish normally') - require(before['reused'] == after['reused'] == 0, 'pressure did not force a cache miss') + require(before['reused'] == after['reused'] == 0, + 'pressure did not force a cache miss; this run did not exercise the required fallback. ' + + pressure_budget_hint(results, budget_mib)) require(before['ids'] == after['ids'], 'pressure output differs') keys = set(STATE_KEYS) require(keys <= before['state'].keys() and keys <= after['state'].keys(), 'missing pressure state') @@ -78,7 +99,8 @@ def verify_pressure(results, budget_mib, oversized=False): else: require(evidence['skips'] == 0 and len(parks) == 3, 'snapshots must fit individually') require(all(0 < p['parked'] < 4 for p in parks), 'slot pressure confounds byte-pressure test') - require(parks[-1]['evictions'] > 0, 'no byte-pressure eviction observed; reduce --cache-mib') + require(parks[-1]['evictions'] > 0, 'no byte-pressure eviction observed. ' + + pressure_budget_hint(results, budget_mib)) def verify_results(results, prompt_tokens, spec): @@ -202,12 +224,15 @@ def main(): results[label] = records if label == 'candidate' and a.scenario != 'reuse': log_text = log.read_text() - parks = re.findall(r'conversation cache: parked \d+ tokens .*?parked=(\d+) bytes=(\d+) evictions=(\d+)', log_text) + parks = re.findall(r'conversation cache: parked \d+ tokens .*?parked=(\d+) bytes=(\d+) evictions=(\d+)(?: snapshot_bytes=(\d+))?', log_text) results['pressure'] = { - 'parks': [dict(zip(('parked', 'bytes', 'evictions'), map(int, p))) for p in parks], + 'parks': [dict(zip(('parked', 'bytes', 'evictions', 'snapshot_bytes'), + (int(value) if value else 0 for value in p))) for p in parks], 'skips': log_text.count('conversation cache: skip parking (snapshot '), 'memory_skips': log_text.count('conversation cache: skip parking (physical RAM admission;')} (a.output / 'results.json').write_text(json.dumps(results, indent=2) + '\n') + if a.scenario == 'pressure': + print(pressure_budget_hint(results, a.cache_mib), flush=True) if a.scenario == 'admission': verify_admission(results, a.cache_mib, a.min_free_mib) print('PASS: physical-memory admission denial, output and byte-exact main-model state') diff --git a/tools/test_conversation_cache_growth.py b/tools/test_conversation_cache_growth.py new file mode 100644 index 00000000..73b3d336 --- /dev/null +++ b/tools/test_conversation_cache_growth.py @@ -0,0 +1,77 @@ +"""Negative controls for the incremental capture model gate.""" +import copy +import hashlib +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +from tools.conversation_cache_growth import NAMES, SECRET, SETTINGS, STATE_KEYS, verify + + +def fixture(): + lengths = [8, 2, 12, 2, 16, 2, 20, 2, 12, 2, 15, 2] + requests = [dict(name=name, ids=[1]*n, max_new=16, expected=name.startswith('A-')) + for name, n in zip(NAMES, lengths)] + digest = hashlib.sha256(json.dumps(requests, sort_keys=True).encode()).hexdigest() + full = dict(name='full', args=['--conversation-cache-mib','1'], request_digest=digest, + info={key: 1 for key in SETTINGS}, draft_verifications=4, + parks=[dict(bytes=100,snapshot_bytes=100,reused_kv_bytes=0) for _ in range(3)], + records=[dict(name=name, ids=[1], text=SECRET, finish='stop', reused=1, + prompt_tokens=n, state={k:'abc' for k in STATE_KEYS}) for name,n in zip(NAMES,lengths)]) + full['info'].update(conversation_cache_mib=1,conversation_cache_slots=4) + incremental = copy.deepcopy(full) + incremental['name'] = 'incremental' + for p in incremental['parks']: + p['reused_kv_bytes'] = 50 + return dict(arms=[full,incremental],requests=requests,request_digest=digest) + + +class GrowthGate(unittest.TestCase): + def test_complete_evidence(self): + verify(fixture()) + + def test_incomplete_or_incorrect_evidence_fails(self): + mutations = [ + lambda r:r['requests'].pop(), + lambda r:r['requests'][0]['ids'].append(2), + lambda r:r['arms'][1]['records'].pop(), + lambda r:r['arms'][1]['records'][2].update(ids=[2]), + lambda r:r['arms'][1]['records'][2].update(text='wrong'), + lambda r:r['arms'][1]['records'][2].update(reused=0), + lambda r:r['arms'][1]['records'][2].update(finish='cancel'), + lambda r:r['arms'][1]['records'][2]['state'].pop('kv'), + lambda r:r['arms'][1]['info'].update(expert_slots=2), + lambda r:r['arms'][1].update(draft_verifications=0), + lambda r:r['arms'][0]['parks'][0].update(reused_kv_bytes=1), + lambda r:[p.update(reused_kv_bytes=0) for p in r['arms'][1]['parks']], + lambda r:r['arms'][1]['parks'][0].update(bytes=2*1024*1024), + lambda r:r['arms'][1]['parks'][0].update(reused_kv_bytes=101), + ] + for i, mutate in enumerate(mutations): + with self.subTest(case=i): + result = fixture() + mutate(result) + with self.assertRaises(AssertionError): + verify(result) + + def test_optimized_python_rejects_missing_reuse(self): + code = ('from tools.test_conversation_cache_growth import fixture,verify; ' + 'r=fixture(); [p.update(reused_kv_bytes=0) for p in r["arms"][1]["parks"]]; verify(r)') + run = subprocess.run([sys.executable,'-O','-c',code],capture_output=True,text=True) + self.assertNotEqual(run.returncode,0) + self.assertIn('did not reuse KV bytes',run.stderr) + + def test_dry_run_leaves_server_and_output_alone(self): + with tempfile.TemporaryDirectory() as tmp: + output = Path(tmp)/'absent' + run = subprocess.run([sys.executable,'tools/conversation_cache_growth.py','--config','/absent', + '--engine','/absent','--output',str(output)],capture_output=True,text=True) + self.assertEqual(run.returncode,0,run.stderr) + self.assertFalse(output.exists()) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/test_conversation_cache_parity.py b/tools/test_conversation_cache_parity.py index 15c9cc40..3f950ebd 100644 --- a/tools/test_conversation_cache_parity.py +++ b/tools/test_conversation_cache_parity.py @@ -6,7 +6,7 @@ import sys import tempfile import unittest -from tools.conversation_cache_parity import STATE_KEYS, engine_args, verify_admission, verify_exchange, verify_pressure, verify_results +from tools.conversation_cache_parity import STATE_KEYS, engine_args, pressure_budget_hint, verify_admission, verify_exchange, verify_pressure, verify_results def fixture(): @@ -89,6 +89,22 @@ def pressure_fixture(): class PressureGate(unittest.TestCase): + def test_pressure_budget_hint_uses_individual_sizes(self): + data = pressure_fixture() + for park in data['pressure']['parks']: + park['snapshot_bytes'] = 266 * 1024 * 1024 + self.assertIn('--cache-mib 266..531', pressure_budget_hint(data, 600)) + data['candidate'][-1]['reused'] = 100 + with self.assertRaisesRegex(AssertionError, r'Configured --cache-mib 600.*266\.00 MiB.*266\.\.531'): + verify_pressure(data, 600) + + def test_pressure_budget_hint_handles_missing_or_incompatible_sizes(self): + data = pressure_fixture() + self.assertIn('No snapshot sizes', pressure_budget_hint(data, 600)) + for park, size in zip(data['pressure']['parks'], [1, 2, 10]): + park['snapshot_bytes'] = size * 1024 * 1024 + self.assertIn('No whole-MiB budget', pressure_budget_hint(data, 600)) + def test_physical_memory_admission_evidence(self): data = pressure_fixture() data['pressure'] = {'memory_skips': 3, 'skips': 0, 'parks': []} From 92a3d5fda7aaf74f4d04418e0b1ed2a531d6725e Mon Sep 17 00:00:00 2001 From: Jeremiah Ritchey <44681828+jeremiahritchey@users.noreply.github.com> Date: Wed, 30 Sep 2026 04:56:15 +0000 Subject: [PATCH 19/22] Bound incremental snapshot fragmentation and preserve cache admission Reserve accounted space for later appends without moving prior payloads. Prefer full capture when optional capacity would evict useful conversations, and report the actual additional RAM required. Exercise 4096 small appends and non-mutating admission checks under sanitizers. --- include/strata/core/conversation_buffer.hpp | 32 +++++++++++++++++---- include/strata/core/conversation_cache.hpp | 4 +++ src/core/conversation_cache_test.cpp | 15 ++++++++++ src/program/generate.cpp | 10 ++++--- 4 files changed, 52 insertions(+), 9 deletions(-) diff --git a/include/strata/core/conversation_buffer.hpp b/include/strata/core/conversation_buffer.hpp index a58a38bf..1cb8af77 100644 --- a/include/strata/core/conversation_buffer.hpp +++ b/include/strata/core/conversation_buffer.hpp @@ -47,21 +47,36 @@ public: size_t allocation_peak(size_t n) const { size_t total = bytes(); if (n <= size_) return total; - const size_t extra = n - size_; - if (!add(total, extra)) return SIZE_MAX; + const size_t spare = segments_.empty() ? 0 : segments_.back().capacity() - segments_.back().size(); + const size_t extra = n - size_ - std::min(n - size_, spare); + const size_t full = extra / segment_bytes, tail = extra % segment_bytes; + if (!add(total, full * segment_bytes)) return SIZE_MAX; + if (tail && !add(total, segment_capacity(tail, full ? segment_bytes : + segments_.empty() ? 0 : segments_.back().capacity(), size_ != 0))) return SIZE_MAX; size_t count = segments_.size(); - if (!add(count, extra / segment_bytes + (extra % segment_bytes != 0))) return SIZE_MAX; + if (!add(count, full + (tail != 0))) return SIZE_MAX; if (count > segments_.capacity() && (count > SIZE_MAX / sizeof(Segment) || !add(total, count * sizeof(Segment)))) return SIZE_MAX; return total; } void resize(size_t n, uint8_t value = 0) { if (n > size_) { - const size_t extra = n - size_; + const bool growing = size_ != 0; + const size_t spare = segments_.empty() ? 0 : segments_.back().capacity() - segments_.back().size(); + const size_t extend = std::min(n - size_, spare); + const size_t extra = n - size_ - extend; segments_.reserve(segments_.size() + extra / segment_bytes + (extra % segment_bytes != 0)); + if (extend) { + segments_.back().resize(segments_.back().size() + extend, value); + size_ += extend; + } while (size_ < n) { const size_t count = std::min(segment_bytes, n - size_); - segments_.emplace_back(count, value); + const size_t previous = segments_.empty() ? 0 : segments_.back().capacity(); + Segment segment; + segment.reserve(segment_capacity(count, previous, growing)); + segment.resize(count, value); + segments_.push_back(std::move(segment)); size_ += count; } } else { @@ -105,6 +120,13 @@ public: private: using Segment = std::vector; + // A fresh capture allocates exactly its payload. Later appends reserve + // geometrically growing segments, bounded by 16 MiB. Small chat turns then + // extend the final allocation instead of adding one transfer per turn. + static size_t segment_capacity(size_t count, size_t previous, bool growing) { + if (!growing) return count; + return std::max(count, std::min(segment_bytes, std::max(65536, std::min(previous, segment_bytes/2)*2))); + } static bool add(size_t& n, size_t extra) { if (extra > SIZE_MAX - n) return false; n += extra; diff --git a/include/strata/core/conversation_cache.hpp b/include/strata/core/conversation_cache.hpp index c1506c91..9a75092a 100644 --- a/include/strata/core/conversation_cache.hpp +++ b/include/strata/core/conversation_cache.hpp @@ -118,6 +118,10 @@ public: } ConversationKvReuse take_reuse() { return std::exchange(reuse_, {}); } size_t retained_bytes() const { return reuse_.bytes(); } + bool can_fit(size_t incoming, size_t held = 0) const { + return enabled() && held <= budget_ && incoming <= budget_ - held && + entries_.size() < slots_ && bytes() <= budget_ - held - incoming; + } template Match best(const std::vector& prompt, const std::vector& images, bool cvec) const { diff --git a/src/core/conversation_cache_test.cpp b/src/core/conversation_cache_test.cpp index 6b002005..ecb71f19 100644 --- a/src/core/conversation_cache_test.cpp +++ b/src/core/conversation_cache_test.cpp @@ -46,6 +46,17 @@ int main() { check(!bytes.read(tail.data(), bytes.size()-1, 2), "range check rejects a truncated payload"); check(bytes.allocation_peak(SIZE_MAX) == SIZE_MAX, "allocation estimate rejects overflow"); } + { + ConversationBuffer bytes; + for (size_t n=1;n<=4096;++n) { + const size_t peak = bytes.allocation_peak(n*17); + bytes.resize(n*17,7); + check(bytes.bytes() <= peak,"small append stays within the predicted allocation peak"); + } + size_t segments = 0; + bytes.visit(0,bytes.size(),[&](const uint8_t*,size_t,size_t){++segments;return true;}); + check(segments <= 4,"thousands of small turns do not create thousands of restore transfers"); + } { ConversationKv layer; layer.k.resize(400); @@ -62,6 +73,10 @@ int main() { check(reuse.unchanged_tokens == 9, "a later continuation cannot undo a rewind's dirty boundary"); check(cache.bytes() == parked, "taking retained buffers releases their budget accounting"); cache.retain(std::move(reuse.kv), 16); + check(!cache.can_fit(parked),"retained storage is counted when checking a capture without eviction"); + check(cache.retained_bytes() == retained && cache.size() == 1 && cache.evictions() == 0, + "optional reuse admission does not evict or release anything"); + check(!cache.can_fit(SIZE_MAX) && !cache.can_fit(1,SIZE_MAX),"non-mutating reservation rejects overflow"); check(cache.make_room(parked), "reservation can discard optional active buffers"); check(cache.retained_bytes() == 0 && cache.size() == 1 && cache.evictions() == 0, "pressure drops retained storage before evicting parked conversations"); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 3851b776..fc11cb04 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -3278,8 +3278,9 @@ int main(int argc, char** argv) { estimate = fresh_estimate; err.clear(); } - if (!conversations.make_room(estimate, held) && !reuse.kv.empty()) { - reuse = {}; // Optional retained storage must not prevent a full capture. + if (!reuse.kv.empty() && !conversations.can_fit(estimate, held)) { + // Optional growth capacity must not evict useful conversations. + reuse = {}; estimate = fresh_estimate; } if (!conversations.make_room(estimate, held)) { @@ -3290,10 +3291,11 @@ int main(int argc, char** argv) { const auto t0 = Clock::now(); try { const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib * 1024 * 1024; + const size_t additional = estimate - reuse.bytes(); if (!strata::core::conversation_memory_admit(strata::core::conversation_available_memory(), - estimate - reuse.bytes(), floor)) { + additional, floor)) { std::fprintf(stderr, "strata serve: conversation cache: skip parking (physical RAM admission; need %zu MiB plus %lld MiB floor, or telemetry unavailable)\n", - estimate >> 20, (long long) o.conversation_cache_min_free_mib); + additional >> 20, (long long) o.conversation_cache_min_free_mib); return true; } strata::core::SavedConversation image; From 7d93cb6b034ebb77005819869366e1d0176b0217 Mon Sep 17 00:00:00 2001 From: Jeremiah Ritchey <44681828+jeremiahritchey@users.noreply.github.com> Date: Wed, 30 Sep 2026 04:59:13 +0000 Subject: [PATCH 20/22] Require fixed binaries and budgets in the incremental capture gate --- docs/DETAILS.md | 2 ++ tools/conversation_cache_growth.py | 6 ++++-- tools/test_conversation_cache_growth.py | 6 ++++-- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 45bc63aa..c2a1f066 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -391,6 +391,8 @@ retained for the next parking operation; growth appends storage without copying the existing pages. Rewinds refresh the affected pages, and running state and checkpoints are captured again. Retained active K/V counts against the same byte budget and is discarded before evicting parked entries under memory pressure. +If reserving space for growth would evict another conversation, parking uses a +full capture instead. Oldest parked entries are evicted first. Oversized snapshots or host allocation failures fall back to ordinary prompt processing. `--conversation-cache-min-free-mib N` (default 2560) additionally requires that diff --git a/tools/conversation_cache_growth.py b/tools/conversation_cache_growth.py index 9a455d4a..d28683a1 100644 --- a/tools/conversation_cache_growth.py +++ b/tools/conversation_cache_growth.py @@ -29,14 +29,16 @@ def verify(results): require(full['name'] == 'full' and incremental['name'] == 'incremental', 'incorrect comparison arms') requests = results['requests'] require([r['name'] for r in requests] == NAMES, 'incomplete growth/rewind requests') + require(all(r['ids'] and r['max_new'] > 0 for r in requests), 'empty growth request') digest = hashlib.sha256(json.dumps(requests, sort_keys=True).encode()).hexdigest() require(digest == results['request_digest'], 'request evidence changed') for arm in (full, incremental): require(arm['request_digest'] == digest and arm['args'] == full['args'], 'inputs or arguments differ') + require(arm['exe_sha256'] == full['exe_sha256'], 'executable changed between comparison arms') require([r['name'] for r in arm['records']] == NAMES, 'incomplete growth/rewind outputs') for key in (*SETTINGS, 'conversation_cache_mib', 'conversation_cache_slots'): require(key in arm['info'] and arm['info'][key] == full['info'][key], f'engine setting differs: {key}') - require(arm['info']['conversation_cache_mib'] > 0, 'cache is not enabled') + require(arm['info']['conversation_cache_mib'] == results['cache_mib'] > 0, 'cache budget differs') budget = arm['info']['conversation_cache_mib'] * 1024 * 1024 require(arm['parks'] and all(0 < p['snapshot_bytes'] <= p['bytes'] <= budget and 0 <= p['reused_kv_bytes'] <= p['snapshot_bytes'] for p in arm['parks']), 'invalid allocation/reuse evidence') @@ -99,7 +101,7 @@ def main(): env['STRATA_SNAPSHOT_VERIFY'] = '1' env['STRATA_MTP_BATCH'] = '1' a.output.mkdir(mode=0o700, parents=False, exist_ok=False) - results = {'requests': [], 'arms': [], 'spec': a.spec, 'paragraphs': a.paragraphs} + results = {'requests': [], 'arms': [], 'spec': a.spec, 'paragraphs': a.paragraphs, 'cache_mib': a.cache_mib} for name in ('full', 'incremental'): current_env = dict(env) if name == 'full': diff --git a/tools/test_conversation_cache_growth.py b/tools/test_conversation_cache_growth.py index 73b3d336..36423449 100644 --- a/tools/test_conversation_cache_growth.py +++ b/tools/test_conversation_cache_growth.py @@ -16,7 +16,7 @@ def fixture(): requests = [dict(name=name, ids=[1]*n, max_new=16, expected=name.startswith('A-')) for name, n in zip(NAMES, lengths)] digest = hashlib.sha256(json.dumps(requests, sort_keys=True).encode()).hexdigest() - full = dict(name='full', args=['--conversation-cache-mib','1'], request_digest=digest, + full = dict(name='full', exe_sha256='fixed', args=['--conversation-cache-mib','1'], request_digest=digest, info={key: 1 for key in SETTINGS}, draft_verifications=4, parks=[dict(bytes=100,snapshot_bytes=100,reused_kv_bytes=0) for _ in range(3)], records=[dict(name=name, ids=[1], text=SECRET, finish='stop', reused=1, @@ -26,7 +26,7 @@ def fixture(): incremental['name'] = 'incremental' for p in incremental['parks']: p['reused_kv_bytes'] = 50 - return dict(arms=[full,incremental],requests=requests,request_digest=digest) + return dict(arms=[full,incremental],requests=requests,request_digest=digest,cache_mib=1) class GrowthGate(unittest.TestCase): @@ -37,6 +37,8 @@ class GrowthGate(unittest.TestCase): mutations = [ lambda r:r['requests'].pop(), lambda r:r['requests'][0]['ids'].append(2), + lambda r:r['arms'][1].update(exe_sha256='different'), + lambda r:r.update(cache_mib=2), lambda r:r['arms'][1]['records'].pop(), lambda r:r['arms'][1]['records'][2].update(ids=[2]), lambda r:r['arms'][1]['records'][2].update(text='wrong'), From 7e94070cf27670cb31a9f4a155e23731d2285f9a Mon Sep 17 00:00:00 2001 From: Jeremiah Ritchey <44681828+jeremiahritchey@users.noreply.github.com> Date: Wed, 30 Sep 2026 05:08:16 +0000 Subject: [PATCH 21/22] Document retained snapshot ownership and admission contract --- include/strata/core/conversation_cache.hpp | 1 + include/strata/core/conversation_snapshot.hpp | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/include/strata/core/conversation_cache.hpp b/include/strata/core/conversation_cache.hpp index 9a75092a..2b26c4f6 100644 --- a/include/strata/core/conversation_cache.hpp +++ b/include/strata/core/conversation_cache.hpp @@ -51,6 +51,7 @@ struct ConversationKv { struct ConversationKvReuse { std::vector kv; + // Original image extent for validation, and the earliest subsequent rewrite. int64_t captured_tokens = 0, unchanged_tokens = 0; size_t bytes() const { size_t n = kv.capacity() * sizeof(ConversationKv); diff --git a/include/strata/core/conversation_snapshot.hpp b/include/strata/core/conversation_snapshot.hpp index d75a017b..22a82533 100644 --- a/include/strata/core/conversation_snapshot.hpp +++ b/include/strata/core/conversation_snapshot.hpp @@ -11,6 +11,9 @@ namespace strata::core { // Caller synchronizes the device before saving, and after restoring all layers. // include_index is false for the draft layer (its attention has no indexer). size_t conversation_kv_bytes(const QsaState& state, const ModelGeometry& g, int64_t upto, bool include_index); +// A nonzero unchanged_tokens is valid only for storage retained from an image +// actually restored into this session, bounded by every subsequent rewrite. +// Equal token IDs alone do not establish that its K/V bytes are unchanged. bool conversation_kv_save(ConversationKv& image, const QsaState& state, const ModelGeometry& g, int64_t upto, bool include_index, std::string& error, int64_t unchanged_tokens = 0, size_t* reused_bytes = nullptr); @@ -49,6 +52,9 @@ bool conversation_snapshot_bytes(const ConversationView& view, const SessionStat bool conversation_snapshot_capture_bytes(const ConversationKvReuse& reuse, const ConversationView& view, const SessionState& session, const ModelGeometry& g, const QsaState& draft, size_t& bytes, std::string& error); +// The capture estimate includes retained capacity and transient segment directories; +// only estimate - reuse.bytes() requires additional physical RAM. Capture consumes +// the uniquely owned reusable buffers, including on failure. // Caller admits the estimate before invoking capture. Allocation failures propagate // to the RAM policy; the active session is never modified by capture. bool conversation_snapshot_save(SavedConversation& image, const ConversationView& view, From 56c7cd2f805c22807ede7c3575d9873c9460e20d Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 30 Sep 2026 16:43:28 +0200 Subject: [PATCH 22/22] STATE_HASH: pooled= keeps its 0.1.29 meaning (the completed indexer rows); the extent with the spare row is pooled_full= pooled= hashes rows [0, L/4) of every QSA layer's idx_pooled again, as in 0.1.29 and earlier, so a state hash from this engine compares with an older one field by field. The PR's extent (those rows plus the spare row at L/4, which a conversation restore writes back) is pooled_full=; dead= stays. The cache gates compare pooled and pooled_full; the cache-off gate against an older engine compares pooled directly and needs pooled_full only as proof that the candidate is this build. A failed checkpoint save/restore prints its reason to stderr (the ERR line has none). The cache harness reads its files as UTF-8 (Windows' default code page stopped it at the tokenizer), and the isolation gate passes absolute fixture paths (the engine runs in the config's cwd). --- src/program/generate.cpp | 23 +++++++++++++++-------- tools/conversation_cache_disabled.py | 14 +++++++------- tools/conversation_cache_growth.py | 4 ++-- tools/conversation_cache_isolation.py | 6 ++++-- tools/conversation_cache_parity.py | 15 ++++++++------- tools/conversation_cache_soak.py | 6 +++--- tools/test_conversation_cache_disabled.py | 6 ++++-- 7 files changed, 43 insertions(+), 31 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index fc11cb04..2afd0591 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -739,13 +739,17 @@ ConvStateSizes conv_state_sizes(const strata::core::ModelGeometry& g) { /// Copies the running state out. The caller has synchronized the device. bool checkpoint_save(ConvCheckpoint& c, const strata::core::SessionState& ss, const strata::core::ModelGeometry& g) { std::string error; - return strata::core::conversation_checkpoint_save(c, ss, g, error); + if (strata::core::conversation_checkpoint_save(c, ss, g, error)) return true; + std::fprintf(stderr, "strata serve: checkpoint save: %s\n", error.c_str()); // the caller's ERR has no reason + return false; } /// Puts a checkpoint's running state back; the positional cells below it are the caller's to guarantee. bool checkpoint_restore(const ConvCheckpoint& c, strata::core::SessionState& ss, const strata::core::ModelGeometry& g) { std::string error; - return strata::core::conversation_checkpoint_restore(c, ss, g, error); + if (strata::core::conversation_checkpoint_restore(c, ss, g, error)) return true; + std::fprintf(stderr, "strata serve: checkpoint restore: %s\n", error.c_str()); + return false; } // --control-vector-scaled: llama.cpp's `common_control_vector_load` (every file's `direction.` times its scale, @@ -4395,8 +4399,10 @@ int main(int argc, char** argv) { } uint64_t h_ple = hash_dev(ss.ple_hist, ss.ple_hist ? z.ple : 0, 1469598103934665603ull); uint64_t h_tail = 1469598103934665603ull, h_pool = h_tail, h_kv = h_tail, h_stale = h_tail; - uint64_t h_dead = h_tail; - uint64_t h_pool_complete = h_tail; // upstream's extent, without the moving spare row + // pooled= keeps its 0.1.29 meaning: the completed rows [0, L / idx_block) only. pooled_full= adds the + // spare row at L / idx_block (the `dead` key the next block completion overwrites), which a + // conversation restore writes back; dead= is the spare key itself + uint64_t h_dead = h_tail, h_pool_full = h_tail; const int64_t kvb = qs.head_dim, scb = (qs.head_dim / 64) * 2; // a state's K/V arrays and their bytes per (cell, head) row: the host copy when it has one auto kv_arrays = [&](const strata::core::QsaState& st) { @@ -4424,8 +4430,9 @@ int main(int argc, char** argv) { const strata::core::QsaState& st = ss.qsa_states[i]; h_tail = hash_dev(st.idx_tail, z.tail, h_tail); h_dead = hash_dev(st.idx_dead, z.dead, h_dead); - h_pool_complete = hash_dev(st.idx_pooled, (size_t) (L / qs.idx_block) * qs.idx_dim * 4, h_pool_complete); - h_pool = hash_dev(st.idx_pooled, (size_t) (L > 0 ? L / qs.idx_block + 1 : 0) * qs.idx_dim * 4, h_pool); + h_pool = hash_dev(st.idx_pooled, (size_t) (L / qs.idx_block) * qs.idx_dim * 4, h_pool); + h_pool_full = hash_dev(st.idx_pooled, (size_t) (L > 0 ? L / qs.idx_block + 1 : 0) * qs.idx_dim * 4, + h_pool_full); // KV streaming: the host copy is the identity layout and holds every cell for (const auto& [pool, w] : kv_arrays(st)) { h_kv = hash_cells(pool, w, 0, L, h_kv); @@ -4442,11 +4449,11 @@ int main(int argc, char** argv) { return 1; } std::fprintf(stderr, "strata serve: STATE_HASH L=%lld gdn=%016llx ple=%016llx tail=%016llx pooled=%016llx " - "kv=%016llx mtp=%016llx stale=%016llx dead=%016llx pooled_complete=%016llx ple_prev=%d,%d\n", (long long) L, + "kv=%016llx mtp=%016llx stale=%016llx dead=%016llx pooled_full=%016llx ple_prev=%d,%d\n", (long long) L, (unsigned long long) h_gdn, (unsigned long long) h_ple, (unsigned long long) h_tail, (unsigned long long) h_pool, (unsigned long long) h_kv, (unsigned long long) h_mtp, (unsigned long long) h_stale, (unsigned long long) h_dead, - (unsigned long long) h_pool_complete, ss.ple_prev[0], ss.ple_prev[1]); + (unsigned long long) h_pool_full, ss.ple_prev[0], ss.ple_prev[1]); } const int64_t req_hits = drive.d.cache_hits - decode_hits0; const int64_t req_look = (drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused) - decode_look0; diff --git a/tools/conversation_cache_disabled.py b/tools/conversation_cache_disabled.py index db3c05f2..15c8d791 100644 --- a/tools/conversation_cache_disabled.py +++ b/tools/conversation_cache_disabled.py @@ -22,7 +22,8 @@ from serve.server import StrataEngine, child_env NAMES = ('short', 'A', 'A-live', 'A-checkpoint', 'B', 'A-return', 'B-return', 'A-return-again') SETTINGS = ('version', 'context', 'kv', 'kv_resident', 'expert_slots', 'spec', 'mtp_max', 'lookup', 'cvec', 'pcie_frac', 'spec_min_p', 'pool_workers') -# Untouched 0.1.27 does not emit the indexer `dead` field added by this PR. +# Untouched upstream does not emit the indexer `dead` and `pooled_full` fields +# added by this PR; `pooled` is the completed-row extent in both engines. # Draft scratch and unused page padding are not comparable authoritative state. STATE_KEYS = ('L', 'gdn', 'ple', 'tail', 'pooled', 'kv', 'ple_prev') @@ -34,10 +35,9 @@ def state_hashes(text, *, candidate=False): fields = dict(re.findall(r'(\w+)=([0-9a-f,-]+)', line)) require(set(STATE_KEYS) <= fields.keys(), 'missing upstream-compatible state fields') if candidate: - # The PR's pooled hash includes the spare row. Require the - # separately emitted upstream extent instead of comparing unlike bytes. - require('pooled_complete' in fields, 'candidate lacks completed-row fingerprint') - fields['pooled'] = fields['pooled_complete'] + # Evidence that the candidate is a build with this change: it + # also fingerprints the spare row (compared by the cache-on gates). + require('pooled_full' in fields, 'candidate lacks the pooled_full fingerprint') hashes.append({key: fields[key] for key in STATE_KEYS}) return hashes @@ -109,7 +109,7 @@ def main(): if not a.run: print('Dry run: upstream and disabled candidates; identical inputs/settings, known answers and state parity.') return - cfg = json.loads(a.config.read_text()) + cfg = json.loads(a.config.read_text(encoding='utf-8')) tok_path = Path(cfg['tokenizer']) tok = load_tokenizer(tok_path) tpl_path = tok_path / 'chat_template.jinja' @@ -176,7 +176,7 @@ def main(): engine.proc.wait(timeout=30) engine.log.close() arm['request_digest'] = hashlib.sha256(json.dumps(results['requests'], sort_keys=True).encode()).hexdigest() - log_text = log.read_text() + log_text = log.read_text(encoding='utf-8') hashes = state_hashes(log_text, candidate=index != 0) require(len(hashes) == len(arm['records']), f'{name}: missing state hashes') for record, fingerprint in zip(arm['records'], hashes): diff --git a/tools/conversation_cache_growth.py b/tools/conversation_cache_growth.py index d28683a1..f52cef83 100644 --- a/tools/conversation_cache_growth.py +++ b/tools/conversation_cache_growth.py @@ -76,7 +76,7 @@ def main(): if not a.run: print('Dry run: paired full/incremental captures; growth, interruption, rewind and branch; no model loaded.') return - cfg = json.loads(a.config.read_text()) + cfg = json.loads(a.config.read_text(encoding='utf-8')) tok_path = Path(cfg['tokenizer']) tok = load_tokenizer(tok_path) template = ChatTemplate(tok_path / 'chat_template.jinja') @@ -147,7 +147,7 @@ def main(): engine.close() engine.proc.wait(timeout=30) engine.log.close() - log_text = log.read_text() + log_text = log.read_text(encoding='utf-8') hashes = state_hashes(log_text) require(len(hashes) == len(arm['records']), 'missing state fingerprints') for record, state in zip(arm['records'], hashes): diff --git a/tools/conversation_cache_isolation.py b/tools/conversation_cache_isolation.py index 5c201300..c0f0d52b 100644 --- a/tools/conversation_cache_isolation.py +++ b/tools/conversation_cache_isolation.py @@ -75,10 +75,12 @@ def main(): ap.add_argument('--scenario', choices=('image', 'add', 'project'), required=True) ap.add_argument('--run', action='store_true') args = ap.parse_args() + # the fixtures are passed to an engine that runs in the config's cwd, not this shell's + args.output = args.output.resolve() if not args.run: print(f'Dry run: {args.scenario} isolation; no model loaded or files created.') return - cfg = json.loads(args.config.read_text()) + cfg = json.loads(args.config.read_text(encoding='utf-8')) native = cfg['args'][cfg['args'].index('--native') + 1] geometry = GGUFFile(native).metadata width = geometry['qwen4exp.embedding_length'] @@ -130,7 +132,7 @@ def main(): generate('off-again', A, steering=False) finally: engine.close() - hashes = state_hashes(log.read_text()) + hashes = state_hashes(log.read_text(encoding='utf-8')) require(len(hashes) == len(records), 'missing isolation state hashes') for record, state in zip(records, hashes): record['state'] = state diff --git a/tools/conversation_cache_parity.py b/tools/conversation_cache_parity.py index cea5fc59..6e7b4fca 100644 --- a/tools/conversation_cache_parity.py +++ b/tools/conversation_cache_parity.py @@ -15,7 +15,8 @@ from serve.server import StrataEngine, child_env from serve.frontend import ChatTemplate import strata_tokenizer as ST -STATE_KEYS = ('L', 'gdn', 'ple', 'tail', 'dead', 'pooled', 'kv', 'ple_prev') +# pooled: the completed indexer rows (the 0.1.29 extent); pooled_full: those plus the spare row +STATE_KEYS = ('L', 'gdn', 'ple', 'tail', 'dead', 'pooled', 'pooled_full', 'kv', 'ple_prev') def require(condition, message): if not condition: @@ -23,12 +24,12 @@ def require(condition, message): def load_tokenizer(path): - vocab = json.loads((path / 'vocab.json').read_text()) + vocab = json.loads((path / 'vocab.json').read_text(encoding='utf-8')) tokens = [None] * len(vocab) for token, index in vocab.items(): tokens[index] = token - return ST.Tokenizer(tokens, (path / 'merges.txt').read_text().split('\n'), - json.loads((path / 'token_type.json').read_text())) + return ST.Tokenizer(tokens, (path / 'merges.txt').read_text(encoding='utf-8').split('\n'), + json.loads((path / 'token_type.json').read_text(encoding='utf-8'))) def state_hashes(text): @@ -170,7 +171,7 @@ def main(): print(f'Dry run: {a.scenario}; paired baseline/candidate; fixed residency, greedy output.') print('No model loaded. Use --run only with a separately available GPU/test window.') return - cfg = json.loads(a.config.read_text()) + cfg = json.loads(a.config.read_text(encoding='utf-8')) p = Path(cfg['tokenizer']) tok = load_tokenizer(p) tpl = ChatTemplate(p / 'chat_template.jinja') @@ -217,13 +218,13 @@ def main(): generate(continuation, 8, 'A+-checkpoint') finally: engine.close() - hashes = state_hashes(log.read_text()) + hashes = state_hashes(log.read_text(encoding='utf-8')) require(len(hashes) == len(records), 'missing state hashes') for record, fingerprint in zip(records, hashes): record['state'] = fingerprint results[label] = records if label == 'candidate' and a.scenario != 'reuse': - log_text = log.read_text() + log_text = log.read_text(encoding='utf-8') parks = re.findall(r'conversation cache: parked \d+ tokens .*?parked=(\d+) bytes=(\d+) evictions=(\d+)(?: snapshot_bytes=(\d+))?', log_text) results['pressure'] = { 'parks': [dict(zip(('parked', 'bytes', 'evictions', 'snapshot_bytes'), diff --git a/tools/conversation_cache_soak.py b/tools/conversation_cache_soak.py index a7c95fdd..fc9bb0e5 100644 --- a/tools/conversation_cache_soak.py +++ b/tools/conversation_cache_soak.py @@ -78,7 +78,7 @@ def main(): print(f'Dry run: {args.cycles} known-answer A/B/A cycles; approximate lengths {lengths}.') print('No model loaded or files created. Use --run only in an exclusive GPU test window.') return - cfg = json.loads(args.config.read_text()) + cfg = json.loads(args.config.read_text(encoding='utf-8')) path = Path(cfg['tokenizer']) tok = load_tokenizer(path) template = ChatTemplate(path / 'chat_template.jinja') @@ -117,7 +117,7 @@ def main(): def generate(ids, count): nonlocal hash_count output = [t for t in engine.generate(ids, count, {'temperature': 0}, threading.Event()) if t is not None] - text = log.read_text() + text = log.read_text(encoding='utf-8') hashes = state_hashes(text) require(len(hashes) == hash_count + 1 and int(hashes[-1]['L']) >= len(ids), 'missing current state fingerprint') hash_count += 1 @@ -125,7 +125,7 @@ def main(): occupancy = re.findall(r'parked=\d+ bytes=(\d+)', text) rss = None try: - match = re.search(r'^VmRSS:\s+(\d+) kB', Path(f'/proc/{engine.proc.pid}/status').read_text(), re.M) + match = re.search(r'^VmRSS:\s+(\d+) kB', Path(f'/proc/{engine.proc.pid}/status').read_text(encoding='utf-8'), re.M) if match: rss = int(match[1]) * 1024 except OSError: diff --git a/tools/test_conversation_cache_disabled.py b/tools/test_conversation_cache_disabled.py index 3eec19b2..d389ac9f 100644 --- a/tools/test_conversation_cache_disabled.py +++ b/tools/test_conversation_cache_disabled.py @@ -35,8 +35,10 @@ class DisabledCacheGateTest(unittest.TestCase): line = 'strata serve: STATE_HASH L=2 gdn=ab ple=cd tail=ef pooled=12 kv=34 mtp=56 stale=78 ple_prev=1,2' self.assertEqual(set(state_hashes(line)[0]), set(STATE_KEYS)) self.assertEqual(state_hashes(line), state_hashes(line + ' dead=99')) - self.assertEqual(state_hashes(line), state_hashes(line.replace('pooled=12', 'pooled=ff') + - ' pooled_complete=12', candidate=True)) + # the candidate's pooled= is the upstream extent; pooled_full= (with the spare row) is not compared + self.assertEqual(state_hashes(line), state_hashes(line + ' dead=99 pooled_full=ff', candidate=True)) + self.assertNotEqual(state_hashes(line), state_hashes(line.replace('pooled=12', 'pooled=ff') + + ' pooled_full=12', candidate=True)) with self.assertRaises(AssertionError): state_hashes(line, candidate=True) with self.assertRaises(AssertionError):