--layer-split K runs layers [0, K) and [K, n_layers) as two verify stages on the same device (sharing weights,
session and expert cache). The hand-off carries R, the last layer's pending write and inject, so the next stage
folds it in exactly as the unsplit window does. The GPU shared-memory opt-ins are now per device.
A prompt read from token 0 is also checkpointed at its first turn boundary when that is 2,048 tokens or
more (--prompt-cache-root N, 0 = off). It becomes the chain's root, which #62's retention policy pins,
so a new chat of the same client reads only what follows the system prompt and tools. Without it, #62's
root existed only for system prompts past --prompt-cache-every (16K).
Co-Authored-By: code-martin <code-martin@users.noreply.github.com>
- Reset cache hits/lookups baseline at start of autoregressive decode to exclude prefill distortion
- Append req_hits and req_look to engine DONE line and log decode hit rate to stderr
- Parse decode hit metrics in server.py and record hit_rate per request in history
- Add Hit rate column to Recent requests table in web monitor
tools/calibrate.py starts the engine through serve's StrataEngine and measures decode speed with the
three settings that depend on the machine: --pcie-frac and --spec-min-p through new per-request GEN
keys (pcie_frac=, spec_min_p=; the server forwards a request's "strata_tune"), then 2-3 worker counts
(a restart each). A setting is kept only when it beats the product default by more than 3% in an
interleaved re-measurement. Setup offers it after an interactive install and runs it with --calibrate;
the result is saved per PC + model + context in the settings file and re-applied when a config is
written, so updates keep it. The engine's INFO line now says pool_workers, pcie_frac and spec_min_p.
tools/test_calibrate.py tests it with a stand-in engine (no GPU).
On Windows every allocation on the graphics card is also charged to the system commit (RAM + page file).
With the page file off or tiny, the expert cache's one big cudaMalloc failed while the VRAM was free and
the engine stopped. An auto-sized cache now retries at three quarters of the size (up to 8 times) and
says how much commit Windows has left; a failure that remains names the page-file setting. Setup warns
when the page file is under 4 GB; DETAILS has a troubleshooting row. STRATA_TEST_CACHE_FAIL=N fakes N
failed opens to test the retry.
- serve: a verify window samples T rows, but only row 0's penalty history was staged; rows 1..T-1 read
unwritten slots (past the allocation at penalty_last_n=4096). Every row now gets its own history
(strata::kernels::penalty_rows: the consumed tail, the fed-back token, the drafts before that row).
- prompt windows (their picks are discarded) skip the head sampling: Verifier::set_head_sampling.
- sampler: history ids outside [0, n_vocab) are ignored (they set bits past the shared bitmap); sampled
top_k 0 or > 64 means 64 and every row is written (0 used to leave the row unwritten).
- server: a client's top_k 0 or > 64 is sent as 64 (it fell back to the default 20).
- CLI: the speculative loop gets the CLI's sampling (it was always greedy), the per-token path draws
Philox(seed, position) like a verify window, and the effective sampling is printed.
- sampler_parity: fixtures 12-15 (per-row histories T=1..8 x H=1..4096, out-of-vocab ids, the top_k
contract, penalty_rows); outputs are pre-filled so an unwritten row fails.
- setup requires engine 0.1.19.
Found by the engineering performance review (C1, C2).
The retained checkpoints are always a prefix chain - the request loop drops
any checkpoint that is not a prefix of the current prompt, because its
positional cells are gone (the KV cache is one arena, one branch of history
at a time). A radix cache's tree collapsed onto the one branch the session
can hold, and the chain's root is the node a radix cache keeps while its
leaves rotate: in practice the end of the system prompt, which every new
chat of the same client mounts through.
First-in-first-out kept that node only by accident of being first: after
prompt_cache newer checkpoints it was gone, and the next chat re-read the
whole prefix at prefill speed (~30 s per 30K tokens). Now the root is
pinned while the budget allows root and leaf apart (cap >= 2; below that
the old behaviour stands), the rest rotates by least recent use, and a
mount re-dates the checkpoint it mounted through.
The policy is one pure function (conv_cache.hpp) with its scenarios in
conv_cache_test.cpp; checkpoint_save/restore and the state format are
untouched, so STRATA_CKPT_REREAD's token-for-token guarantee holds.
- iq_pack.py: derive n_expert from the router tensor shape (was hardcoded 512)
- expert_layout.cpp: parse the pack header's recorded n_expert instead of the
caller's compile-time canonical geometry; use it for the contiguity stride
- gguf_reader.hpp: Qwen4ExpGuard expert-count checks become presence-only
- generate.cpp: read qwen4exp.expert_count/expert_used_count from the model
file into the runtime geometry; MTP drafter keeps canonical geometry (the
draft is the original 512-expert head); serve gate allows profile-less
caches; K from metadata
- layer.cpp: native fused router stays 512x10-only, generic top-k fallback
- prefill: expert count taken from the geometry everywhere; route_kernel
templatized (512->16, 256->8 registers/lane, else generic router_top10)
With lazy loading, a kernel first used mid-prompt found no VRAM left for its code
once the expert cache and the prompt path had taken it: IQ3_XXS at 64K and 128K on
a 12 GB card ended with 'out of memory: cudaFuncSetAttribute' in the MMQ launch.
Loaded at start the kernels cost ~30 MB, accounted before the cache is sized
(~23 fewer slots). A user's own CUDA_MODULE_LOADING is kept.
- --pcie-mode auto is the copy kernel for native packs too. Issue #31's thread
dumps show the host stuck for good in the DMA path's cudaMemcpyAsync (a driver
lock) inside a verify window while the GPU spins on the flag those copies
raise. The copy kernel needs no host CUDA call there; IQ3_S decode 45.3 -> 44.8
tok/s. --pcie-mode dma keeps the old path.
- setup: a locally compiled engine records its version; one kept after a failed
compile is recognised by the version in its binary, and a config it cannot
read (--prefill auto on 0.1.12) goes back to 2048 (#49).
- setup: nvcc in /opt/cuda (Arch), a clearer message off Ubuntu/Debian (#46);
a failed build is tried once more (#45: ptxas's intermittent PTX parse error).
- data/expert-profile.bin ranks all 24,576 experts (the first 8,000 unchanged):
the cache stopped at 8,000 slots on 24-32 GB cards (#46). tools/make_profile.py
builds or extends a profile from --dump-routing traces; --expert-cache 0 with a
profile now means auto.
pcie_frac's defaults (0.55 native / 0.2 canonical) were measured on a PCIe 4.0 x16 link.
A x8 card in a x8 slot carries about half of that, and the copy engine's share then waits
for DMA that arrived late. Probe the H2D bandwidth once at startup the way the engine uses
it (DMA reads from pinned host memory) and scale the default by it: an RTX 5060 Ti at x8
probes 14.1 GB/s -> pcie_frac 0.29 instead of 0.55. --pcie-frac still wins when given, and
a machine that cannot run the probe keeps the current default.
The notice printed 'the expert kernels run on AVX2' whether or not the AVX2 i-quant row
kernels were used, and with STRATA_NO_IQ256 set they are not: the run is on ggml's vec_dot.
Name the kernel, and name the switch that changed it.
- The --serve stdin reader reads the descriptor instead of std::cin: glibc's
exit() waits for stdin's lock, which getline held while waiting for input,
so an engine ending on any error hung in exit() and the server waited forever.
- session_init fails when a QSA layer could not pin its KV streaming copy; it
used to continue half-built and hit an illegal memory access at the first
request (seen under WSL, where the driver pins only about 1 GiB). The message
says how much was pinned and what to change.
- setup: no KV streaming under WSL (new installs and existing configs).
- server: an engine ERR after an SSE stream started is sent as an error event
(it was a 400 response written into the open stream: an empty answer), and
the request is recorded as "error".
Prompt path (bench/results/2026-09-28-prefill-speed):
- `--prefill auto`: chunks up to 8192 tokens, sized to the cache slots the prompt path may borrow; a
request borrows only what its prompt needs (Prefill::relayout). setup writes it and switches old
`--prefill 2048` configs once the engine supports it.
- The attention and MoE halves share one scratch region (~260 KB less per token).
- Experts through llama.cpp's MMQ kernels (ggml-cuda mmq.cuh, compiled from the same checkout as ggml
into strata_mmq; Strata Q2_0 blobs converted to GGUF blocks on the gather; IQ1_M layers keep FP16).
- Chunks >= 2048: every non-resident expert streams through a ring in a fixed order across layers, so
the next layer's arrive during its attention half (384 slots when the arena is pinned, else 96).
- The PLE block for the whole chunk at once; the next chunk's PLE rows read on a thread; unpinned
experts copied by stager threads (epoch-tagged claims).
- STRATA_PREFILL_TIMING=1 prints a per-phase GPU timeline.
Q2_0 32K prompt 572 -> 1290 tok/s, IQ3_S 383 -> 1208 (RTX 5070 12 GB). Needles 5/5 1K-262K.
Issue #31 / #29: the serve watchdog (now 60 s) prints a stall report - each expert-pool thread's state,
the verify window's flags, layers served during the stall, memory and page faults - and on Windows
writes a minidump with every thread's stack; Release builds keep a PDB. The engine prints its version.
On a card with most experts in VRAM (RTX 4090) generation could stop for
good after thousands of tokens: the GPU "100%" at low power, one CPU core
busy, no tokens, no error.
- The pool's workers sleep after 20 ms without work (issue #4). With most
experts resident many layers have no CPU work, so they also slept
mid-request, and a worker that woke late was still counted as parked: it
could claim from the next batch while the host was writing it, run a job
twice, or add to `done` after the reset - and `done != n` then never
ended while the GPU waited on the pool. Every claim now carries its
batch: `head` is one 64-bit word (epoch | njobs | index), a claim is a
CAS that only succeeds for the epoch the worker woke for, and the host
waits with `<` instead of `!=`. Same speed (pool_test 47.2 GB/s).
- Every pool wait is bounded (60 s: a message and the engine stops), and
--serve runs a watchdog: a request with no progress (tokens, prompt
chunks, verify windows) for STRATA_WATCHDOG_S (120) seconds ends the
engine with where it was stuck (strata/core/progress.hpp). The server
(issue #27) answers with an error, names the cause from the log, and
starts the engine again on the next request.
- pool_stress: tiny batches with sleeping workers; STRATA_POOL_SPIN_US
shortens the spin to make them sleep constantly.
Tested: pool_test, pool_stress; 25,000-token generation at 262K with KV
streaming and constantly sleeping workers (73.9 tok/s, unchanged); the
watchdog deliberately tripped (2 s): error, log line, restart, next answer.
On Linux with too little RAM for the model's experts (IQ3_XXS on 47 GB), the
out-of-memory killer ended the engine mid-answer. The server then recorded
the reply as "length" ("Max tokens" in the Monitor, no tok/s), the stream
was cut with a traceback, and every later request failed on the dead pipe.
- The engine's death is EngineDied: the reply ends with a clear error event
(OpenAI and Anthropic streams; 503 before the answer), the Monitor says
Error, and the server window names the likely cause (RAM; dmesg).
- The next request starts the engine again (same command) instead of
failing forever; the engine counts as gone as soon as its output closes,
and a failed write to it is not mistaken for the client leaving.
- The engine's INFO line reports its expert arena (arena_mib); at start the
server warns when less than ~6 GB of RAM is left beside it.
- Test: a fake engine dies mid-stream -> error event + [DONE], Monitor
"error", the next request restarts it and answers. End to end with Q2_0:
strata.exe killed mid-answer -> error (exit code 1); next request restarts
it (31 s) and answers.
The engine takes llama.cpp's control-vector flags (--control-vector-scaled
FILE:SCALE, --control-vector-layer-range A B, --cvec-mode add|project,
--cvec-dir per-layer|single:L) and applies the vector after each steered
layer's FFN write on every hyper-connection stream: project h -= s (h.v) v,
or add h += d - where the experimental-speed-projection package's patched
llama.cpp applies it (build_cvec after the layer's second combine).
- strata/kernels/cvec: one kernel per (stream, token); with a pending fused
write it applies it first with the fused read's own arithmetic, so a
loaded-but-off vector is bitwise the stock engine. cvec_parity tests it.
- Per request: cvec=0|1 on the GEN/GENI line, the API field
"experimental_speed_projection", a switch in the web app's Sampling
drawer; a switch drops the conversation cache once. About and the
Monitor say which way each request ran.
- setup asks (default off; --experimental-speed-projection on|off|GGUF),
original Qwen3.8-Flash-Next only. The vector ships in
data/experimental-speed-projection with a README that says what it is:
its package describes it as a refusal-direction projection.
Measured (bench/results/2026-09-27-esp): off = stock token for token; on
costs 0.2-0.4% per token; mean KL 0.063 on 2,557 teacher-forced tokens.
The expert cache takes what is free minus --vram-reserve-mib (700), so
everything allocated after it comes out of that reserve. The native output
head (0.44 GB Q2_0, 0.52 GB IQ3_S) was loaded after it and ate most of it:
IQ3_S at 128K ended with 30 MiB free, the driver paged GPU memory, and a
request stalled for good at its first verify window (GPU "100%" at 45 W).
Q2_0 at 32K ended with 75 MiB.
The head now loads before the cache is sized. Same reserve, now actually
free: 480-626 MiB with everything loaded (Q2_0 32K, IQ3_S 128K + vision).
The cache is ~8% smaller (Q2_0 32K: 3,848 slots vs 4,167) and decode is not
slower: 78-79 tok/s median vs 71.7 for 0.1.8 on the same greedy prompts.
Below 256 MiB the startup line now says which --vram-reserve-mib to add.
The browser page at http://127.0.0.1:8080 is now the Strata app, in the
Strata design language (serve/web, same origin, no CDN):
- Chat: streaming answers, collapsible thinking, Markdown with code copy,
images when enabled, sampling/thinking settings, export, new chat.
- Monitor: live model state (reading with progress / generating at tok/s),
GPU load, VRAM, temperature, power, PCIe traffic, CPU, RAM, disk, the
context fill and the last requests, each with a minute of history.
- About: the model and engine settings, this PC, the API addresses.
Server: GET /metrics (API key when set), /web/* app files, /fonts/* only
when installed locally (not shipped; the page falls back to the system
font). serve/telemetry.py reads NVML via ctypes and psutil (new setup
dependency) with fallbacks. The engine prints an INFO line before READY
(kv, expert slots, speculation); older servers ignore it and the server
works with older engines.
Based on the dashboard idea in PR #22 by code-martin.
PR #21 (code-martin): a 4-bit K/V format (orthonormal FWHT-256 rotation of K, V and Q, then q4_0 blocks). On merge:
- Q4 is a full third format of the KV-streaming code (host copy, block residency, prompt-path staging, MTP ring,
STATE_HASH): with --kv-resident the PR wrote K/V through the residency map's -1 entries. kv_stream_parity now
checks Q4 streamed vs resident, bitwise.
- The per-token path ran attention twice (once before the blocks were resident); once now.
- The q4 group maximum breaks |x| ties the same way in every lane (one scale per block).
- Dropped: the duplicate path fixes (in 0.1.7), personal .gitignore entries, the re-encoded CMakeLists.
- Measured (bench/results/2026-09-27-kv-q4): int8 matches fp16; q4_0 costs precision on long documents
(perplexity +8-12%), needles 5/5, +3.7% decode at 128K. Opt-in: setup asks above 8K context (int8 recommended),
START-HERE.bat --kv q4_0, or --kv q4_0 in the config.
#23: the start-up warning "the GPU hit path is NOT CORRECT" dated from a long-fixed fault. Measured teacher-forced
on 2,557 tokens (bench/results/2026-09-27-cache-parity): cache on vs off, 95-98% same top-1 and equal perplexity
(-0.005 +- 0.005 nats); the warning is now one accurate line.
Co-Authored-By: code-martin <code-martin@users.noreply.github.com>
- Implement Q4_0 KV quantization and dequantization kernels with scale/offset
- Implement fast Walsh-Hadamard transform (FWHT-256) rotation for outlier suppression
- Add Q4_0 attention decode support in qsa_decode_attn
- Add kv_q4_parity parity test verifying CPU vs CUDA numerical accuracy
- Support --kv q4_0 in generate CLI and runtime layer allocation
- Update .gitignore for build and repository hygiene
- Prompt lookup on by default: the suffix drafter's windows are taken only where a learned policy (measured
acceptance per match length, measured window cost) expects more tokens per ms than the MTP window; lookup windows
up to --spec + 2. Code edits +6-11%, other text unchanged, verified output identical. --suffix-draft 0 = off.
- Per-request sampling (#19) keeps greedy requests on the in-graph sampler (no extra launch per window), and draws
row t of a window with Philox(seed, pos0 + t), so a seed replays the same text whatever the drafts were.
- tools: a shallow install (G:\Strata) no longer crashes the MTP packer and the pack tools (IndexError, #20).
- setup: says at step 1 when the PC has less RAM than the smallest model needs; requires engine 0.1.7.
From 64K context the KV cache lives in pinned RAM and a VRAM block cache holds the part the sparse attention reads
(--kv-resident N; setup turns it on with 32768 when RAM allows). Blocks the indexer selects are made resident on
the device inside the captured graphs (clock eviction, zero-copy reads of misses); writers write through, so the
attention reads exactly the same values. The freed VRAM goes to the expert cache: Q2_0 at 262K decodes 62.6 tok/s
instead of 50.9. The MTP drafter keeps its window in a ring. New ctest kv_stream_parity. Also wires the opt-in
suffix drafter (--suffix-draft) into the engine.
The sampled chain's last two gaps close: `min_p` and the llama.cpp
penalty set (repeat/freq/present over a history window) are live end
to end - GEN keys, per-request params, and the token history the
penalties count over.
- GEN accepts min_p=F penalty_last_n=N penalty_repeat=F penalty_freq=F
penalty_present=F between max_new and the ids (the server's
spelling); the engine clamps defensively (min_p to 0..1, a negative
last_n to 0) and skips what it does not know, as before.
- min_p cuts the top_k survivors to the prefix with p >= min_p * p_max
- in logits, sel_logit >= sel_logit[0] + logf(min_p) - before top_p,
so the two cuts compose; 0 disables, and the head always survives,
so the kept count never reaches zero.
- the penalties need the token history: the serve loop uploads the
last penalty_last_n tokens - the consumed tail plus the fed-back
head, which joins consumed_seq only after the window commits - into
one device row before every window. A request without penalties
hands the sampler a null row and takes the byte-for-byte neutral
path (no upload, nothing handed over).
Verified: sampler_parity grows a full-chain host reference (the Philox
draw transcribed host-side) and fixtures for the sampled chain with
penalties and for min_p at 0/0.5/0.9 - the kernel matches the
reference on all of them, and each fixture first asserts it can SEE
the feature before asserting the kernel matches. On the IQ3_XXS
artifact, same seed: a request with neutral penalty keys is
token-identical to one without them; a six-copy prompt that loops
24/24 on one token clean produces 24 distinct tokens with repeat 1.5
+ present 0.5; min_p 0.9 changes the pick.
The sampled path requires top_k in 1..64 (the selection loop is
O(k*n_vocab) by design); with the engine-default top_k=0 it returned
without writing the token, leaking stale buffer contents as output.
Sampled requests now default to the sampler's own top_k=20.
The Philox draw counter also must persist across a request's verify
windows - it was read from a run-local variable that reset every
window, so every window redrew the same numbers (identical sampled
output on identical requests).
The batched prompt path costs ~300 ms per run however few tokens it
has (it streams every non-resident expert the chunk routes to over
PCIe), plus ~180 ms to refill the expert-cache slots it borrows. So a
one-word message waited ~1.4 s for its first token, and every chat
follow-up paid the same fixed cost.
Each part of the prompt (up to the checkpoint, then the assistant
header) now picks its own path: parts of at most --short-read N tokens
(default 64, 0 = off) go through the verify windows, S tokens at a
time, as decode reads them (~16 ms a token). Longer parts and parts
with picture rows stay batched. Slots are lent just before a batched
run and refilled before a window read, so windows always see the whole
expert cache. STRATA_CKPT_REREAD keeps every read batched.
Every request used to start from session_zero and read its whole prompt again,
so a long chat or an agent loop waited minutes per turn. The engine now keeps
the live session and up to 6 checkpoints of the running state in RAM and reads
only the part of a prompt after the longest one it starts with.
- A checkpoint is the state that cannot be rewound - the 36 GDN recurrences and
conv histories, the 12 QSA indexer tails, the PLE history (~118 MB). The KV
cache and the pooled indexer keys are positional (a query reads only cells
below it, and `dead` for its own block), so they stay in place.
- Taken at the last <|im_start|> of each prompt (the prompt is read in two parts
there: the history, then the new turn's header) and every 16K fresh tokens.
- Used only when the prompt starts with exactly its tokens and pictures (images
are compared by a hash of their embeddings and grid); checkpoints the next
request would overwrite are dropped.
- New lines on stdout: RESUME <n> before reading, PP <pos> <n> <ms> <tok/s> per
chunk, REUSED <n> after; DONE gains <drafts accepted> <drafts offered>
<reused>. The server ignores what it does not know; PP lines now count as its
heartbeat, so keep-alives keep flowing during a long prompt.
- --prompt-cache N (default 6, 0 = off), --prompt-cache-every N, --turn-token ID.
- Checks: STRATA_CKPT_REREAD=1 reads a checkpoint's tokens again instead of
restoring it; STRATA_STATE_HASH=1 prints a fingerprint of every state part
after each request.
Streaming
- tool calls stream as they are written (OpenAI tool_calls deltas, Anthropic input_json_delta)
- keep-alives while a long prompt is read, progress in the server window, GET /status
- closing the connection or pressing stop really stops the engine (STOP)
Stalled requests (mostly image turns)
- the expert cache is sized after its slots are written (Windows only counts GPU memory once it is
touched), so the reserve really stays free instead of the card running at 0 MiB and paging
- the prompt chunk shrinks when its buffers do not fit in the cache, instead of allocating on top
- the image encoder warms up before the engine starts; images are encoded in request order
- the log shows the VRAM left once everything is loaded
setup.py now requires engine 0.1.2 (downloaded automatically on the next START-HERE.bat).
The setup now asks which model first: Qwen3.8-Flash-Next (the original) or Swift 1.5. The engine reads models
whose GGUF shards split the layers; the ready-made engine v0.1.1 is on the Releases page.
Inference engine, OpenAI/Anthropic API on localhost, optional image input, one-file setup
(START-HERE.bat / setup.sh). Model files are downloaded from Hugging Face by the setup.