diff --git a/docs/upstream-digest-2026-10-25.md b/docs/upstream-digest-2026-10-25.md new file mode 100644 index 00000000..4fc5d275 --- /dev/null +++ b/docs/upstream-digest-2026-10-25.md @@ -0,0 +1,375 @@ +# Upstream digest: Strata 0.1.35 (`d9ab8435`) to 0.1.50 (`41cf05a0`), 2026-10-25 + +For the owner. Short, ranked, with SHAs and paths. Provenance and what the merge did to our tree: [upstream.md](upstream.md). +All speed and quality numbers below are **upstream's claims on upstream's hardware, not measured by us**. Commit SHAs are 8 characters of +upstream `origin/main`. Upstream rewrote its history: the old pin `d9ab8435` is tree-identical to `5b734e42`, and the real distance is +3630 commits (not 4175). Of these, 996 touch the engine outside the DeepSeek, Gemma and Qwen3.6 trees. + +What was read: commit subjects and diffstats of the whole range, the diffs of the commits quoted here, `src/dsv41` headers and selected +kernels, `docs/DEEPSEEK41.md`, `CMakeLists.txt`, the packaging scripts, the serve protocol in `src/program/generate.cpp`. What was not +read is listed at the end. + +## Top five + +1. **Route tail skip** (`65268d99`, default on since `b4e3407b`): the only upstream change that attacks our actual bottleneck (the CPU + expert pool is about 25 of 36 ms of a verify window on the 5090, `docs/original-serve.md`). Claimed decode +10..20 percent on 12-16 GB + cards, +11.5 percent on an RTX 5090 (NVFP4 pack). It is lossy: it must be a flagged experiment for us until a quality gate passes. +2. **The sm_120 bitwise decode set** (`ba2c2d5f`, `94104176`, `75afe3f4`, `44997124`, `ffac97f7`, `731528be`): claimed bit-identical, + claimed -14 percent round time with all experts resident. Needs re-sealing PTX. +3. **Non-finite fixes** (`2b726ba6`, `f6601bf8`, `7a0e3023`, `e372d4ff`): q8_1 scale overflow turns into NaN and "!!!!" output. Our sealed + copies of the quantizers almost certainly carry the old formula. Cheap correctness work. +4. **DeepSeek-V4.1-Flash runs on CUDA sm_120** (`src/dsv41`, `docs/DEEPSEEK41.md`) and its line protocol is a compatible subset of the + Qwen engine's. The cheapest second model is `strata-dsv41` as a second supervised worker behind our gateway (about 7-10 days), not a Rust + port (8-14 weeks). +5. **"KAR for any MoE model" is true for the archive format and false for our runtime**: expert geometry is a compile-time constant in 17 + files (and in sealed kernels), and for the official 2-bit DeepSeek sets KAR level 2 (2.5 bits per weight) is larger than the source. + Details in part 2. + +--- + +# Part 1. Qwen-path changes worth taking into the Rust runtime (owner priority 1) + +Scope: `src/core`, `src/prefill`, `src/kernels`, `src/spec`, `src/ngram`, `src/program`, `include/strata`, `serve/`, `strata_control/`. +Target: RTX 5090 (sm_120, CPU pool bound) first, the sm_86 laptop second. "Numerics" is the question that matters for our quality gate: +does greedy output or any tensor differ from the pinned `stra169-ladder` Original (old pin, which stays the reference). + +## 1.1 Ranked shortlist + +| # | Change | Upstream SHAs and files | Upstream's claimed gain | Value for us | Effort | Numerics vs the Original | +|---|---|---|---|---|---|---| +| 1 | **Route tail skip**: a missed expert that every token of a window routes at rank 7 or lower is neither copied nor computed. Off at 90 percent or more of experts cached, with `--batch`, with NVFP4 experts | `65268d99`, `b4e3407b`, `6ab541f6`, `55e2072c`; `src/core/expert_source.cpp` (~4763-5083), `src/program/generate.cpp` (~10110) | decode +10..20 percent on 12-16 GB cards (3060 x1.156, A4000 x1.129, P100 x1.146); +11.5 percent RTX 5090 with an NVFP4 pack; KL 0.003-0.006, perplexity x1.005-1.011 against skip off | High: cuts the CPU-pool share of the window. Expected effect on our IQ3_S pack is unknown; the claims are on other packs | S, 1-2 d (`original_serve_pool.rs` group split) | **Changes output.** Experimental flag only; own quality gate first | +| 2 | **sm_120 bitwise decode set**: `SIDE_MIXER=2`, `ATTN_DAILY`, `GR_UP75`, `GR_DOWN_TG=1`, `GU_SWIGLU`; interleaved MMVQ for 2-4 columns (default on CUDA), 5-8 columns with sm_120 tables | `ba2c2d5f`, `94104176`, `75afe3f4`, `75fabbd9`, `44997124`, `b1e0fdaa`, `ffac97f7` (+`668072aa`), `731528be`, `ffc30b8d`; `include/strata/core/sm120_series.hpp`, `fused_gr.cu`, `qsa_decode_attn.cu`, `native_mmvq.cu`, `iq_kernels.cu`, `verify.cpp` | RTX PRO 5000 (110 SMs, all experts in VRAM): 4-token round 13.70 to 11.80 ms, decode +13.6..15.8 percent; head at 5 columns 899 to 491 us | High for the GPU share; our windows reach T=5-6 where the old code falls back to `native_mmvq_multi` | M, 4-6 d plus re-sealing PTX | No (commits say bitwise; parity tests `mmvq_il_parity`, `qsa_merge_daily_parity`, gr parity) | +| 3 | **Non-finite fixes**: q8_1 scale/sum clamps, NaN guard with self-healing, prompt retry after a non-finite window | `2b726ba6`, `f6601bf8`, `7a0e3023`, `e372d4ff`, `f332a855`, `894f133b` | fixes "!!!!" degeneration (#606, #879) | High as correctness; our sealed `q8_1_store`, `native_quantize_q8_1`, SwiGLU quantizer, `gr_q8_tail`, `gdn_q8_1_store` copies probably have the old formula | S, 1-2 d | Finite blocks claimed bit-identical; only overflowing blocks change (they were garbage) | +| 4 | **QSA top-k at long context**: 1024-thread "wide" kernel past ~135K cells; on sm_90+ thread-block-cluster top-k and cluster greedy argmax | `586367cb`, `d05d26e9`, `6ef23b89`; `qsa_select.cu`, `sampler.cu` | 9-12x at 262K-524K cells; per call 200 to 22 us at 262K (5070); argmax 39.6 to 5.9 us; 243K prompt +26 percent (3060) | High at our 262K and 512K contexts | S-M, 2-3 d | No ("same ids"; `qsa_topk_parity`, `decode_cluster_parity`) | +| 5 | **Bitwise prefill kernels**: GDN recurrence with 3 value heads per thread, no dead FP32 store in the output norm; quantize each token's MoE input once and scatter it; `DEQUANT_WIDE` (default on sm_86) | `4e69f974`, `c675f5b7`, `5f843a92`; `src/prefill/kernels.cu`, `prefill.cpp` | 18.8 to 13.0 and 4.65 to 3.05 ms per layer at 32K; 5090 32K quantization 77.5 to 58.1 ms; 3060 TTFT -12..20 percent | Medium (TTFT) | S-M, 2-4 d | No ("same bits"; `gdn_rec_parity`, `prefill_mmq_scatter_test`) | +| 6 | **Callback-thread affinity**: one no-op host callback before the host thread pins itself | `0e20d9ae`, `c08fd902` | 5090 + 9950X: 142.82 to 207.75 tok/s with the adaptive overlap; one callback 985 to 4 us | Check first: our DMA staging uses host functions | S, 0.5 d | No | +| 7 | **#783 decode series and F7 ports**: multi-token router, float4 combine, multi-token GR read/write, fused per-head RMSNorm+RoPE, batched K/V and indexer append, exact-T GDN, 16-lane sub-warp expert kernels, MTP catch-up skipping rejected rows, late shared-expert fork, multi-block argmax, one-token window commits itself, `COMMIT_BATCH` | `1690a4a3`, `ae3b249f`, `822251be`, `44ffa86c`, `fe4de5de`, `088e8a82`, `104a8485`, `2715a752`, `3fd0460b`, `8b5dd7ad`, `868f2ef0`; fixes `0c86bbec`, `9d9c9ca2`, `023dd015`; F7 `3e4aa1d6`, `ca833116`, `352cad8f`, `4a5713fb`, `edc592b1`, `6f3e3810` | graph build on R9700 2.35 to 0.65 ms; otherwise no numbers | Medium-high, but **overlaps our chain kernels** (`docs/chain-kernels.md`): compare item by item before porting | L, 8-12 d | Claimed no (memcmp tests `gdn_parity`, `kv_steps_parity`, `native_multi_parity`, `gr_multi_parity`, `rope_parity` check 6). First versions were not bitwise (`0c86bbec`, `9d9c9ca2`): port the fixed forms | +| 8 | **Expert-tier policy**: `pcie_frac` refined from measured CPU speed (PcieAuto); async tier chosen by measurement; `ADAPT_LAG`, `ADAPT_NOWAIT` (default on sm_86) and its eviction fix | `aa7b0cb1`, `ab97f174`, `b18700c8`, `b437b8ea`, `d69424c9`, `3f2db5e2`; `generate.cpp`, `adapt_async_default.hpp`, `nv_defaults.cpp` | 3060 x1.300 from PcieAuto; sm_86 set +9.6 / +14.6 percent | Medium for the laptop; on the 5090 our own measurement already put the PCIe share at 0.55 | M, 3-4 d | Changes placement, so changes rounding. Their "identity gate" runs `--adapt-every 100000` and never exercises it | +| 9 | **Fused int8 prompt experts** (default on sm_120 with 80+ SMs) | `959e6c34`, `b1e0fdaa`; `src/prefill/moe_fused_iq.cu` | prompt +7.0 / +5.2 / +3.4 percent at 4K / 20K / 98K; KL vs MMQ 0.0002 | Medium | M, 3-5 d | **Changes output** (rounds differently) | +| 10 | **WSL KV host copy** pinned with `cudaHostRegister` (the driver caps `cudaHostAlloc(Mapped)` at about 1 GiB under WSL2) | `c41c0ebb`; `src/core/layer.cpp` `kv_host_alloc` | lifts the cap | Medium for laptop WSL runs | S | No | +| 11 | **CPU expert rows**: router dot accumulators in registers; Q5_1/Q8_0 down-row dots; 512-bit gathers (Intel); default worker count | `2a669f3c`, `79376a27`, `16c4da94`, `5ece068f` | router 2.1x (Zen 3), down rows 1.24-1.30x (Zen 5) | Medium: `crates/native-cpu-expert` vendors these files, so it is a copy job | S | No (bit-identical to ggml, FNV-hash tested) | +| 12 | **Chunked GDN prompt recurrence** (opt-in) | `0f78032f` | 1.81x on the recurrence (5090); 32K prompt -3.7 percent | Low-medium | M | Changes output | +| 13 | **Speculation extras** (cost-aware MTP window, probabilistic acceptance, DFlash2 drafter, `--lookup-chain`, `--mtp-q4`), all opt-in | `68781055`, `5f49ec45`, `d232721d`, `b1ebc3d7`; `33356f72`; `7f97c35a`, `5bc7f8ca`, `89799596`, `ff9ca03f`; `2312c83b`, `e35a061f` | spec-prob: none on a 3060; the rest unpublished | Low; compare ideas against our adaptive window only | L for DFlash2 | Probabilistic acceptance and `mtp-q4` change output | + +Not worth taking: Qwen3.6-35B-A3B path (`src/qwen35`, a different model family), Metal/SYCL/HIP-only changes, the K8V4 streaming and elastic KV +(`--kv-grow`; our serve path excludes K8V4). + +## 1.2 What we already have under another name + +| Upstream feature | Our equivalent | Remaining delta worth looking at | +|---|---|---| +| Conversation cache, parking, `pin=N` prefix, message-boundary checkpoints (`f0010a60`, `d9cb22d2`, `940011da`, `c9e571e0`, `13d14a49`, `9c139846`, `b5de344b`) | cross-session prefix cache with request-end checkpoints (`docs/prefix-cache.md`) | park-gain (claimed 1418 parks to 1), evict-to-pass-the-RAM-gate, `pin=N` for the shared system prompt and tools block. More cut points change greedy tokens, so each is a numerics decision | +| Cost-aware MTP window, `spec_min_p` | MTP depth-4 adaptive window (`spec_min_p 0`, +5.1 percent measured) | none to port; compare the cost model on paper | +| KV host copy streaming, KV upload overlapped with prefill, `STRATA_RING_BYTES` | INT8 KV streaming; expert-stream prefill overlap | the `RING_BYTES` default changes bits on native packs for long prompts (see 1.3) | +| 4096-byte direct reads (`direct_file`, PLE/expert stores) | 4 KiB aligned expert copies | none | +| Adaptive expert tier, residency table, lookahead, VRAM/PCIe/CPU tiers | expert tiers (VRAM slots / PCIe stream / CPU pool), seed residency, lookahead | PcieAuto, async-by-measurement, ADAPT_LAG (row 8) | +| Fused norm+RoPE, batched appends, multi-token GR (#783) | chain kernels | row 7: compare list against `docs/chain-kernels.md` | +| PLE table with row cache (table-driven formats Q8_0/Q5_1/Q4_0/BF16/NVFP4) | KAR level-2 PLE rows (50-byte rows) with a bounded GPU row cache | their formats are other quantizations of the same table; nothing to port | + +## 1.3 Defaults flipped upstream (relative to 0.1.35) + +An upstream build now behaves differently from the old pin with no flags. For any A/B against the Original set these explicitly: + +| Default now on | Changes output? | Old behaviour | +|---|---|---| +| `STRATA_ROUTE_TAIL_SKIP=7` (CUDA serve, under 90 percent cached; `b4e3407b`) | yes | `STRATA_ROUTE_TAIL_SKIP=0` | +| PcieAuto (CUDA, one GPU, no `--pcie-frac`) | yes (placement) | `STRATA_PCIE_FRAC_DEFAULT=old` | +| `STRATA_PREFILL_CPU_SHARE=auto` for chunks under 1024 tokens | yes (mean KL 0.004) | `=0` | +| `STRATA_RING_BYTES` (#583) on native packs | yes for long prompts | `=0` | +| sm_120 set (bitwise) and `PF_FUSED` on 80+ SM cards | `PF_FUSED` yes, the rest no | `STRATA_SM120_PERF=0`, `STRATA_PF_FUSED=0` | +| sm_86 set: `ADAPT_NOWAIT`, `ADAPT_LAG=2`, `CPU_IQ_ALL_EXACT1`, `SIDE_MIXER=2`, `ATTN_DAILY`, `GR_UP75`, `GU_SWIGLU`, `QSA_ROWS`, `B6_MMVQ_ROWS`, `DEQUANT_WIDE` | adapt flags yes | `STRATA_SM86_PERF=0` | +| async adaptive tier chosen by measurement | yes (placement) | `--adapt-async 0` | +| bitwise switches: `COMMIT_BATCH`, `ONE_TOKEN_COMMIT`, `HEAD_MIX_MULTI`, multi-block argmax, fused norm+rope, `MMVQ_IL`, cluster top-k/argmax (sm_90+), MTP catch-up skip, `SH_FORK_LATE` | no | n/a | +| `STRATA_NAN_GUARD=1` | no | n/a | +| `--conversation-cache-mib` 0 to auto (parking on); `--ple-inflight` 64 to 256; `--ple-io direct` no longer switches itself to mmap | cache sizing only | `--conversation-cache-mib 0` | +| Server: a request with no sampling gets the model card's sampling instead of greedy (`a8091f4d`); `max_tokens` keeps a quarter for the answer (`d0e990ba`); empty assistant turns dropped (`ffbc39f4`) | yes (server side) | send explicit sampling | + +## 1.4 Upstream fixes that may be bugs in our port (check these first, they are cheap) + +1. q8_1 overflow becoming NaN (`2b726ba6`, `f6601bf8`, `7a0e3023`, `e372d4ff`): see shortlist row 3. +2. `--dump-logits` on a native pack wrote a header claiming 64-66 rows and wrote none (`504579da`); a reader that trusts the header reports + "0 differing positions". **Check whether any of our parity harnesses compared against the Original this way.** +3. Spec window and MTP drafts near the context end ran past `max_cells` and killed the request with "ran out of context" (`e85567b6`). +4. PLE `gather_batch` matched prefetched rows by position, so reordered or duplicated keys were read twice (`36381540`). Check our async PLE reader. +5. Control-token text (`<|im_end|>`, ``) inside message content was encoded as real special tokens (`c16f31f8`, `98b7ea94`, + `0d613031`). `crates/tokenizer` parses specials across the whole rendered prompt: probably the same prompt-injection bug. +6. Residency table uploads must wait for their own copy (`53ab5f71`); non-waiting swaps made greedy decode non-reproducible (`63b4bf0c`) + (our port already waits, `3eb7405`). +7. Conversation cache: a request cancelled between two prompt windows lost the conversation it had restored (`8824e217`); a full cache dropped + the snapshot instead of evicting (`940011da`); 1-token prompt with `--spec` (`aece46db`). +8. Callback-thread affinity (`0e20d9ae`), shortlist row 6. + +--- + +# Part 2. Can KAR host a second MoE model? DeepSeek-V4.1-Flash against our KAR runtime (owner priority 2) + +The owner's statement: "KAR can be applied to any MoE model". Checked against upstream's DeepSeek engine (`src/dsv41`) and against our KAR +code (`docs/compressed-runtime.md`, `crates/model-format/src/kar*.rs`, `crates/leleka-runtime/src/model_binding/kar_expert_source.rs`, +`crates/leleka-runtime/src/qwen_forward/original_serve_*.rs`). Short answer: **the KAR container and codec are model-agnostic; the expert +source, the tier machinery and every kernel are Qwen3.8 geometry compiled in; and for the official DeepSeek 2-bit sets KAR level 2 does not +save memory, it costs more.** + +## 2.1 How DeepSeek-V4.1-Flash stores and streams its experts and Engram + +All from `src/dsv41` and `docs/DEEPSEEK41.md` at `41cf05a0`; sizes are upstream's. + +- **Model files stay as they are.** `tools/dsv41/pack_gguf.py` writes a small "pack" beside the GGUF shards (`ds4.txt` geometry, + `tensors.txt` with `t `, `engram.bin` hash header, tokenizer, template); no weights are + copied. The routed experts are one tensor per layer and role (`[n_exp][out][in]`); every expert is three matrices at three file offsets. +- **Expert formats.** Official ISTA-DASLab sets (GSQ-RCO): IQ1_M 1.75 bpw (121 GB), IQ2_XXS 2.00 bpw (138 GB), IQ2_XS 2.25 bpw (155 GB); + Unsloth UD-Q8_K_XL: MXFP4 experts (288.8 GB for 15,360 experts of about 18.8 MB). 40 layers, 384 experts, 6 used. Dense weights Q8_0/Q5_K/BF16 + (16.8 GB). Kernels: dp4a token path, nvcuda::wmma F16 tensor-core prompt path on CUDA, matrix-core tiles on HIP gfx11/gfx12 only, AVX2/AVX-512 + rows on the CPU. +- **Three tiers, the same shape as Strata's and ours:** + 1. VRAM: "as many experts as fit" (`--vram-experts` fraction, ranked by the shipped hot-expert profile `data/dsv41/profile-2.00.bin`), + in slots in the engine's blob layout (gate | up | down). + 2. RAM: `ExpertStore` (`src/dsv41/ds4_store.hpp`): a fixed arena of slots in the same blob layout, filled by unbuffered 4096-aligned + reads (8192-byte gaps between matrices for the aligned spans), LRU or LFU replacement (`--ssd-policy`), pinned while a window computes + them, filled on demand and by the lookahead's guesses, registered with the GPU so kernels read hits over PCIe zero-copy through the same + plan pointers as VRAM experts. Auto-sized to free RAM minus 12 GB. + 3. SSD: the GGUF in place (`--mmap-experts`), with the CPU lane computing whatever is not in VRAM (`ds4_gguf_cpu.cpp`, `ds4_iq_cpu.cpp`, + computing store hits while misses are read, `6fcde7e3`). +- **Engram (the 111 GB IQ4_NL table, or 203 GB Q8):** read on demand from the SSD with `pread`, never loaded whole. A token's rows depend + only on its id (compressed-vocab map, per-layer multipliers, XOR roll, `rolling % prime + off`), so the reads for a window are issued as + soon as the tokens are known and collected just before layers 1 and 14 (`src/dsv41/ds4_engram_io.hpp`): 24 rows per layer per token, on + their own reader threads, with a bounded clock-eviction row cache. Row formats: MXFP8, Q6_K or IQ4_NL. +- **Structural reading:** upstream's expert RAM store is a sibling of the Strata expert pool (same 4096 alignment, blob layout, lookahead, + LRU/LFU, pinned during the window, CPU lane on misses); the Engram reader is a sibling of the Qwen3.8 PLE n-gram table reader (rows + addressed only by token ids, prefetched before the layer that adds them, row cache). Both are the two things we already built for Qwen. + +## 2.2 What KAR is in our tree + +- **Container and codec** (`crates/model-format/src/kar.rs`, `kar_levels.rs`, `kar_nested.rs`, `kar_kernel_model.rs`; spec: koference + `format-kar-v2.md`): one KAR-2 archive per model with source digest and directory digest; per tensor, nested MSB-first bit planes with + group-of-32 f16 scales and f16 codebooks; runtime levels 2..5 read the first N planes. Sources are F32/F16/BF16; GGUF quantized types are + handled through a "virtual F32 identity" (the quantized block values expanded to F32, `model derive-*-identity`), so any tensor that can + be dequantized to F32 can be put into KAR. In that sense "any MoE model" is true at the container level. +- **Expert source** (`kar_expert_source.rs`): decodes `ffn_{gate,up,down}_exps` of every layer on demand through a closed CUDA program + (`kar_decode_levels_gpu`) into bounded F32 scratch, then multiplies and applies SwiGLU. Its own header says it is **not verified on a GPU** + (`docs/experiments/2026-10-14-kar-levels-gpu-port.md`). Used in the engine as the `STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS` cache-miss arm + (a local patch, unqualified) and as level-2 PLE rows (50 bytes for 160 values: 5 words of 2 planes plus a scale) with a GPU row cache. +- **Size arithmetic (ours, from block sizes; an estimate):** KAR level 2 is 10 bytes per 32 weights = **2.5 bpw**. Per DeepSeek expert + (about 35.4 M weights): KAR L2 about 11.1 MB, against IQ2_XS 10.2 MB, IQ2_XXS 9.1 MB, IQ1_M 7.7 MB, MXFP4 18.8 MB. So for the official + 2-bit sets KAR L2 is larger than the source and lossy on top (it transcodes an already quantized tensor); it only compresses the MXFP4/Q8 + source (4.25 bpw, 508 GB set) and it is the same story for Qwen3.8's IQ3_S (3.44 bpw), where it is a lossy experiment. KAR's real + property is **selectable precision per level**, not a smaller size than a good 2-bit codec. + +## 2.3 What would have to be generalised + +**In KAR / the expert source** + +| Item | Today | Needed for DeepSeek | Effort | +|---|---|---|---| +| Geometry | `LAYERS=48, EXPERTS=512, HIDDEN=2560, FF=640` in `kar_expert_source.rs`; names `ffn_{gate,up,down}_exps` | a `MoeGeometry { layers, experts, top_k, hidden, ff, per-layer overrides, shared expert, tensor names }` read from the pack (`ds4.txt` / GGUF `deepseek41.*`) | S-M, 2 d | +| Source types | `IQ3_S` and mixed Qwen types via virtual identity | IQ1_M, IQ2_XXS, IQ2_XS, MXFP4, MXFP8, trellis TQK: new dequantizers in `quant-core` / `model-format` (we have IQ2_S, IQ3_S, IQ3_XXS, IQ4_NL, IQ4_XS reference parity, not these) | M, 4-6 d for the 3 IST-DAS types plus MXFP4 | +| Expert layout | three 2-D matrices; blob = gate, up, down | DeepSeek's `[n_exp][out][in]` with 3 separate file offsets: fits the same "three ranges per expert" model | S | +| Expert FFN math | SwiGLU, 512 x top 10 sigmoid/softmax router | sqrt-softplus biased top-6 of 384, renormalised, `--experts N`; check activation clamp in `ds4_kernels.cu` (not read) | model-specific, see below | +| Value of doing it | n/a | only for the MXFP4/Q8 source set (508 GB); no benefit over the official 2-bit sets (2.2) | decide before building | +| Engram | n/a | a tensor class of row-gathered n-gram tables: our PLE reader (`model-format/ple_reader*`, 90-byte IQ4_NL rows, KAR 50-byte rows, row cache) generalised to a row size, a format and a row-address function; Engram lookups are 24 rows x 2 layers per token | M, 4-5 d | + +**In the runtime.** Geometry is compiled in. The named constants (`EXPERTS = 512`, `TOP_K = 10`, `LAYERS = 48`, `HIDDEN = 2560`, `FF = 640`, +`VOCABULARY = 248_320`) are defined in 17+ files, and the literals 512, 2560, 640, 248320 appear in 94-189 files each (tests and docs +included). Concretely: + +- `crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs:26-28` (`HIDDEN`, `TOP_K`, `EXPERTS` as i32; `index = [usize::MAX; EXPERTS]` + stack arrays, `layer >= 48`, a 10-wide selection `[u32; TOP_K]`, the window of at most 8 rows, `PCIE_EXPERTS = 12`); + `original_serve_residency.rs`, `original_serve_lookahead.rs`, `original_serve_seed.rs`, `cache_profile.rs`, `cache_strata_adaptive.rs`, + `moe_route.rs`, `moe_prefill_batch.rs` (runtime and `cuda-driver`), `mtp_original_physical_layout.rs`, `original_file_expert_source.rs`, + `model_binding/qwen4exp_moe_expert.rs`, `native-cpu-expert/src/lib.rs` (`FF = 640`); +- `crates/cuda-driver`: 98 `.cu` files and sealed PTX with pinned shapes (head dim 256, `N_EMBD` 2560 in `gdn_fused_t1.rs`, 12 QSA layers in + `qsa_selected_kv.rs`); a different geometry means new kernels or re-sealing, not a constant change; +- the tokenizer is pinned to the `qwen35` pre-tokenizer (`crates/tokenizer/src/lib.rs`), the chat template and reasoning wrap-up text are + Qwen's, `<|im_end|>` is hard-coded as the stop token in places. + +Turning those 17 constants into a `ModelGeometry` value threaded through the pool, residency, lookahead and seed code is mechanical but wide +(M, 5-8 d) and must keep the Qwen path bit-identical (rerun the quality gate). It is only worth doing if we host DeepSeek in our own runtime; +hosting `strata-dsv41` as an external worker (part 3) needs none of it. + +## 2.4 Model-agnostic and model-specific parts + +| Model-agnostic (reusable for a second MoE) | Model-specific (Qwen3.8-Flash-Next only) | +|---|---| +| Expert archive and file formats: KAR-2 container and codec, GGUF index/digests/sharding, `gguf_expert_file_source`, pack index | Attention: QSA indexer + sparse selection + KV layout (INT8 KV streaming) vs DeepSeek's 128-row sliding ring plus compressed FP4 KV and a lightning-style indexer (both have a top-k indexer, but the kernels differ) | +| Tier machinery: VRAM slots, PCIe stream, CPU pool, residency table, lookahead, seed residency, ledger, adaptive tier policy, 4 KiB aligned copies, pinned arena plan (all take (layer, expert) ids and byte ranges; only the constants are Qwen's) | GDN (gated delta net, Qwen only); DeepSeek instead has hyper-connections (mHC, Sinkhorn) | +| Streaming/prefill overlap scheduler | Router (512 experts, top 10) vs DeepSeek's sqrt-softplus biased top-6 of 384; shared expert | +| Prefix cache and request-end checkpoints (policy, keys, eviction); the state **codec** is model-specific (Qwen: GDN states + KV; DeepSeek: window rings, compressor partials, compressed KV, about 17 MB per 6.5K tokens) | Head, embedding, vocabulary (248,320), sampler ABI | +| Memory governor (`leleka-memory`), serving-policy, deploy, preflight, gateway (`control-plane`: HTTP surface, queue, supervisor, switching, MCP hub, auth) | Drafter: MTP depth-4 vs DeepSeek's DSpark; PLE table vs Engram (same reader pattern, different rows) | +| Row-addressed n-gram table reader and row cache (PLE today, Engram tomorrow) | Tokenizer pre-tokenizer, chat template, tool-call format (Qwen `` vs DeepSeek DSML), reasoning budget, stop tokens | +| Quality-gate machinery (`docs/quality-gate.md` harness, paired A/B scripts) | All fused kernels, PTX seals, MMQ/MMVQ tables, GDN chain kernels | + +## 2.5 Recommendation + +1. Do **not** make KAR the path to a second model. For DeepSeek the official 2-bit sets are smaller than KAR level 2 and already tiered by the + upstream engine. +2. Host DeepSeek as a second supervised worker (`strata-dsv41`) behind our gateway (part 3). The model-agnostic parts we own (gateway, memory + governor, switching) are exactly what that needs; the tier machinery, Engram reader and kernels come with upstream's engine. +3. If we later want a second MoE **in our runtime**, the first step is the `ModelGeometry` refactor above, validated by a bit-identical Qwen + run, not KAR work. Keep KAR for what it is good at: level-selectable precision of Qwen3.8's PLE and (after a GPU check) experts. + +--- + +# Part 3. The DeepSeek-V4.1-Flash engine (b) + +## 3.1 Architecture as implemented (`src/dsv41/ds4_model.cu`, `ds4_kernels.cu`) + +Imported from Project Maya `maya-ds4` v1.1.17 (MIT, `third_party/project-maya`) at `bbd0a2c6`, first built inside Strata at `453cc0d5`; 136 +commits in 5 days since; `src/dsv41` is 23.8 K lines (18.3 K in CUDA files), `tools/dsv41` 6.2 K lines of Python. Geometry comes from the +pack's `ds4.txt`, nothing is hard-coded. + +- 40 layers, 384 routed experts plus a shared expert; router sqrt-softplus with bias, top 6; `--experts N` takes the top N and renormalises + (`3dd11c6d`). Default `auto`: 5 on 16 GiB of cards or less, or on a GPU that shares system RAM (`c4ce40bf`); 6 elsewhere (`ds4_experts_rule.hpp`). + On a 32 GB 5090: 6. +- Attention is not V3-style MLA (no kv_lora). Low-rank Q (`wq_a`/`wq_b`); one shared K=V row per token in a 128-slot sliding ring; learned + sinks; layers with `compress_ratio > 0` also attend to up to 512 compressed rows chosen by an indexer over FP4 index keys. Layers 20-39 own + no compressed KV and read the sharing layers' copies; the chunked prompt path exploits this by default (`8a7102ec`, + `STRATA_DS4_PROMPT_SKIP=1`: layers 20-39 run only on the last 2,668 rows; the comment says exact up to summing order, mode 2 is lossy). Run + our own parity check of mode 1 against 0 before trusting it. +- Hyper-connections: `hc_mult` residual streams, `hc_mix`, Sinkhorn `hc_split`, `hc_post`; fused into one launch for decode (`60d856a1`). +- Engram at layers 1 and 14 (see 2.1). KV: window ring FP8 E4M3 (UE8M0 scales per 32), compressed KV and index keys FP4 E2M1, about + 2.6 KB per token for saved slots. Default `--max-context` 32768 in the engine, 8192 written by setup (the size upstream checked). YaRN RoPE. +- DSpark drafter: the checkpoint's `mtp.*` blocks (8 GB Q8_0), block drafts verified by min(1, p/q); `--dspark auto` loads it only where the + experts nearly fit VRAM, so on a 5090 with a 121-155 GB set it will not load. `--dspark off` still loads it and costs about 7 GB VRAM. +- Thinking on by default (effort low 50 / medium 62 / high 75 / max 100); tool calls are DSML (`serve/dsml.py`, 256 lines, rewritten into the + Qwen `` text form for the shared parser). Vision tower exists, unused by the server in this version. + +## 3.2 How it is served + +- Binary `strata-dsv41` (a separate executable; upstream says a family switch inside `strata` comes later). Flags (`ds4_main.cpp`): + `--pack`, `--gpus`, `--max-context`, `--reserve-mib`, `--vram-experts`, `--cpu-threads`, `--expert-profile`, `--ssd-cache GB`, + `--ssd-policy lru|lfu|lfulru`, `--mmap-experts on|off|auto`, `--dspark`, `--dspark-conf`, `--dspark-block`, `--experts N|auto`, `--tp N`, + `--prefill-chunk`, `--eos`, `--serve`, `--pack-info`, `--version`; offline `--score`, `--ids`, `--spec-eval`. +- **Protocol: a compatible subset of the Qwen engine's stdin/stdout loop.** Requests `GEN [k=v ...] ids`, `GENI`, `STOP`, `QUIT`; + keys honoured: `temperature top_p top_k min_p seed spec dspark_conf pin dspark_cum` (penalties, `pcie_frac`, `cvec` silently ignored). + Output: `READY stop`, `T `, `PP`, `STAT` every 8 tokens, `NOTE`, `ERR`, and a 10-field `DONE`. Upstream's Python `serve/server.py` + drives it with only a family switch; `setup.py` writes `--pack --max-context 8192 --eos 1 --dspark auto [--dspark-conf 0.65]` and + `"engine_ready_s": 3600`. One request at a time; displaced conversations are saved to RAM then disk (`ds4-slots`, 2 GB cap, one week). + +## 3.3 Resource needs and speed (upstream's numbers) + +| Item | Size | +|---|---| +| Sets 1.75 / 2.00 / 2.25 bpw | 121 / 138 / 155 GB | +| Engram IQ4_NL (shared) / DSpark drafter | 111 GB / 8 GB | +| Disk, three sets | 239 / 257 / 274 GB; pack about 6 GB; slots up to 2 GB | +| UD-Q8_K_XL | 508 GB (experts 288.8, dense 16.8, Engram 202.8) | + +Dense weights about 16 GB of VRAM on one card (UD set); RAM should hold the CPU-lane experts (under 40 GB "untested and slow"); Engram wants +NVMe. Speeds: RTX 5070 12 GB + 64 GB RAM + 3.6 GB/s NVMe about 4.7 tok/s decode, 121-231 tok/s prefill; RTX 3060 12 GB + 46 GB about 8-10 tok/s; +4x R9700 about 48 tok/s (2.00) and 80 (2.25). **No upstream measurement on a 5090.** Quality vs the original (4,995 positions): IQ1_M KL 0.217 / +perplexity +21 percent, 2.00 KL 0.170 / +15.5 percent, 2.25 KL 0.107 / +7.3 percent. + +## 3.4 GPU support + +CUDA sm_120 is supported: default `CMAKE_CUDA_ARCHITECTURES 120`, packaging scripts build `86-real;120` (SASS for sm_86 and sm_120), CUDA 13 +needed for sm_120 (CMake warns below 13.0; feed minimum driver 580.65). The Windows build ran on an RTX 5070 and the Linux sm_86 build on an +RTX 3060. On CUDA the IQ and MXFP4 prompt sets use nvcuda::wmma F16 tensor cores, token GEMVs use dp4a, dense prefill uses cuBLAS. The +gfx11/gfx12 WMMA paths and the trellis WMMA are HIP-only (trellis falls back to FMA tiles on CUDA). No dsv41 path in `sycl/` or `metal/`, +none for gfx906. The 16 GB laptop sm_86 card defaults to 5 experts; our memory notes say avoid long laptop GPU jobs. + +## 3.5 Hosting it behind our gateway (cheapest first) + +Our gateway supervises one stdio engine child (`control-plane/src/worker.rs`, `wire.rs`); model switching is an exclusive transaction +(`service_switch.rs`, `scripts/strata-model-switch.py`), which suits a 32 GB card that cannot hold both models. + +| Option | Work | Effort | Verdict | +|---|---|---|---| +| (i) `strata-dsv41` as a second switchable worker profile | ignore `STAT`/`NOTE` lines (`wire::parse_line` errors on unknown tags, 0.5 d); `deepseek3` pre-tokenizer in `crates/tokenizer` with parity vs HF tokenizers (2 d); load the GGUF Jinja template and port goldens (1-2 d); port `dsml.py` and its 60 tests, `tool_choice`, calls inside thinking (2 d); family plumbing: stop id 1, effort map, defaults, refuse penalties/images/cvec (1-1.5 d); live bring-up on the 5090 (1-2 d). `startup_timeout_s` already allows 3600 | **M, 7-10 d** | recommended; production stays Python-free | +| (ii) upstream Python `serve/` as a DeepSeek sidecar | 0.5-1 d | S | violates "production serving independent of Python"; use only offline as an oracle for goldens | +| (iii) Rust port of the engine | 23.8 K lines + 5.1 K vendor + ggml-cpu dependence; reusable from `cuda-driver`: driver, arenas, PTX pipeline, IQ2_S/IQ3_S/IQ3_XXS/IQ4_NL/IQ4_XS kernels; missing: IQ1_M/IQ2_XXS/IQ2_XS, MXFP4, FP8/FP4 KV, compressor, indexer, sparse attention, mHC, Engram I/O, RAM store, DSpark, TP, CPU lane | **L, 8-14 weeks**, chasing about 27 commits a day | not now | + +Risks: lossy defaults to pin in any quality gate (`--experts`, `STRATA_DS4_PROMPT_SKIP`, DSpark acceptance, the 2-bit quants themselves); +slot files are model state on disk (retention and privacy); 3600 s cold loads; one request at a time; unmeasured on a 5090. + +--- + +# Part 4. New tools and features worth knowing (c) + +Ranked by likely use to us: + +1. `tools/quant_quality.py` + `data/quant_quality/v1` (committed `set.ids.json`): fixed code/docs/English/multilingual/agent set, teacher-forced + top-64 log-probs, top-1 agreement, mean/p99 KL, perplexity. Directly usable as a quality-gate set; `strata-dsv41 --score` writes the same TSV. +2. `tools/agent_turns_bench.py`: deterministic paired A/B over 23 coding-agent turns (2.5K-100K tokens, shared prefixes, mirrored arm order, + fresh server per arm). Matches our "paired A/B on the same workload" rule. +3. `tools/dsv41/smoke.py` (16-token "Paris" check) and `strata-dsv41 --pack-info`: cheap readiness gates. +4. Signed update feed (`packaging/UPDATES.md`, `strata_control/update_keys.json`, `strata_control/dsv41_engine.py`): Ed25519 feed key signs + `strata-feed.json` and every package manifest; client checks pinned key id, channel, expiry, sequence (anti-replay and anti-downgrade), + archive SHA-256, manifest signature, every file hash, then a test start. Weak spot: the one-line installers (`install.sh`, `install.ps1`) + check the Terminal archive only against a manifest from the same GitHub release folder, so the first install's root of trust is GitHub + HTTPS plus the release account. Nothing was run. +5. `strata_cli`: `launch [--plan --yes --no-tui]`, `tune`, `bench run|compare|report`, `timeskip`, `components verify`, `doctor`, `update`; + `tests/tuning` has a stub engine and session worth copying for testing our supervisor; `tests/time_skip` has negative tests that insist a + missing check never becomes a pass (a model for our gate state machine). +6. **Windows** (relevant to the laptop): `START-HERE.bat` / `SETUP.bat` bootstrap Python and run setup. A source build needs Visual Studio 2022 + (C++20; nvcc silently drops `-std=c++20` under VS 2019, #3566; CUDA 13.0-13.2 rejects VS 2026). `packaging/build_dsv41_windows.bat` uses + CUDA 13.0, `86-real;120`, static cudart, needs `STRATA_GGML_DIR` (pinned llama.cpp `3cf03257`), produces a 66 MB exe. No Windows CUDA build + script exists for the Qwen engine except through `setup.py`; `packaging/build_cuda_linux.sh` is the Linux reference. +7. `apps/host` (Node server + TypeScript/Vite UI on 127.0.0.1:8791 driving Python Control on 8080: model catalog, downloads, monitor, agents, + tunnels) and `apps/desktop` (Tauri shell): not relevant to our gateway. SYCL (`sycl/`, Intel Arc) and Metal (`metal/`, Apple Silicon): Qwen + only, no DeepSeek. `tools/trellis`, `tools/dflash2`: research. + +--- + +# Part 5. Compatibility with our artifacts and deploy flow (d) + +| Area | Status | +|---|---| +| `serve/chat_template.jinja`, `serve/chat_golden.json`, `tests/data/native_experts/*.txt`, `LICENSE`, `serve/mcp_fake_server.py` (all `include_str!`'d or used as goldens by `control-plane`) | unchanged upstream; our Rust tests are unaffected | +| Native pack (`native_experts.txt` v3/v4), `tools/mtp_rt.py`, `mtp_pack.py`, `pack_index.py`, `src/core/mtp.cpp` | unchanged layout; `mtp.cpp` adds opt-in flags only. v5 plus `hadamard.txt` is only for Hadamard-folded packs. `iq_pack` now keeps IQ3_XXS/IQ4_XS PLE keys native instead of BF16 (`035da7f8`): our `native_pack.rs` would diverge on such models; resumable `experts.bin` writes (`970c75c8`) | +| `tools/mtp_fetch.py` | rewritten for multi-connection SHA-pinned downloads (`e193161d`, `96a9107a`); output layout not checked, our `mtp_fetch.rs` mirrors the old script | +| Expert profiles (`data/expert-profile*.bin`) | the engine now refuses a header version other than 1 (`536db01a`); the layout is the same, so ours are fine | +| KAR archives | upstream has no KAR; the local patches are re-applied (docs/upstream.md); GPU behaviour of the KAR arms is unverified on the merged tree | +| GGUF shards | no format change; the engine now identifies the family by name and reads geometry from metadata (`f812e9a1`, `51329cff`); all-zero `compress_ratios` treated as absent (`94d189fc`); `tools/gguf_reader.py` +4 lines, not read | +| Tokenizer | ids for ordinary text unchanged; `plain=` spans change ids only for messages containing control-token or think-tag text (`f346dc6b`, `f13a870d`; the bug in 1.4 item 5) | +| Engine serve protocol | backward compatible: new optional `GEN` keys (`logit_bias`, `ckpt`, `pin`, `pipe`, `aux_cpus`, `img_keys`) are skipped by the engine when unknown; `DONE` has trailing fields (our `parse_done` reads the first 10); `INFO` starts with `logit_bias=1` (we ignore it). **Risk:** `control-plane/src/wire.rs::parse_line` errors on any unknown tag. A new engine run with `--batch`, session files or `/v1/vram` emits `BT`, `BDONE`, `BADM`, `YIELDED`, `BSTAT`, `PSTAT`, `VRAM`, `SAVED`, `RESTORED`, `SERR`, `SWAIT`, `FATAL`, `SESSION`, and our worker would break. Do not enable those without extending `wire.rs` | +| CLI flags | none of the 132 flags the old parser matched was removed; 48 added. Defaults changed as in 1.3 | +| Engine config `"args"` | a single entry `"--flag value"` is now split into two (`8101a890`); `--reasoning-effort` in args is lifted into a top-level key (`a6ae2475`); new `user_args` and `pool_cores` keys; not compared against our `config.rs` | +| `SamplerParams` ABI | `logit_bias` (pointer) and `gumbel` (bool) added (`dcc6f756`, `6381df34`); porting the new `sampler.cu` breaks our checked 64-byte ABI | +| Deploy flow | `scripts/build-cpu.sh` had to list 11 more test targets (done). Upstream's new defaults (1.3) change behaviour of any upstream-built engine, so do not swap it into the deploy profile without the explicit old-behaviour switches. Upstream's `docker-entrypoint.sh` moved to `docker/entrypoint.sh` | + +--- + +# Part 6. Build plan for the new Strata CUDA engine with `strata-dsv41` on the 5090 server (NOT RUN) + +Assumptions: Linux, RTX 5090, CUDA 13.2.2 at `~/cuda-toolkits/13.2.2`, driver at least 580.65, 38 GB free of 260 GB disk. **Nothing below was +executed, and nothing may be downloaded until disk exists.** Sizes and times are estimates. + +1. NOT RUN. Pinned llama.cpp for ggml-cpu (about 100-300 MB): `git clone https://github.com/ggml-org/llama.cpp ~/src/llama.cpp && git -C ~/src/llama.cpp checkout 3cf03257f219afbe7334045ff7c6a06ac68c627d` +2. NOT RUN. Export the merged tree with LF endings and a build id: `git -c core.autocrlf=false archive engine/strata | tar -x -C ~/work/strata-src --strip-components=2 && echo <9-hex> > ~/work/strata-src/BUILD_ID` (the dsv41 binary must carry a build id, `--version` prints "unknown" otherwise) +3. NOT RUN. Configure out of tree (build dir about 2-4 GB for one arch and the dsv41 targets; ccache optional): + ``` + export PATH=~/cuda-toolkits/13.2.2/bin:$PATH + cmake -G Ninja -S ~/work/strata-src -B ~/work/build-dsv41 -DCMAKE_BUILD_TYPE=Release \ + -DSTRATA_ENABLE_CUDA=ON -DSTRATA_BUILD_DSV41=ON -DSTRATA_NATIVE_EXPERTS=ON -DSTRATA_BUILD_TESTS=OFF \ + -DCMAKE_CUDA_ARCHITECTURES=120 -DCMAKE_CUDA_COMPILER=$HOME/cuda-toolkits/13.2.2/bin/nvcc \ + -DCUDAToolkit_ROOT=$HOME/cuda-toolkits/13.2.2 -DSTRATA_GGML_DIR=$HOME/src/llama.cpp + ``` + Do not add `STRATA_CUDA_STATIC=ON` for the first build (static cublasLt is several hundred MB and links slowly; the `-static-libstdc++` flag + applies to `strata` only). `STRATA_PORTABLE=ON` is what upstream packages use; leave it off for a native build. The `ds4_*` test targets + are gated on `STRATA_NATIVE_EXPERTS`, not on `STRATA_BUILD_TESTS`. +4. NOT RUN. Build only what is needed (estimate 15-40 min at `-j8`: `ds4_model.cu` is a 9.4 K-line unit): `ninja -C ~/work/build-dsv41 -j 8 strata-dsv41 ds4_slot_test ds4_experts_rule_test ds4_pick_rule_test ds4_iq_test ds4_tq_test ds4_gg_bench` +5. NOT RUN. No model, no GPU: `strata-dsv41 --version`, `ds4_slot_test`, `ds4_experts_rule_test`, `ds4_pick_rule_test`, `ds4_gg_bench`. +6. NOT RUN. One GPU, no model: `ds4_iq_test`, `ds4_tq_test`. +7. Blocked by disk: `--pack-info` needs a real pack (no tiny pack exists upstream). The 2.00 set needs 257 GB (138 + 111 + 8) plus about 6 GB + for the pack; even 1.75 needs 239 GB. With 38 GB free nothing fits: a dedicated NVMe of at least 300 GB (512 GB preferred) is required, + because Engram wants NVMe. RAM 121 GB holds the 1.75 set's CPU-lane experts; the 2.00 set is tight. +8. Packing is offline Python: `python tools/dsv41/pack_gguf.py --model SET --shards ... --engram engram-IQ4_NL.gguf --engram-meta [--dspark-gguf ...]`; + do not add `--skip-tensors` or `--dense-override` (upstream: they pack without error and give garbage text). + +--- + +# What was not read + +- Most of the ~11.7 K-line `generate.cpp` diff (only options, the `GEN` parser, protocol prints, tail-skip and PcieAuto blocks), most kernel + bodies, `expert_source.cpp`/`prefill.cpp`/`verify.cpp` beyond sampled sections and the merge hunks; `serve/server.py` and `strata_control/` + beyond subjects and one diff; `setup.py` policy changes against `setup_policy.rs`; `tools/gguf_reader.py`; the `mtp_fetch.py` rewrite; the + DFlash2 and SPEC_COST code; `src/qwen35`; HIP, SYCL, Metal; `bench/results`. +- DeepSeek: only focused ranges of `ds4_model.cu` (9.4 K lines); not the DSpark draft/verify bodies, TP all-reduce, store zero-copy paths, + vision or the split-KV attention; per-layer `compress_ratios`, `hc_mult`, `index_topk` and the Engram n-gram values come from GGUF + metadata and were not seen; the IST-DAS per-tensor types beyond "IQ1_M/IQ2/IQ3 experts, Q8_0/Q5_K dense"; the expert activation clamp; + `apps/host` server modules (names only); `install.ps1` in full; `docs/AI_SETUP.md` and `AI_REFERENCE.md` (upstream's agent instructions, + not followed). +- Our side: `original_serve_*` and `kar_expert_source.rs` were read for constants and structure, not audited; the KAR GPU path was not run. +- The size arithmetic in 2.2 is ours from block sizes (KAR level 2 = 10 bytes per 32 weights) and upstream's per-expert size; the DeepSeek + expert weight count (about 35.4 M) is derived from "18.8 MB of MXFP4 at 17 bytes per 32". +- Nothing upstream was executed: no script, installer, binary, or model. No model was downloaded and the 5090 server was not touched. +- The merged subtree's CUDA objects were compiled for sm_86 only (see docs/upstream.md), never run. diff --git a/docs/upstream.md b/docs/upstream.md index cbab5eed..5ce46dc4 100644 --- a/docs/upstream.md +++ b/docs/upstream.md @@ -1,20 +1,135 @@ # Strata upstream provenance -**Status:** source imported as a local Git subtree and preserved in a private hosted repository. +**Status:** `engine/strata/` was brought to upstream `41cf05a0` (engine 0.1.50, app 0.2.5) on 2026-10-25 on branch +`claude/upstream-sync`, with the local patches re-applied. The previous pin (`d9ab8435`, engine 0.1.35) is kept below and in Git +history (`570201a:engine/strata`). Nothing was pushed. The quality-gate reference build (`stra169-ladder` Original) stays a build of the +OLD pin plus the old local patches; the new subtree is not that reference (see "What this does to the quality reference"). + +## Current pin | Field | Value | | --- | --- | | Upstream repository URL | https://github.com/Niko1221/Strata.git | -| Upstream commit SHA | `d9ab8435f654c368c586340d490915f6addf56a3` | +| Upstream commit SHA | `41cf05a06a25dd29103b7b27a2279a3f60c21876` | +| Upstream commit date | 2026-10-25 11:35 +0100 ("README (all 7 languages): models in the order Qwen3.8-Flash-Next, Qwen3.6-35B-A3B, DeepSeek V4.1-Flash") | +| Upstream version at the pin | engine and Control 0.1.50, Terminal and app 0.2.5 (`1aff6d14`, 2026-10-24) | +| Upstream tree object of the pin | not recorded (the subtree is the pin plus local patches and omissions; the exact differences are listed below) | | Local repository path | `engine/strata/` | +| Update date | 2026-10-25 | +| Update method | documented tree replacement: 3-way `git merge-tree` of the old subtree against the new upstream, base = the old pin (see "How this update was made") | | Hosted project repository URL | https://github.com/paveldhq/strata-next (private) | -| Import date | 2026-10-02 | -| Engine build instructions | `scripts/build-cpu.sh` for source checks; CUDA build still to validate on Linux GPU | -| Local patch strategy | Squashed Git subtree; preserve upstream commit IDs in subtree merge messages | +| Engine build instructions | `scripts/build-cpu.sh` for source checks (needs network once: it fetches llama.cpp `3cf03257f` through CMake FetchContent); CUDA builds: see `deploy/README.md` and `docs/build-validation.md`. Upstream's `packaging/build_cuda_linux.sh` and `packaging/build_dsv41_cuda.sh` are the reference recipes and have not been run here | -The local Git remote `strata-upstream` points to the URL above. To review an update, run `git fetch strata-upstream main`, inspect the diff from the pinned SHA, choose a specific new commit, then run `git subtree merge --prefix=engine/strata --squash ` and the relevant checks. Do not silently advance to whatever happens to be latest. +## Pin history -The imported upstream tree includes its own small optional experimental control-vector GGUF and reference data. Production model weights, captures, and generated output remain outside this repository. The private project repository was created on 2026-10-04; its initial `main` is `858e7aa050f56b051dac5e3d7b765a05cb958aee`. This preserves the existing subtree history and does not change the pinned upstream identity. +| Pin | Upstream commit | Date | Engine | In this repository | +| --- | --- | --- | --- | --- | +| 1 (initial import) | `d9ab8435f654c368c586340d490915f6addf56a3` | 2026-10-02 | 0.1.35 | `engine/strata/` up to `570201a` (git subtree merge `c4e2137` of squash `906afc5de9dd` in the pre-squash history; later squashed into `4013e0c`) | +| 2 (this update) | `41cf05a06a25dd29103b7b27a2279a3f60c21876` | 2026-10-25 | 0.1.50 | `engine/strata/` on `claude/upstream-sync` | + +**Upstream rewrote its history.** `d9ab8435` is not an ancestor of upstream `origin/main` (`git merge-base --is-ancestor` fails). Its +tree is identical (`git diff` is empty, tree `487c4cc0`) to upstream commit `5b734e42` ("Engine 0.1.35", same date), which is an +ancestor of `41cf05a0`. So the real distance from the old pin to the new one is 3630 commits (`git rev-list 5b734e42..origin/main`), not +the 4175 that `git rev-list d9ab8435..origin/main` prints. Both SHAs identify the same source tree; record both when comparing. + +The local Git remote `strata-upstream` points to the URL above. Do not silently advance to whatever happens to be latest: choose a +specific commit, fetch it, review the diff from the pin, and update this file in the same commit. + +## How this update was made (repeat it the same way) + +The pre-squash `git subtree` metadata does not exist in this repository's history (the project history was rebuilt from snapshots), +so `git subtree pull` has nothing to anchor on. The update therefore used a tree replacement that still keeps a true 3-way merge: + +1. In a scratch clone of upstream: `base` = tree of the old pin, `ours` = `git rev-parse 570201a:engine/strata` (the old subtree with + the local patches), `theirs` = upstream `41cf05a0`. +2. `git merge-tree --write-tree --merge-base= `; conflicts were resolved by hand (below); the result was checked by + listing every blob that differs from upstream `41cf05a0` (only the 21 patched files, the 4 added files and the left-out files differ). +3. The result tree went into `engine/strata/` with `git read-tree --prefix=engine/strata/ -u` (`core.autocrlf=false`, LF kept), then the + left-out files were removed from the index and the working tree. +4. `docs/upstream/local-patches-on-0.1.35.patch` is the patch that was re-applied (old pin to old subtree, 25 files); + `docs/upstream/local-patches-on-0.1.50.patch` is the same patches as they stand on the new pin (new pin to new subtree, 25 files). + The next update should treat the second file as its `ours` side: the merge base is then `41cf05a0`. + +## Local patches (as re-applied, 2026-10-25) + +All of them are default-off or build-profile only. None changes the default behaviour of the engine. + +| Local patch | Files | Status after the update | +| --- | --- | --- | +| `STRATA_CUDA_STATIC` CMake profile (static CUDA toolkit libraries and GNU C++ runtime, Linux; STRA-23, `a36e45a`) | `CMakeLists.txt` | Re-applied. Added `OR STRATA_HIP_GFX906` to its refusal condition (upstream added a gfx906 compat build that also sets `STRATA_ENABLE_CUDA`). Upstream's own tests that link `CUDA::cudart` directly are not switched to the static target (as before) | +| `STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS`: native verifier cache-miss callback to the external `gpu/kar` component (`87fdec7`, `53c9d7b`, `33f075f`, `b6563e3`) | `CMakeLists.txt`, `include/strata/core/expert_source.hpp`, `src/core/expert_source.cpp`, `src/program/generate.cpp` | Re-applied. The callback now runs before the CPU-work scan so `any_cpu` sees what is left; a completed row (`kind == 3`) is excluded from the new zeroing, offload-count and peer-count rules. Compiles (sm_86 objects, with `STRATA_NEXT_KAR_DIR=gpu/kar` of this repository); never run, and not exercised against upstream's new device-plan and route-tail-skip paths | +| Experimental KAR PLE CPU quality arm and compressed GPU row cache, PLE row trace (`80f6670`, `e4d0c2d`, `36e512a`, `78e92d5` telemetry) | `include/strata/kernels/ngram.hpp`, `src/kernels/ngram.cpp`, `src/prefill/prefill.cpp`, `src/program/generate.cpp`, `CMakeLists.txt` | Re-applied on top of upstream's table-driven PLE formats (`fmt->dequant`, recursive mutex, `wait_prefetches`). The GPU-cache arm lands its rows through upstream's new `ple_land` path. Compiles with `STRATA_NEXT_EXPERIMENTAL_KAR_PLE=ON` and `STRATA_NEXT_EXPERIMENTAL_PLE_TRACE=ON` (sm_86 objects); never run | +| Keyless V-only QSA arm (`a8411b5`; failed its quality gate, see `docs/experiments/2026-10-04-keyless-runtime.md`, `docs/keyless-runtime.md`) | `include/strata/core/keyless.hpp`, `src/core/keyless.cpp`, `src/kernels/cuda/keyless.cu`, `src/kernels/keyless_parity.cpp` (new files), plus `layer.cpp/.hpp`, `verify.cpp/.hpp`, `prefill.cpp`, `src/prefill/kernels.cu`, `kv_q8.cu`, `kv_stream.cu/.hpp`, `qsa_decode_attn.cu/.hpp`, `kv_stream_parity.cpp`, `conversation_snapshot.cpp/_test.cpp`, `mtp.cpp`, `generate.cpp` | Re-applied by hand (see conflicts). Needs `STRATA_KEYLESS_ROUTING` and `--kv int8`; refuses K8V4 and the new fused norm+rope; no slots / rows attention variant (falls back to per-query calls) | +| Mode bits | `setup.sh` | The 0644 mode our 2026-10-14 snapshot (`7f896a8`) set on `setup.sh` and `docker-entrypoint.sh` is not carried: `setup.sh` is 0755 as upstream; upstream deleted `docker-entrypoint.sh` (it is `docker/entrypoint.sh` now) | + +Other commits that touched `engine/strata` in the pre-squash history (`b1da05f` first-window logits capture, `78e92d5` telemetry) are +either not part of the tracked snapshot at `570201a` or are the telemetry line listed above; `git grep` for the capture finds nothing in +`570201a:engine/strata`, so nothing was lost by this update. + +### Conflicts and how they were resolved + +Content conflicts (15 files, 44 hunks) and one modify/delete. Everything else in the 25 patched files merged cleanly. + +| File | Conflict | Resolution | +| --- | --- | --- | +| `CMakeLists.txt` (4) | STATIC option next to upstream's new gfx906 block; PLE/KAR targets next to upstream's new gfx1100 score test; `strata_engine` source list (upstream added `remote_expert_opt.cu`, `dflash2`, `peer_experts`, `vmm`, ...); `strata` link options next to upstream's Windows HIP delay-load and the whole `strata-dsv41` block | Union. `keyless.cpp` added to upstream's longer `strata_engine` source list. `STRATA_CUDA_STATIC` refuses `STRATA_HIP_GFX906` | +| `kv_stream.hpp` | Our `kKvValueInt8 = 4` against upstream's new `kKvHybrid = 3` (K8V4 streaming) and its two helper functions | Both: `kKvF16=0, kKvInt8=1, kKvQ4=2, kKvHybrid=3, kKvValueInt8=4` | +| `layer.hpp` | `qsa_kv_format()`: our hard refusal of hybrid state vs upstream's `kKvHybrid` | Upstream's hybrid line first, then ours for `without_key`. The old "hybrid never reaches the block movers" exit is gone because it is now false | +| `kv_stream.cu` (2) | `runs_of()` and `kv_block_bytes()` | Chain `kKvHybrid`, `kKvValueInt8`, `kKvQ4`, `kKvInt8` | +| `kv_q8.cu` | `is_v` computation vs upstream's `MULTI` template parameter | `k_q == nullptr \|\| (MULTI ? (z & 1) : z == 1)`. With keyless + `kv_append_q8_steps` the grid is 2 x tokens and both halves write the same V (redundant, correct) | +| `qsa_decode_attn.cu` (4) | Upstream split the dispatch into `launch_chunks_batch`, `launch_merge_batch`, `qsa_decode_attn_slots`, `qsa_decode_attn_batch_rows`, added lane-cell/gfx906/`attn_v3`/daily variants | Took upstream's structure; `attn_kv_mode()` knows mode 4; mode 4 is dispatched in `launch_chunks_batch` and `qsa_decode_attn_step`; lane-cell is disabled for it; the slots variant returns false and the rows variant goes per row so they fall back to the per-query calls | +| `verify.hpp` / `verify.cpp` (7 hunks) | Our keyless trace members and query routing against upstream's new fused norm+rope, `side_proj`/`q_chain`, `mm()` helper, `collect_profile()`, `launch_o->finish()` | Query routing moved into `norm_rope_on` (between norm and RoPE, all callers go through it); `fuse_nr` is off for keyless; K projection and K norm skipped for keyless; trace members renamed `kl_trace_*` because upstream already owns `trace_h_` (found only by compiling: a clean textual merge produced a duplicate member); the trace writer was re-added after the window's synchronize | +| `layer.cpp` (3) | `qsa_layer` is one giant line; upstream dropped `n_bid`/`width` and re-wrapped the gemv lines | Upstream's text with our `without_key` guards re-inserted | +| `expert_source.cpp` (2) | KAR miss callback vs upstream's `dec_batch`/`gpu_zeroes_hits`/`any_cpu`/`kind == -2` tail skip | Callback first, then upstream's block; kind 3 handled as above | +| `ngram.cpp` (5) | KAR PLE vs `PleFormat` table, `std::recursive_mutex`, `wait_prefetches()` | Upstream's format table; KAR decode and cleanup kept under their macro; `close()` waits for prefetches first; `format()` falls back to `fmt->name` | +| `prefill.cpp` (3) | PLE gpu-cache branch vs upstream's `ple_land`, `C`, pageable PLE ring | GPU-cache branch gathers on the device; else upstream's code | +| `generate.cpp` (9) | Includes, options struct, keyless trace check vs upstream's host-core / pool-cores / aux-cpus / memory-guard blocks, KAR PLE open vs the new direct-read probe, `Drive` setup, request keys, serve-loop epilogue | Union; the PLE direct-read probe is skipped for the KAR PLE arm | +| `kv_stream_parity.cpp` (2) | `append()` and the format name | Both formats | +| `expert_source.hpp`, `verify.hpp`, `kv_stream.hpp` | adjacent member / enum additions | Union | +| `docker-entrypoint.sh` | modified (mode only) by us, deleted by upstream | Deleted (upstream moved it to `docker/entrypoint.sh`) | + +### What this does to the quality reference + +`engine/strata/` on this branch is a different engine from the one the `stra169-ladder` Original was built from: with default flags it +behaves differently from the old pin (upstream flipped defaults on: route tail skip, PcieAuto, sm_120 and sm_86 kernel sets, fused int8 +prompt experts, auto conversation cache; see `docs/upstream-digest-2026-10-25.md`). Do not use a build of this subtree for the greedy/tensor +baselines of `docs/quality-gate.md`. The old pin remains reproducible from `git show 570201a:engine/strata` and from the upstream tree +`487c4cc0` (upstream commit `5b734e42` / `d9ab8435`). Anything compared against the new subtree must set the old behaviour explicitly +(the digest lists the switches). + +## Left out of the subtree (rule: weights, captures, credentials, logs, media and generated artifacts stay out of Git) + +Upstream content at `41cf05a0` that was not committed (2140 files in total; everything else in the upstream tree is committed byte for byte). +The root `.gitignore` already drops `*.bin`, `*.gguf`, `*.log` and `models/`; the rest was left out by the rules below. + +| Group | Files | Why | Where it is | +| --- | --- | --- | --- | +| New `bench/results/**` (community benchmark runs: request captures `requests/*.json.gz`, `*-request.json` prompts, engine logs `*.log`, monitor screenshots, build recipes, fixtures) | 2022 added | request captures and logs; 23 MB; the 162 older files of that directory that the first import carried are unchanged | upstream `bench/results/` | +| Binary media and assets added by upstream | 61 | `apps/desktop/src-tauri/icons/**` and `nsis/*.bmp` (app icons), `apps/host/public/**` (favicons, three GT Walsheim Pro `*.woff2` commercial fonts, an example gif/mp4/pdf), `docs/terminal-previews/*.png` (7), `docs/media/*.png` (2), `docs/media/models/*` | upstream | +| `docs/work/evidence/**` | 24 | test-run transcripts and JSON self-test output (logs) | upstream | +| Model-adjacent binaries that the root `.gitignore` also matches | `data/dsv41/profile-2.00.bin`, `profile-2.25.bin` (hot-expert profiles for the DeepSeek packs), `data/draft_vocab_fr.bin`, `data/expert-profile-sycl.bin`, `tests/fixtures/dsv41/engram-final-header.gguf` | binary data files; needed only to run the DeepSeek engine or its SYCL path | upstream | +| Already left out by the first import and still left out | `data/draft_vocab.bin`, `data/draft_vocab_cyrillic.bin`, `data/draft_vocab_en.bin`, `data/expert-profile.bin`, `data/expert-profile-coder.bin`, `data/experimental-speed-projection/*.gguf`, `bench/results/2026-09-30-community-rtx-5090/engine.log` | same rule | upstream | + +Kept on purpose although they look large: `apps/host` and `apps/desktop` source (TypeScript / Rust text; 8 MB), `tools/qwen35/pictures/*.png` +(three small test inputs), `docs/work/*.md`, `bench/prompts/**` (frozen benchmark prompts, hashed byte for byte), `sycl/`, `metal/`, +`packaging/` (installer scripts, text), `third_party/` (ggml-tq headers, Project Maya license and notice). A scan of every kept blob found +no private key, token or credential pattern. The kept scripts and installers are source only; none of them was run. + +Consequences to know: `data/dsv41/profile-*.bin` must be fetched from upstream if the DeepSeek engine is ever built from this tree; +`apps/host`, `apps/desktop` and the packaging flow will not build from this tree without the left-out icons and fonts. Neither is used by +Leleka. Also, upstream's own `AGENTS.md` and `docs/AI_SETUP.md` tell an agent to run installers and `strata launch --yes`; they are +upstream's instructions for its product and do not apply to work in this repository. + +## Verification of this update + +| Check | Result | +| --- | --- | +| Tree identity: every blob of `engine/strata/` compared with upstream `41cf05a0` | identical except the 21 patched files + 4 new files (and the left-out files) | +| `git diff --stat` for line-ending churn | none (LF kept, `core.autocrlf=false`; the nested `.gitattributes` of the subtree sets `eol=crlf` for `*.bat/*.cmd/*.ps1` as upstream does) | +| `scripts/build-cpu.sh` in WSL Ubuntu 24.04, GCC 13.3, CMake 3.31.6 | 16 of 16 ctest tests pass (the script's target list had to be extended: upstream registers 11 more CPU tests than the old pin; `Not Run` otherwise) | +| CUDA compile (sm_86 only, `nvcc` 13.2, no GPU use) of the patched translation units: `kv_q8.cu`, `kv_stream.cu`, `qsa_decode_attn.cu`, `keyless.cu`, `prefill/kernels.cu`, `prefill.cpp`, `layer.cpp`, `verify.cpp`, `expert_source.cpp`, `mtp.cpp`, `conversation_snapshot.cpp`, `keyless.cpp`, `ngram.cpp`, `generate.cpp`, `kv_stream_parity.cpp`, `keyless_parity.cpp` | all 17 objects compile (warnings only) in the default configuration; the 7 objects that depend on the KAR/PLE macros (`ngram.cpp`, `expert_source.cpp`, `prefill.cpp`, `generate.cpp`, `kar_ple_cache.cu`, `kar_expert.cu`, `kar_expert_miss.cpp`) also compile with `STRATA_NEXT_EXPERIMENTAL_KAR_PLE=ON`, `STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS=ON`, `STRATA_NEXT_EXPERIMENTAL_PLE_TRACE=ON`. The compile found one error a textual merge cannot (a duplicate `trace_h_` member in `verify.hpp`), fixed by renaming ours to `kl_trace_*`. Not built: link, the `strata` binary, the parity tests, the sm_120 PTX | +| GPU parity, quality gate, any model run | not run (by instruction); the keyless, KAR and PLE arms are default off and unexercised | +| Port crates that `include_str!` files from `engine/strata` | none of those files changed upstream (`LICENSE`, `serve/chat_template.jinja`, `serve/chat_golden.json`, `tests/data/native_experts/*.txt`, `serve/mcp_fake_server.py`, `tools/mtp_rt.py`) | ## Local CUDA validation, 2026-10-04 @@ -24,6 +139,8 @@ V-only streaming and conversation snapshots passed. Pretrained-model quality failed; see [the report](experiments/2026-10-04-keyless-runtime.md). The ordinary K+V profile remains the production choice. +(That validation was on the 0.1.35 sources; it has not been repeated on the merged tree.) + ## Local Linux packaging profile, 2026-10-04 STRA-23 adds the default-off `STRATA_CUDA_STATIC` CMake profile: static toolkit @@ -34,6 +151,8 @@ candidate still needs host glibc 2.43 and an NVIDIA driver; model qualification is pending. See `deploy/README.md` and `docs/build-validation.md` for the exact scope, artifact identity and remaining packaging limits. +(Re-applied on the 0.1.50 `CMakeLists.txt`; the ELF audit has not been repeated.) + ## Experimental KAR expert integration, 2026-10-05 The pinned upstream commit remains unchanged. Local default-off @@ -45,10 +164,15 @@ environment settings, validates the archive payload and expert geometry, and rejects unsupported pool/multi-device configurations. This is an experimental quality arm, not full compressed-model residency or a qualified speedup. +(Written against the 0.1.35 sources; re-applied on 0.1.50, see the table above.) + ## Port provenance, 2026-10-25 -`engine/strata/` is unchanged since the import recorded at the top of this file (the Original used as the quality reference and for the -vanilla baselines is a separate build of that commit plus the local patches above). The Leleka runtime under `crates/`, `desktop-core/` and -`control-plane/` is a Rust/CUDA port of the Original mode17 serve path written for this project; it shares the model artifacts and the -algorithms (not the C++ code) with Strata. The agreement of the port with the Original is measured in `docs/quality-gate.md`; the request-end -prefix checkpoints (`docs/prefix-cache.md`) and the chain kernels (`docs/chain-kernels.md`) are port-side additions with their own gates. +The Leleka runtime under `crates/`, `desktop-core/` and `control-plane/` is a Rust/CUDA port of the Original mode17 serve path written +for this project; it shares the model artifacts and the algorithms (not the C++ code) with Strata. The Original used as the quality +reference and for the vanilla baselines is a separate build of the OLD pin (`d9ab8435` / `5b734e42`, engine 0.1.35) plus the local +patches that were in `engine/strata/` before this update; `engine/strata/` itself is no longer that source. The agreement of the port +with the Original is measured in `docs/quality-gate.md`; the request-end prefix checkpoints (`docs/prefix-cache.md`) and the chain +kernels (`docs/chain-kernels.md`) are port-side additions with their own gates. + +A digest of what changed upstream and what is worth taking is in [upstream-digest-2026-10-25.md](upstream-digest-2026-10-25.md). diff --git a/docs/upstream/local-patches-on-0.1.35.patch b/docs/upstream/local-patches-on-0.1.35.patch new file mode 100644 index 00000000..8afc4cee --- /dev/null +++ b/docs/upstream/local-patches-on-0.1.35.patch @@ -0,0 +1,2147 @@ +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 4efc2976..4d9f2ca1 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -34,6 +34,15 @@ endif() + + option(STRATA_ENABLE_CUDA "Build the CUDA targets (Phase 2+)" OFF) + option(STRATA_ENABLE_HIP "Build the HIP targets for wave32 AMD GPUs (gfx1100, gfx1201; gfx1030 unvalidated)" OFF) ++option(STRATA_CUDA_STATIC "Linux GNU engine: static CUDA toolkit and C++ runtimes (host glibc and NVIDIA driver required)" OFF) ++if(STRATA_CUDA_STATIC) ++ if(NOT STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP OR NOT CMAKE_SYSTEM_NAME STREQUAL "Linux" ++ OR NOT CMAKE_CXX_COMPILER_ID STREQUAL "GNU") ++ message(FATAL_ERROR "STRATA_CUDA_STATIC requires Linux, GNU C++, and STRATA_ENABLE_CUDA=ON (HIP disabled)") ++ endif() ++ # Applies to subsequently created CUDA targets, including device-link runtime edges. ++ set(CMAKE_CUDA_RUNTIME_LIBRARY Static) ++endif() + option(STRATA_PREFILL_MMQ "Build the optional GGML MMQ prefill path for HIP" OFF) + # CUDA: MMQ prompt kernels for Q4_K / Q5_K / Q5_1 (Unsloth's UD-Q4_K_XL experts). Off by default: the engine loads + # every kernel when it starts (CUDA_MODULE_LOADING=EAGER), so these took ~5 MB of VRAM - 1-3 expert slots - from every +@@ -110,6 +119,16 @@ if(STRATA_ENABLE_CUDA) + message(STATUS "Strata: CUDA enabled, arch ${CMAKE_CUDA_ARCHITECTURES}") + set(_strata_gpu_runtime_target CUDA::cudart) + set(_strata_gpu_blas_target CUDA::cublas) ++ if(STRATA_CUDA_STATIC) ++ foreach(_required CUDA::cudart_static CUDA::cublas_static CUDA::cublasLt_static CUDA::culibos) ++ if(NOT TARGET ${_required}) ++ message(FATAL_ERROR "STRATA_CUDA_STATIC requires toolkit archive target ${_required}") ++ endif() ++ endforeach() ++ set(_strata_gpu_runtime_target CUDA::cudart_static) ++ set(_strata_gpu_blas_target CUDA::cublas_static) ++ message(STATUS "Strata: static CUDA toolkit libraries; host glibc and NVIDIA driver remain required") ++ endif() + set(_strata_gpu_include_directories ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) + elseif(STRATA_ENABLE_HIP) + set(_strata_gpu_runtime_target strata_hip_runtime) +@@ -257,6 +276,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) + src/kernels/cuda/fused_gr.cu + src/kernels/cuda/cvec.cu + src/kernels/cuda/qsa_decode_attn.cu ++ src/kernels/cuda/keyless.cu + src/kernels/cuda/qsa_prompt_attn.cu + src/kernels/cuda/fused_gdn.cu + src/kernels/cuda/dequant_bf16.cu +@@ -267,12 +287,41 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) + src/ngram/ple_reader.cpp + src/platform/direct_file.cpp) + target_link_libraries(strata_kernels PUBLIC strata_core strata_artifact) ++ option(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE "Capture private PLE row traces for offline cache studies" OFF) ++ if(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE) ++ if(NOT CMAKE_SYSTEM_NAME STREQUAL "Linux") ++ message(FATAL_ERROR "The experimental PLE row trace requires Linux") ++ endif() ++ target_compile_definitions(strata_kernels PRIVATE STRATA_NEXT_EXPERIMENTAL_PLE_TRACE=1) ++ endif() ++ option(STRATA_NEXT_EXPERIMENTAL_KAR_PLE "Build optional KAR PLE CPU and GPU-cache experiment arms" OFF) ++ set(STRATA_NEXT_KAR_DIR "" CACHE PATH "Path to strata-next/gpu/kar (required for KAR PLE)") ++ if(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ if(NOT STRATA_ENABLE_CUDA OR NOT CMAKE_SYSTEM_NAME STREQUAL "Linux") ++ message(FATAL_ERROR "The experimental KAR PLE quality arm requires Linux CUDA") ++ endif() ++ if(NOT EXISTS "${STRATA_NEXT_KAR_DIR}/vendor/libkar.cu") ++ message(FATAL_ERROR "Set STRATA_NEXT_KAR_DIR to the strata-next/gpu/kar source directory") ++ endif() ++ add_library(strata_next_kar STATIC ++ "${STRATA_NEXT_KAR_DIR}/vendor/libkar.cu" ++ "${STRATA_NEXT_KAR_DIR}/src/kar_ple_cache.cu") ++ target_include_directories(strata_next_kar PUBLIC ++ "${STRATA_NEXT_KAR_DIR}/vendor" ++ "${STRATA_NEXT_KAR_DIR}/include") ++ target_link_libraries(strata_next_kar PUBLIC ${_strata_gpu_runtime_target}) ++ set_target_properties(strata_next_kar PROPERTIES CUDA_STANDARD 17 CUDA_STANDARD_REQUIRED ON) ++ target_link_libraries(strata_kernels PUBLIC strata_next_kar) ++ target_compile_definitions(strata_kernels PRIVATE STRATA_NEXT_EXPERIMENTAL_KAR_PLE=1) ++ add_executable(strata_next_kar_ple_probe "${STRATA_NEXT_KAR_DIR}/src/kar_ple_cpu_probe.cpp") ++ target_link_libraries(strata_next_kar_ple_probe PRIVATE strata_kernels) ++ endif() + # perf-review D-1: the tensor-core prompt attention vs the FP32 kernel and FP64 (GPU, synthetic, no model); with + # the tests, or alone with -DSTRATA_PARITY_PROMPT_ATTN=ON. CUDA only: HIP compiles the tensor-core kernel out. + if((STRATA_BUILD_TESTS OR STRATA_PARITY_PROMPT_ATTN) AND STRATA_ENABLE_CUDA) + add_executable(qsa_prompt_attn_parity src/kernels/qsa_prompt_attn_parity.cpp) + target_include_directories(qsa_prompt_attn_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) +- target_link_libraries(qsa_prompt_attn_parity PRIVATE strata_kernels CUDA::cudart) ++ target_link_libraries(qsa_prompt_attn_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + endif() + # the QSA selection (block scores on the warp kernel and the tensor-core one, top-k): a GPU bench with a + # scorer-vs-scorer comparison and an FP64 accuracy gate (synthetic, no model); the ctest runs a 32K context under a +@@ -338,11 +387,35 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) + # already links `strata_core` - putting `gdn_layer` in core would make the two mutually dependent. A third + # 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 ++ add_library(strata_engine STATIC src/core/keyless.cpp 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/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}) ++ option(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS "Build the opt-in KAR native decode cache-miss arm" OFF) ++ if(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) ++ if(NOT STRATA_ENABLE_CUDA OR NOT CMAKE_SYSTEM_NAME STREQUAL "Linux") ++ message(FATAL_ERROR "Experimental KAR experts require Linux CUDA") ++ endif() ++ if(NOT EXISTS "${STRATA_NEXT_KAR_DIR}/src/kar_expert_miss.cpp") ++ message(FATAL_ERROR "Set STRATA_NEXT_KAR_DIR to strata-next/gpu/kar") ++ endif() ++ add_library(strata_next_kar_experts STATIC ++ "${STRATA_NEXT_KAR_DIR}/vendor/libkar.cu" ++ "${STRATA_NEXT_KAR_DIR}/src/kar_expert.cu" ++ "${STRATA_NEXT_KAR_DIR}/src/kar_expert_miss.cpp") ++ target_include_directories(strata_next_kar_experts PUBLIC ++ "${STRATA_NEXT_KAR_DIR}/vendor" "${STRATA_NEXT_KAR_DIR}/include") ++ target_link_libraries(strata_next_kar_experts PUBLIC ${_strata_gpu_runtime_target}) ++ set_target_properties(strata_next_kar_experts PROPERTIES CUDA_STANDARD 17 CUDA_STANDARD_REQUIRED ON) ++ target_compile_features(strata_next_kar_experts PRIVATE cxx_std_20) ++ target_link_libraries(strata_engine PUBLIC strata_next_kar_experts) ++ target_compile_definitions(strata_engine PUBLIC STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS=1) ++ endif() ++ add_executable(keyless_parity src/kernels/keyless_parity.cpp) ++ target_link_libraries(keyless_parity PRIVATE strata_engine) ++ add_test(NAME keyless_parity COMMAND keyless_parity) ++ set_tests_properties(keyless_parity PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/file_expert_source_test.cpp") + enable_testing() + add_executable(file_expert_source_test tests/core/file_expert_source_test.cpp) +@@ -369,6 +442,10 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) + set_tests_properties(expert_cache_per_layer_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + endif() + if(STRATA_BUILD_CONVERSATION_TESTS) ++ add_executable(keyless_stream_parity src/kernels/kv_stream_parity.cpp) ++ target_link_libraries(keyless_stream_parity PRIVATE strata_engine) ++ add_test(NAME keyless_stream_parity COMMAND keyless_stream_parity --v-only) ++ set_tests_properties(keyless_stream_parity PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + 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) +@@ -406,6 +483,10 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) + add_executable(strata src/program/generate.cpp) + target_include_directories(strata PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(strata PRIVATE strata_engine strata_prefill strata_spec ${_strata_gpu_runtime_target}) ++ if(STRATA_CUDA_STATIC) ++ target_link_options(strata PRIVATE -static-libstdc++ -static-libgcc) ++ set_target_properties(strata PROPERTIES SKIP_BUILD_RPATH TRUE INSTALL_RPATH "") ++ endif() + + if(STRATA_ENABLE_HIP) + enable_testing() +diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp +index 307edd98..e2669ebe 100644 +--- a/include/strata/core/expert_source.hpp ++++ b/include/strata/core/expert_source.hpp +@@ -211,6 +211,12 @@ struct GpuPlanSink { + + /// The adapter's own state. One per session, reused every layer so the token path allocates nothing (P2.T10). + struct ExpertDispatch { ++ // Default-off local extension. The callback owns only kind==-1 entries and ++ // marks completed host rows as kind=3. Native hits/PCIe/remote rows are untouched. ++ using ExperimentalMiss = bool (*)(void*, int64_t, const float*, const int32_t*, ++ int64_t, int64_t, int32_t*, float*, std::string&); ++ ExperimentalMiss experimental_miss = nullptr; ++ void* experimental_miss_user = nullptr; + strata::kernels::cpu::ExpertPool* pool = nullptr; + ExpertSource* src = nullptr; + RouterLookahead* lookahead = nullptr; ///< CS-T: warms the next layer's predicted file-tier experts +diff --git a/include/strata/core/keyless.hpp b/include/strata/core/keyless.hpp +new file mode 100644 +index 00000000..4665c458 +--- /dev/null ++++ b/include/strata/core/keyless.hpp +@@ -0,0 +1,11 @@ ++#pragma once ++#include "strata/core/layout.hpp" ++#include ++namespace strata::core { ++bool keyless_load(const char* path, const WeightTable& weights, const ModelGeometry& g, std::string& error); ++const float* keyless_routing(int64_t layer); ++} ++namespace strata::kernels { ++// In-place, one independent matrix for each query head. No cached keys are produced. ++void keyless_route_query(float* q, const float* output_major_matrices, int64_t tokens, int heads, int dim, void* stream); ++} +diff --git a/include/strata/core/layer.hpp b/include/strata/core/layer.hpp +index a8965da1..e7cfeb24 100644 +--- a/include/strata/core/layer.hpp ++++ b/include/strata/core/layer.hpp +@@ -204,6 +204,7 @@ struct QsaState { + uint16_t* k_pool = nullptr; ///< [page][kv_head][page_size][head_dim] fp16 (null in INT8 mode) + uint16_t* v_pool = nullptr; + /// Plan v0.3 P7: INT8 KV (qsa_set_kv_int8). Codes [page][kv_head][page_size][head_dim], one FP16 scale per 64. ++ bool without_key = false; + bool kv_int8 = false; + int8_t* k_q = nullptr; + int8_t* v_q = nullptr; +@@ -282,6 +283,8 @@ uint64_t qsa_kv_host_bytes(); + /// Plan v0.3 P7: store K/V as INT8 with FP16 scales per 64 values (half the VRAM of FP16). Set before sizing and + /// initializing the session; default off until gate G-C accepts it. + void qsa_set_kv_int8(bool enabled); ++void qsa_set_without_key(bool enabled); ++bool qsa_without_key(); + /// INT8 K/V through the Hadamard rotation (off by default: STRATA_KV_ROT=1) + void qsa_set_kv_int8_rotate(bool enabled); + bool qsa_kv_int8(); +@@ -299,6 +302,7 @@ inline int qsa_kv_format(const QsaState& st) { + std::fprintf(stderr, "strata: qsa_kv_format: a hybrid K8V4 state must never reach the block movers\n"); + std::exit(1); // the kernels' own "unsupported geometry" convention (kv_q8.cu, qsa_decode_attn.cu) + } ++ if (st.without_key) return strata::kernels::kKvValueInt8; + return st.kv_q4 ? strata::kernels::kKvQ4 : st.kv_int8 ? strata::kernels::kKvInt8 : strata::kernels::kKvF16; + } + uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, QsaState& st, +diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp +index 5717eb4f..29b064fb 100644 +--- a/include/strata/core/verify.hpp ++++ b/include/strata/core/verify.hpp +@@ -213,6 +213,10 @@ private: + int32_t* h_commit_ = nullptr; int32_t* m_commit_ = nullptr; // [n_keep, n_keep-1, pos_0 .. pos_{T-1}] + float* h_ple_ = nullptr; float* m_ple_ = nullptr; // T * n_embd + int32_t* h_out_ = nullptr; int32_t* m_out_ = nullptr; // T argmax ids ++ float* trace_h_ = nullptr; // optional pinned K/V activation trace for offline keyless study ++ std::FILE* trace_file_ = nullptr; ++ float* trace_q_h_ = nullptr; // first accepted token's Q, per QSA layer ++ std::FILE* trace_q_file_ = nullptr; + float* h_x_ = nullptr; float* m_x_ = nullptr; // doorbell payload: T * n_embd + int32_t* h_ids_ = nullptr; int32_t* m_ids_ = nullptr; // T * k + float* h_w_ = nullptr; float* m_w_ = nullptr; // T * k +diff --git a/include/strata/kernels/kv_stream.hpp b/include/strata/kernels/kv_stream.hpp +index b3ebee34..90483fa0 100644 +--- a/include/strata/kernels/kv_stream.hpp ++++ b/include/strata/kernels/kv_stream.hpp +@@ -38,12 +38,12 @@ struct KvHostPools { + uint16_t* v_scale = nullptr; + uint8_t* k_q4 = nullptr; ///< q4_0 mode (kv_q4.hpp): block_q4_0 codes, 144 B per cell and head + uint8_t* v_q4 = nullptr; +- bool present() const { return k_pool != nullptr || k_q != nullptr || k_q4 != nullptr; } ++ bool present() const { return k_pool != nullptr || k_q != nullptr || k_q4 != nullptr || v_q != nullptr; } + }; + + /// The KV storage format, for the functions below that move whole blocks (`fmt`): fp16, int8 (+ scales), q4_0. + /// (A bool `int8` argument still reads as kKvF16 / kKvInt8.) +-enum KvFormat : int { kKvF16 = 0, kKvInt8 = 1, kKvQ4 = 2 }; ++enum KvFormat : int { kKvF16 = 0, kKvInt8 = 1, kKvQ4 = 2, kKvValueInt8 = 4 }; + + /// The residency map of a streamed layer, all device memory at fixed addresses (the graphs bake them in). + struct KvStreamMap { +diff --git a/include/strata/kernels/ngram.hpp b/include/strata/kernels/ngram.hpp +index 3c6f8fab..688c74d9 100644 +--- a/include/strata/kernels/ngram.hpp ++++ b/include/strata/kernels/ngram.hpp +@@ -22,6 +22,7 @@ + // All of those are asserted observable in `ple_parity.cpp` rather than trusted. + #pragma once + ++#include + #include + #include + +@@ -139,6 +140,21 @@ public: + /// Open with an explicit I/O mode. The two-argument `open` below is the default (Direct). + bool open(const std::string& gguf_path, std::string& err, const PleIoOptions& io); + ++ /// Experimental CPU quality arm: read rows from a verified KAR-2 archive ++ /// while the rest of the engine continues to use its normal model pack. ++ /// The CUDA selective-row path is measured separately and is not used here. ++ bool open_kar(const std::string& kar_path, uint32_t level, std::string& err, ++ uint64_t expected_rows = PLE_TABLE_ROWS); ++ ++ /// Experimental bounded compressed-row cache. It accepts only the ++ /// level-2/group-32 KAR PLE layout and leaves the CPU gather available ++ /// for consumers that still use mapped host memory. ++ bool enable_kar_gpu_cache(uint32_t cache_mib, std::string& err); ++ bool kar_gpu_cache_enabled() const; ++ bool collect_device(float* device_out2560, void* stream, std::string& err); ++ bool gather_batch_device(const uint32_t* rows, size_t n_tokens, float* device_out, ++ void* stream, std::string& err); ++ + /// The split the plan asks for: `issue` as soon as the token id is known, `collect` just before layer 1 + /// needs the rows. `gather` is `issue` followed by `collect`. In Mmap mode `issue` only prefetches. + bool issue(const uint32_t* rows16); +diff --git a/include/strata/kernels/qsa_decode_attn.hpp b/include/strata/kernels/qsa_decode_attn.hpp +index 45c0f301..f67bfad2 100644 +--- a/include/strata/kernels/qsa_decode_attn.hpp ++++ b/include/strata/kernels/qsa_decode_attn.hpp +@@ -21,6 +21,11 @@ + namespace strata::kernels { + + struct QsaAttnPools { ++ bool without_key = false; ++ const float* keyless_cos = nullptr; ++ const float* keyless_sin = nullptr; ++ int keyless_n_rot = 0; ++ const int32_t* keyless_mrope = nullptr; // optional per-cell time/height/width positions + const uint16_t* k_pool = nullptr; ///< fp16 [page][kv_head][page_size][head_dim], or null when int8 + const uint16_t* v_pool = nullptr; + const int8_t* k_q = nullptr; ///< int8 codes, same layout +diff --git a/src/core/conversation_snapshot.cpp b/src/core/conversation_snapshot.cpp +index 759daa65..0d8453d9 100644 +--- a/src/core/conversation_snapshot.cpp ++++ b/src/core/conversation_snapshot.cpp +@@ -59,6 +59,7 @@ bool layout(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index + } + l.value_data = l.data; + l.value_scales = l.scales; ++ if (st.without_key) { l.data = 0; l.scales = 0; } + 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)})) { +@@ -98,7 +99,7 @@ bool valid(const QsaState& st, const Layout& l, int64_t upto, std::string& error + } + } + 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.without_key ? !st.v_q || !st.v_scale : 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; +diff --git a/src/core/conversation_snapshot_test.cpp b/src/core/conversation_snapshot_test.cpp +index da95113c..3792cd4b 100644 +--- a/src/core/conversation_snapshot_test.cpp ++++ b/src/core/conversation_snapshot_test.cpp +@@ -42,13 +42,14 @@ struct Fixture { + } + Fixture(int fmt, int mode) { + auto& st = state; +- st.kv_mode = mode; st.kv_int8 = fmt==kKvInt8; st.kv_q4 = fmt==kKvQ4; st.kv_hybrid = fmt==3; ++ st.kv_mode = mode; st.without_key = fmt==kKvValueInt8; st.kv_int8 = fmt==kKvInt8 || st.without_key; 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 || 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}; ++ sizes = {rows*per, rows*per, (fmt==kKvInt8 || fmt==kKvValueInt8) ? rows*(g.head_dim/64)*2:0, ++ (fmt==kKvInt8 || fmt==kKvValueInt8) ? rows*(g.head_dim/64)*2:0, (size_t)st.idx_pooled_rows*g.idx_key_dim*4}; ++ if (st.without_key) { sizes[0]=0; sizes[2]=0; } + 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}; +@@ -58,9 +59,11 @@ struct Fixture { + 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); ++ } else if (st.kv_int8) { ++ if (!st.without_key) alloc(st.k_q,slot_rows*per); ++ alloc(st.v_q,slot_rows*per); ++ if (!st.without_key) 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); +@@ -105,7 +108,7 @@ bool equal(const ConversationKv& a,const ConversationKv& b) { + } + + void full_session(int fmt, int mode, int experts) { +- Fixture main(fmt,mode), draft(fmt==3?kKvInt8:fmt,2); ++ Fixture main(fmt,mode), draft((fmt==3 || fmt==kKvValueInt8)?kKvInt8:fmt,2); + auto& g=main.g; + g.n_layers=4; g.n_expert=experts; + g.ssm_state_size=2; g.ssm_v_heads=2; g.ssm_conv_channels=8; +@@ -162,7 +165,7 @@ void full_session(int fmt, int mode, int experts) { + 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;}); ++ reuse.kv[0].v.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); +@@ -179,7 +182,7 @@ void full_session(int fmt, int mode, int experts) { + incremental.live.dead==fresh.live.dead && equal(incremental.kv[0],fresh.kv[0]) && + equal(incremental.kv[1],fresh.kv[1]),"incremental capture equals full capture after growth or rewind"); + check((dirty>=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){ ++ incremental.kv[0].v.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"); +@@ -198,7 +201,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 : std::array{kKvF16,kKvInt8,kKvQ4,3}) for (int mode : {0,1,2}) { ++ for (int fmt : std::array{kKvF16,kKvInt8,kKvQ4,3,kKvValueInt8}) for (int mode : {0,1,2}) { + if (fmt==3 && mode!=0) continue; + Fixture f(fmt,mode); + if (fmt==3) { +@@ -227,6 +230,12 @@ int main() { + ConversationKv a,b,restored; + cuda_check(cudaDeviceSynchronize()); + check(conversation_kv_save(a,f.state,f.g,upto,index,err),"save A"); ++ if (fmt==kKvValueInt8) { ++ check(a.k.empty() && a.k_scale.empty() && !f.state.k_q && !f.state.host.k_q, ++ "V-only snapshot and resident/host pools have no K"); ++ auto wrong=a; wrong.format=kKvInt8; ++ check(!conversation_kv_restore(wrong,f.state,f.g,upto,index,err),"reject K+V snapshot in V-only state"); ++ } + 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"); +@@ -247,13 +256,13 @@ int main() { + const int64_t b1=(upto+s.page_size-1)/s.page_size,b0=std::max(0,b1-f.state.n_slots); + 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; ++ const size_t code_block=(fmt==kKvInt8 || fmt==kKvValueInt8) ? s.page_size*s.n_head_kv*s.head_dim : block; ++ const void* slots=fmt==kKvValueInt8?(void*)f.state.v_q: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 expected(code_block); +- check(a.k.read(expected.data(), page*code_block, code_block),"read segmented expected draft page"); ++ check((fmt==kKvValueInt8?a.v:a.k).read(expected.data(), page*code_block, code_block),"read segmented expected draft page"); + check(got == expected,"draft ring contains restored pages"); + } + } +@@ -276,7 +285,7 @@ int main() { + } + } + } +- for (int fmt : {kKvF16,kKvInt8,kKvQ4}) for (int mode : {0,1}) for (int experts : {256,512}) ++ for (int fmt : {kKvF16,kKvInt8,kKvQ4,kKvValueInt8}) for (int mode : {0,1}) for (int experts : {256,512}) + full_session(fmt,mode,experts); + for (int experts : {256,512}) full_session(3,0,experts); + std::printf("conversation_snapshot_test: %d checks passed\n",checks); +diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp +index 087854ed..4d3cb759 100644 +--- a/src/core/expert_source.cpp ++++ b/src/core/expert_source.cpp +@@ -1745,6 +1745,13 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 + for (int64_t i = 0; i < n; ++i) if (d.remote[r]->owns(i)) kind[i] = 2; + } + } ++ if (d.experimental_miss != nullptr) { ++ static thread_local std::string miss_error; ++ if (!d.experimental_miss(d.experimental_miss_user, d.layers, x_f, ids, ++ n_tok, k, kind, out, miss_error)) { ++ d.failed = true; d.fail = miss_error.c_str(); d.fail_layer = d.layers; return; ++ } ++ } + const auto c1 = std::chrono::steady_clock::now(); + if (native && lay.fmt[(size_t) d.layers].gu_type == 42) // a native Q2_0 pack: the Q2_0 kernels' activations + for (int64_t t = 0; t < n_tok; ++t) act_quant_any(x_f + (size_t) t * H, H, d.act_multi[(size_t) t]); +@@ -1776,9 +1783,10 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 + d.fail_expert = e; + return; + } +- if (kind[i] >= 0) { // CUDA0, PCIe, or a remote result staged into this row below ++ if (kind[i] >= 0) { // CUDA0, PCIe, remote, or completed experimental host row + if (kind[i] == 0) ++d.cache_hits; +- std::memset(row, 0, (size_t) H * sizeof(float)); ++ if (kind[i] == 3) ++d.cache_refused; ++ else std::memset(row, 0, (size_t) H * sizeof(float)); + continue; + } + ++d.cache_refused; +diff --git a/src/core/keyless.cpp b/src/core/keyless.cpp +new file mode 100644 +index 00000000..7699b579 +--- /dev/null ++++ b/src/core/keyless.cpp +@@ -0,0 +1,79 @@ ++#include "strata/core/keyless.hpp" ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++namespace strata::core { ++namespace { ++std::map routes; ++uint32_t u32(std::istream& f) { ++ unsigned char b[4]{}; f.read((char*) b, 4); ++ return (uint32_t)b[0] | (uint32_t)b[1]<<8 | (uint32_t)b[2]<<16 | (uint32_t)b[3]<<24; ++} ++uint64_t u64(std::istream& f) { const uint64_t a = u32(f); return a | (uint64_t)u32(f)<<32; } ++} ++const float* keyless_routing(int64_t layer) { ++ const auto it = routes.find(layer); ++ return it == routes.end() ? nullptr : it->second; ++} ++bool keyless_load(const char* path, const WeightTable& weights, const ModelGeometry& g, std::string& error) { ++ if (!routes.empty()) { error = "keyless routing already loaded"; return false; } ++ std::ifstream f(path, std::ios::binary); ++ std::array magic{}; f.read(magic.data(), 8); ++ const uint32_t version = u32(f), layers = u32(f), heads = u32(f), dim = u32(f); ++ if (!f || std::memcmp(magic.data(), "SKLROUT1", 8) || version != 1 || ++ layers != (uint32_t)g.n_qsa_layers() || heads != (uint32_t)g.n_head || dim != (uint32_t)g.head_dim || dim != 256) { ++ error = "invalid keyless artifact header/geometry"; return false; ++ } ++ std::map pending; ++ auto fail = [&](const std::string& why) { ++ error = why; for (auto& row : pending) cudaFree(row.second); return false; ++ }; ++ for (uint32_t ordinal = 0; ordinal < layers; ++ordinal) { ++ const uint32_t layer = u32(f); ++ if (!f || layer >= g.n_layers || !is_qsa_layer(g, layer) || pending.count(layer)) ++ return fail("keyless artifact has invalid/duplicate layer"); ++ for (const char* role : {"q", "k", "v"}) { ++ const uint32_t kind = u32(f); const uint64_t bytes = u64(f), wanted = u64(f); ++ const auto* w = weights.find("blk." + std::to_string(layer) + ".attn_" + role + ".weight"); ++ // Quantized projection size is recorded by the source decoder. Bound before any device read. ++ const uint64_t expected_elements = (uint64_t)g.n_embd * g.head_dim * ++ (std::strcmp(role,"q") == 0 ? g.n_head * 2 : g.n_head_kv); ++ if (!f || !w || !w->native_data || w->native_type != (int)kind || ++ bytes == 0 || bytes > expected_elements * 4 || expected_elements != (uint64_t)w->elements) ++ return fail("keyless artifact source projection geometry/type mismatch"); ++ // NativeDense owns source GGUF blocks. Verify the artifact was derived from these actual bytes. ++ // Source byte length must agree with ggml geometry; ne0/ne1 cannot validate a quantized byte span. ++ const uint64_t block_elements = kind == 42 ? 64 : kind == 8 ? 32 : 256; ++ const uint64_t block_bytes = kind == 42 ? 18 : kind == 11 ? 110 : kind == 12 ? 144 : ++ kind == 13 ? 176 : kind == 14 ? 210 : kind == 23 ? 136 : kind == 8 ? 34 : 0; ++ if (!block_bytes || expected_elements % block_elements || bytes != expected_elements / block_elements * block_bytes) ++ return fail("keyless artifact unsupported/mismatched native projection encoding"); ++ std::vector raw((size_t)bytes); ++ if (cudaMemcpy(raw.data(), w->native_data, raw.size(), cudaMemcpyDeviceToHost) != cudaSuccess) ++ return fail("keyless source projection readback failed"); ++ uint64_t hash = 0xcbf29ce484222325ull; ++ for (uint8_t byte : raw) hash = (hash ^ byte) * 0x100000001b3ull; ++ if (hash != wanted) return fail("keyless artifact source projection fingerprint mismatch"); ++ } ++ std::vector matrix((size_t)heads * dim * dim); ++ f.read((char*)matrix.data(), matrix.size()*sizeof(float)); ++ if (!f || !std::all_of(matrix.begin(), matrix.end(), [](float v) { return std::isfinite(v); })) ++ return fail("truncated/nonfinite keyless query matrix"); ++ float* device = nullptr; ++ if (cudaMalloc((void**)&device, matrix.size()*sizeof(float)) != cudaSuccess) ++ return fail("keyless query matrices do not fit in GPU memory"); ++ pending[layer] = device; ++ if (cudaMemcpy(device, matrix.data(), matrix.size()*sizeof(float), cudaMemcpyHostToDevice) != cudaSuccess) ++ return fail("keyless query matrix upload failed"); ++ } ++ if (f.peek() != std::char_traits::eof()) return fail("keyless artifact has trailing data"); ++ routes = std::move(pending); ++ return true; ++} ++} +diff --git a/src/core/layer.cpp b/src/core/layer.cpp +index ff7fc17b..7e132895 100644 +--- a/src/core/layer.cpp ++++ b/src/core/layer.cpp +@@ -1,6 +1,7 @@ + + // src/core/layer.cpp - the GDN layer, composed. See the header for the operation order and its traps. + #include "strata/core/layer.hpp" ++#include "strata/core/keyless.hpp" + #include "strata/core/native_head.hpp" + #include "strata/kernels/bf16_bits.hpp" + #include "strata/kernels/bf16_gemv.hpp" +@@ -173,7 +174,9 @@ if (!w.wants_q8k()) { s_gemv_q8_0_split(x80, p.codes, p.scales, p.offset, + // namespace + void layer_set_native_bf16(bool enabled) { native_bf16_projections = enabled; } + void layer_set_native_flash_attn_short(bool enabled) { native_flash_attn_short = enabled; } +-namespace { bool g_kv_int8 = false, g_kv_q4 = false, g_kv_hybrid = false, g_kv_int8_rot = false; } ++namespace { bool g_without_key = false, g_kv_int8 = false, g_kv_q4 = false, g_kv_hybrid = false, g_kv_int8_rot = false; } ++void qsa_set_without_key(bool enabled) { g_without_key = enabled; } ++bool qsa_without_key() { return g_without_key; } + void qsa_set_kv_int8(bool enabled) { g_kv_int8 = enabled; } + void qsa_set_kv_int8_rotate(bool enabled) { g_kv_int8_rot = enabled; } + bool qsa_kv_int8() { return g_kv_int8; } +@@ -512,6 +515,7 @@ KvPlan kv_plan(const QsaShapes& s, int64_t max_cells, int64_t ring_cells) { + return p; + } + uint64_t kv_pool_bytes(const QsaShapes& s, int64_t pages, bool hybrid, bool int8) { ++ if (g_without_key) return (uint64_t)pages * s.page_size * strata::kernels::kv_q8_bytes_per_cell(s) / 2 + 64; + if (hybrid) { // K8V4: the INT8 K half (codes + scales) plus the Q4_0 V half (kv_q4.hpp's rotation) + const uint64_t rows = (uint64_t) pages * s.page_size * s.n_head_kv; + return rows * (uint64_t) s.head_dim + rows * (uint64_t) (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2 + +@@ -552,6 +556,7 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q + const KvPlan p = kv_plan(s, max_cells, ring_cells); + const int64_t pages = p.pages; + Cursor c{(uint8_t*) base}; ++ st.without_key = g_without_key; + st.kv_int8 = g_kv_int8 && !g_kv_q4; + st.kv_q4 = g_kv_q4; + // Hybrid K8V4, main layers only (the drafter's state is created with the globals toggled to INT8 - +@@ -578,9 +583,9 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q + st.k_q4 = c.take(rows * q4_row); + st.v_q4 = c.take(rows * q4_row); + } else if (st.kv_int8) { // st, not the global: the drafter's ring is INT8 under --kv k8v4 too +- st.k_q = c.take(rows * s.head_dim); ++ if (!st.without_key) st.k_q = c.take(rows * s.head_dim); + st.v_q = c.take(rows * s.head_dim); +- st.k_scale = c.take(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); ++ if (!st.without_key) st.k_scale = c.take(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); + st.v_scale = c.take(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); + } else { + st.k_pool = c.take(rows * s.head_dim); +@@ -646,9 +651,9 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q + st.host.k_q4 = hc.take(hrows * q4_row); + st.host.v_q4 = hc.take(hrows * q4_row); + } else if (st.kv_int8) { +- st.host.k_q = hc.take(hrows * s.head_dim); ++ if (!st.without_key) st.host.k_q = hc.take(hrows * s.head_dim); + st.host.v_q = hc.take(hrows * s.head_dim); +- st.host.k_scale = hc.take(hrows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); ++ if (!st.without_key) st.host.k_scale = hc.take(hrows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); + st.host.v_scale = hc.take(hrows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); + } else { + st.host.k_pool = hc.take(hrows * s.head_dim); +@@ -689,16 +694,16 @@ void qsa_state_zero(const QsaState& st, const ModelGeometry& g, void* stream) { + cudaStream_t cs = (cudaStream_t) stream; + const size_t rows = (size_t) st.n_slots * s.n_head_kv * s.page_size; + if (st.kv_hybrid) { +- cudaMemsetAsync(st.k_q, 0, rows * s.head_dim, cs); +- cudaMemsetAsync(st.k_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs); ++ if (st.k_q) cudaMemsetAsync(st.k_q, 0, rows * s.head_dim, cs); ++ if (st.k_scale) cudaMemsetAsync(st.k_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs); + cudaMemsetAsync(st.v_q4, 0, rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), cs); + } else if (st.kv_q4) { + cudaMemsetAsync(st.k_q4, 0, rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), cs); + cudaMemsetAsync(st.v_q4, 0, rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), cs); + } else if (st.kv_int8) { +- cudaMemsetAsync(st.k_q, 0, rows * s.head_dim, cs); ++ if (st.k_q) cudaMemsetAsync(st.k_q, 0, rows * s.head_dim, cs); + cudaMemsetAsync(st.v_q, 0, rows * s.head_dim, cs); +- cudaMemsetAsync(st.k_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs); ++ if (st.k_scale) cudaMemsetAsync(st.k_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs); + cudaMemsetAsync(st.v_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs); + } else { + cudaMemsetAsync(st.k_pool, 0, rows * s.head_dim * 2, cs); +@@ -716,6 +721,8 @@ void qsa_state_zero(const QsaState& st, const ModelGeometry& g, void* stream) { + strata::kernels::QsaAttnPools qsa_attn_pools(const QsaState& st) { + strata::kernels::QsaAttnPools pools; + pools.page_table = st.page_table; ++ pools.without_key = st.without_key; ++ pools.keyless_cos = st.cos_tab; pools.keyless_sin = st.sin_tab; pools.keyless_n_rot = 64; pools.keyless_mrope = strata::kernels::mrope_table(); + if (st.kv_hybrid) { pools.k_q = st.k_q; pools.k_scale = st.k_scale; pools.v_q4 = st.v_q4; } + else if (st.kv_q4) { pools.k_q4 = st.k_q4; pools.v_q4 = st.v_q4; } + else if (st.kv_int8) { pools.k_q = st.k_q; pools.v_q = st.v_q; pools.k_scale = st.k_scale; pools.v_scale = st.v_scale; } +@@ -845,11 +852,12 @@ void stage_timing_report(int64_t n_layers) { + // needs nothing from the layer it is called for beyond its index. + static void dump_slot(float* dump, const ModelGeometry& g, int64_t layer, const float* src, uint64_t off, + uint64_t n, void* stream); +-bool qsa_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t pos, int32_t pos_base, const QsaState& st, const QsaBuffers& b, const float* x, float* out, void* stream, std::string& err, float* dump) { using namespace strata::kernels; const QsaShapes s = qsa_shapes(g); const LayerView v(tables, layer); const int64_t n_kv = pos + 1; /* P7 audit: RoPE reads cos/sin row pos_base + pos, and the table holds max_cells rows. */ if ((int64_t) pos_base + pos >= st.max_cells || pos_base < 0) { err = "qsa_layer: position " + std::to_string((long long) pos_base + pos) + " is outside the RoPE table (" + std::to_string((long long) st.max_cells) + " rows)"; return false; } const int64_t n_bid = n_kv / s.idx_block; const int64_t width = qsa_selection_width(n_kv, s); const int64_t cap = qsa_selection_width(kTopkMaxCells, s); ++bool qsa_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t pos, int32_t pos_base, const QsaState& st, const QsaBuffers& b, const float* x, float* out, void* stream, std::string& err, float* dump) { using namespace strata::kernels; const QsaShapes s = qsa_shapes(g); const LayerView v(tables, layer); const int64_t n_kv = pos + 1; if (st.without_key && pos_base != 0) { err = "V-only requires zero position base"; return false; } /* P7 audit: RoPE reads cos/sin row pos_base + pos, and the table holds max_cells rows. */ if ((int64_t) pos_base + pos >= st.max_cells || pos_base < 0) { err = "qsa_layer: position " + std::to_string((long long) pos_base + pos) + " is outside the RoPE table (" + std::to_string((long long) st.max_cells) + " rows)"; return false; } const int64_t n_bid = n_kv / s.idx_block; const int64_t width = qsa_selection_width(n_kv, s); const int64_t cap = qsa_selection_width(kTopkMaxCells, s); + const auto normalize_rotate = [&](float* data, const WeightRef* norm, int rows, int cols) { + try { + if (native_qsa_enabled()) native_qsa_rms_norm_weighted(data, (const float*) norm->data, data, cols, rows, RMS_EPS, stream); + else rms_norm_weighted(data, (const float*) norm->data, rows, cols, RMS_EPS, stream); ++ if (st.without_key && data == b.qcur) keyless_route_query(data, keyless_routing(layer), 1, (int)g.n_head, (int)g.head_dim, stream); + if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, rope_scaling(), st.pos_dev, stream); + else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st.cos_tab, st.sin_tab, st.pos_dev, stream); + return true; +@@ -893,7 +901,7 @@ SForm f_k, f_v, f_o, f_q; if (!sform_of(*w_attnk, f_k, v.name("attn_k.weight" + // k and v, with the activation THIS layer's tensors ask for. Both are K-quants in every QSA layer of this + // artifact, but the dispatch is here for the same reason it is in `gdn_layer`: the pack decides per tensor, + // and "it happens to be uniform here" is the assumption that was wrong for `attn_q`. +-if (!gemv_quantized(*w_attnk, p_k, f_k, b.x_q8_0, b.x_q8k, b.kcur, g.n_embd, g.n_head_kv * g.head_dim, v.name("attn_k.weight"), stream, err, x)) return false; if (!gemv_quantized(*w_attnv, p_v, f_v, b.x_q8_0, b.x_q8k, b.vcur, g.n_embd, g.n_head_kv * g.head_dim, v.name("attn_v.weight"), stream, err, x, w_attnk->native_data && w_attnv->native_data)) return false; dump_slot(dump, g, layer, b.vcur, (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim, (uint64_t) g.n_head_kv * g.head_dim, stream); if (!normalize_rotate(b.kcur, w_kn, (int) g.n_head_kv, (int) g.head_dim)) return false; ++if (!st.without_key && !gemv_quantized(*w_attnk, p_k, f_k, b.x_q8_0, b.x_q8k, b.kcur, g.n_embd, g.n_head_kv * g.head_dim, v.name("attn_k.weight"), stream, err, x)) return false; if (!gemv_quantized(*w_attnv, p_v, f_v, b.x_q8_0, b.x_q8k, b.vcur, g.n_embd, g.n_head_kv * g.head_dim, v.name("attn_v.weight"), stream, err, x, !st.without_key && w_attnk->native_data && w_attnv->native_data)) return false; dump_slot(dump, g, layer, b.vcur, (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim, (uint64_t) g.n_head_kv * g.head_dim, stream); if (!st.without_key && !normalize_rotate(b.kcur, w_kn, (int) g.n_head_kv, (int) g.head_dim)) return false; + // ---- 5. into the cache, and the indexer's append (which pools AND rotates on a block completion). + // EVERY ENTRY POINT FROM HERE ON IS THE CAPTURABLE ONE: the per-token counts come from `st.step` and every + // launch is sized from a capacity in `st`/`b`, so this sequence can be captured and replayed. The +@@ -947,7 +955,7 @@ int64_t max_blocks = (st.max_cells / s.idx_block) + 2; + // KV streaming: every block the selection names is made resident before anything reads it + qsa_kv_resolve(st, g, b.ids, st.step, 1, cap, stream); + if (st.kv_rot) strata::kernels::fwht256_inplace_cuda(b.qcur, g.n_head, stream); // = +- if (g_fast_attn && !native_flash_attn_short && dump == nullptr) { ++ if (st.without_key || (g_fast_attn && !native_flash_attn_short && dump == nullptr)) { + const strata::kernels::QsaAttnPools pools = qsa_attn_pools(st); + strata::kernels::qsa_decode_attn_step(b.qcur, pools, b.ids, st.step, cap, s, b.attn_scratch, b.attn, stream); + } else { +@@ -1269,6 +1277,13 @@ bool ple_issue_token(const PleRun& p, std::string& err) { + + bool ple_finish_token(const PleRun& p, void* stream, std::string& err) { + if (!p.ready()) { err = "ple_finish_token: the PLE run is not ready"; return false; } ++ if (p.table->kar_gpu_cache_enabled()) { ++ if (!p.table->collect_device(p.emb_dev, stream, err)) { ++ err = "ple_finish_token: " + err; ++ return false; ++ } ++ return true; ++ } + if (!p.table->collect(p.emb_host, err)) { err = "ple_finish_token: " + err; return false; } + if (cudaMemcpyAsync(p.emb_dev, p.emb_host, (size_t) strata::kernels::NG_N_EMBD * sizeof(float), + cudaMemcpyHostToDevice, (cudaStream_t) stream) != cudaSuccess) { +diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp +index 17e36556..5db90887 100644 +--- a/src/core/mtp.cpp ++++ b/src/core/mtp.cpp +@@ -212,6 +212,11 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session + int64_t ring = (window > 0 && window < max_cells) ? window + 4 * (int64_t) max_t + 64 : 0; + // K8V4 never applies to the drafter: its own attention paths (below, and verify.cpp) handle whole formats + // only, whatever ring shape it takes (0, a window, or the -1 fully-resident fallback). ++ struct RestoreKeylessMode { ++ bool previous = qsa_without_key(); ++ ~RestoreKeylessMode() { qsa_set_without_key(previous); } ++ } restore_keyless_mode; ++ qsa_set_without_key(false); + const bool kv_hybrid_was = qsa_kv_hybrid(); + const bool kv_int8_was = qsa_kv_int8(); + qsa_set_kv_hybrid(false); +diff --git a/src/core/verify.cpp b/src/core/verify.cpp +index 999f85d8..58f7594b 100644 +--- a/src/core/verify.cpp ++++ b/src/core/verify.cpp +@@ -1,5 +1,6 @@ + // src/core/verify.cpp - see include/strata/core/verify.hpp. + #include "strata/core/verify.hpp" ++#include "strata/core/keyless.hpp" + #if defined(_WIN32) + #include + #endif +@@ -179,7 +180,9 @@ Verifier::~Verifier() { + if (copy_) { cudaStreamSynchronize(copy_); cudaStreamDestroy(copy_); } + if (commit_done_) cudaEventDestroy(commit_done_); + if (arena_) cudaFree(arena_); +- void* hosts[] = {h_tok_, h_step_, h_pos_, h_commit_, h_ple_, h_out_, h_x_, h_ids_, h_w_, h_seq_, h_flag_, h_ymiss_, ++ if (trace_file_) std::fclose(trace_file_); ++ if (trace_q_file_) std::fclose(trace_q_file_); ++ void* hosts[] = {h_tok_, h_step_, h_pos_, h_commit_, h_ple_, h_out_, trace_h_, trace_q_h_, h_x_, h_ids_, h_w_, h_seq_, h_flag_, h_ymiss_, + h_flagA_, h_plan_, h_flagB_}; + for (void* h : hosts) + if (h) cudaFreeHost(h); +@@ -202,6 +205,21 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& + hits_ = hits; + head_ = head; + max_t_ = max_t; ++ if (const char* path = std::getenv("STRATA_KEYLESS_TRACE")) { ++ if (!*path) { err = "verify: STRATA_KEYLESS_TRACE needs a private output path"; return false; } ++ trace_file_ = std::fopen(path, "wb"); ++ trace_q_file_ = std::fopen((std::string(path) + ".q").c_str(), "wb"); ++ const size_t trace_bytes = (size_t) g.n_qsa_layers() * (size_t) max_t * ++ (size_t) g.n_head_kv * (size_t) g.head_dim * 2 * sizeof(float); ++ const size_t query_bytes = (size_t) g.n_qsa_layers() * (size_t) g.n_head * ++ (size_t) g.head_dim * sizeof(float); ++ if (!trace_file_ || !trace_q_file_ || ++ cudaHostAlloc((void**) &trace_h_, trace_bytes, cudaHostAllocDefault) != cudaSuccess || ++ cudaHostAlloc((void**) &trace_q_h_, query_bytes, cudaHostAllocDefault) != cudaSuccess) { ++ err = "verify: cannot create pinned keyless activation trace"; ++ return false; ++ } ++ } + sampling_.greedy = true; // a fresh verifier samples greedily until set_sampling says otherwise + sampling_.temperature = 0.0f; + if (max_t < 2 || max_t > strata::kernels::kVerifyMaxT || max_t > strata::kernels::cpu::MAXT) { +@@ -557,6 +575,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { + auto norm_rope = [&](float* data, const WeightRef* norm, int rows, int cols, const int32_t* pos) { + if (native_qsa_enabled()) native_qsa_rms_norm_weighted(data, (const float*) norm->data, data, cols, rows, EPS, cs); + else rms_norm_weighted(data, (const float*) norm->data, rows, cols, EPS, cs); ++ if (st.without_key && norm == wqn) keyless_route_query(data, keyless_routing(l), rows / (int)NH, (int)NH, (int)HD, cs); + if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, rope_scaling(), pos, cs); + else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st.cos_tab, st.sin_tab, pos, cs); + }; +@@ -569,16 +588,29 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { + else for (int t = tb; t < te; ++t) + bf16_gemv_fp32_mmvf(mixed_ + t * N, (const uint16_t*) wik->data, idx_raw + t * ID, (int) N, (int) ID, cs); + stamp(l, 7, grp); +- native_mmvq(wk->native_type, wk->native_data, xq_, kcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD), n, cs); ++ if (!st.without_key) native_mmvq(wk->native_type, wk->native_data, xq_, kcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD), n, cs); + native_mmvq(wv->native_type, wv->native_data, xq_, vcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD), n, cs); +- if (qb) norm_rope(kcur_ + tb * NKV * HD, wkn, (int) (n * NKV), (int) HD, pos_k + tb * NKV); +- else for (int t = tb; t < te; ++t) norm_rope(kcur_ + t * NKV * HD, wkn, (int) NKV, (int) HD, pos_ + t * NH); ++ if (!st.without_key && qb) norm_rope(kcur_ + tb * NKV * HD, wkn, (int) (n * NKV), (int) HD, pos_k + tb * NKV); ++ else if (!st.without_key) for (int t = tb; t < te; ++t) norm_rope(kcur_ + t * NKV * HD, wkn, (int) NKV, (int) HD, pos_ + t * NH); + if (st.kv_rot) { // K and V rotated before they are stored (kv_q4.hpp) + fwht256_inplace_cuda(kcur_ + tb * NKV * HD, (int64_t) n * NKV, cs); + fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs); + } else if (st.kv_hybrid) { // K8V4: only V is rotated + fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs); + } ++ if (trace_h_) { ++ const size_t width = (size_t) NKV * HD; ++ for (int t = tb; t < te; ++t) { ++ float* dst = trace_h_ + ((size_t) qi * max_t_ + t) * 2 * width; ++ if (cudaMemcpyAsync(dst, kcur_ + (size_t) t * width, width * sizeof(float), ++ cudaMemcpyDeviceToHost, cs) != cudaSuccess || ++ cudaMemcpyAsync(dst + width, vcur_ + (size_t) t * width, width * sizeof(float), ++ cudaMemcpyDeviceToHost, cs) != cudaSuccess) { ++ err = "verify: keyless trace copy could not be captured"; ++ return false; ++ } ++ } ++ } + stamp(l, 8, grp); + if (grp == 0) copy_from_mapped(tail_snap_ + (size_t) qi * TS, st.idx_tail, TS, cs); + for (int t = tb; t < te; ++t) { +@@ -646,6 +678,12 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { + const QsaAttnPools pools = qsa_attn_pools(st); + qsa_decode_attn_batch(qcur_ + tb * NH * HD, pools, sel_ + (size_t) tb * cap_, step_ + tb * kStepCount, cap_, + s, attn_scratch_ + (size_t) tb * attn_scratch_floats_, attn_ + tb * NH * HD, n, cs); ++ if (trace_q_h_ && tb == 0 && ++ cudaMemcpyAsync(trace_q_h_ + (size_t) qi * NH * HD, qcur_, ++ (size_t) NH * HD * sizeof(float), cudaMemcpyDeviceToHost, cs) != cudaSuccess) { ++ err = "verify: keyless query trace copy could not be captured"; ++ return false; ++ } + stamp(l, 13, grp); + if (st.kv_rot || st.kv_hybrid) fwht256_inplace_cuda(attn_ + tb * NH * HD, (int64_t) n * NH, cs); // back: H^-1 = H + if (qb) native_qsa_gate_apply(attn_ + tb * NH * HD, qfull_ + tb * NH * 2 * HD, attn32_ + tb * NH * HD, +@@ -1127,6 +1165,30 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, + // beside the expert workers). + const cudaError_t se = cudaStreamSynchronize(cs_); + if (se != cudaSuccess) { err = std::string("verify: ") + cudaGetErrorString(se); return false; } ++ if (trace_file_) { ++ const uint32_t count = (uint32_t) T; ++ const size_t width = (size_t) g_->n_head_kv * (size_t) g_->head_dim; ++ bool written = std::fwrite(&count, sizeof(count), 1, trace_file_) == 1 && ++ std::fwrite(&pos0, sizeof(pos0), 1, trace_file_) == 1; ++ for (int64_t q = 0; written && q < g_->n_qsa_layers(); ++q) ++ for (int t = 0; written && t < T; ++t) ++ written = std::fwrite(trace_h_ + ((size_t) q * max_t_ + t) * 2 * width, ++ sizeof(float), 2 * width, trace_file_) == 2 * width; ++ if (!written || std::fflush(trace_file_) != 0) { ++ err = "verify: cannot write keyless activation trace"; ++ return false; ++ } ++ const size_t query_width = (size_t) g_->n_head * (size_t) g_->head_dim; ++ bool q_written = std::fwrite(&count, sizeof(count), 1, trace_q_file_) == 1 && ++ std::fwrite(&pos0, sizeof(pos0), 1, trace_q_file_) == 1 && ++ std::fwrite(trace_q_h_, sizeof(float), ++ (size_t) g_->n_qsa_layers() * query_width, trace_q_file_) == ++ (size_t) g_->n_qsa_layers() * query_width; ++ if (!q_written || std::fflush(trace_q_file_) != 0) { ++ err = "verify: cannot write keyless query trace"; ++ return false; ++ } ++ } + progress_at("verify window: waiting for the expert copies", (int64_t) T); + cudaStreamSynchronize(copy_); // no host function of this window may raise flag B in the next one + if (prof_on_ && G == 1) { // the window's GPU stage stamps +diff --git a/src/kernels/cuda/keyless.cu b/src/kernels/cuda/keyless.cu +new file mode 100644 +index 00000000..16485d30 +--- /dev/null ++++ b/src/kernels/cuda/keyless.cu +@@ -0,0 +1,25 @@ ++#include "strata/core/keyless.hpp" ++#include ++#include ++namespace strata::kernels { ++namespace { ++__global__ void route_kernel(float* q, const float* matrices, int heads) { ++ __shared__ float row[256]; ++ const int d = threadIdx.x, h = blockIdx.x % heads; ++ float* query = q + (size_t)blockIdx.x * 256; ++ row[d] = query[d]; ++ __syncthreads(); ++ const float* weight = matrices + ((size_t)h * 256 + d) * 256; ++ float sum = 0; ++ for (int i = 0; i < 256; ++i) sum = fmaf(row[i], weight[i], sum); ++ query[d] = sum; ++} ++} ++void keyless_route_query(float* q, const float* matrices, int64_t tokens, int heads, int dim, void* stream) { ++ if (!q || !matrices || tokens < 1 || heads < 1 || dim != 256 || tokens > INT32_MAX / heads) ++ throw std::runtime_error("invalid keyless query routing geometry or artifact"); ++ route_kernel<<<(unsigned)(tokens*heads),256,0,(cudaStream_t)stream>>>(q, matrices, heads); ++ const auto error = cudaGetLastError(); ++ if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); ++} ++} +diff --git a/src/kernels/cuda/kv_q8.cu b/src/kernels/cuda/kv_q8.cu +index fb2ccec4..077e3167 100644 +--- a/src/kernels/cuda/kv_q8.cu ++++ b/src/kernels/cuda/kv_q8.cu +@@ -34,7 +34,7 @@ __global__ void kv_append_q8_kernel(int8_t* __restrict__ k_q, int8_t* __restrict + int head_dim, int page_size, KvHostPools host) { + const long long pos = (long long) __ldg(step + kStepPos); + const int h = blockIdx.x, g = blockIdx.y, t = threadIdx.x; +- const bool is_v = blockIdx.z == 1; ++ const bool is_v = k_q == nullptr || blockIdx.z == 1; + const int groups = head_dim / KV_Q8_GROUP; + const float x = (is_v ? vcur : kcur)[h * head_dim + g * KV_Q8_GROUP + t]; + // max |x| over the 64 values: two warps, then combine through shared memory in a fixed order +@@ -58,7 +58,7 @@ __global__ void kv_append_q8_kernel(int8_t* __restrict__ k_q, int8_t* __restrict + (is_v ? v_q : k_q)[row * head_dim + g * KV_Q8_GROUP + t] = (int8_t) q; + if (t == 0) (is_v ? v_scale : k_scale)[row * groups + g] = sbits; + } +- if (host.k_q != nullptr) { ++ if ((is_v ? host.v_q : host.k_q) != nullptr) { + const long long row = ((pos / page_size) * kv_heads + h) * page_size + (pos % page_size); + (is_v ? host.v_q : host.k_q)[row * head_dim + g * KV_Q8_GROUP + t] = (int8_t) q; + if (t == 0) (is_v ? host.v_scale : host.k_scale)[row * groups + g] = sbits; +@@ -104,7 +104,7 @@ void kv_append_q8_step(int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_ + const int32_t* step, const float* kcur, const float* vcur, const QsaShapes& s, void* stream, + const KvHostPools* host) { + validate(s, "kv_append_q8"); +- const dim3 grid((unsigned) s.n_head_kv, (unsigned) (s.head_dim / KV_Q8_GROUP), 2); ++ const dim3 grid((unsigned) s.n_head_kv, (unsigned) (s.head_dim / KV_Q8_GROUP), k_q ? 2 : 1); + kv_append_q8_kernel<<>>( + k_q, v_q, k_scale, v_scale, page_table, step, kcur, vcur, (int) s.n_head_kv, (int) s.head_dim, + (int) s.page_size, host ? *host : KvHostPools{}); +diff --git a/src/kernels/cuda/kv_stream.cu b/src/kernels/cuda/kv_stream.cu +index ec01ff22..ae78d8f0 100644 +--- a/src/kernels/cuda/kv_stream.cu ++++ b/src/kernels/cuda/kv_stream.cu +@@ -33,7 +33,11 @@ struct Runs { + Runs runs_of(const QsaAttnPools& slots, const KvHostPools& host, int fmt, const QsaShapes& s) { + const int rows = (int) (s.n_head_kv * s.page_size); + Runs r{}; +- if (fmt == kKvQ4) { ++ if (fmt == kKvValueInt8) { ++ r.src[0] = (const uint8_t*) host.v_q; r.dst[0] = (uint8_t*) slots.v_q; r.len[0] = rows * (int)s.head_dim; ++ r.src[1] = (const uint8_t*) host.v_scale; r.dst[1] = (uint8_t*) slots.v_scale; r.len[1] = rows * (int)(s.head_dim / KV_Q8_GROUP) * 2; ++ r.n = 2; ++ } else if (fmt == kKvQ4) { + const int bytes = rows * (int) kv_q4_bytes_per_head((int) s.head_dim); + r.src[0] = (const uint8_t*) host.k_q4; r.dst[0] = (uint8_t*) slots.k_q4; r.len[0] = bytes; + r.src[1] = (const uint8_t*) host.v_q4; r.dst[1] = (uint8_t*) slots.v_q4; r.len[1] = bytes; +@@ -191,6 +195,7 @@ __global__ void ring_kernel(int32_t* table, long long n_blocks, long long n_slot + + uint64_t kv_block_bytes(const QsaShapes& s, int fmt) { + const uint64_t rows = (uint64_t) (s.n_head_kv * s.page_size); ++ if (fmt == kKvValueInt8) return rows * ((uint64_t)s.head_dim + (uint64_t)(s.head_dim / KV_Q8_GROUP)*2); + if (fmt == kKvQ4) return rows * kv_q4_bytes_per_head((int) s.head_dim) * 2; + return fmt == kKvInt8 ? rows * (uint64_t) s.head_dim * 2 + rows * (uint64_t) (s.head_dim / KV_Q8_GROUP) * 2 * 2 + : rows * (uint64_t) s.head_dim * 2 * 2; +diff --git a/src/kernels/cuda/qsa_decode_attn.cu b/src/kernels/cuda/qsa_decode_attn.cu +index 4035999a..c59f21d4 100644 +--- a/src/kernels/cuda/qsa_decode_attn.cu ++++ b/src/kernels/cuda/qsa_decode_attn.cu +@@ -1,5 +1,6 @@ + // src/kernels/cuda/qsa_decode_attn.cu - see include/strata/kernels/qsa_decode_attn.hpp. + #include "strata/kernels/qsa_decode_attn.hpp" ++#include "strata/kernels/mrope.hpp" + #include "strata/kernels/kv_q8.hpp" + #include "strata/kernels/kv_q4.hpp" + +@@ -71,7 +72,7 @@ __device__ __forceinline__ void load8_q4(const QsaAttnPools& p, bool value, long + template + __device__ __forceinline__ void load8(const QsaAttnPools& p, bool value, long long row, int d0, float* out) { + if constexpr (KV_MODE == 0) load8_f16(p, value, row, d0, out); +- else if constexpr (KV_MODE == 1) load8_q8(p, value, row, d0, out); ++ else if constexpr (KV_MODE == 1 || KV_MODE == 4) load8_q8(p, value, row, d0, out); + else if constexpr (KV_MODE == 3) { + // hybrid K8V4: both sides are defined - K unrotated INT8, V rotated Q4_0 - so a value=true call + // reads the Q4_0 pool instead of dereferencing the null v_q (no call site does today; PR review) +@@ -127,7 +128,22 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __rest + continue; + } + float k8[8]; +- load8(p, false, srow[c], lane * 8, k8); ++ load8(p, KV_MODE == 4, srow[c], lane * 8, k8); ++ if constexpr (KV_MODE == 4) { ++ const int d0 = lane * 8, half = p.keyless_n_rot / 2; ++ if (d0 < p.keyless_n_rot) { ++ float paired[8]; ++ load8_q8(p, true, srow[c], d0 < half ? d0 + half : d0 - half, paired); ++ const int cell = ids[c0 + c]; ++ for (int d = 0; d < 8; ++d) { ++ const int pair = (d0 + d) % half; ++ const int rotary_pos = mrope_pos(p.keyless_mrope, cell, pair); ++ const float co = p.keyless_cos[(size_t)rotary_pos * half + pair]; ++ const float si = p.keyless_sin[(size_t)rotary_pos * half + pair]; ++ k8[d] = d0 < half ? k8[d]*co - paired[d]*si : k8[d]*co + paired[d]*si; ++ } ++ } ++ } + #pragma unroll + for (int h = 0; h < G; ++h) { + const float4 qa = *reinterpret_cast(&sq[h][lane * 8]); +@@ -160,7 +176,7 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __rest + float v; + if constexpr (KV_MODE == 0) { + v = __half2float(__ushort_as_half(p.v_pool[srow[c] * HD + t])); +- } else if constexpr (KV_MODE == 1) { ++ } else if constexpr (KV_MODE == 1 || KV_MODE == 4) { + const float sc = __half2float(__ushort_as_half(p.v_scale[srow[c] * (HD / KV_Q8_GROUP) + t / KV_Q8_GROUP])); + v = (float) p.v_q[srow[c] * HD + t] * sc; + } else { // modes 2 and 3: V is rotated Q4_0 (kv_q4.hpp); the caller rotates the output back +@@ -211,13 +227,18 @@ __global__ void __launch_bounds__(HD) attn_merge_kernel(const float* __restrict_ + void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, + int64_t cap, const QsaShapes& s, float* scratch, float* attn, int64_t n_q, void* stream) { + if (n_q <= 0) return; +- if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !scratch || !ids || !steps || ++ if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !q || !attn || !scratch || !ids || !steps || + !pools.page_table || n_q > 65535) { + std::fprintf(stderr, "qsa_decode_attn_batch: unsupported geometry or missing buffers\n"); + std::exit(1); + } +- const int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3 ++ const int kv_mode = pools.without_key ? 4 : pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3 + : (pools.k_q != nullptr ? 1 : 0)); ++ if (kv_mode == 4 && (pools.k_pool || pools.k_q || pools.k_scale || pools.k_q4 || ++ !pools.v_q || !pools.v_scale || !pools.keyless_cos || !pools.keyless_sin || pools.keyless_n_rot != 64)) { ++ std::fprintf(stderr, "qsa_decode_attn: V-only requires only V codes/scales and RoPE tables\n"); ++ std::exit(1); ++ } + const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK); + // per query: [acc: n_chunks*n_head*HD][m: n_chunks*n_head][l: n_chunks*n_head], all offsets from one stride + const long long stride = (long long) qsa_decode_attn_scratch_floats(cap, s); +@@ -227,7 +248,9 @@ void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int3 + const float scale = 1.0f / sqrtf((float) HD); + const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv, (unsigned) n_q); + cudaStream_t st = (cudaStream_t) stream; +- if (kv_mode == 3) ++ if (kv_mode == 4) ++ attn_chunk_kernel<4><<>>(q, pools, ids, steps, (int)s.n_head_kv, (int)s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int)cap, stride); ++ else if (kv_mode == 3) + attn_chunk_kernel<3><<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, + scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); + else if (kv_mode == 2) +@@ -255,19 +278,25 @@ uint64_t qsa_decode_attn_scratch_floats(int64_t cap, const QsaShapes& s) { + + void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* step, + int64_t cap, const QsaShapes& s, float* scratch, float* attn, void* stream) { +- if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !scratch || !ids || !step || ++ if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !q || !attn || !scratch || !ids || !step || + !pools.page_table) { + std::fprintf(stderr, "qsa_decode_attn: unsupported geometry or missing buffers\n"); + std::exit(1); + } +- const int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3 ++ const int kv_mode = pools.without_key ? 4 : pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3 + : (pools.k_q != nullptr ? 1 : 0)); +- if (kv_mode == 3 ? (!pools.k_scale || !pools.v_q4) ++ if (kv_mode == 4 ? (!pools.v_q || !pools.v_scale || !pools.keyless_cos || !pools.keyless_sin || pools.keyless_n_rot != 64) ++ : (kv_mode == 3 ? (!pools.k_scale || !pools.v_q4) + : (kv_mode == 2 ? (!pools.v_q4) : (kv_mode == 1 ? (!pools.v_q || !pools.k_scale || !pools.v_scale) +- : (!pools.k_pool || !pools.v_pool)))) { ++ : (!pools.k_pool || !pools.v_pool))))) { + std::fprintf(stderr, "qsa_decode_attn: incomplete KV pools\n"); + std::exit(1); + } ++ if (kv_mode == 4 && (pools.k_pool || pools.k_q || pools.k_scale || pools.k_q4 || ++ !pools.v_q || !pools.v_scale || !pools.keyless_cos || !pools.keyless_sin || pools.keyless_n_rot != 64)) { ++ std::fprintf(stderr, "qsa_decode_attn: V-only requires only V codes/scales and RoPE tables\n"); ++ std::exit(1); ++ } + const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK); + float* part_acc = scratch; + float* part_m = scratch + (size_t) n_chunks * s.n_head * HD; +@@ -275,7 +304,9 @@ void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32 + const float scale = 1.0f / sqrtf((float) HD); + const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv); + cudaStream_t st = (cudaStream_t) stream; +- if (kv_mode == 3) ++ if (kv_mode == 4) ++ attn_chunk_kernel<4><<>>(q, pools, ids, step, (int)s.n_head_kv, (int)s.page_size, scale, part_acc, part_m, part_l, n_chunks); ++ else if (kv_mode == 3) + attn_chunk_kernel<3><<>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size, + scale, part_acc, part_m, part_l, n_chunks); + else if (kv_mode == 2) +diff --git a/src/kernels/keyless_parity.cpp b/src/kernels/keyless_parity.cpp +new file mode 100644 +index 00000000..107ebf2b +--- /dev/null ++++ b/src/kernels/keyless_parity.cpp +@@ -0,0 +1,119 @@ ++// Independent CPU reference for query routing and physical V-only attention. ++#include "strata/core/keyless.hpp" ++#include "strata/core/layer.hpp" ++#include "strata/kernels/qsa_decode_attn.hpp" ++#include "strata/kernels/f16_bits.hpp" ++#include "strata/kernels/kv_stream.hpp" ++#include ++#include ++#include ++#include ++#include ++#include ++ ++namespace { ++void check(cudaError_t e) { if (e != cudaSuccess) throw std::runtime_error(cudaGetErrorString(e)); } ++template T* device(const std::vector& values) { ++ T* p; check(cudaMalloc((void**)&p, values.size()*sizeof(T))); ++ check(cudaMemcpy(p, values.data(), values.size()*sizeof(T), cudaMemcpyHostToDevice)); return p; ++} ++} ++int main() { ++ using namespace strata::kernels; ++ try { ++ int count=0; if (cudaGetDeviceCount(&count)!=cudaSuccess || count==0) return 77; ++ constexpr int H=24, D=256, KV=2, CELLS=96, PAGE=4, BATCH=3, CAP=96; ++ std::vector query(BATCH*H*D), routing(H*D*D), routed(query.size()), co(CELLS*32), si(co.size()); ++ for (size_t i=0;i actual(query.size()); check(cudaMemcpy(actual.data(),dq,actual.size()*4,cudaMemcpyDeviceToHost)); ++ double route_error=0; for(size_t i=0;i2e-6) throw std::runtime_error("query routing disagrees with independent matrix product"); ++ const int pos[BATCH]={31,63,95}; ++ for(int p=0;p unrotated=routed; ++ std::vector positions(CELLS*3); ++ for(int cell=0;cell table(CELLS/PAGE), ids(BATCH*CAP,-1), steps(BATCH*kStepCount); ++ for(int page=0;page values(CELLS*KV*D); ++ std::vector scales(CELLS*KV*4); ++ for(int cell=0;cell scratch(BATCH*qsa_decode_attn_scratch_floats(CAP,qsa_real_shapes())), result(BATCH*H*D); ++ float *dsc=device(scratch), *dout=device(result); ++ qsa_decode_attn_batch(dq,pools,di,ds,CAP,qsa_real_shapes(),dsc,dout,BATCH,nullptr); ++ check(cudaMemcpy(result.data(),dout,result.size()*4,cudaMemcpyDeviceToHost)); ++ double error_sq=0, reference_sq=0, max_error=0; ++ for(int b=0;b scores(width), weights(width), reference(D,0); ++ for(int j=0;j1e-5 || max_error>1e-5) throw std::runtime_error("V-only attention disagrees with positional CPU reference"); ++ if(kv_block_bytes(qsa_real_shapes(),kKvValueInt8)*2!=kv_block_bytes(qsa_real_shapes(),kKvInt8)) ++ throw std::runtime_error("V-only block accounting is not half of K+V"); ++ std::printf("mrope=%d query_max_abs_error=%.9g attention_relative_l2=%.9g attention_max_abs_error=%.9g\n",vision,route_error,l2,max_error); ++ } ++ ++ std::printf("PASS: routed queries; three causal selections; permuted pages; raw value retrieval; no K allocation\n"); ++ return 0; ++ } catch(const std::exception& e) { std::fprintf(stderr,"keyless parity: %s\n",e.what()); return 1; } ++} +diff --git a/src/kernels/kv_stream_parity.cpp b/src/kernels/kv_stream_parity.cpp +index 07557347..e8b28765 100644 +--- a/src/kernels/kv_stream_parity.cpp ++++ b/src/kernels/kv_stream_parity.cpp +@@ -24,11 +24,13 @@ + #include + #include + #include ++#include + + namespace k = strata::kernels; + + namespace { + int g_fail = 0; ++float *keyless_cos=nullptr, *keyless_sin=nullptr; + void ck(cudaError_t e, const char* w) { + if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); } + } +@@ -55,10 +57,10 @@ struct Pools { // one K/V pool set of `pages` pages + const size_t b = rows * k::kv_q4_bytes_per_head((int) s.head_dim); + p.k_q4 = host ? halloc(b) : dalloc(b); + p.v_q4 = host ? halloc(b) : dalloc(b); +- } else if (fmt == k::kKvInt8) { +- p.k_q = host ? halloc(rows * s.head_dim) : dalloc(rows * s.head_dim); ++ } else if (fmt == k::kKvInt8 || fmt == k::kKvValueInt8) { ++ if (fmt != k::kKvValueInt8) p.k_q = host ? halloc(rows * s.head_dim) : dalloc(rows * s.head_dim); + p.v_q = host ? halloc(rows * s.head_dim) : dalloc(rows * s.head_dim); +- p.k_scale = host ? halloc(rows * 4) : dalloc(rows * 4); ++ if (fmt != k::kKvValueInt8) p.k_scale = host ? halloc(rows * 4) : dalloc(rows * 4); + p.v_scale = host ? halloc(rows * 4) : dalloc(rows * 4); + } else { + p.k_pool = host ? halloc(rows * s.head_dim) : dalloc(rows * s.head_dim); +@@ -68,6 +70,8 @@ struct Pools { // one K/V pool set of `pages` pages + k::QsaAttnPools attn(const int32_t* table) const { + k::QsaAttnPools a; + a.k_pool = p.k_pool; a.v_pool = p.v_pool; a.k_q = p.k_q; a.v_q = p.v_q; a.k_scale = p.k_scale; ++ a.without_key = p.v_q && !p.k_q; ++ a.keyless_cos=keyless_cos; a.keyless_sin=keyless_sin; a.keyless_n_rot=64; + a.v_scale = p.v_scale; a.k_q4 = p.k_q4; a.v_q4 = p.v_q4; a.page_table = table; + return a; + } +@@ -76,7 +80,7 @@ struct Pools { // one K/V pool set of `pages` pages + void append(const Pools& pl, const int32_t* table, const int32_t* step, const float* kc, const float* vc, + const k::QsaShapes& s, int fmt, const k::KvHostPools* host) { + if (fmt == k::kKvQ4) k::kv_append_q4_step(pl.p.k_q4, pl.p.v_q4, table, step, kc, vc, s, nullptr, host); +- else if (fmt == k::kKvInt8) k::kv_append_q8_step(pl.p.k_q, pl.p.v_q, pl.p.k_scale, pl.p.v_scale, table, step, kc, vc, s, nullptr, host); ++ else if (fmt == k::kKvInt8 || fmt == k::kKvValueInt8) k::kv_append_q8_step(pl.p.k_q, pl.p.v_q, pl.p.k_scale, pl.p.v_scale, table, step, kc, vc, s, nullptr, host); + else k::kv_append_step(pl.p.k_pool, pl.p.v_pool, table, step, kc, vc, s, nullptr, host); + } + +@@ -103,7 +107,7 @@ std::vector selection(int64_t n_kv, int64_t width, std::mt19937& rng) { + } + + bool run(int fmt) { +- const char* name = fmt == k::kKvQ4 ? "q4_0" : fmt == k::kKvInt8 ? "int8" : "fp16"; ++ const char* name = fmt == k::kKvValueInt8 ? "v-only-int8" : fmt == k::kKvQ4 ? "q4_0" : fmt == k::kKvInt8 ? "int8" : "fp16"; + k::QsaShapes s = k::qsa_real_shapes(); + const int64_t N = 40000, n_blocks = (N + 3) / 4, n_slots = 8 * 516 + 700; // must evict: slots < blocks + const int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s), NQ = 8; +@@ -111,6 +115,16 @@ bool run(int fmt) { + std::mt19937 rng(7 + 4 * fmt); + std::normal_distribution nd(0.f, 1.f); + ++ if (fmt == k::kKvValueInt8) { ++ std::vector co(N*32), si(N*32); ++ for(int64_t pos=0;pos(co.size()); keyless_sin=dalloc(si.size()); ++ ck(cudaMemcpy(keyless_cos,co.data(),co.size()*4,cudaMemcpyHostToDevice),"cos"); ++ ck(cudaMemcpy(keyless_sin,si.data(),si.size()*4,cudaMemcpyHostToDevice),"sin"); ++ } + Pools ref, slots, host; + ref.alloc(n_blocks, s, fmt, false); + slots.alloc(n_slots, s, fmt, false); +@@ -225,7 +239,9 @@ bool run(int fmt) { + } + } // namespace + +-int main() { ++int main(int argc, char** argv) { ++ int count=0; if(cudaGetDeviceCount(&count)!=cudaSuccess || !count) return 77; ++ if(argc==2 && std::strcmp(argv[1],"--v-only")==0) return run(k::kKvValueInt8)?0:1; + std::printf("kv_stream_parity: streamed vs resident KV, bitwise\n"); + const bool a = run(k::kKvInt8), b = run(k::kKvF16), c = run(k::kKvQ4); + if (!a || !b || !c) ++g_fail; +diff --git a/src/kernels/ngram.cpp b/src/kernels/ngram.cpp +index 1a1552bf..bcb611c1 100644 +--- a/src/kernels/ngram.cpp ++++ b/src/kernels/ngram.cpp +@@ -11,12 +11,31 @@ + #include + #include + #include ++#include ++#include ++#include + #if !defined(_WIN32) + #include + #endif + #include + #include + ++#if defined(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE) ++#include ++#include ++#endif ++ ++#if defined(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE) || defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++#include ++#include ++#endif ++ ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++#include "kar_ple_cache.hpp" ++#include "libkar.h" ++#include ++#endif ++ + #if defined(_WIN32) + // `PrefetchVirtualMemory` (memoryapi.h, Windows 8+) is the whole point of the change in `gather` below. + #define WIN32_LEAN_AND_MEAN +@@ -29,6 +48,69 @@ namespace strata::kernels { + namespace { + /// The A/B arm. Host-token-path only, so it needs no atomics; see the note on `ple_prefetch_enable`. + bool g_ple_prefetch = true; ++#if defined(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE) ++struct PleRowTrace { ++ int fd = -1; ++ std::mutex lock; ++ bool failed = false; ++ ++ PleRowTrace() { ++ const char* path = std::getenv("STRATA_PLE_ROW_TRACE_PATH"); ++ if (!path) return; ++ if (!*path) { ++ std::fprintf(stderr, "PLE row trace needs a private output path\n"); ++ return; ++ } ++ fd = open(path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, 0600); ++ if (fd < 0) { ++ std::perror("cannot create private PLE row trace"); ++ return; ++ } ++ constexpr char header[] = "# strata-ple-rows v1: 16 global u32 row IDs per line\n"; ++ if (write(fd, header, sizeof(header) - 1) != static_cast(sizeof(header) - 1)) { ++ std::fprintf(stderr, "cannot write PLE row trace header\n"); ++ failed = true; ++ } ++ } ++ ++ ~PleRowTrace() { if (fd >= 0) close(fd); } ++ ++ void emit(const uint32_t* rows) { ++ if (fd < 0) return; ++ std::lock_guard guard(lock); ++ if (failed) return; ++ char line[PLE_N_HEADS * 12]; ++ size_t used = 0; ++ for (int h = 0; h < PLE_N_HEADS; ++h) { ++ const int written = std::snprintf(line + used, sizeof(line) - used, "%u%c", ++ rows[h], h + 1 == PLE_N_HEADS ? '\n' : ' '); ++ if (written < 0 || static_cast(written) >= sizeof(line) - used) { ++ failed = true; ++ std::fprintf(stderr, "PLE row trace line exceeded its buffer\n"); ++ return; ++ } ++ used += static_cast(written); ++ } ++ size_t done = 0; ++ while (done < used) { ++ const ssize_t n = write(fd, line + done, used - done); ++ if (n < 0 && errno == EINTR) continue; ++ if (n <= 0) { ++ failed = true; ++ if (n < 0) std::perror("cannot write PLE row trace"); ++ else std::fprintf(stderr, "cannot write PLE row trace: short write\n"); ++ return; ++ } ++ done += static_cast(n); ++ } ++ } ++}; ++ ++PleRowTrace& ple_row_trace() { ++ static PleRowTrace trace; ++ return trace; ++} ++#endif + } // namespace + + void ple_prefetch_enable(bool on) { g_ple_prefetch = on; } +@@ -89,6 +171,9 @@ void ngram_rows(const int32_t* tokens, const int32_t* prev, int n_tokens, const + out[i * PLE_N_HEADS + h] = (uint32_t) (mixed % c.vocab[h] + c.offset[h]); + } + } ++#if defined(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE) ++ ple_row_trace().emit(out + i * PLE_N_HEADS); ++#endif + } + } + +@@ -153,6 +238,51 @@ struct PleTable::Impl { + bool fp8 = false; // F8_E4M3 rows (tools/ple_fp8_pack.py); else IQ4_NL + float scale = 1.0f; // the FP8 table's one scale + uint32_t rb = PLE_ROW_BYTES; // bytes per row ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ struct KarPart { ++ uint32_t number = 0; ++ uint64_t row_base = 0; ++ const kar_tensor_info* tensor = nullptr; ++ }; ++ kar_archive* kar = nullptr; ++ int kar_fd = -1; ++ const uint8_t* kar_map = nullptr; ++ size_t kar_bytes = 0; ++ uint32_t kar_level = 0; ++ std::string kar_format; ++ std::vector kar_parts; ++ std::unique_ptr kar_gpu_cache; ++ void decode_kar_row(uint32_t row, float* out160) const { ++ const auto part = std::lower_bound(kar_parts.begin(), kar_parts.end(), row, ++ [](const KarPart& item, uint32_t wanted) { ++ return item.row_base + item.tensor->row_count <= wanted; ++ }); ++ const kar_tensor_info* t = part->tensor; ++ const uint64_t local_row = uint64_t(row) - part->row_base; ++ const uint64_t first_word = local_row * t->row_words; ++ const uint64_t book_offset = t->books_offset + ((uint64_t{1} << kar_level) - 2) * 2; ++ for (uint32_t word = 0; word < t->row_words; ++word) { ++ const uint64_t source_word = first_word + word; ++ const uint64_t scale_offset = t->scales_offset + 2 * (source_word / (t->group / 32)); ++ const float scale = strata::fp16_to_fp32(strata::read_u16(kar_map + scale_offset)); ++ uint32_t bits[8] = {}; ++ for (uint32_t level = 0; level < kar_level; ++level) { ++ const uint8_t* p = kar_map + t->planes_offset + uint64_t(level) * t->plane_stride_bytes ++ + source_word * 4; ++ bits[level] = uint32_t(p[0]) | (uint32_t(p[1]) << 8) | ++ (uint32_t(p[2]) << 16) | (uint32_t(p[3]) << 24); ++ } ++ for (uint32_t bit = 0; bit < 32; ++bit) { ++ uint32_t code = 0; ++ for (uint32_t level = 0; level < kar_level; ++level) ++ code = (code << 1) | ((bits[level] >> bit) & 1u); ++ const float book = strata::fp16_to_fp32(strata::read_u16(kar_map + book_offset + code * 2)); ++ out160[word * 32 + bit] = book * scale; ++ } ++ } ++ bytes_read += t->row_words * (uint64_t(kar_level) * 4 + 2); ++ } ++#endif + void decode(const uint8_t* row, float* out160) const { + if (fp8) fp8_e4m3_dequant_row(row, scale, out160); + else if (q5_0) +@@ -164,6 +294,177 @@ struct PleTable::Impl { + PleTable::PleTable() : impl_(new Impl) {} + PleTable::~PleTable() { close(); delete impl_; } + ++bool PleTable::open_kar(const std::string& kar_path, uint32_t level, std::string& err, ++ uint64_t expected_rows) { ++#if !defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ (void) kar_path; (void) level; (void) expected_rows; ++ err = "experimental KAR PLE support is not compiled into this engine"; ++ return false; ++#else ++ close(); ++ if (level < 1 || level > 8 || expected_rows == 0) { ++ err = "KAR PLE level or expected row count is invalid"; ++ return false; ++ } ++ kar_archive* archive = nullptr; ++ const kar_status status = kar_open(kar_path.c_str(), KAR_OPEN_VERIFY_PAYLOAD, &archive); ++ if (status != KAR_OK) { ++ err = std::string("KAR PLE archive: ") + kar_strerror(status) + ": " + kar_last_error(); ++ return false; ++ } ++ impl_->kar = archive; ++ impl_->kar_fd = ::open(kar_path.c_str(), O_RDONLY | O_CLOEXEC); ++ struct stat file_info {}; ++ if (impl_->kar_fd < 0 || fstat(impl_->kar_fd, &file_info) || file_info.st_size <= 0 || ++ uint64_t(file_info.st_size) != kar_info(impl_->kar)->archive_bytes) { ++ err = "KAR PLE cannot reopen the verified archive at its expected length"; ++ close(); ++ return false; ++ } ++ impl_->kar_bytes = size_t(file_info.st_size); ++ void* map = mmap(nullptr, impl_->kar_bytes, PROT_READ, MAP_PRIVATE, impl_->kar_fd, 0); ++ if (map == MAP_FAILED) { ++ err = "KAR PLE cannot map the verified archive"; ++ close(); ++ return false; ++ } ++ impl_->kar_map = static_cast(map); ++ const std::string parent = "per_layer_token_embd.weight"; ++ const std::string prefix = parent + "#strata-part-"; ++ uint32_t declared_parts = 0; ++ for (uint32_t i = 0; i < kar_tensor_count(impl_->kar); ++i) { ++ const kar_tensor_info* t = kar_tensor(impl_->kar, i); ++ const std::string name = t->name; ++ uint32_t number = 0, total = 0; ++ if (name == parent) { ++ number = total = 1; ++ } else if (name.rfind(prefix, 0) == 0) { ++ char extra = 0; ++ if (std::sscanf(name.c_str() + prefix.size(), "%u-of-%u%c", &number, &total, &extra) != 2) { ++ err = "KAR PLE part name is malformed"; ++ close(); ++ return false; ++ } ++ } else { ++ continue; ++ } ++ if (!number || !total || number > total || (declared_parts && declared_parts != total) || ++ t->storage_class != KAR_NESTED || t->source_dtype != KAR_F32 || ++ t->nesting != KAR_TOPDOWN || t->n_dims != 2 || ++ t->dims[0] != PLE_HEAD_DIM || t->row_words != PLE_HEAD_DIM / 32 || ++ t->n_elements % PLE_HEAD_DIM || t->group < 32 || t->group % 32 || ++ level < t->planes_min || level > t->planes_max) { ++ err = "KAR PLE part geometry or precision level differs from the model"; ++ close(); ++ return false; ++ } ++ declared_parts = total; ++ impl_->kar_parts.push_back({number, 0, t}); ++ } ++ std::sort(impl_->kar_parts.begin(), impl_->kar_parts.end(), ++ [](const Impl::KarPart& left, const Impl::KarPart& right) { ++ return left.number < right.number; ++ }); ++ if (!declared_parts || impl_->kar_parts.size() != declared_parts) { ++ err = "KAR PLE parts are absent or incomplete"; ++ close(); ++ return false; ++ } ++ uint64_t rows = 0; ++ for (uint32_t i = 0; i < impl_->kar_parts.size(); ++i) { ++ auto& part = impl_->kar_parts[i]; ++ if (part.number != i + 1 || part.tensor->row_count == 0 || ++ part.tensor->row_count > expected_rows - rows) { ++ err = "KAR PLE parts are out of order or exceed expected rows"; ++ close(); ++ return false; ++ } ++ part.row_base = rows; ++ rows += part.tensor->row_count; ++ } ++ if (rows != expected_rows) { ++ err = "KAR PLE row count differs from the model"; ++ close(); ++ return false; ++ } ++ impl_->n_rows = rows; ++ impl_->kar_level = level; ++ impl_->kar_format = "KAR-L" + std::to_string(level) + "-CPU"; ++ impl_->mode = PleIo::Mmap; ++ return true; ++#endif ++} ++ ++bool PleTable::enable_kar_gpu_cache(uint32_t cache_mib, std::string& err) { ++#if !defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ (void) cache_mib; ++ err = "experimental KAR PLE support is not compiled into this engine"; ++ return false; ++#else ++ if (!impl_->kar || impl_->kar_level != 2 || impl_->kar_gpu_cache) { ++ err = "KAR PLE GPU cache requires an open level-2 archive and no existing cache"; ++ return false; ++ } ++ std::vector parts; ++ parts.reserve(impl_->kar_parts.size()); ++ for (const auto& part : impl_->kar_parts) parts.push_back({part.row_base, part.tensor}); ++ auto cache = std::make_unique(); ++ if (!cache->open(impl_->kar_map, impl_->kar_bytes, parts, cache_mib, 65536, err)) return false; ++ impl_->kar_gpu_cache = std::move(cache); ++ impl_->kar_format = "KAR-L2-GPU-cache"; ++ return true; ++#endif ++} ++ ++bool PleTable::kar_gpu_cache_enabled() const { ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ return impl_->kar_gpu_cache != nullptr; ++#else ++ return false; ++#endif ++} ++ ++bool PleTable::collect_device(float* device_out2560, void* stream, std::string& err) { ++#if !defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ (void) device_out2560; (void) stream; ++ err = "experimental KAR PLE support is not compiled into this engine"; ++ return false; ++#else ++ if (!impl_->kar_gpu_cache || !impl_->pending) { ++ err = "KAR PLE GPU collect requires a cache and an issued token"; ++ return false; ++ } ++ if (!impl_->kar_gpu_cache->enqueue(impl_->rows, PLE_N_HEADS, device_out2560, ++ reinterpret_cast(stream), err)) return false; ++ impl_->pending = false; ++ return true; ++#endif ++} ++ ++bool PleTable::gather_batch_device(const uint32_t* rows, size_t n_tokens, float* device_out, ++ void* stream, std::string& err) { ++#if !defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ (void) rows; (void) n_tokens; (void) device_out; (void) stream; ++ err = "experimental KAR PLE support is not compiled into this engine"; ++ return false; ++#else ++ if (!impl_->kar_gpu_cache || impl_->pending || !rows || !device_out || ++ n_tokens == 0 || n_tokens > 65536) { ++ err = "KAR PLE GPU gather requires a cache, no pending token, and 1..65536 tokens"; ++ return false; ++ } ++ const size_t count = n_tokens * PLE_N_HEADS; ++ const size_t chunk_rows = std::min(65536, impl_->kar_gpu_cache->slots()); ++ for (size_t offset = 0; offset < count; offset += chunk_rows) { ++ const size_t length = std::min(chunk_rows, count - offset); ++ if (!impl_->kar_gpu_cache->enqueue(rows + offset, length, ++ device_out + offset * PLE_HEAD_DIM, ++ reinterpret_cast(stream), err)) return false; ++ } ++ return true; ++#endif ++} ++ + bool PleTable::open(const std::string& gguf_path, std::string& err) { + return open(gguf_path, err, PleIoOptions{}); + } +@@ -280,6 +581,19 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO + } + + void PleTable::close() { ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ impl_->kar_gpu_cache.reset(); ++ if (impl_->kar_map) munmap(const_cast(impl_->kar_map), impl_->kar_bytes); ++ impl_->kar_map = nullptr; ++ impl_->kar_bytes = 0; ++ if (impl_->kar_fd >= 0) ::close(impl_->kar_fd); ++ impl_->kar_fd = -1; ++ if (impl_->kar) kar_close(impl_->kar); ++ impl_->kar = nullptr; ++ impl_->kar_parts.clear(); ++ impl_->kar_level = 0; ++ impl_->kar_format.clear(); ++#endif + impl_->reader.close(); + impl_->pending = false; + impl_->locked = false; // the unmap below releases the lock +@@ -293,14 +607,31 @@ void PleTable::close() { + impl_->fp8 = false; + } + +-bool PleTable::is_open() const { return impl_->data != nullptr || impl_->reader.is_open(); } ++bool PleTable::is_open() const { ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ if (impl_->kar) return true; ++#endif ++ return impl_->data != nullptr || impl_->reader.is_open(); ++} + bool PleTable::locked() const { return impl_->locked; } +-const char* PleTable::format() const { return impl_->fp8 ? "F8_E4M3" : impl_->q5_0 ? "Q5_0" : "IQ4_NL"; } ++const char* PleTable::format() const { ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ if (impl_->kar) return impl_->kar_format.c_str(); ++#endif ++ return impl_->fp8 ? "F8_E4M3" : impl_->q5_0 ? "Q5_0" : "IQ4_NL"; ++} + PleIo PleTable::mode() const { return impl_->mode; } + uint64_t PleTable::rows() const { return impl_->n_rows; } + uint64_t PleTable::bytes_read() const { return impl_->bytes_read; } + + void PleTable::read_row(uint32_t row, float* out160) const { ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ if (impl_->kar) { ++ if (row >= impl_->n_rows) std::memset(out160, 0, (size_t) PLE_HEAD_DIM * sizeof(float)); ++ else impl_->decode_kar_row(row, out160); ++ return; ++ } ++#endif + if (impl_->mode == PleIo::Direct && impl_->reader.is_open()) { + uint8_t raw[PLE_ROW_BYTES_MAX]; + std::string err; +@@ -378,6 +709,21 @@ bool PleTable::gather_batch(const uint32_t* rows, size_t n_tokens, float* out, s + void PleTable::set_injected_delay_us(double us) { impl_->reader.set_injected_delay_us(us); } + + std::string PleTable::io_report() const { ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ if (impl_->kar_gpu_cache) { ++ const auto s = impl_->kar_gpu_cache->stats(); ++ char buf[300]; ++ std::snprintf(buf, sizeof buf, ++ "PLE GPU cache: %llu hits, %llu misses (%.2f%% hit), %u slots (%.1f MiB compressed), " ++ "%llu compressed bytes, %llu H2D argument bytes", ++ (unsigned long long) s.hits, (unsigned long long) s.misses, ++ s.hits + s.misses ? 100.0 * double(s.hits) / double(s.hits + s.misses) : 0.0, ++ impl_->kar_gpu_cache->slots(), double(impl_->kar_gpu_cache->slots()) * 64.0 / 1048576.0, ++ (unsigned long long) s.compressed_bytes, ++ (unsigned long long) s.host_to_device_bytes); ++ return buf; ++ } ++#endif + if (impl_->mode != PleIo::Direct || !impl_->reader.is_open()) return {}; + const strata::ngram::ReaderStats s = impl_->reader.snapshot(); + char buf[400]; +diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu +index de833442..4c5f4b82 100644 +--- a/src/prefill/kernels.cu ++++ b/src/prefill/kernels.cu +@@ -604,8 +604,9 @@ __global__ void kv_append_kernel(const float* __restrict__ K, const float* __res + uint16_t* v_pool, int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale, + strata::kernels::KvHostPools host, strata::kernels::KvHostPools stage) { + const int64_t t = blockIdx.x; +- const int kvh = blockIdx.y, g = blockIdx.z >> 1; +- const bool is_v = (blockIdx.z & 1) != 0; ++ const bool value_only = k_pool == nullptr && k_q == nullptr; ++ const int kvh = blockIdx.y, g = value_only ? blockIdx.z : blockIdx.z >> 1; ++ const bool is_v = value_only || (blockIdx.z & 1) != 0; + const int d = g * 64 + threadIdx.x; + const float x = (is_v ? V : K)[t * 512 + kvh * 256 + d]; + const int64_t pos = pos0 + t; +@@ -633,11 +634,11 @@ __global__ void kv_append_kernel(const float* __restrict__ K, const float* __res + (is_v ? v_q : k_q)[row * 256 + d] = (int8_t) q; + if (threadIdx.x == 0) (is_v ? v_scale : k_scale)[row * 4 + g] = sb; + } +- if (host.k_q != nullptr) { ++ if ((is_v ? host.v_q : host.k_q) != nullptr) { + (is_v ? host.v_q : host.k_q)[row_id * 256 + d] = (int8_t) q; + if (threadIdx.x == 0) (is_v ? host.v_scale : host.k_scale)[row_id * 4 + g] = sb; + } +- if (stage.k_q != nullptr) { ++ if ((is_v ? stage.v_q : stage.k_q) != nullptr) { + (is_v ? stage.v_q : stage.k_q)[row_id * 256 + d] = (int8_t) q; + if (threadIdx.x == 0) (is_v ? stage.v_scale : stage.k_scale)[row_id * 4 + g] = sb; + } +@@ -665,7 +666,7 @@ void kv_append(const float* K, const float* V, int64_t T, int64_t pos0, const in + uint16_t* k_pool, uint16_t* v_pool, int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale, + void* stream, const strata::kernels::KvHostPools* host, const strata::kernels::KvHostPools* stage) { + if (T <= 0) return; +- kv_append_kernel<<>>( ++ kv_append_kernel<<>>( + K, V, pos0, page_table, page_size, k_pool, v_pool, k_q, v_q, k_scale, v_scale, + host ? *host : strata::kernels::KvHostPools{}, stage ? *stage : strata::kernels::KvHostPools{}); + check("kv_append"); +diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp +index ed47b975..37edb9f0 100644 +--- a/src/prefill/prefill.cpp ++++ b/src/prefill/prefill.cpp +@@ -13,10 +13,12 @@ + #include "strata/kernels/iq_kernels.hpp" + #include "strata/kernels/cpu/expert_layout.hpp" + #include "strata/kernels/qsa.hpp" ++#include "strata/kernels/mrope.hpp" + #include "strata/kernels/kv_stream.hpp" + #include "strata/kernels/cvec.hpp" + #include "strata/kernels/kv_q4.hpp" + #include "strata/core/layer.hpp" ++#include "strata/core/keyless.hpp" + #include "strata/core/native_head.hpp" + #include "strata/kernels/verify_kernels.hpp" + #include "strata/kernels/qsa_decode_attn.hpp" +@@ -40,6 +42,8 @@ + #include + #include + #include ++#include ++#include + + #ifndef STRATA_PREFILL_MMQ + // A build without the llama.cpp sources (no STRATA_NATIVE_EXPERTS): no MMQ, the FP16 expert path everywhere. +@@ -386,9 +390,9 @@ void take_stage(Alloc& o_borrowed, const core::SessionState& ss, const strata::k + st.k_q4 = o.take(rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), ok); + st.v_q4 = o.take(rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), ok); + } else if (q0.kv_int8) { +- st.k_q = o.take(rows * s.head_dim, ok); ++ if (!q0.without_key) st.k_q = o.take(rows * s.head_dim, ok); + st.v_q = o.take(rows * s.head_dim, ok); +- st.k_scale = o.take(rows * (s.head_dim / 64), ok); ++ if (!q0.without_key) st.k_scale = o.take(rows * (s.head_dim / 64), ok); + st.v_scale = o.take(rows * (s.head_dim / 64), ok); + } else { + st.k_pool = o.take(rows * s.head_dim, ok); +@@ -998,6 +1002,21 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e + const core::ModelGeometry& g = *m.g; + core::SessionState& ss = *m.ss; + const auto t_start = Clock::now(); ++ // Offline teacher capture for fitting only the paper's query-routing parameters. ++ // Explicitly bounded and prohibited in serving; this path never predicts or stores K in V-only mode. ++ std::ofstream keyless_trace; ++ if (const char* path = std::getenv("STRATA_KEYLESS_PREFILL_TRACE")) { ++ if (!*path || n > 4096 || pos0 != 0 || ss.qsa_states[0].without_key || std::filesystem::exists(path)) { ++ err = "keyless teacher trace requires a new private file, ordinary K+V and at most 4096 prompt tokens"; ++ return false; ++ } ++ keyless_trace.open(path, std::ios::binary); ++ if (!keyless_trace) { err = "cannot open keyless teacher trace"; return false; } ++ std::filesystem::permissions(path, std::filesystem::perms::owner_read | std::filesystem::perms::owner_write); ++ keyless_trace.write("SKLTRACE", 8); ++ const uint32_t header[5] = {1, (uint32_t)g.n_qsa_layers(), (uint32_t)g.n_head, (uint32_t)g.n_head_kv, (uint32_t)g.head_dim}; ++ keyless_trace.write((const char*)header, sizeof(header)); ++ } + const int64_t LB = stage_lb_, LE = stage_le_; + // the next stage reads chunk c on a thread while this one reads chunk c + 1 (declared first: an early return + // waits for it before anything it reads goes away) +@@ -1020,6 +1039,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e + // after this one is read on a thread while the GPU runs this one, into the other of two buffers. The rows + // depend only on the tokens (the two before a position name its n-grams), so this is the same data. + const bool ple_on = ss.ple.ready() && LB <= 1 && 1 < LE; ++ const bool ple_gpu_cache = ple_on && ss.ple.table->kar_gpu_cache_enabled(); + // the PLE block batched over the chunk: the pinned postops and a BF16 or GGUF-native key (else token by token); + // STRATA_PLE_BATCH=0 keeps the per-token block (the A/B) + static const bool ple_batch_env = [] { +@@ -1030,7 +1050,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e + (ss.ple.w.key_bf16 != nullptr || ss.ple.w.key_native_data != nullptr) && + m.region_bytes / ((uint64_t) (3 * strata::kernels::NG_HC_DIM + N + 4) * 4 + (uint64_t) N * 2 + 4096) >= 64; + const int32_t prev0[2] = {prev[0], prev[1]}; +- auto ple_gather = [&m, &ss, tokens, n, prev0](int64_t c0, int buf, std::string& e) -> bool { ++ auto ple_gather = [&m, &ss, tokens, n, prev0, ple_gpu_cache](int64_t c0, int buf, std::string& e) -> bool { + const int64_t T = std::min(m.T, n - c0); + auto at = [&](int64_t i) { return i < 2 ? prev0[i] : (int32_t) tokens[i - 2]; }; // prev0, then the tokens + int32_t pv[2] = {at(c0), at(c0 + 1)}; +@@ -1041,7 +1061,8 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e + pv[0] = pv[1]; + pv[1] = tok; + } +- return ss.ple.table->gather_batch(m.ple_rows[buf].data(), (size_t) T, m.ple_emb_host[buf], e); ++ return ple_gpu_cache || ss.ple.table->gather_batch(m.ple_rows[buf].data(), (size_t) T, ++ m.ple_emb_host[buf], e); + }; + std::string ple_next_err; + std::future ple_next; // declared after everything it reads: an early return waits for it +@@ -1112,21 +1133,27 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e + // ---- the PLE rows of the whole chunk, one batched SSD request (read ahead on a thread, see ple_gather) + if (ple_on) { + const auto tp = Clock::now(); +- if (!ple_next.valid()) { ++ if (ple_gpu_cache) { ++ if (!ple_gather(c0, 0, err) || ++ !ss.ple.table->gather_batch_device(m.ple_rows[0].data(), (size_t) T, ++ m.ple_emb, m.cs, err)) return false; ++ } else if (!ple_next.valid()) { + if (!ple_gather(c0, ple_buf, err)) return false; + } else if (!ple_next.get()) { + err = ple_next_err; + return false; + } +- cudaMemcpyAsync(m.ple_emb, m.ple_emb_host[ple_buf], (size_t) T * N * 4, cudaMemcpyHostToDevice, m.cs); +- cudaEventRecord(m.ple_copied[ple_buf], m.cs); +- if (c0 + m.T < n) { +- cudaEventSynchronize(m.ple_copied[ple_buf ^ 1]); // the other buffer's upload (a chunk ago) is done +- ple_next = std::async(std::launch::async, [&ple_gather, &ple_next_err, c1 = c0 + m.T, b = ple_buf ^ 1] { +- return ple_gather(c1, b, ple_next_err); +- }); ++ if (!ple_gpu_cache) { ++ cudaMemcpyAsync(m.ple_emb, m.ple_emb_host[ple_buf], (size_t) T * N * 4, cudaMemcpyHostToDevice, m.cs); ++ cudaEventRecord(m.ple_copied[ple_buf], m.cs); ++ if (c0 + m.T < n) { ++ cudaEventSynchronize(m.ple_copied[ple_buf ^ 1]); // the other buffer's upload (a chunk ago) is done ++ ple_next = std::async(std::launch::async, [&ple_gather, &ple_next_err, c1 = c0 + m.T, b = ple_buf ^ 1] { ++ return ple_gather(c1, b, ple_next_err); ++ }); ++ } ++ ple_buf ^= 1; + } +- ple_buf ^= 1; + stats_.ms_ple += ms_since(tp); + } + for (int64_t t = 0; t < T; ++t) { prev[0] = prev[1]; prev[1] = (int32_t) tokens[c0 + t]; } +@@ -1374,13 +1401,13 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e + *wikn = need(v, "indexer.k_norm.weight", err); + if (!wq || !wk || !wv || !wo || !wik || !wiq || !wqn || !wkn || !wiqn || !wikn) return false; + pt.mark(kPfQsa, cs); +- if (!native_proj(m.gemm, wk, m.mixed_h, m.Kc, T, v.name("attn_k.weight"), err)) return false; ++ if (!st.without_key && !native_proj(m.gemm, wk, m.mixed_h, m.Kc, T, v.name("attn_k.weight"), err)) return false; + if (!native_proj(m.gemm, wv, m.mixed_h, m.Vc, T, v.name("attn_v.weight"), err)) return false; + if (!native_proj(m.gemm, wq, m.mixed_h, m.Qf, T, v.name("attn_q.weight"), err)) return false; + if (!bf16_proj(m.gemm, wik, m.mixed_bf, m.idx_raw, T, v.name("indexer.k_proj.weight"), err, 0, m.mixed_bf_lo)) return false; + if (!bf16_proj(m.gemm, wiq, m.mixed_bf, m.q_idx, T, v.name("indexer.q_proj.weight"), err, 0, m.mixed_bf_lo)) return false; +- rms_rows(m.Kc, (const float*) wkn->data, T * 2, 256, 256, EPS, m.cs); +- rope(m.Kc, T, 2, 256, 512, p0, strata::kernels::rope_scaling(), m.cs); ++ if (!st.without_key) rms_rows(m.Kc, (const float*) wkn->data, T * 2, 256, 256, EPS, m.cs); ++ if (!st.without_key) rope(m.Kc, T, 2, 256, 512, p0, strata::kernels::rope_scaling(), m.cs); + // KV streaming: this layer's cells [0, p0) come in from the host copy to the staging pool, and the + // chunk's cells go to the host copy, the staging pool, and the VRAM slots of resident blocks + const bool staged = st.kv_mode == 1; +@@ -1413,6 +1440,19 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e + } + split_q(m.Qf, m.q, T, m.cs); + rms_rows(m.q, (const float*) wqn->data, T * 24, 256, 256, EPS, m.cs); ++ if (keyless_trace.is_open()) { ++ const int32_t record[3] = {(int32_t)l, (int32_t)p0, (int32_t)T}; ++ keyless_trace.write((const char*)record, sizeof(record)); ++ for (const auto& tensor : std::vector>{ ++ {m.q,(size_t)T*24*256}, {m.Kc,(size_t)T*2*256}, {m.Vc,(size_t)T*2*256}}) { ++ std::vector host(tensor.second); ++ if (cudaMemcpyAsync(host.data(), tensor.first, host.size()*sizeof(float), cudaMemcpyDeviceToHost, cs) != cudaSuccess || ++ cudaStreamSynchronize(cs) != cudaSuccess) { err="keyless teacher readback failed"; return false; } ++ keyless_trace.write((const char*)host.data(), host.size()*sizeof(float)); ++ } ++ if (!keyless_trace) { err="keyless teacher trace write failed"; return false; } ++ } ++ if (st.without_key) strata::kernels::keyless_route_query(m.q, core::keyless_routing(l), T, 24, 256, m.cs); + rope(m.q, T, 24, 256, 6144, p0, strata::kernels::rope_scaling(), m.cs); + if (st.kv_rot) strata::kernels::fwht256_inplace_cuda(m.q, T * 24, m.cs); + rms_rows(m.q_idx, (const float*) wiqn->data, T * 4, 128, 128, EPS, m.cs); +@@ -1539,15 +1579,17 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e + } + } + } +- const strata::kernels::QsaAttnPools pools = staged ? pools_of(m.stage, m.ident_table) ++ strata::kernels::QsaAttnPools pools = staged ? pools_of(m.stage, m.ident_table) + : core::qsa_attn_pools(st); ++ pools.without_key = st.without_key; ++ pools.keyless_cos = st.cos_tab; pools.keyless_sin = st.sin_tab; pools.keyless_n_rot = 64; pools.keyless_mrope = strata::kernels::mrope_table(); + pt.mark(kPfQsaAttn, cs); + // perf-review D-1: the whole chunk on tensor cores, one block per (query, KV head), FP32-level + // accuracy but not bitwise (qsa_prompt_attn.hpp). Q4_0 KV, or STRATA_PROMPT_ATTN_OLD=1: the + // decode kernel, 32 queries at a time (K8V4 runs the tensor kernel's mode 3: INT8 K, + // V dequantized from its q4_0 blocks to fp16 at gather) + static const bool old_attn = std::getenv("STRATA_PROMPT_ATTN_OLD") != nullptr; +- if (old_attn || !strata::kernels::qsa_prompt_attn_batch(m.q, pools, m.sel_ids, m.steps_dev, m.cap, s, ++ if (st.without_key || old_attn || !strata::kernels::qsa_prompt_attn_batch(m.q, pools, m.sel_ids, m.steps_dev, m.cap, s, + m.attn, T, m.cs)) + for (int64_t t0 = 0; t0 < T; t0 += m.attn_batch) { + const int64_t nb = std::min(m.attn_batch, T - t0); +diff --git a/src/program/generate.cpp b/src/program/generate.cpp +index 53c38a00..1e8cdfa3 100644 +--- a/src/program/generate.cpp ++++ b/src/program/generate.cpp +@@ -20,6 +20,9 @@ + #include "strata/core/conversation_memory.hpp" + #include "strata/core/coupled_draft.hpp" + #include "strata/core/expert_source.hpp" ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) ++#include "kar_expert_miss.hpp" ++#endif + #include "strata/core/pinned.hpp" + #include "strata/core/remote_experts.hpp" + #include "strata/core/on_device.hpp" +@@ -50,6 +53,7 @@ + #include "strata/core/mtp.hpp" + #include "strata/prefill/prefill.hpp" + #include "strata/core/native_dense.hpp" ++#include "strata/core/keyless.hpp" + #include "strata/program/logits_selection.hpp" + #include "strata/program/conv_cache.hpp" + #include "strata/spec/draft_policy.hpp" +@@ -220,6 +224,9 @@ struct Options { + std::string embd_gguf; + /// Plan v0.3 P2: how the n-gram table is read. Direct (default) = unbuffered SSD reads, table never in RAM. + std::string ple_io = "direct"; ++ std::string ple_kar; ///< experimental PLE-only KAR quality arm; all other weights stay native ++ uint32_t ple_kar_level = 2; ++ uint32_t ple_kar_gpu_cache_mib = 0; ///< opt-in bounded compressed GPU PLE cache; 0 keeps CPU gather + int64_t ple_row_cache = 1 << 20; ///< bounded row cache (rows of 90 B); 0 disables + int ple_inflight = 64; + double ple_delay_us = 0; ///< fault injection: every row read completes no earlier than this +@@ -423,6 +430,9 @@ void usage() { + " --tokens-file PATH pretokenized prompt, commas or whitespace (alternative to --tokens)\n" + " --ple-gguf PATH required PLE table (original second GGUF shard); with --native, the model's\n" + " shard that holds per_layer_token_embd.weight when not given\n" ++ " --ple-kar PATH experimental PLE-only KAR CPU quality arm (requires a KAR-enabled build)\n" ++ " --ple-kar-level N precision of the experimental PLE KAR arm (default 2)\n" ++ " --ple-kar-gpu-cache-mib N experimental compressed PLE row cache in VRAM (1..1024; level 2)\n" + " --no-ple explicit diagnostic ablation of the PLE layer\n" + " --ple-io direct|mmap|ram n-gram table reads (plan v0.3 P2). direct (default): unbuffered SSD\n" + " reads, the table never enters RAM or the file cache; mmap: A/B arm;\n" +@@ -1053,6 +1063,29 @@ int main(int argc, char** argv) { + else if (a == "--dump-halves") o.dump_halves = next("--dump-halves"); + else if (a == "--dump-routing") o.dump_routing = next("--dump-routing"); + else if (a == "--ple-gguf") o.ple_gguf = next("--ple-gguf"); ++ else if (a == "--ple-kar") o.ple_kar = next("--ple-kar"); ++ else if (a == "--ple-kar-level") { ++ const std::string value = next("--ple-kar-level"); ++ unsigned level = 0; ++ const auto parsed = std::from_chars(value.data(), value.data() + value.size(), level); ++ if (parsed.ec != std::errc{} || parsed.ptr != value.data() + value.size() || ++ level < 1 || level > 8) { ++ std::fprintf(stderr, "strata generate: --ple-kar-level must be an integer from 1 to 8\n"); ++ return 2; ++ } ++ o.ple_kar_level = level; ++ } ++ else if (a == "--ple-kar-gpu-cache-mib") { ++ const std::string value = next("--ple-kar-gpu-cache-mib"); ++ unsigned mib = 0; ++ const auto parsed = std::from_chars(value.data(), value.data() + value.size(), mib); ++ if (parsed.ec != std::errc{} || parsed.ptr != value.data() + value.size() || ++ mib < 1 || mib > 1024) { ++ std::fprintf(stderr, "strata generate: --ple-kar-gpu-cache-mib must be 1..1024\n"); ++ return 2; ++ } ++ o.ple_kar_gpu_cache_mib = mib; ++ } + else if (a == "--no-ple") o.no_ple = true; + else if (a == "--ple-io") o.ple_io = next("--ple-io"); + else if (a == "--ple-row-cache") o.ple_row_cache = std::atoll(next("--ple-row-cache")); +@@ -1254,6 +1287,10 @@ int main(int argc, char** argv) { + } + } + strata::core::set_coupled_draft(o.coupled_draft); ++ if ((std::getenv("STRATA_KEYLESS_TRACE") || std::getenv("STRATA_KEYLESS_PREFILL_TRACE")) && (o.serve || o.max_new > 512)) { ++ std::fprintf(stderr, "strata generate: STRATA_KEYLESS_TRACE is offline only and needs --max-new <= 512\n"); ++ 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"); +@@ -1469,6 +1506,11 @@ int main(int argc, char** argv) { + std::fprintf(stderr, "strata generate: --kv must be fp16, int8, q4_0 or k8v4\n"); + return 2; + } ++ const char* keyless_path = std::getenv("STRATA_KEYLESS_ROUTING"); ++ if (keyless_path && (!*keyless_path || o.kv != "int8" || o.gpu_stages || !o.dump_halves.empty() || std::getenv("STRATA_KEYLESS_TRACE") || std::getenv("STRATA_KEYLESS_PREFILL_TRACE") || (std::getenv("STRATA_KV_ROT") && std::getenv("STRATA_KV_ROT")[0] == '1'))) { ++ std::fprintf(stderr, "strata: keyless requires INT8, no Hadamard rotation, one GPU stage and no diagnostic dumps\n"); return 2; ++ } ++ strata::core::qsa_set_without_key(keyless_path != nullptr); + strata::core::qsa_set_kv_int8(o.kv == "int8"); + strata::core::qsa_set_kv_q4(o.kv == "q4_0"); // PR #21: 4-bit codes after a Hadamard rotation (kv_q4.hpp) + // STRATA_KV_ROT=1: INT8 K/V through the Hadamard rotation --kv q4_0 already uses. Opt-in: first-token KL to +@@ -1547,6 +1589,15 @@ int main(int argc, char** argv) { + std::fprintf(stderr, "strata generate: --no-ple and --ple-gguf are mutually exclusive\n"); + return 2; + } ++ if ((o.no_ple && !o.ple_kar.empty()) || (o.ple_kar.empty() && o.ple_kar_level != 2) || ++ (!o.ple_kar.empty() && (o.ple_kar_level < 1 || o.ple_kar_level > 8 || o.ple_io != "direct"))) { ++ std::fprintf(stderr, "strata generate: --ple-kar requires PLE, level 1..8, and default --ple-io\n"); ++ return 2; ++ } ++ if (o.ple_kar_gpu_cache_mib && (o.ple_kar.empty() || o.ple_kar_level != 2)) { ++ std::fprintf(stderr, "strata generate: --ple-kar-gpu-cache-mib requires --ple-kar at level 2\n"); ++ return 2; ++ } + if (o.native_ple_postops && o.no_ple) { + std::fprintf(stderr, "strata generate: --native-ple-postops requires PLE enabled\n"); + return 2; +@@ -1843,6 +1894,37 @@ int main(int argc, char** argv) { + rope_cfg.type == RST::YaRN ? "YaRN" : "--yarn-attn-factor", rope_cfg.mscale()); + } + } ++ const char* kar_expert_archive = std::getenv("STRATA_NEXT_KAR_EXPERTS_ARCHIVE"); ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) ++ strata::kar::ExpertMiss kar_expert_miss; ++ if (kar_expert_archive != nullptr) { ++ const char* level_text = std::getenv("STRATA_NEXT_KAR_EXPERTS_LEVEL"); ++ if (!native_pack || o.no_pool || !split_devs.empty() || remote_caches || ++ !level_text || std::strlen(level_text) != 1 || level_text[0] < '1' || level_text[0] > '8' || ++ g.n_embd != strata::kernels::cpu::H) { ++ std::fprintf(stderr, "strata generate: experimental KAR misses require a native pack, one GPU, " ++ "the expert pool and explicit STRATA_NEXT_KAR_EXPERTS_LEVEL=1..8\n"); ++ return 2; ++ } ++ for (const auto& f : strata::kernels::cpu::expert_layout().fmt) ++ if (f.n_embd != strata::kernels::cpu::H || f.n_ff != strata::kernels::cpu::FF) { ++ std::fprintf(stderr, "strata generate: unsupported KAR expert geometry\n"); return 2; ++ } ++ if (!kar_expert_miss.open(kar_expert_archive, (uint32_t) g.n_layers, (uint32_t) g.n_expert, ++ (uint32_t) g.n_embd, strata::kernels::cpu::FF, ++ (uint32_t) (level_text[0] - '0'), err)) { ++ std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; ++ } ++ // Native resident hits are the baseline. Route all otherwise CPU/PCIe ++ // misses to the explicit experimental arm; use pcie-frac=0 in its baseline. ++ o.pcie_frac = 0; ++ } ++#else ++ if (kar_expert_archive != nullptr) { ++ std::fprintf(stderr, "strata generate: this build has no experimental KAR expert support\n"); ++ return 2; ++ } ++#endif + strata::core::NativeEmbed native_embed; + if (native_pack) { + if (o.native_preset.empty() || o.spec < 2 || o.keep_canonical || +@@ -1965,6 +2047,10 @@ int main(int argc, char** argv) { + return 2; + } + ++ if (keyless_path && !strata::core::keyless_load(keyless_path, wt, g, err)) { ++ std::fprintf(stderr, "strata: keyless routing: %s\n", err.c_str()); return 1; ++ } ++ if (keyless_path) std::fprintf(stderr, "strata: experimental V-only QSA query routing; indexer and MTP keys retained; quality gate pending\n"); + strata::core::SessionState ss; + void* sbuf = nullptr; // allocated after the layer-split search, sized to CUDA0's own layer range (the carve) + // **THE ENGINE RAN ON THE LEGACY DEFAULT STREAM, WHICH ON WDDM IS THE SLOW PATH.** All four session +@@ -2041,15 +2127,26 @@ int main(int argc, char** argv) { + pio.keepalive_window_s = kw != nullptr && *kw ? std::clamp(std::atof(kw), 1.0, 86400.0) : 60.0; + if (pio.mode != strata::kernels::PleIo::Direct || !pio.io_thread) pio.keepalive_ms = 0; + } +- if (!ple_table.open(o.ple_gguf, err, pio)) { ++ const bool ple_open = o.ple_kar.empty() ? ple_table.open(o.ple_gguf, err, pio) ++ : ple_table.open_kar(o.ple_kar, o.ple_kar_level, err); ++ if (!ple_open) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } ++ if (o.ple_kar_gpu_cache_mib && !ple_table.enable_kar_gpu_cache(o.ple_kar_gpu_cache_mib, err)) { ++ std::fprintf(stderr, "strata generate: PLE GPU cache: %s\n", err.c_str()); ++ return 1; ++ } + if (pio.lock) + std::fprintf(stderr, "strata generate: PLE table %s (--ple-io ram) in %.1f s\n", + ple_table.locked() ? "locked in RAM" : "loaded (not locked)", + std::chrono::duration(Clock::now() - tpl).count()); +- if (pio.keepalive_ms > 0) ++ if (!o.ple_kar.empty()) ++ std::fprintf(stderr, "strata generate: experimental PLE KAR %s arm at level %u%s\n", ++ o.ple_kar_gpu_cache_mib ? "bounded GPU-cache" : "CPU quality", ++ o.ple_kar_level, ++ o.ple_kar_gpu_cache_mib ? " (prefill/decode CUDA, speculative verification CPU)" : ""); ++ else if (pio.keepalive_ms > 0) + std::fprintf(stderr, "strata generate: the SSD is kept awake while rows are read: one page of the table after " + "%.0f ms without a read, until %.0f s after the last request " + "(STRATA_SSD_KEEPALIVE=0 turns it off)\n", pio.keepalive_ms, pio.keepalive_window_s); +@@ -2468,7 +2565,8 @@ int main(int argc, char** argv) { + return 1; + } + std::fprintf(stderr, "strata generate: PLE on, table %llu rows of %s\n", +- (unsigned long long) ple_table.rows(), o.ple_gguf.c_str()); ++ (unsigned long long) ple_table.rows(), ++ o.ple_kar.empty() ? o.ple_gguf.c_str() : o.ple_kar.c_str()); + } + } + for (size_t i = 0; i < stages.size(); ++i) { +@@ -3022,6 +3120,12 @@ int main(int argc, char** argv) { + } + + Drive drive; ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) ++ if (kar_expert_archive != nullptr) { ++ drive.d.experimental_miss = &strata::kar::ExpertMiss::dispatch; ++ drive.d.experimental_miss_user = &kar_expert_miss; ++ } ++#endif + for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0) + drive.d.remote[drive.d.remote_count++] = &remote_experts[(size_t) r]; + drive.d.hit_cpu_order = o.expert_cache_cpu_order; +@@ -4791,6 +4895,10 @@ int main(int argc, char** argv) { + // unknown keys are skipped: the ids start at the first token without '=' + } + } ++ if (kar_expert_archive != nullptr && req_pcie_frac != 0.0) { ++ std::printf("ERR experimental KAR misses require pcie_frac=0\n"); ++ continue; ++ } + std::string emb_path; + if (geni && endp != nullptr) { + while (*endp == ' ') ++endp; +@@ -5586,6 +5694,8 @@ 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 if (st.without_key) { ++ a = {{h ? st.host.v_q : st.v_q, kvb}, {h ? st.host.v_scale : st.v_scale, scb}}; + } 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}}; +@@ -5651,6 +5761,11 @@ int main(int argc, char** argv) { + 100.0 * (double) req_hits / (double) req_look, + (long long) req_hits, (long long) req_look); + } ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) ++ if (kar_expert_archive != nullptr) ++ std::fprintf(stderr, "strata serve: KAR verifier entries computed since startup: %llu\n", ++ (unsigned long long) kar_expert_miss.computed()); ++#endif + // the resident RAM mode, cumulative: experts read from experts.bin since the copy was made (what the plain + // mmap mode reads through the OS file cache, from the SSD when the RAM could not keep it) + if (src.complement_ready()) +@@ -5703,6 +5818,8 @@ int main(int argc, char** argv) { + remote_experts[(size_t) r].ms_begin() - begin_before[(size_t) r], + remote_experts[(size_t) r].ms_wait() - wait_before[(size_t) r]); + } ++ if (o.stats && ple_table.kar_gpu_cache_enabled()) ++ std::fprintf(stderr, "strata serve: %s\n", ple_table.io_report().c_str()); + return 0; + } + diff --git a/docs/upstream/local-patches-on-0.1.50.patch b/docs/upstream/local-patches-on-0.1.50.patch new file mode 100644 index 00000000..79d4a0e0 --- /dev/null +++ b/docs/upstream/local-patches-on-0.1.50.patch @@ -0,0 +1,2243 @@ +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 46ebf034..ef1a1aec 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -80,6 +80,15 @@ if(STRATA_HIP_GFX906) + set(STRATA_ENABLE_CUDA ON CACHE BOOL "" FORCE) + endif() + option(STRATA_ENABLE_HIP "Build the HIP targets for wave32 AMD GPUs (gfx1100, gfx1201; gfx1012/gfx1030 unvalidated)" OFF) ++option(STRATA_CUDA_STATIC "Linux GNU engine: static CUDA toolkit and C++ runtimes (host glibc and NVIDIA driver required)" OFF) ++if(STRATA_CUDA_STATIC) ++ if(NOT STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP OR STRATA_HIP_GFX906 OR NOT CMAKE_SYSTEM_NAME STREQUAL "Linux" ++ OR NOT CMAKE_CXX_COMPILER_ID STREQUAL "GNU") ++ message(FATAL_ERROR "STRATA_CUDA_STATIC requires Linux, GNU C++, and STRATA_ENABLE_CUDA=ON (HIP disabled)") ++ endif() ++ # Applies to subsequently created CUDA targets, including device-link runtime edges. ++ set(CMAKE_CUDA_RUNTIME_LIBRARY Static) ++endif() + option(STRATA_PREFILL_MMQ "Build the optional GGML MMQ prefill path for HIP" OFF) + # MMQ prompt kernels for Q4_K / Q5_K / Q5_1 / Q6_K (Unsloth's UD-Q4/Q5/Q6_K_XL experts; on HIP also the dense GGUF + # projections, STRATA_DENSE_MMQ). On by default since MODEL-UPDATE Phase 1: on CUDA they are their own library +@@ -220,6 +229,16 @@ elseif(STRATA_ENABLE_CUDA) + message(STATUS "Strata: CUDA enabled, arch ${CMAKE_CUDA_ARCHITECTURES}") + set(_strata_gpu_runtime_target CUDA::cudart) + set(_strata_gpu_blas_target CUDA::cublas) ++ if(STRATA_CUDA_STATIC) ++ foreach(_required CUDA::cudart_static CUDA::cublas_static CUDA::cublasLt_static CUDA::culibos) ++ if(NOT TARGET ${_required}) ++ message(FATAL_ERROR "STRATA_CUDA_STATIC requires toolkit archive target ${_required}") ++ endif() ++ endforeach() ++ set(_strata_gpu_runtime_target CUDA::cudart_static) ++ set(_strata_gpu_blas_target CUDA::cublas_static) ++ message(STATUS "Strata: static CUDA toolkit libraries; host glibc and NVIDIA driver remain required") ++ endif() + set(_strata_gpu_include_directories ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) + elseif(STRATA_ENABLE_HIP) + set(_strata_gpu_runtime_target strata_hip_runtime) +@@ -415,6 +434,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) + src/kernels/cuda/fused_gr.cu + src/kernels/cuda/cvec.cu + src/kernels/cuda/qsa_decode_attn.cu ++ src/kernels/cuda/keyless.cu + src/kernels/cuda/qsa_prompt_attn.cu + src/kernels/cuda/fused_gdn.cu + src/kernels/cuda/dequant_bf16.cu +@@ -426,6 +446,35 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) + src/ngram/ple_reader.cpp + src/platform/direct_file.cpp) + target_link_libraries(strata_kernels PUBLIC strata_core strata_artifact) ++ option(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE "Capture private PLE row traces for offline cache studies" OFF) ++ if(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE) ++ if(NOT CMAKE_SYSTEM_NAME STREQUAL "Linux") ++ message(FATAL_ERROR "The experimental PLE row trace requires Linux") ++ endif() ++ target_compile_definitions(strata_kernels PRIVATE STRATA_NEXT_EXPERIMENTAL_PLE_TRACE=1) ++ endif() ++ option(STRATA_NEXT_EXPERIMENTAL_KAR_PLE "Build optional KAR PLE CPU and GPU-cache experiment arms" OFF) ++ set(STRATA_NEXT_KAR_DIR "" CACHE PATH "Path to strata-next/gpu/kar (required for KAR PLE)") ++ if(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ if(NOT STRATA_ENABLE_CUDA OR NOT CMAKE_SYSTEM_NAME STREQUAL "Linux") ++ message(FATAL_ERROR "The experimental KAR PLE quality arm requires Linux CUDA") ++ endif() ++ if(NOT EXISTS "${STRATA_NEXT_KAR_DIR}/vendor/libkar.cu") ++ message(FATAL_ERROR "Set STRATA_NEXT_KAR_DIR to the strata-next/gpu/kar source directory") ++ endif() ++ add_library(strata_next_kar STATIC ++ "${STRATA_NEXT_KAR_DIR}/vendor/libkar.cu" ++ "${STRATA_NEXT_KAR_DIR}/src/kar_ple_cache.cu") ++ target_include_directories(strata_next_kar PUBLIC ++ "${STRATA_NEXT_KAR_DIR}/vendor" ++ "${STRATA_NEXT_KAR_DIR}/include") ++ target_link_libraries(strata_next_kar PUBLIC ${_strata_gpu_runtime_target}) ++ set_target_properties(strata_next_kar PROPERTIES CUDA_STANDARD 17 CUDA_STANDARD_REQUIRED ON) ++ target_link_libraries(strata_kernels PUBLIC strata_next_kar) ++ target_compile_definitions(strata_kernels PRIVATE STRATA_NEXT_EXPERIMENTAL_KAR_PLE=1) ++ add_executable(strata_next_kar_ple_probe "${STRATA_NEXT_KAR_DIR}/src/kar_ple_cpu_probe.cpp") ++ target_link_libraries(strata_next_kar_ple_probe PRIVATE strata_kernels) ++ endif() + # Exact gfx1100 prompt scorer (PR1825 method port): optional standalone test, + # also available where the published source omits tests/. + option(STRATA_PARITY_GFX1100_QSA_SCORES "Build the exact gfx1100 QSA score/ID check" OFF) +@@ -446,7 +495,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) + if((STRATA_BUILD_TESTS OR STRATA_PARITY_PROMPT_ATTN) AND STRATA_ENABLE_CUDA) + add_executable(qsa_prompt_attn_parity src/kernels/qsa_prompt_attn_parity.cpp) + target_include_directories(qsa_prompt_attn_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) +- target_link_libraries(qsa_prompt_attn_parity PRIVATE strata_kernels CUDA::cudart) ++ target_link_libraries(qsa_prompt_attn_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + endif() + # PR #600: the Volta (sm_70) prompt attention's latency pipeline against the FP32 kernel it replaces. Only in the + # experimental sm_60/sm_70 build, where prompt_attn_v70_kernel is compiled in. +@@ -580,7 +629,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) + # already links `strata_core` - putting `gdn_layer` in core would make the two mutually dependent. A third + # 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 ++ add_library(strata_engine STATIC src/core/keyless.cpp src/core/layer.cpp src/core/session.cpp src/core/expert_source.cpp src/core/remote_experts.cpp + src/core/remote_expert_opt.cu + 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/dflash2.cpp + src/core/conversation_snapshot.cpp src/core/conversation_state.cpp src/core/conversation_memory.cpp src/core/peer_experts.cpp +@@ -611,6 +660,30 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) + set_tests_properties(memory_guard_test PROPERTIES TIMEOUT 60) + endif() + ++ option(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS "Build the opt-in KAR native decode cache-miss arm" OFF) ++ if(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) ++ if(NOT STRATA_ENABLE_CUDA OR NOT CMAKE_SYSTEM_NAME STREQUAL "Linux") ++ message(FATAL_ERROR "Experimental KAR experts require Linux CUDA") ++ endif() ++ if(NOT EXISTS "${STRATA_NEXT_KAR_DIR}/src/kar_expert_miss.cpp") ++ message(FATAL_ERROR "Set STRATA_NEXT_KAR_DIR to strata-next/gpu/kar") ++ endif() ++ add_library(strata_next_kar_experts STATIC ++ "${STRATA_NEXT_KAR_DIR}/vendor/libkar.cu" ++ "${STRATA_NEXT_KAR_DIR}/src/kar_expert.cu" ++ "${STRATA_NEXT_KAR_DIR}/src/kar_expert_miss.cpp") ++ target_include_directories(strata_next_kar_experts PUBLIC ++ "${STRATA_NEXT_KAR_DIR}/vendor" "${STRATA_NEXT_KAR_DIR}/include") ++ target_link_libraries(strata_next_kar_experts PUBLIC ${_strata_gpu_runtime_target}) ++ set_target_properties(strata_next_kar_experts PROPERTIES CUDA_STANDARD 17 CUDA_STANDARD_REQUIRED ON) ++ target_compile_features(strata_next_kar_experts PRIVATE cxx_std_20) ++ target_link_libraries(strata_engine PUBLIC strata_next_kar_experts) ++ target_compile_definitions(strata_engine PUBLIC STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS=1) ++ endif() ++ add_executable(keyless_parity src/kernels/keyless_parity.cpp) ++ target_link_libraries(keyless_parity PRIVATE strata_engine) ++ add_test(NAME keyless_parity COMMAND keyless_parity) ++ set_tests_properties(keyless_parity PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/file_expert_source_test.cpp") + enable_testing() + add_executable(file_expert_source_test tests/core/file_expert_source_test.cpp) +@@ -682,6 +755,10 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) + set_tests_properties(expert_cache_slot_guard_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + endif() + if(STRATA_BUILD_CONVERSATION_TESTS) ++ add_executable(keyless_stream_parity src/kernels/kv_stream_parity.cpp) ++ target_link_libraries(keyless_stream_parity PRIVATE strata_engine) ++ add_test(NAME keyless_stream_parity COMMAND keyless_stream_parity --v-only) ++ set_tests_properties(keyless_stream_parity PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + 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) +@@ -760,6 +837,10 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) + strata_utf8_manifest(strata) + target_include_directories(strata PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(strata PRIVATE strata_engine strata_prefill strata_spec ${_strata_gpu_runtime_target}) ++ if(STRATA_CUDA_STATIC) ++ target_link_options(strata PRIVATE -static-libstdc++ -static-libgcc) ++ set_target_properties(strata PROPERTIES SKIP_BUILD_RPATH TRUE INSTALL_RPATH "") ++ endif() + if(WIN32 AND STRATA_ENABLE_HIP) + # 0.2.1.2: the ROCm math libraries live in \rocm\bin, which is on PATH only when the launcher starts the engine; load them on first + # use (main() adds that folder to the DLL search first) so `strata.exe --version` works from the package folder. amdhip64_7.dll and the +diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp +index 3ab77dc2..d73d1492 100644 +--- a/include/strata/core/expert_source.hpp ++++ b/include/strata/core/expert_source.hpp +@@ -484,6 +484,12 @@ struct ForesightSwap; + + struct ExpertDispatch { + ForesightSwap* fs = nullptr; ///< Foresight swap space (STRATA_FS_SLOTS; null = off) ++ // Default-off local extension. The callback owns only kind==-1 entries and ++ // marks completed host rows as kind=3. Native hits/PCIe/remote rows are untouched. ++ using ExperimentalMiss = bool (*)(void*, int64_t, const float*, const int32_t*, ++ int64_t, int64_t, int32_t*, float*, std::string&); ++ ExperimentalMiss experimental_miss = nullptr; ++ void* experimental_miss_user = nullptr; + strata::kernels::cpu::ExpertPool* pool = nullptr; + ExpertSource* src = nullptr; + RouterLookahead* lookahead = nullptr; ///< CS-T: warms the next layer's predicted file-tier experts +diff --git a/include/strata/core/keyless.hpp b/include/strata/core/keyless.hpp +new file mode 100644 +index 00000000..4665c458 +--- /dev/null ++++ b/include/strata/core/keyless.hpp +@@ -0,0 +1,11 @@ ++#pragma once ++#include "strata/core/layout.hpp" ++#include ++namespace strata::core { ++bool keyless_load(const char* path, const WeightTable& weights, const ModelGeometry& g, std::string& error); ++const float* keyless_routing(int64_t layer); ++} ++namespace strata::kernels { ++// In-place, one independent matrix for each query head. No cached keys are produced. ++void keyless_route_query(float* q, const float* output_major_matrices, int64_t tokens, int heads, int dim, void* stream); ++} +diff --git a/include/strata/core/layer.hpp b/include/strata/core/layer.hpp +index 9e0361ac..44c7001f 100644 +--- a/include/strata/core/layer.hpp ++++ b/include/strata/core/layer.hpp +@@ -210,6 +210,7 @@ struct QsaState { + uint16_t* k_pool = nullptr; ///< [page][kv_head][page_size][head_dim] fp16 (null in INT8 mode) + uint16_t* v_pool = nullptr; + /// Plan v0.3 P7: INT8 KV (qsa_set_kv_int8). Codes [page][kv_head][page_size][head_dim], one FP16 scale per 64. ++ bool without_key = false; + bool kv_int8 = false; + int8_t* k_q = nullptr; + int8_t* v_q = nullptr; +@@ -309,6 +310,8 @@ uint64_t qsa_kv_host_bytes(); + /// Plan v0.3 P7: store K/V as INT8 with FP16 scales per 64 values (half the VRAM of FP16). Set before sizing and + /// initializing the session; default off until gate G-C accepts it. + void qsa_set_kv_int8(bool enabled); ++void qsa_set_without_key(bool enabled); ++bool qsa_without_key(); + /// INT8 K/V through the Hadamard rotation (off by default: STRATA_KV_ROT=1) + void qsa_set_kv_int8_rotate(bool enabled); + bool qsa_kv_int8(); +@@ -321,6 +324,7 @@ bool qsa_kv_hybrid(); + /// The state's KV format for the block-moving functions of kv_stream.hpp (kKvF16 / kKvInt8 / kKvQ4 / kKvHybrid). + inline int qsa_kv_format(const QsaState& st) { + if (st.kv_hybrid) return strata::kernels::kKvHybrid; // K8V4: its own three runs (kv_stream.cu) ++ if (st.without_key) return strata::kernels::kKvValueInt8; // local keyless arm (default off) + return st.kv_q4 ? strata::kernels::kKvQ4 : st.kv_int8 ? strata::kernels::kKvInt8 : strata::kernels::kKvF16; + } + uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, QsaState& st, +diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp +index dc6613da..3b24d4cb 100644 +--- a/include/strata/core/verify.hpp ++++ b/include/strata/core/verify.hpp +@@ -563,6 +563,10 @@ private: + int32_t* h_commit_ = nullptr; int32_t* m_commit_ = nullptr; // [n_keep, n_keep-1, pos_0 .. pos_{T-1}] + float* h_ple_ = nullptr; float* m_ple_ = nullptr; // T * n_embd + int32_t* h_out_ = nullptr; int32_t* m_out_ = nullptr; // T argmax ids ++ float* kl_trace_h_ = nullptr; // optional pinned K/V activation trace for offline keyless study ++ std::FILE* kl_trace_file_ = nullptr; ++ float* kl_trace_q_h_ = nullptr; // first accepted token's Q, per QSA layer ++ std::FILE* kl_trace_q_file_ = nullptr; + // STRATA_TAP_FILE (off by default; nothing is allocated or captured without it): the DFlash2 experiment's hook. + // After each layer in STRATA_TAP_LAYERS (default 5,15,25,35,45) the window copies the layer's completed output + // (the residual with its pending FFN write applied, the mean of the hc streams) per row; run() appends +diff --git a/include/strata/kernels/kv_stream.hpp b/include/strata/kernels/kv_stream.hpp +index 8108795b..8e630031 100644 +--- a/include/strata/kernels/kv_stream.hpp ++++ b/include/strata/kernels/kv_stream.hpp +@@ -38,14 +38,14 @@ struct KvHostPools { + uint16_t* v_scale = nullptr; + uint8_t* k_q4 = nullptr; ///< q4_0 mode (kv_q4.hpp): block_q4_0 codes, 144 B per cell and head + uint8_t* v_q4 = nullptr; +- bool present() const { return k_pool != nullptr || k_q != nullptr || k_q4 != nullptr; } ++ bool present() const { return k_pool != nullptr || k_q != nullptr || k_q4 != nullptr || v_q != nullptr; } + }; + + /// The KV storage format, for the functions below that move whole blocks (`fmt`): fp16, int8 (+ scales), q4_0, and + /// K8V4 (`--kv k8v4`: K as int8 codes + scales, V as rotated q4_0 - three runs, `k_q`, `k_scale`, `v_q4`). + /// (A bool `int8` argument still reads as kKvF16 / kKvInt8.) kKvHybrid is 3, the number conversation snapshots +-/// already give K8V4. +-enum KvFormat : int { kKvF16 = 0, kKvInt8 = 1, kKvQ4 = 2, kKvHybrid = 3 }; ++/// already give K8V4. kKvValueInt8 (4) is the local, default-off V-only (keyless) format: int8 V + scales only. ++enum KvFormat : int { kKvF16 = 0, kKvInt8 = 1, kKvQ4 = 2, kKvHybrid = 3, kKvValueInt8 = 4 }; + + /// K8V4's halves as the single-format append kernels see them, so a hybrid layer's host copy (and the prompt path's + /// staging pool) is written by the same calls that write its VRAM pools: K is "int8 whose V is K", V is "q4_0 whose +diff --git a/include/strata/kernels/ngram.hpp b/include/strata/kernels/ngram.hpp +index 4452b4f6..ec62a24e 100644 +--- a/include/strata/kernels/ngram.hpp ++++ b/include/strata/kernels/ngram.hpp +@@ -22,6 +22,7 @@ + // All of those are asserted observable in `ple_parity.cpp` rather than trusted. + #pragma once + ++#include + #include + #include + +@@ -176,6 +177,21 @@ public: + /// Open with an explicit I/O mode. The two-argument `open` below is the default (Direct). + bool open(const std::string& gguf_path, std::string& err, const PleIoOptions& io); + ++ /// Experimental CPU quality arm: read rows from a verified KAR-2 archive ++ /// while the rest of the engine continues to use its normal model pack. ++ /// The CUDA selective-row path is measured separately and is not used here. ++ bool open_kar(const std::string& kar_path, uint32_t level, std::string& err, ++ uint64_t expected_rows = PLE_TABLE_ROWS); ++ ++ /// Experimental bounded compressed-row cache. It accepts only the ++ /// level-2/group-32 KAR PLE layout and leaves the CPU gather available ++ /// for consumers that still use mapped host memory. ++ bool enable_kar_gpu_cache(uint32_t cache_mib, std::string& err); ++ bool kar_gpu_cache_enabled() const; ++ bool collect_device(float* device_out2560, void* stream, std::string& err); ++ bool gather_batch_device(const uint32_t* rows, size_t n_tokens, float* device_out, ++ void* stream, std::string& err); ++ + /// The split the plan asks for: `issue` as soon as the token id is known, `collect` just before layer 1 + /// needs the rows. `gather` is `issue` followed by `collect`. In Mmap mode `issue` only prefetches. + bool issue(const uint32_t* rows16); +diff --git a/include/strata/kernels/qsa_decode_attn.hpp b/include/strata/kernels/qsa_decode_attn.hpp +index e782035d..4e9adb46 100644 +--- a/include/strata/kernels/qsa_decode_attn.hpp ++++ b/include/strata/kernels/qsa_decode_attn.hpp +@@ -21,6 +21,11 @@ + namespace strata::kernels { + + struct QsaAttnPools { ++ bool without_key = false; ++ const float* keyless_cos = nullptr; ++ const float* keyless_sin = nullptr; ++ int keyless_n_rot = 0; ++ const int32_t* keyless_mrope = nullptr; // optional per-cell time/height/width positions + const uint16_t* k_pool = nullptr; ///< fp16 [page][kv_head][page_size][head_dim], or null when int8 + const uint16_t* v_pool = nullptr; + const int8_t* k_q = nullptr; ///< int8 codes, same layout +diff --git a/src/core/conversation_snapshot.cpp b/src/core/conversation_snapshot.cpp +index 76e69b5f..c4f7355a 100644 +--- a/src/core/conversation_snapshot.cpp ++++ b/src/core/conversation_snapshot.cpp +@@ -61,6 +61,7 @@ bool layout(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index + } + l.value_data = l.data; + l.value_scales = l.scales; ++ if (st.without_key) { l.data = 0; l.scales = 0; } + 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)})) { +@@ -102,7 +103,7 @@ bool valid(const QsaState& st, const Layout& l, int64_t upto, std::string& error + } + } + 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.without_key ? !st.v_q || !st.v_scale : 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; +diff --git a/src/core/conversation_snapshot_test.cpp b/src/core/conversation_snapshot_test.cpp +index 074a3ae9..37335f4b 100644 +--- a/src/core/conversation_snapshot_test.cpp ++++ b/src/core/conversation_snapshot_test.cpp +@@ -48,13 +48,14 @@ struct Fixture { + } + Fixture(int fmt, int mode) { + auto& st = state; +- st.kv_mode = mode; st.kv_int8 = fmt==kKvInt8; st.kv_q4 = fmt==kKvQ4; st.kv_hybrid = fmt==3; ++ st.kv_mode = mode; st.without_key = fmt==kKvValueInt8; st.kv_int8 = fmt==kKvInt8 || st.without_key; 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 || 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}; ++ sizes = {rows*per, rows*per, (fmt==kKvInt8 || fmt==kKvValueInt8) ? rows*(g.head_dim/64)*2:0, ++ (fmt==kKvInt8 || fmt==kKvValueInt8) ? rows*(g.head_dim/64)*2:0, (size_t)st.idx_pooled_rows*g.idx_key_dim*4}; ++ if (st.without_key) { sizes[0]=0; sizes[2]=0; } + 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}; +@@ -64,9 +65,11 @@ struct Fixture { + 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); ++ } else if (st.kv_int8) { ++ if (!st.without_key) alloc(st.k_q,slot_rows*per); ++ alloc(st.v_q,slot_rows*per); ++ if (!st.without_key) 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); +@@ -111,7 +114,7 @@ bool equal(const ConversationKv& a,const ConversationKv& b) { + } + + void full_session(int fmt, int mode, int experts) { +- Fixture main(fmt,mode), draft(fmt==3?kKvInt8:fmt,2); ++ Fixture main(fmt,mode), draft((fmt==3 || fmt==kKvValueInt8)?kKvInt8:fmt,2); + auto& g=main.g; + g.n_layers=4; g.n_expert=experts; + g.ssm_state_size=2; g.ssm_v_heads=2; g.ssm_conv_channels=8; +@@ -228,7 +231,7 @@ void full_session(int fmt, int mode, int experts) { + 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;}); ++ reuse.kv[0].v.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); +@@ -245,7 +248,7 @@ void full_session(int fmt, int mode, int experts) { + incremental.live.dead==fresh.live.dead && equal(incremental.kv[0],fresh.kv[0]) && + equal(incremental.kv[1],fresh.kv[1]),"incremental capture equals full capture after growth or rewind"); + check((dirty>=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){ ++ incremental.kv[0].v.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"); +@@ -305,7 +308,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 : std::array{kKvF16,kKvInt8,kKvQ4,3}) for (int mode : {0,1,2}) { ++ for (int fmt : std::array{kKvF16,kKvInt8,kKvQ4,3,kKvValueInt8}) for (int mode : {0,1,2}) { + if (fmt==3 && mode!=0) continue; + Fixture f(fmt,mode); + if (fmt==3) { +@@ -334,6 +337,12 @@ int main() { + ConversationKv a,b,restored; + cuda_check(cudaDeviceSynchronize()); + check(conversation_kv_save(a,f.state,f.g,upto,index,err),"save A"); ++ if (fmt==kKvValueInt8) { ++ check(a.k.empty() && a.k_scale.empty() && !f.state.k_q && !f.state.host.k_q, ++ "V-only snapshot and resident/host pools have no K"); ++ auto wrong=a; wrong.format=kKvInt8; ++ check(!conversation_kv_restore(wrong,f.state,f.g,upto,index,err),"reject K+V snapshot in V-only state"); ++ } + 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"); +@@ -373,13 +382,13 @@ int main() { + const int64_t b1=(upto+s.page_size-1)/s.page_size,b0=std::max(0,b1-f.state.n_slots); + 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; ++ const size_t code_block=(fmt==kKvInt8 || fmt==kKvValueInt8) ? s.page_size*s.n_head_kv*s.head_dim : block; ++ const void* slots=fmt==kKvValueInt8?(void*)f.state.v_q: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 expected(code_block); +- check(a.k.read(expected.data(), page*code_block, code_block),"read segmented expected draft page"); ++ check((fmt==kKvValueInt8?a.v:a.k).read(expected.data(), page*code_block, code_block),"read segmented expected draft page"); + check(got == expected,"draft ring contains restored pages"); + } + } +@@ -402,7 +411,7 @@ int main() { + } + } + } +- for (int fmt : {kKvF16,kKvInt8,kKvQ4}) for (int mode : {0,1}) for (int experts : {256,512}) ++ for (int fmt : {kKvF16,kKvInt8,kKvQ4,kKvValueInt8}) for (int mode : {0,1}) for (int experts : {256,512}) + full_session(fmt,mode,experts); + for (int experts : {256,512}) full_session(3,0,experts); + std::printf("conversation_snapshot_test: %d checks passed\n",checks); +diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp +index b8ad8fb4..66b60d9b 100644 +--- a/src/core/expert_source.cpp ++++ b/src/core/expert_source.cpp +@@ -4986,6 +4986,13 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 + for (int64_t i = 0; i < n; ++i) if (d.remote[r]->owns(i)) kind[i] = 2; + } + } ++ if (d.experimental_miss != nullptr) { ++ static thread_local std::string miss_error; ++ if (!d.experimental_miss(d.experimental_miss_user, d.layers, x_f, ids, ++ n_tok, k, kind, out, miss_error)) { ++ d.failed = true; d.fail = miss_error.c_str(); d.fail_layer = d.layers; return; ++ } ++ } + static const bool dec_batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }(); + // the GPU's copy_rows_from_mapped zeroes the rows it computed itself (dec_batch); STRATA_VERIFY_DEVICE_PLAN's + // copy_or_zero_from_mapped copies every row, so there the host still zeroes them +@@ -5078,13 +5085,14 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 + ++d.tail_skipped; + continue; + } +- if (kind[i] >= 0) { // CUDA0, PCIe, or a remote/peer result staged into this row below ++ if (kind[i] >= 0) { // CUDA0, PCIe, a remote/peer result staged into this row below, or a completed experimental KAR host row (kind 3) + if (kind[i] == 0) ++d.cache_hits; ++ else if (kind[i] == 3) ++d.cache_refused; // local KAR arm: the row already holds its result, never zeroed + else ++d.offload_entries; // #588: PCIe or another GPU + if (kind[i] == 2 && d.peer != nullptr) ++d.peer_entries; + // multi-GPU: a direct peer launch is writing this row right now - zeroing it would race it; + // dec_batch: copy_rows_from_mapped_kernel already zeroes kind 0/1 rows on the GPU +- if (!((kind[i] == 2 && d.peer != nullptr && d.peer->launched_direct()) || ++ if (kind[i] != 3 && !((kind[i] == 2 && d.peer != nullptr && d.peer->launched_direct()) || + (gpu_zeroes_hits && (kind[i] == 0 || kind[i] == 1)))) + std::memset(row, 0, (size_t) H * sizeof(float)); + continue; +diff --git a/src/core/keyless.cpp b/src/core/keyless.cpp +new file mode 100644 +index 00000000..7699b579 +--- /dev/null ++++ b/src/core/keyless.cpp +@@ -0,0 +1,79 @@ ++#include "strata/core/keyless.hpp" ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++namespace strata::core { ++namespace { ++std::map routes; ++uint32_t u32(std::istream& f) { ++ unsigned char b[4]{}; f.read((char*) b, 4); ++ return (uint32_t)b[0] | (uint32_t)b[1]<<8 | (uint32_t)b[2]<<16 | (uint32_t)b[3]<<24; ++} ++uint64_t u64(std::istream& f) { const uint64_t a = u32(f); return a | (uint64_t)u32(f)<<32; } ++} ++const float* keyless_routing(int64_t layer) { ++ const auto it = routes.find(layer); ++ return it == routes.end() ? nullptr : it->second; ++} ++bool keyless_load(const char* path, const WeightTable& weights, const ModelGeometry& g, std::string& error) { ++ if (!routes.empty()) { error = "keyless routing already loaded"; return false; } ++ std::ifstream f(path, std::ios::binary); ++ std::array magic{}; f.read(magic.data(), 8); ++ const uint32_t version = u32(f), layers = u32(f), heads = u32(f), dim = u32(f); ++ if (!f || std::memcmp(magic.data(), "SKLROUT1", 8) || version != 1 || ++ layers != (uint32_t)g.n_qsa_layers() || heads != (uint32_t)g.n_head || dim != (uint32_t)g.head_dim || dim != 256) { ++ error = "invalid keyless artifact header/geometry"; return false; ++ } ++ std::map pending; ++ auto fail = [&](const std::string& why) { ++ error = why; for (auto& row : pending) cudaFree(row.second); return false; ++ }; ++ for (uint32_t ordinal = 0; ordinal < layers; ++ordinal) { ++ const uint32_t layer = u32(f); ++ if (!f || layer >= g.n_layers || !is_qsa_layer(g, layer) || pending.count(layer)) ++ return fail("keyless artifact has invalid/duplicate layer"); ++ for (const char* role : {"q", "k", "v"}) { ++ const uint32_t kind = u32(f); const uint64_t bytes = u64(f), wanted = u64(f); ++ const auto* w = weights.find("blk." + std::to_string(layer) + ".attn_" + role + ".weight"); ++ // Quantized projection size is recorded by the source decoder. Bound before any device read. ++ const uint64_t expected_elements = (uint64_t)g.n_embd * g.head_dim * ++ (std::strcmp(role,"q") == 0 ? g.n_head * 2 : g.n_head_kv); ++ if (!f || !w || !w->native_data || w->native_type != (int)kind || ++ bytes == 0 || bytes > expected_elements * 4 || expected_elements != (uint64_t)w->elements) ++ return fail("keyless artifact source projection geometry/type mismatch"); ++ // NativeDense owns source GGUF blocks. Verify the artifact was derived from these actual bytes. ++ // Source byte length must agree with ggml geometry; ne0/ne1 cannot validate a quantized byte span. ++ const uint64_t block_elements = kind == 42 ? 64 : kind == 8 ? 32 : 256; ++ const uint64_t block_bytes = kind == 42 ? 18 : kind == 11 ? 110 : kind == 12 ? 144 : ++ kind == 13 ? 176 : kind == 14 ? 210 : kind == 23 ? 136 : kind == 8 ? 34 : 0; ++ if (!block_bytes || expected_elements % block_elements || bytes != expected_elements / block_elements * block_bytes) ++ return fail("keyless artifact unsupported/mismatched native projection encoding"); ++ std::vector raw((size_t)bytes); ++ if (cudaMemcpy(raw.data(), w->native_data, raw.size(), cudaMemcpyDeviceToHost) != cudaSuccess) ++ return fail("keyless source projection readback failed"); ++ uint64_t hash = 0xcbf29ce484222325ull; ++ for (uint8_t byte : raw) hash = (hash ^ byte) * 0x100000001b3ull; ++ if (hash != wanted) return fail("keyless artifact source projection fingerprint mismatch"); ++ } ++ std::vector matrix((size_t)heads * dim * dim); ++ f.read((char*)matrix.data(), matrix.size()*sizeof(float)); ++ if (!f || !std::all_of(matrix.begin(), matrix.end(), [](float v) { return std::isfinite(v); })) ++ return fail("truncated/nonfinite keyless query matrix"); ++ float* device = nullptr; ++ if (cudaMalloc((void**)&device, matrix.size()*sizeof(float)) != cudaSuccess) ++ return fail("keyless query matrices do not fit in GPU memory"); ++ pending[layer] = device; ++ if (cudaMemcpy(device, matrix.data(), matrix.size()*sizeof(float), cudaMemcpyHostToDevice) != cudaSuccess) ++ return fail("keyless query matrix upload failed"); ++ } ++ if (f.peek() != std::char_traits::eof()) return fail("keyless artifact has trailing data"); ++ routes = std::move(pending); ++ return true; ++} ++} +diff --git a/src/core/layer.cpp b/src/core/layer.cpp +index 273b2293..978d41b5 100644 +--- a/src/core/layer.cpp ++++ b/src/core/layer.cpp +@@ -1,6 +1,7 @@ + + // src/core/layer.cpp - the GDN layer, composed. See the header for the operation order and its traps. + #include "strata/core/layer.hpp" ++#include "strata/core/keyless.hpp" + #include "strata/core/pin_budget.hpp" + #include "strata/core/native_dense.hpp" + #include "strata/core/native_head.hpp" +@@ -201,7 +202,9 @@ if (!w.wants_q8k()) { s_gemv_q8_0_split(x80, p.codes, p.scales, p.offset, + // namespace + void layer_set_native_bf16(bool enabled) { native_bf16_projections = enabled; } + void layer_set_native_flash_attn_short(bool enabled) { native_flash_attn_short = enabled; } +-namespace { bool g_kv_int8 = false, g_kv_q4 = false, g_kv_hybrid = false, g_kv_int8_rot = false; } ++namespace { bool g_without_key = false, g_kv_int8 = false, g_kv_q4 = false, g_kv_hybrid = false, g_kv_int8_rot = false; } ++void qsa_set_without_key(bool enabled) { g_without_key = enabled; } ++bool qsa_without_key() { return g_without_key; } + void qsa_set_kv_int8(bool enabled) { g_kv_int8 = enabled; } + void qsa_set_kv_int8_rotate(bool enabled) { g_kv_int8_rot = enabled; } + bool qsa_kv_int8() { return g_kv_int8; } +@@ -755,6 +758,7 @@ KvPlan kv_plan(const QsaShapes& s, int64_t max_cells, int64_t ring_cells) { + return p; + } + uint64_t kv_pool_bytes(const QsaShapes& s, int64_t pages, bool hybrid, bool int8) { ++ if (g_without_key) return (uint64_t)pages * s.page_size * strata::kernels::kv_q8_bytes_per_cell(s) / 2 + 64; + if (hybrid) { // K8V4: the INT8 K half (codes + scales) plus the Q4_0 V half (kv_q4.hpp's rotation) + const uint64_t rows = (uint64_t) pages * s.page_size * s.n_head_kv; + return rows * (uint64_t) s.head_dim + rows * (uint64_t) (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2 + +@@ -796,6 +800,7 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q + const KvPlan p = kv_plan(s, max_cells, ring_cells); + const int64_t pages = p.pages; + Cursor c{(uint8_t*) base}; ++ st.without_key = g_without_key; + st.kv_int8 = g_kv_int8 && !g_kv_q4; + st.kv_q4 = g_kv_q4; + // Hybrid K8V4, main layers only (the drafter's state is created with the globals toggled to INT8 - +@@ -854,9 +859,9 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q + st.k_q4 = c.take(rows * q4_row); + st.v_q4 = c.take(rows * q4_row); + } else if (st.kv_int8) { // st, not the global: the drafter's ring is INT8 under --kv k8v4 too +- st.k_q = c.take(rows * s.head_dim); ++ if (!st.without_key) st.k_q = c.take(rows * s.head_dim); + st.v_q = c.take(rows * s.head_dim); +- st.k_scale = c.take(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); ++ if (!st.without_key) st.k_scale = c.take(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); + st.v_scale = c.take(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); + } else { + st.k_pool = c.take(rows * s.head_dim); +@@ -926,9 +931,9 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q + st.host.k_q4 = hc.take(hrows * q4_row); + st.host.v_q4 = hc.take(hrows * q4_row); + } else if (st.kv_int8) { +- st.host.k_q = hc.take(hrows * s.head_dim); ++ if (!st.without_key) st.host.k_q = hc.take(hrows * s.head_dim); + st.host.v_q = hc.take(hrows * s.head_dim); +- st.host.k_scale = hc.take(hrows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); ++ if (!st.without_key) st.host.k_scale = hc.take(hrows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); + st.host.v_scale = hc.take(hrows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); + } else { + st.host.k_pool = hc.take(hrows * s.head_dim); +@@ -971,16 +976,16 @@ void qsa_state_zero(const QsaState& st, const ModelGeometry& g, void* stream) { + const int64_t live_slots = st.kv_elastic >= 0 ? pool_slots_mapped(*g_pools[(size_t) st.kv_elastic]) : st.n_slots; + const size_t rows = (size_t) live_slots * s.n_head_kv * s.page_size; + if (st.kv_hybrid) { +- cudaMemsetAsync(st.k_q, 0, rows * s.head_dim, cs); +- cudaMemsetAsync(st.k_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs); ++ if (st.k_q) cudaMemsetAsync(st.k_q, 0, rows * s.head_dim, cs); ++ if (st.k_scale) cudaMemsetAsync(st.k_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs); + cudaMemsetAsync(st.v_q4, 0, rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), cs); + } else if (st.kv_q4) { + cudaMemsetAsync(st.k_q4, 0, rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), cs); + cudaMemsetAsync(st.v_q4, 0, rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), cs); + } else if (st.kv_int8) { +- cudaMemsetAsync(st.k_q, 0, rows * s.head_dim, cs); ++ if (st.k_q) cudaMemsetAsync(st.k_q, 0, rows * s.head_dim, cs); + cudaMemsetAsync(st.v_q, 0, rows * s.head_dim, cs); +- cudaMemsetAsync(st.k_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs); ++ if (st.k_scale) cudaMemsetAsync(st.k_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs); + cudaMemsetAsync(st.v_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs); + } else { + cudaMemsetAsync(st.k_pool, 0, rows * s.head_dim * 2, cs); +@@ -998,6 +1003,8 @@ void qsa_state_zero(const QsaState& st, const ModelGeometry& g, void* stream) { + strata::kernels::QsaAttnPools qsa_attn_pools(const QsaState& st) { + strata::kernels::QsaAttnPools pools; + pools.page_table = st.page_table; ++ pools.without_key = st.without_key; ++ pools.keyless_cos = st.cos_tab; pools.keyless_sin = st.sin_tab; pools.keyless_n_rot = 64; pools.keyless_mrope = strata::kernels::mrope_table(); + if (st.kv_hybrid) { pools.k_q = st.k_q; pools.k_scale = st.k_scale; pools.v_q4 = st.v_q4; } + else if (st.kv_q4) { pools.k_q4 = st.k_q4; pools.v_q4 = st.v_q4; } + else if (st.kv_int8) { pools.k_q = st.k_q; pools.v_q = st.v_q; pools.k_scale = st.k_scale; pools.v_scale = st.v_scale; } +@@ -1127,11 +1134,12 @@ void stage_timing_report(int64_t n_layers) { + // needs nothing from the layer it is called for beyond its index. + static void dump_slot(float* dump, const ModelGeometry& g, int64_t layer, const float* src, uint64_t off, + uint64_t n, void* stream); +-bool qsa_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t pos, int32_t pos_base, const QsaState& st, const QsaBuffers& b, const float* x, float* out, void* stream, std::string& err, float* dump) { using namespace strata::kernels; const QsaShapes s = qsa_shapes(g); const LayerView v(tables, layer); const int64_t n_kv = pos + 1; /* P7 audit: RoPE reads cos/sin row pos_base + pos, and the table holds max_cells rows. */ if ((int64_t) pos_base + pos >= st.max_cells || pos_base < 0) { err = "qsa_layer: position " + std::to_string((long long) pos_base + pos) + " is outside the RoPE table (" + std::to_string((long long) st.max_cells) + " rows)"; return false; } const int64_t cap = qsa_selection_width(kTopkMaxCells, s); ++bool qsa_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t pos, int32_t pos_base, const QsaState& st, const QsaBuffers& b, const float* x, float* out, void* stream, std::string& err, float* dump) { using namespace strata::kernels; const QsaShapes s = qsa_shapes(g); const LayerView v(tables, layer); const int64_t n_kv = pos + 1; if (st.without_key && pos_base != 0) { err = "V-only requires zero position base"; return false; } /* P7 audit: RoPE reads cos/sin row pos_base + pos, and the table holds max_cells rows. */ if ((int64_t) pos_base + pos >= st.max_cells || pos_base < 0) { err = "qsa_layer: position " + std::to_string((long long) pos_base + pos) + " is outside the RoPE table (" + std::to_string((long long) st.max_cells) + " rows)"; return false; } const int64_t cap = qsa_selection_width(kTopkMaxCells, s); + const auto normalize_rotate = [&](float* data, const WeightRef* norm, int rows, int cols) { + try { + if (native_qsa_enabled()) native_qsa_rms_norm_weighted(data, (const float*) norm->data, data, cols, rows, RMS_EPS, stream); + else rms_norm_weighted(data, (const float*) norm->data, rows, cols, RMS_EPS, stream); ++ if (st.without_key && data == b.qcur) keyless_route_query(data, keyless_routing(layer), 1, (int)g.n_head, (int)g.head_dim, stream); + if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, rope_scaling(), st.pos_dev, stream); + else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st.cos_tab, st.sin_tab, st.pos_dev, stream); + return true; +@@ -1197,9 +1205,9 @@ SForm f_k, f_v, f_o, f_q; if (!sform_of(*w_attnk, f_k, v.name("attn_k.weight" + // k and v, with the activation THIS layer's tensors ask for. Both are K-quants in every QSA layer of this + // artifact, but the dispatch is here for the same reason it is in `gdn_layer`: the pack decides per tensor, + // and "it happens to be uniform here" is the assumption that was wrong for `attn_q`. +-if (!gemv_quantized(*w_attnk, p_k, f_k, b.x_q8_0, b.x_q8k, b.kcur, g.n_embd, g.n_head_kv * g.head_dim, v.name("attn_k.weight"), stream, err, x)) return false; +- if (!gemv_quantized(*w_attnv, p_v, f_v, b.x_q8_0, b.x_q8k, b.vcur, g.n_embd, g.n_head_kv * g.head_dim, v.name("attn_v.weight"), stream, err, x, w_attnk->native_data && w_attnv->native_data)) return false; dump_slot(dump, g, layer, b.vcur, (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim, (uint64_t) g.n_head_kv * g.head_dim, stream); +- if (!normalize_rotate(b.kcur, w_kn, (int) g.n_head_kv, (int) g.head_dim)) return false; ++if (!st.without_key && !gemv_quantized(*w_attnk, p_k, f_k, b.x_q8_0, b.x_q8k, b.kcur, g.n_embd, g.n_head_kv * g.head_dim, v.name("attn_k.weight"), stream, err, x)) return false; ++ if (!gemv_quantized(*w_attnv, p_v, f_v, b.x_q8_0, b.x_q8k, b.vcur, g.n_embd, g.n_head_kv * g.head_dim, v.name("attn_v.weight"), stream, err, x, !st.without_key && w_attnk->native_data && w_attnv->native_data)) return false; dump_slot(dump, g, layer, b.vcur, (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim, (uint64_t) g.n_head_kv * g.head_dim, stream); ++ if (!st.without_key && !normalize_rotate(b.kcur, w_kn, (int) g.n_head_kv, (int) g.head_dim)) return false; + // ---- 5. into the cache, and the indexer's append (which pools AND rotates on a block completion). + // EVERY ENTRY POINT FROM HERE ON IS THE CAPTURABLE ONE: the per-token counts come from `st.step` and every + // launch is sized from a capacity in `st`/`b`, so this sequence can be captured and replayed. The +@@ -1261,7 +1269,7 @@ int64_t max_blocks = (st.max_cells / s.idx_block) + 2; + // KV streaming: every block the selection names is made resident before anything reads it + qsa_kv_resolve(st, g, b.ids, st.step, 1, cap, stream); + if (st.kv_rot) strata::kernels::fwht256_inplace_cuda(b.qcur, g.n_head, stream); // = +- if (g_fast_attn && !native_flash_attn_short && dump == nullptr) { ++ if (st.without_key || (g_fast_attn && !native_flash_attn_short && dump == nullptr)) { + const strata::kernels::QsaAttnPools pools = qsa_attn_pools(st); + strata::kernels::qsa_decode_attn_step(b.qcur, pools, b.ids, st.step, cap, s, b.attn_scratch, b.attn, stream); + } else { +@@ -1586,6 +1594,13 @@ bool ple_issue_token(const PleRun& p, std::string& err) { + + bool ple_finish_token(const PleRun& p, void* stream, std::string& err) { + if (!p.ready()) { err = "ple_finish_token: the PLE run is not ready"; return false; } ++ if (p.table->kar_gpu_cache_enabled()) { ++ if (!p.table->collect_device(p.emb_dev, stream, err)) { ++ err = "ple_finish_token: " + err; ++ return false; ++ } ++ return true; ++ } + if (!p.table->collect(p.emb_host, err)) { err = "ple_finish_token: " + err; return false; } + if (cudaMemcpyAsync(p.emb_dev, p.emb_host, (size_t) strata::kernels::NG_N_EMBD * sizeof(float), + cudaMemcpyHostToDevice, (cudaStream_t) stream) != cudaSuccess) { +diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp +index f4b82b33..4b4a0d9e 100644 +--- a/src/core/mtp.cpp ++++ b/src/core/mtp.cpp +@@ -345,6 +345,11 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session + int64_t ring = (window > 0 && window < max_cells) ? window + 4 * (int64_t) max_t + 64 : 0; + // K8V4 never applies to the drafter: its own attention paths (below, and verify.cpp) handle whole formats + // only, whatever ring shape it takes (0, a window, or the -1 fully-resident fallback). ++ struct RestoreKeylessMode { ++ bool previous = qsa_without_key(); ++ ~RestoreKeylessMode() { qsa_set_without_key(previous); } ++ } restore_keyless_mode; ++ qsa_set_without_key(false); + const bool kv_hybrid_was = qsa_kv_hybrid(); + const bool kv_int8_was = qsa_kv_int8(); + qsa_set_kv_hybrid(false); +diff --git a/src/core/verify.cpp b/src/core/verify.cpp +index 3d6f48b2..1859853b 100644 +--- a/src/core/verify.cpp ++++ b/src/core/verify.cpp +@@ -4,6 +4,7 @@ + #include "strata/core/sm120_series.hpp" + #include "strata/kernels/gfx_arch.hpp" + #include "strata/core/verify.hpp" ++#include "strata/core/keyless.hpp" + #include "strata/core/pin_budget.hpp" + #if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) + #include "strata/core/host_graph_launch.hpp" +@@ -654,8 +655,10 @@ Verifier::~Verifier() { + for (cudaEvent_t e : df_join_) + if (e) cudaEventDestroy(e); + if (arena_) cudaFree(arena_); ++ if (kl_trace_file_) std::fclose(kl_trace_file_); ++ if (kl_trace_q_file_) std::fclose(kl_trace_q_file_); + if (hcount_d_) cudaFree(hcount_d_); +- void* hosts[] = {h_tok_, h_step_, h_pos_, h_commit_, h_ple_, h_out_, h_x_, h_ids_, h_w_, h_seq_, h_flag_, h_ymiss_, ++ void* hosts[] = {h_tok_, h_step_, h_pos_, h_commit_, h_ple_, h_out_, kl_trace_h_, kl_trace_q_h_, h_x_, h_ids_, h_w_, h_seq_, h_flag_, h_ymiss_, + h_flagA_, h_plan_, h_flagB_, h_plan_err_, h_nf_, herr_h_, hdrop_h_, h_bal_}; + for (void* h : hosts) + if (h) cudaFreeHost(h); +@@ -711,6 +714,21 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& + hits_ = hits; + head_ = head; + max_t_ = max_t; ++ if (const char* path = std::getenv("STRATA_KEYLESS_TRACE")) { ++ if (!*path) { err = "verify: STRATA_KEYLESS_TRACE needs a private output path"; return false; } ++ kl_trace_file_ = std::fopen(path, "wb"); ++ kl_trace_q_file_ = std::fopen((std::string(path) + ".q").c_str(), "wb"); ++ const size_t trace_bytes = (size_t) g.n_qsa_layers() * (size_t) max_t * ++ (size_t) g.n_head_kv * (size_t) g.head_dim * 2 * sizeof(float); ++ const size_t query_bytes = (size_t) g.n_qsa_layers() * (size_t) g.n_head * ++ (size_t) g.head_dim * sizeof(float); ++ if (!kl_trace_file_ || !kl_trace_q_file_ || ++ cudaHostAlloc((void**) &kl_trace_h_, trace_bytes, cudaHostAllocDefault) != cudaSuccess || ++ cudaHostAlloc((void**) &kl_trace_q_h_, query_bytes, cudaHostAllocDefault) != cudaSuccess) { ++ err = "verify: cannot create pinned keyless activation trace"; ++ return false; ++ } ++ } + sampling_.greedy = true; // a fresh verifier samples greedily until set_sampling says otherwise + sampling_.temperature = 0.0f; + #if defined(STRATA_GPU_METAL) +@@ -1560,12 +1578,13 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { + cudaStream_t sx) { + if (native_qsa_enabled()) native_qsa_rms_norm_weighted(data, (const float*) norm->data, data, cols, rows, EPS, sx); + else rms_norm_weighted(data, (const float*) norm->data, rows, cols, EPS, sx); ++ if (st.without_key && norm == wqn) keyless_route_query(data, keyless_routing(l), rows / (int) NH, (int) NH, (int) HD, sx); // local keyless arm, between the norm and the rope + if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, rope_scaling(), pos, sx); + else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st.cos_tab, st.sin_tab, pos, sx); + }; + // #783 PR-f (stuchapin909): the per-head RMSNorm and the rope in one launch, bit-identical to the pair + // (rope_parity check 6); STRATA_NO_NORM_ROPE=1 keeps the two; off on HIP until its parity check passes +- const bool fuse_nr = native_qsa_enabled() && native_rope_enabled() && native_norm_rope_usable((int) HD, (int) s.n_rot); ++ const bool fuse_nr = !st.without_key && native_qsa_enabled() && native_rope_enabled() && native_norm_rope_usable((int) HD, (int) s.n_rot); + auto norm_rope = [&](float* data, const WeightRef* norm, int rows, int cols, const int32_t* pos) { + if (fuse_nr && native_norm_rope_usable(cols, (int) s.n_rot)) { + native_qsa_rms_norm_rope(data, cols, (const float*) norm->data, data, rows, cols, (int) s.n_rot, EPS, +@@ -1726,16 +1745,29 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { + } + if (!sidem) idx_key(cs); + stamp(l, 7, grp); +- mm(wk, kcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD)); ++ if (!st.without_key) mm(wk, kcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD)); // V-only (keyless) arm: no K + mm(wv, vcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD)); +- if (qb) norm_rope(kcur_ + tb * NKV * HD, wkn, (int) (n * NKV), (int) HD, pos_k + tb * NKV); +- else for (int t = tb; t < te; ++t) norm_rope(kcur_ + t * NKV * HD, wkn, (int) NKV, (int) HD, pos_ + t * NH); ++ if (!st.without_key && qb) norm_rope(kcur_ + tb * NKV * HD, wkn, (int) (n * NKV), (int) HD, pos_k + tb * NKV); ++ else if (!st.without_key) for (int t = tb; t < te; ++t) norm_rope(kcur_ + t * NKV * HD, wkn, (int) NKV, (int) HD, pos_ + t * NH); + if (st.kv_rot) { // K and V rotated before they are stored (kv_q4.hpp) + fwht256_inplace_cuda(kcur_ + tb * NKV * HD, (int64_t) n * NKV, cs); + fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs); + } else if (st.kv_hybrid) { // K8V4: only V is rotated + fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs); + } ++ if (kl_trace_h_) { ++ const size_t width = (size_t) NKV * HD; ++ for (int t = tb; t < te; ++t) { ++ float* dst = kl_trace_h_ + ((size_t) qi * max_t_ + t) * 2 * width; ++ if (cudaMemcpyAsync(dst, kcur_ + (size_t) t * width, width * sizeof(float), ++ cudaMemcpyDeviceToHost, cs) != cudaSuccess || ++ cudaMemcpyAsync(dst + width, vcur_ + (size_t) t * width, width * sizeof(float), ++ cudaMemcpyDeviceToHost, cs) != cudaSuccess) { ++ err = "verify: keyless trace copy could not be captured"; ++ return false; ++ } ++ } ++ } + stamp(l, 8, grp); + if (!sidem) idx_snap(cs); + // #783 PR-d (stuchapin909): the window's K/V cells in one launch per pool instead of one per token (a +@@ -1896,6 +1928,12 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { + (uint64_t) n * (uint64_t) attn_scratch_floats_, attn_ + tb * NH * HD, n, cs))) + qsa_decode_attn_batch(qcur_ + tb * NH * HD, pools, sel_ + (size_t) tb * cap_, step_ + tb * kStepCount, cap_, + s, attn_scratch_ + (size_t) tb * attn_scratch_floats_, attn_ + tb * NH * HD, n, cs); ++ if (kl_trace_q_h_ && tb == 0 && ++ cudaMemcpyAsync(kl_trace_q_h_ + (size_t) qi * NH * HD, qcur_, ++ (size_t) NH * HD * sizeof(float), cudaMemcpyDeviceToHost, cs) != cudaSuccess) { ++ err = "verify: keyless query trace copy could not be captured"; ++ return false; ++ } + } + stamp(l, 13, grp); + if (st.kv_rot || st.kv_hybrid) fwht256_inplace_cuda(attn_ + tb * NH * HD, (int64_t) n * NH, cs); // back: H^-1 = H +@@ -3140,6 +3178,30 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, + const cudaError_t se = cudaStreamSynchronize(cs_); + trace_ev("SYNCED", -1, -1, (int64_t) se); + if (se != cudaSuccess) { err = std::string("verify: ") + cudaGetErrorString(se); return false; } ++ if (kl_trace_file_) { // local keyless study (STRATA_KEYLESS_TRACE): the window's K/V and first query, written once the GPU has finished ++ const uint32_t count = (uint32_t) T; ++ const size_t width = (size_t) g_->n_head_kv * (size_t) g_->head_dim; ++ bool written = std::fwrite(&count, sizeof(count), 1, kl_trace_file_) == 1 && ++ std::fwrite(&pos0, sizeof(pos0), 1, kl_trace_file_) == 1; ++ for (int64_t q = 0; written && q < g_->n_qsa_layers(); ++q) ++ for (int t = 0; written && t < T; ++t) ++ written = std::fwrite(kl_trace_h_ + ((size_t) q * max_t_ + t) * 2 * width, ++ sizeof(float), 2 * width, kl_trace_file_) == 2 * width; ++ if (!written || std::fflush(kl_trace_file_) != 0) { ++ err = "verify: cannot write keyless activation trace"; ++ return false; ++ } ++ const size_t query_width = (size_t) g_->n_head * (size_t) g_->head_dim; ++ bool q_written = std::fwrite(&count, sizeof(count), 1, kl_trace_q_file_) == 1 && ++ std::fwrite(&pos0, sizeof(pos0), 1, kl_trace_q_file_) == 1 && ++ std::fwrite(kl_trace_q_h_, sizeof(float), ++ (size_t) g_->n_qsa_layers() * query_width, kl_trace_q_file_) == ++ (size_t) g_->n_qsa_layers() * query_width; ++ if (!q_written || std::fflush(kl_trace_q_file_) != 0) { ++ err = "verify: cannot write keyless query trace"; ++ return false; ++ } ++ } + if (handoff_failed(err)) return false; // a stale hand-off: nothing of this window is used + if (ar_on() && h_plan_err_ != nullptr && *(volatile uint32_t*) h_plan_err_ != 0) { // #871: refresh_ar saw the table whole + *(volatile uint32_t*) h_plan_err_ = 0; +diff --git a/src/kernels/cuda/keyless.cu b/src/kernels/cuda/keyless.cu +new file mode 100644 +index 00000000..16485d30 +--- /dev/null ++++ b/src/kernels/cuda/keyless.cu +@@ -0,0 +1,25 @@ ++#include "strata/core/keyless.hpp" ++#include ++#include ++namespace strata::kernels { ++namespace { ++__global__ void route_kernel(float* q, const float* matrices, int heads) { ++ __shared__ float row[256]; ++ const int d = threadIdx.x, h = blockIdx.x % heads; ++ float* query = q + (size_t)blockIdx.x * 256; ++ row[d] = query[d]; ++ __syncthreads(); ++ const float* weight = matrices + ((size_t)h * 256 + d) * 256; ++ float sum = 0; ++ for (int i = 0; i < 256; ++i) sum = fmaf(row[i], weight[i], sum); ++ query[d] = sum; ++} ++} ++void keyless_route_query(float* q, const float* matrices, int64_t tokens, int heads, int dim, void* stream) { ++ if (!q || !matrices || tokens < 1 || heads < 1 || dim != 256 || tokens > INT32_MAX / heads) ++ throw std::runtime_error("invalid keyless query routing geometry or artifact"); ++ route_kernel<<<(unsigned)(tokens*heads),256,0,(cudaStream_t)stream>>>(q, matrices, heads); ++ const auto error = cudaGetLastError(); ++ if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); ++} ++} +diff --git a/src/kernels/cuda/kv_q8.cu b/src/kernels/cuda/kv_q8.cu +index a03e171b..3610dbfa 100644 +--- a/src/kernels/cuda/kv_q8.cu ++++ b/src/kernels/cuda/kv_q8.cu +@@ -42,7 +42,7 @@ __global__ void kv_append_q8_kernel(int8_t* __restrict__ k_q, int8_t* __restrict + } + const long long pos = (long long) __ldg(step + kStepPos); + const int h = blockIdx.x, g = blockIdx.y, t = threadIdx.x; +- const bool is_v = MULTI ? (blockIdx.z & 1) == 1 : blockIdx.z == 1; ++ const bool is_v = k_q == nullptr || (MULTI ? (blockIdx.z & 1) == 1 : blockIdx.z == 1); // k_q == nullptr: V-only (keyless) arm + const int groups = head_dim / KV_Q8_GROUP; + const float x = (is_v ? vcur : kcur)[h * head_dim + g * KV_Q8_GROUP + t]; + // max |x| over the 64 values: two warps, then combine through shared memory in a fixed order +@@ -66,7 +66,7 @@ __global__ void kv_append_q8_kernel(int8_t* __restrict__ k_q, int8_t* __restrict + (is_v ? v_q : k_q)[row * head_dim + g * KV_Q8_GROUP + t] = (int8_t) q; + if (t == 0) (is_v ? v_scale : k_scale)[row * groups + g] = sbits; + } +- if (host.k_q != nullptr) { ++ if ((is_v ? host.v_q : host.k_q) != nullptr) { + const long long row = ((pos / page_size) * kv_heads + h) * page_size + (pos % page_size); + (is_v ? host.v_q : host.k_q)[row * head_dim + g * KV_Q8_GROUP + t] = (int8_t) q; + if (t == 0) (is_v ? host.v_scale : host.k_scale)[row * groups + g] = sbits; +@@ -183,7 +183,7 @@ void kv_append_q8_step(int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_ + const int32_t* step, const float* kcur, const float* vcur, const QsaShapes& s, void* stream, + const KvHostPools* host) { + validate(s, "kv_append_q8"); +- const dim3 grid((unsigned) s.n_head_kv, (unsigned) (s.head_dim / KV_Q8_GROUP), 2); ++ const dim3 grid((unsigned) s.n_head_kv, (unsigned) (s.head_dim / KV_Q8_GROUP), k_q ? 2 : 1); + kv_append_q8_kernel<<>>( + k_q, v_q, k_scale, v_scale, page_table, step, kcur, vcur, (int) s.n_head_kv, (int) s.head_dim, + (int) s.page_size, host ? *host : KvHostPools{}); +diff --git a/src/kernels/cuda/kv_stream.cu b/src/kernels/cuda/kv_stream.cu +index 209984b4..dc8ece7b 100644 +--- a/src/kernels/cuda/kv_stream.cu ++++ b/src/kernels/cuda/kv_stream.cu +@@ -40,6 +40,10 @@ Runs runs_of(const QsaAttnPools& slots, const KvHostPools& host, int fmt, const + r.src[1] = (const uint8_t*) host.k_scale; r.dst[1] = (uint8_t*) slots.k_scale; r.len[1] = scales; + r.src[2] = (const uint8_t*) host.v_q4; r.dst[2] = (uint8_t*) slots.v_q4; r.len[2] = v; + r.n = 3; ++ } else if (fmt == kKvValueInt8) { // local keyless arm: V codes + scales only ++ r.src[0] = (const uint8_t*) host.v_q; r.dst[0] = (uint8_t*) slots.v_q; r.len[0] = rows * (int)s.head_dim; ++ r.src[1] = (const uint8_t*) host.v_scale; r.dst[1] = (uint8_t*) slots.v_scale; r.len[1] = rows * (int)(s.head_dim / KV_Q8_GROUP) * 2; ++ r.n = 2; + } else if (fmt == kKvQ4) { + const int bytes = rows * (int) kv_q4_bytes_per_head((int) s.head_dim); + r.src[0] = (const uint8_t*) host.k_q4; r.dst[0] = (uint8_t*) slots.k_q4; r.len[0] = bytes; +@@ -198,6 +202,7 @@ __global__ void ring_kernel(int32_t* table, long long n_blocks, long long n_slot + + uint64_t kv_block_bytes(const QsaShapes& s, int fmt) { + const uint64_t rows = (uint64_t) (s.n_head_kv * s.page_size); ++ if (fmt == kKvValueInt8) return rows * ((uint64_t)s.head_dim + (uint64_t)(s.head_dim / KV_Q8_GROUP)*2); + if (fmt == kKvHybrid) + return rows * (uint64_t) s.head_dim + rows * (uint64_t) (s.head_dim / KV_Q8_GROUP) * 2 + + rows * kv_q4_bytes_per_head((int) s.head_dim); +diff --git a/src/kernels/cuda/qsa_decode_attn.cu b/src/kernels/cuda/qsa_decode_attn.cu +index fbbef636..bffbf8c2 100644 +--- a/src/kernels/cuda/qsa_decode_attn.cu ++++ b/src/kernels/cuda/qsa_decode_attn.cu +@@ -1,5 +1,6 @@ + // src/kernels/cuda/qsa_decode_attn.cu - see include/strata/kernels/qsa_decode_attn.hpp. + #include "strata/kernels/qsa_decode_attn.hpp" ++#include "strata/kernels/mrope.hpp" + #include "strata/core/sm75_series.hpp" + #include "strata/core/sm120_series.hpp" + #include "strata/core/geometry.hpp" +@@ -79,7 +80,7 @@ __device__ __forceinline__ void load8_q4(const QsaAttnPools& p, bool value, long + template + __device__ __forceinline__ void load8(const QsaAttnPools& p, bool value, long long row, int d0, float* out) { + if constexpr (KV_MODE == 0) load8_f16(p, value, row, d0, out); +- else if constexpr (KV_MODE == 1) load8_q8(p, value, row, d0, out); ++ else if constexpr (KV_MODE == 1 || KV_MODE == 4) load8_q8(p, value, row, d0, out); + else if constexpr (KV_MODE == 3) { + // hybrid K8V4: both sides are defined - K unrotated INT8, V rotated Q4_0 - so a value=true call + // reads the Q4_0 pool instead of dereferencing the null v_q (no call site does today; PR review) +@@ -230,7 +231,22 @@ __device__ __forceinline__ void attn_chunk_body(const float* __restrict__ q, Qsa + if ((lane & 1) == 0 && head < G) sp[head][c] = score * scale; + } else { + float k8[8]; +- load8(p, false, srow[c], lane * 8, k8); ++ load8(p, KV_MODE == 4, srow[c], lane * 8, k8); ++ if constexpr (KV_MODE == 4) { ++ const int d0 = lane * 8, half = p.keyless_n_rot / 2; ++ if (d0 < p.keyless_n_rot) { ++ float paired[8]; ++ load8_q8(p, true, srow[c], d0 < half ? d0 + half : d0 - half, paired); ++ const int cell = ids[c0 + c]; ++ for (int d = 0; d < 8; ++d) { ++ const int pair = (d0 + d) % half; ++ const int rotary_pos = mrope_pos(p.keyless_mrope, cell, pair); ++ const float co = p.keyless_cos[(size_t)rotary_pos * half + pair]; ++ const float si = p.keyless_sin[(size_t)rotary_pos * half + pair]; ++ k8[d] = d0 < half ? k8[d]*co - paired[d]*si : k8[d]*co + paired[d]*si; ++ } ++ } ++ } + #pragma unroll + for (int h = 0; h < G; ++h) { + const int qflip = QUERY_SWIZZLE ? (lane & 4) : 0; +@@ -265,7 +281,7 @@ __device__ __forceinline__ void attn_chunk_body(const float* __restrict__ q, Qsa + float v; + if constexpr (KV_MODE == 0) { + v = __half2float(__ushort_as_half(p.v_pool[srow[c] * HD + t])); +- } else if constexpr (KV_MODE == 1) { ++ } else if constexpr (KV_MODE == 1 || KV_MODE == 4) { + const float sc = __half2float(__ushort_as_half(p.v_scale[srow[c] * (HD / KV_Q8_GROUP) + t / KV_Q8_GROUP])); + v = (float) p.v_q[srow[c] * HD + t] * sc; + } else { // modes 2 and 3: V is rotated Q4_0 (kv_q4.hpp); the caller rotates the output back +@@ -917,9 +933,9 @@ bool lane_cell_attn() { + return on; + } + +-// 0 fp16, 1 int8, 2 q4_0, 3 int8 K with q4_0 V ++// 0 fp16, 1 int8, 2 q4_0, 3 int8 K with q4_0 V, 4 (local, default-off keyless arm) int8 V only, K rebuilt from V + int attn_kv_mode(const QsaAttnPools& p) { +- return p.k_q4 != nullptr ? 2 : (p.k_q != nullptr && p.v_q4 != nullptr ? 3 : (p.k_q != nullptr ? 1 : 0)); ++ return p.without_key ? 4 : p.k_q4 != nullptr ? 2 : (p.k_q != nullptr && p.v_q4 != nullptr ? 3 : (p.k_q != nullptr ? 1 : 0)); + } + + // STRATA_ATTN_MERGE_V2: 1 merges with attn_merge_v2_kernel, 0 with attn_merge_kernel. Unset it follows +@@ -947,8 +963,12 @@ void launch_merge(int v2, const float* part_acc, const float* part_m, const floa + // kernel where it is built (the parity harness: never the environment). + void launch_chunks_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, + int64_t cap, const QsaShapes& s, float* scratch, int64_t n_q, cudaStream_t st, int kernel) { +- const int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3 +- : (pools.k_q != nullptr ? 1 : 0)); ++ const int kv_mode = attn_kv_mode(pools); ++ if (kv_mode == 4 && (pools.k_pool || pools.k_q || pools.k_scale || pools.k_q4 || ++ !pools.v_q || !pools.v_scale || !pools.keyless_cos || !pools.keyless_sin || pools.keyless_n_rot != 64)) { ++ std::fprintf(stderr, "qsa_decode_attn: V-only requires only V codes/scales and RoPE tables\n"); ++ std::exit(1); ++ } + const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK); + // per query: [acc: n_chunks*n_head*HD][m: n_chunks*n_head][l: n_chunks*n_head], all offsets from one stride + const long long stride = (long long) qsa_decode_attn_scratch_floats(cap, s); +@@ -961,7 +981,7 @@ void launch_chunks_batch(const float* q, const QsaAttnPools& pools, const int32_ + const bool pre = kernel < 0 ? pre75_attn() : kernel == 1; + #endif + // S25: STRATA_ATTN_LANECELL=1 - the score phase one cell per thread (bit-identical scores, no shuffle reductions) +- const bool lane_cell = kernel < 0 && lane_cell_attn(); ++ const bool lane_cell = kernel < 0 && lane_cell_attn() && kv_mode != 4; // the keyless arm has no lane-cell variant + #if defined(STRATA_HIP_GFX906) + static const bool query_swizzle = [] { + const char* v = std::getenv("STRATA_GFX906_ATTN_QUERY_SWIZZLE"); return v && v[0] == '1'; +@@ -1014,6 +1034,10 @@ void launch_chunks_batch(const float* q, const QsaAttnPools& pools, const int32_ + } + } else + #endif ++ if (kv_mode == 4) // local keyless arm (default off): V-only int8 pools, K rebuilt from V and the RoPE tables ++ attn_chunk_kernel<4><<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, scale, ++ part_acc, part_m, part_l, n_chunks, (int) cap, stride); ++ else + #if !defined(__HIPCC__) + if (kernel < 0 && kv_mode == 1 && attn_v3_on()) // (the parity harness names its kernel: never the environment) + attn_chunk_q8_v3_kernel<<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, +@@ -1078,6 +1102,7 @@ bool qsa_decode_attn_slots(const float* q, const QsaAttnSlotPools& pools, const + std::exit(1); + } + const int kv_mode = attn_kv_mode(pools.p[0]); ++ if (kv_mode == 4) return false; // the keyless arm keeps the per-query calls (no slots kernel for it) + for (int64_t z = 0; z < n_q; ++z) { + if (!pools.p[z].page_table) { + std::fprintf(stderr, "qsa_decode_attn_slots: missing page table\n"); +@@ -1136,8 +1161,7 @@ void qsa_decode_attn_batch_rows(const float* q, const QsaAttnPoolsRows& rows, co + std::fprintf(stderr, "qsa_decode_attn_batch_rows: unsupported geometry or missing buffers\n"); + std::exit(1); + } +- const int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3 +- : (pools.k_q != nullptr ? 1 : 0)); ++ const int kv_mode = attn_kv_mode(pools); + const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK); + const long long stride = (long long) qsa_decode_attn_scratch_floats(cap, s); + float* part_acc = scratch; +@@ -1149,7 +1173,7 @@ void qsa_decode_attn_batch_rows(const float* q, const QsaAttnPoolsRows& rows, co + // The plain kernel is what qsa_decode_attn_batch runs unless one of its variants is on (lane-cell scoring, the + // pre-sm_75 / gfx103x kernel, the gfx906 swizzle): there each row goes through that call, one launch per row. + static const bool lane_cell_rows = [] { const char* v = std::getenv("STRATA_ATTN_LANECELL"); return v && v[0] == '1'; }(); +- bool per_row = lane_cell_rows; ++ bool per_row = lane_cell_rows || kv_mode == 4; // the keyless arm has no rows kernel: one qsa_decode_attn_batch per row + #if defined(STRATA_ATTN_PRE75_BUILT) + per_row = per_row || pre75_attn(); + #endif +@@ -1186,19 +1210,24 @@ uint64_t qsa_decode_attn_scratch_floats(int64_t cap, const QsaShapes& s) { + + void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* step, + int64_t cap, const QsaShapes& s, float* scratch, float* attn, void* stream) { +- if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !scratch || !ids || !step || ++ if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !q || !attn || !scratch || !ids || !step || + !pools.page_table) { + std::fprintf(stderr, "qsa_decode_attn: unsupported geometry or missing buffers\n"); + std::exit(1); + } +- const int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3 +- : (pools.k_q != nullptr ? 1 : 0)); +- if (kv_mode == 3 ? (!pools.k_scale || !pools.v_q4) ++ const int kv_mode = attn_kv_mode(pools); ++ if (kv_mode == 4 ? (!pools.v_q || !pools.v_scale || !pools.keyless_cos || !pools.keyless_sin || pools.keyless_n_rot != 64) ++ : (kv_mode == 3 ? (!pools.k_scale || !pools.v_q4) + : (kv_mode == 2 ? (!pools.v_q4) : (kv_mode == 1 ? (!pools.v_q || !pools.k_scale || !pools.v_scale) +- : (!pools.k_pool || !pools.v_pool)))) { ++ : (!pools.k_pool || !pools.v_pool))))) { + std::fprintf(stderr, "qsa_decode_attn: incomplete KV pools\n"); + std::exit(1); + } ++ if (kv_mode == 4 && (pools.k_pool || pools.k_q || pools.k_scale || pools.k_q4 || ++ !pools.v_q || !pools.v_scale || !pools.keyless_cos || !pools.keyless_sin || pools.keyless_n_rot != 64)) { ++ std::fprintf(stderr, "qsa_decode_attn: V-only requires only V codes/scales and RoPE tables\n"); ++ std::exit(1); ++ } + const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK); + float* part_acc = scratch; + float* part_m = scratch + (size_t) n_chunks * s.n_head * HD; +@@ -1206,6 +1235,10 @@ void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32 + const float scale = 1.0f / sqrtf((float) HD); + const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv); + cudaStream_t st = (cudaStream_t) stream; ++ if (kv_mode == 4) // local keyless arm (default off) ++ attn_chunk_kernel<4><<>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size, scale, ++ part_acc, part_m, part_l, n_chunks, 0, 0); ++ else + #if !defined(__HIPCC__) + if (kv_mode == 1 && attn_v3_on()) + attn_chunk_q8_v3_kernel<<>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size, +diff --git a/src/kernels/keyless_parity.cpp b/src/kernels/keyless_parity.cpp +new file mode 100644 +index 00000000..107ebf2b +--- /dev/null ++++ b/src/kernels/keyless_parity.cpp +@@ -0,0 +1,119 @@ ++// Independent CPU reference for query routing and physical V-only attention. ++#include "strata/core/keyless.hpp" ++#include "strata/core/layer.hpp" ++#include "strata/kernels/qsa_decode_attn.hpp" ++#include "strata/kernels/f16_bits.hpp" ++#include "strata/kernels/kv_stream.hpp" ++#include ++#include ++#include ++#include ++#include ++#include ++ ++namespace { ++void check(cudaError_t e) { if (e != cudaSuccess) throw std::runtime_error(cudaGetErrorString(e)); } ++template T* device(const std::vector& values) { ++ T* p; check(cudaMalloc((void**)&p, values.size()*sizeof(T))); ++ check(cudaMemcpy(p, values.data(), values.size()*sizeof(T), cudaMemcpyHostToDevice)); return p; ++} ++} ++int main() { ++ using namespace strata::kernels; ++ try { ++ int count=0; if (cudaGetDeviceCount(&count)!=cudaSuccess || count==0) return 77; ++ constexpr int H=24, D=256, KV=2, CELLS=96, PAGE=4, BATCH=3, CAP=96; ++ std::vector query(BATCH*H*D), routing(H*D*D), routed(query.size()), co(CELLS*32), si(co.size()); ++ for (size_t i=0;i actual(query.size()); check(cudaMemcpy(actual.data(),dq,actual.size()*4,cudaMemcpyDeviceToHost)); ++ double route_error=0; for(size_t i=0;i2e-6) throw std::runtime_error("query routing disagrees with independent matrix product"); ++ const int pos[BATCH]={31,63,95}; ++ for(int p=0;p unrotated=routed; ++ std::vector positions(CELLS*3); ++ for(int cell=0;cell table(CELLS/PAGE), ids(BATCH*CAP,-1), steps(BATCH*kStepCount); ++ for(int page=0;page values(CELLS*KV*D); ++ std::vector scales(CELLS*KV*4); ++ for(int cell=0;cell scratch(BATCH*qsa_decode_attn_scratch_floats(CAP,qsa_real_shapes())), result(BATCH*H*D); ++ float *dsc=device(scratch), *dout=device(result); ++ qsa_decode_attn_batch(dq,pools,di,ds,CAP,qsa_real_shapes(),dsc,dout,BATCH,nullptr); ++ check(cudaMemcpy(result.data(),dout,result.size()*4,cudaMemcpyDeviceToHost)); ++ double error_sq=0, reference_sq=0, max_error=0; ++ for(int b=0;b scores(width), weights(width), reference(D,0); ++ for(int j=0;j1e-5 || max_error>1e-5) throw std::runtime_error("V-only attention disagrees with positional CPU reference"); ++ if(kv_block_bytes(qsa_real_shapes(),kKvValueInt8)*2!=kv_block_bytes(qsa_real_shapes(),kKvInt8)) ++ throw std::runtime_error("V-only block accounting is not half of K+V"); ++ std::printf("mrope=%d query_max_abs_error=%.9g attention_relative_l2=%.9g attention_max_abs_error=%.9g\n",vision,route_error,l2,max_error); ++ } ++ ++ std::printf("PASS: routed queries; three causal selections; permuted pages; raw value retrieval; no K allocation\n"); ++ return 0; ++ } catch(const std::exception& e) { std::fprintf(stderr,"keyless parity: %s\n",e.what()); return 1; } ++} +diff --git a/src/kernels/kv_stream_parity.cpp b/src/kernels/kv_stream_parity.cpp +index 722b7bc1..1b884944 100644 +--- a/src/kernels/kv_stream_parity.cpp ++++ b/src/kernels/kv_stream_parity.cpp +@@ -25,11 +25,13 @@ + #include + #include + #include ++#include + + namespace k = strata::kernels; + + namespace { + int g_fail = 0; ++float *keyless_cos=nullptr, *keyless_sin=nullptr; + void ck(cudaError_t e, const char* w) { + if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); } + } +@@ -61,10 +63,10 @@ struct Pools { // one K/V pool set of `pages` pages + const size_t b = rows * k::kv_q4_bytes_per_head((int) s.head_dim); + p.k_q4 = host ? halloc(b) : dalloc(b); + p.v_q4 = host ? halloc(b) : dalloc(b); +- } else if (fmt == k::kKvInt8) { +- p.k_q = host ? halloc(rows * s.head_dim) : dalloc(rows * s.head_dim); ++ } else if (fmt == k::kKvInt8 || fmt == k::kKvValueInt8) { ++ if (fmt != k::kKvValueInt8) p.k_q = host ? halloc(rows * s.head_dim) : dalloc(rows * s.head_dim); + p.v_q = host ? halloc(rows * s.head_dim) : dalloc(rows * s.head_dim); +- p.k_scale = host ? halloc(rows * 4) : dalloc(rows * 4); ++ if (fmt != k::kKvValueInt8) p.k_scale = host ? halloc(rows * 4) : dalloc(rows * 4); + p.v_scale = host ? halloc(rows * 4) : dalloc(rows * 4); + } else { + p.k_pool = host ? halloc(rows * s.head_dim) : dalloc(rows * s.head_dim); +@@ -74,6 +76,8 @@ struct Pools { // one K/V pool set of `pages` pages + k::QsaAttnPools attn(const int32_t* table) const { + k::QsaAttnPools a; + a.k_pool = p.k_pool; a.v_pool = p.v_pool; a.k_q = p.k_q; a.v_q = p.v_q; a.k_scale = p.k_scale; ++ a.without_key = p.v_q && !p.k_q; ++ a.keyless_cos=keyless_cos; a.keyless_sin=keyless_sin; a.keyless_n_rot=64; + a.v_scale = p.v_scale; a.k_q4 = p.k_q4; a.v_q4 = p.v_q4; a.page_table = table; + return a; + } +@@ -88,7 +92,7 @@ void append(const Pools& pl, const int32_t* table, const int32_t* step, const fl + host ? &hk : nullptr); + k::kv_append_q4_step(pl.p.v_q4, pl.p.v_q4, table, step, vc, vc, s, nullptr, host ? &hv : nullptr); + } else if (fmt == k::kKvQ4) k::kv_append_q4_step(pl.p.k_q4, pl.p.v_q4, table, step, kc, vc, s, nullptr, host); +- else if (fmt == k::kKvInt8) k::kv_append_q8_step(pl.p.k_q, pl.p.v_q, pl.p.k_scale, pl.p.v_scale, table, step, kc, vc, s, nullptr, host); ++ else if (fmt == k::kKvInt8 || fmt == k::kKvValueInt8) k::kv_append_q8_step(pl.p.k_q, pl.p.v_q, pl.p.k_scale, pl.p.v_scale, table, step, kc, vc, s, nullptr, host); + else k::kv_append_step(pl.p.k_pool, pl.p.v_pool, table, step, kc, vc, s, nullptr, host); + } + +@@ -115,7 +119,7 @@ std::vector selection(int64_t n_kv, int64_t width, std::mt19937& rng) { + } + + bool run(int fmt) { +- const char* name = fmt == k::kKvHybrid ? "k8v4" : fmt == k::kKvQ4 ? "q4_0" : fmt == k::kKvInt8 ? "int8" : "fp16"; ++ const char* name = fmt == k::kKvValueInt8 ? "v-only-int8" : fmt == k::kKvHybrid ? "k8v4" : fmt == k::kKvQ4 ? "q4_0" : fmt == k::kKvInt8 ? "int8" : "fp16"; + k::QsaShapes s = k::qsa_real_shapes(); + const int64_t N = 40000, n_blocks = (N + 3) / 4, n_slots = 8 * 516 + 700; // must evict: slots < blocks + const int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s), NQ = 8; +@@ -123,6 +127,16 @@ bool run(int fmt) { + std::mt19937 rng(7 + 4 * fmt); + std::normal_distribution nd(0.f, 1.f); + ++ if (fmt == k::kKvValueInt8) { ++ std::vector co(N*32), si(N*32); ++ for(int64_t pos=0;pos(co.size()); keyless_sin=dalloc(si.size()); ++ ck(cudaMemcpy(keyless_cos,co.data(),co.size()*4,cudaMemcpyHostToDevice),"cos"); ++ ck(cudaMemcpy(keyless_sin,si.data(),si.size()*4,cudaMemcpyHostToDevice),"sin"); ++ } + Pools ref, slots, host; + ref.alloc(n_blocks, s, fmt, false); + slots.alloc(n_slots, s, fmt, false); +@@ -237,7 +251,9 @@ bool run(int fmt) { + } + } // namespace + +-int main() { ++int main(int argc, char** argv) { ++ int count=0; if(cudaGetDeviceCount(&count)!=cudaSuccess || !count) return 77; ++ if(argc==2 && std::strcmp(argv[1],"--v-only")==0) return run(k::kKvValueInt8)?0:1; + std::printf("kv_stream_parity: streamed vs resident KV, bitwise\n"); + const bool a = run(k::kKvInt8), b = run(k::kKvF16), c = run(k::kKvQ4), d = run(k::kKvHybrid); + if (!a || !b || !c || !d) ++g_fail; +diff --git a/src/kernels/ngram.cpp b/src/kernels/ngram.cpp +index 07636d0f..b8c2e7f8 100644 +--- a/src/kernels/ngram.cpp ++++ b/src/kernels/ngram.cpp +@@ -12,6 +12,9 @@ + #include + #include + #include ++#include ++#include ++#include + #include + #if !defined(_WIN32) + #include +@@ -23,6 +26,22 @@ + #include + #include + ++#if defined(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE) ++#include ++#include ++#endif ++ ++#if defined(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE) || defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++#include ++#include ++#endif ++ ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++#include "kar_ple_cache.hpp" ++#include "libkar.h" ++#include ++#endif ++ + #if defined(_WIN32) + // `PrefetchVirtualMemory` (memoryapi.h, Windows 8+) is the whole point of the change in `gather` below. + #define WIN32_LEAN_AND_MEAN +@@ -35,6 +54,69 @@ namespace strata::kernels { + namespace { + /// The A/B arm. Host-token-path only, so it needs no atomics; see the note on `ple_prefetch_enable`. + bool g_ple_prefetch = true; ++#if defined(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE) ++struct PleRowTrace { ++ int fd = -1; ++ std::mutex lock; ++ bool failed = false; ++ ++ PleRowTrace() { ++ const char* path = std::getenv("STRATA_PLE_ROW_TRACE_PATH"); ++ if (!path) return; ++ if (!*path) { ++ std::fprintf(stderr, "PLE row trace needs a private output path\n"); ++ return; ++ } ++ fd = open(path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, 0600); ++ if (fd < 0) { ++ std::perror("cannot create private PLE row trace"); ++ return; ++ } ++ constexpr char header[] = "# strata-ple-rows v1: 16 global u32 row IDs per line\n"; ++ if (write(fd, header, sizeof(header) - 1) != static_cast(sizeof(header) - 1)) { ++ std::fprintf(stderr, "cannot write PLE row trace header\n"); ++ failed = true; ++ } ++ } ++ ++ ~PleRowTrace() { if (fd >= 0) close(fd); } ++ ++ void emit(const uint32_t* rows) { ++ if (fd < 0) return; ++ std::lock_guard guard(lock); ++ if (failed) return; ++ char line[PLE_N_HEADS * 12]; ++ size_t used = 0; ++ for (int h = 0; h < PLE_N_HEADS; ++h) { ++ const int written = std::snprintf(line + used, sizeof(line) - used, "%u%c", ++ rows[h], h + 1 == PLE_N_HEADS ? '\n' : ' '); ++ if (written < 0 || static_cast(written) >= sizeof(line) - used) { ++ failed = true; ++ std::fprintf(stderr, "PLE row trace line exceeded its buffer\n"); ++ return; ++ } ++ used += static_cast(written); ++ } ++ size_t done = 0; ++ while (done < used) { ++ const ssize_t n = write(fd, line + done, used - done); ++ if (n < 0 && errno == EINTR) continue; ++ if (n <= 0) { ++ failed = true; ++ if (n < 0) std::perror("cannot write PLE row trace"); ++ else std::fprintf(stderr, "cannot write PLE row trace: short write\n"); ++ return; ++ } ++ done += static_cast(n); ++ } ++ } ++}; ++ ++PleRowTrace& ple_row_trace() { ++ static PleRowTrace trace; ++ return trace; ++} ++#endif + } // namespace + + void ple_prefetch_enable(bool on) { g_ple_prefetch = on; } +@@ -95,6 +177,9 @@ void ngram_rows(const int32_t* tokens, const int32_t* prev, int n_tokens, const + out[i * PLE_N_HEADS + h] = (uint32_t) (mixed % c.vocab[h] + c.offset[h]); + } + } ++#if defined(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE) ++ ple_row_trace().emit(out + i * PLE_N_HEADS); ++#endif + } + } + +@@ -242,12 +327,228 @@ struct PleTable::Impl { + uint8_t prefetch_raw[kMaxPrefetch][PLE_N_HEADS * PLE_ROW_BYTES_MAX] = {}; + float scale = 1.0f; // the FP8 table's one scale + uint32_t rb = PLE_ROW_BYTES; // bytes per row ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ struct KarPart { ++ uint32_t number = 0; ++ uint64_t row_base = 0; ++ const kar_tensor_info* tensor = nullptr; ++ }; ++ kar_archive* kar = nullptr; ++ int kar_fd = -1; ++ const uint8_t* kar_map = nullptr; ++ size_t kar_bytes = 0; ++ uint32_t kar_level = 0; ++ std::string kar_format; ++ std::vector kar_parts; ++ std::unique_ptr kar_gpu_cache; ++ void decode_kar_row(uint32_t row, float* out160) const { ++ const auto part = std::lower_bound(kar_parts.begin(), kar_parts.end(), row, ++ [](const KarPart& item, uint32_t wanted) { ++ return item.row_base + item.tensor->row_count <= wanted; ++ }); ++ const kar_tensor_info* t = part->tensor; ++ const uint64_t local_row = uint64_t(row) - part->row_base; ++ const uint64_t first_word = local_row * t->row_words; ++ const uint64_t book_offset = t->books_offset + ((uint64_t{1} << kar_level) - 2) * 2; ++ for (uint32_t word = 0; word < t->row_words; ++word) { ++ const uint64_t source_word = first_word + word; ++ const uint64_t scale_offset = t->scales_offset + 2 * (source_word / (t->group / 32)); ++ const float scale = strata::fp16_to_fp32(strata::read_u16(kar_map + scale_offset)); ++ uint32_t bits[8] = {}; ++ for (uint32_t level = 0; level < kar_level; ++level) { ++ const uint8_t* p = kar_map + t->planes_offset + uint64_t(level) * t->plane_stride_bytes ++ + source_word * 4; ++ bits[level] = uint32_t(p[0]) | (uint32_t(p[1]) << 8) | ++ (uint32_t(p[2]) << 16) | (uint32_t(p[3]) << 24); ++ } ++ for (uint32_t bit = 0; bit < 32; ++bit) { ++ uint32_t code = 0; ++ for (uint32_t level = 0; level < kar_level; ++level) ++ code = (code << 1) | ((bits[level] >> bit) & 1u); ++ const float book = strata::fp16_to_fp32(strata::read_u16(kar_map + book_offset + code * 2)); ++ out160[word * 32 + bit] = book * scale; ++ } ++ } ++ bytes_read += t->row_words * (uint64_t(kar_level) * 4 + 2); ++ } ++#endif + void decode(const uint8_t* row, float* out160) const { fmt->dequant(row, scale, out160); } + }; + + PleTable::PleTable() : impl_(new Impl) {} + PleTable::~PleTable() { close(); delete impl_; } + ++bool PleTable::open_kar(const std::string& kar_path, uint32_t level, std::string& err, ++ uint64_t expected_rows) { ++#if !defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ (void) kar_path; (void) level; (void) expected_rows; ++ err = "experimental KAR PLE support is not compiled into this engine"; ++ return false; ++#else ++ close(); ++ if (level < 1 || level > 8 || expected_rows == 0) { ++ err = "KAR PLE level or expected row count is invalid"; ++ return false; ++ } ++ kar_archive* archive = nullptr; ++ const kar_status status = kar_open(kar_path.c_str(), KAR_OPEN_VERIFY_PAYLOAD, &archive); ++ if (status != KAR_OK) { ++ err = std::string("KAR PLE archive: ") + kar_strerror(status) + ": " + kar_last_error(); ++ return false; ++ } ++ impl_->kar = archive; ++ impl_->kar_fd = ::open(kar_path.c_str(), O_RDONLY | O_CLOEXEC); ++ struct stat file_info {}; ++ if (impl_->kar_fd < 0 || fstat(impl_->kar_fd, &file_info) || file_info.st_size <= 0 || ++ uint64_t(file_info.st_size) != kar_info(impl_->kar)->archive_bytes) { ++ err = "KAR PLE cannot reopen the verified archive at its expected length"; ++ close(); ++ return false; ++ } ++ impl_->kar_bytes = size_t(file_info.st_size); ++ void* map = mmap(nullptr, impl_->kar_bytes, PROT_READ, MAP_PRIVATE, impl_->kar_fd, 0); ++ if (map == MAP_FAILED) { ++ err = "KAR PLE cannot map the verified archive"; ++ close(); ++ return false; ++ } ++ impl_->kar_map = static_cast(map); ++ const std::string parent = "per_layer_token_embd.weight"; ++ const std::string prefix = parent + "#strata-part-"; ++ uint32_t declared_parts = 0; ++ for (uint32_t i = 0; i < kar_tensor_count(impl_->kar); ++i) { ++ const kar_tensor_info* t = kar_tensor(impl_->kar, i); ++ const std::string name = t->name; ++ uint32_t number = 0, total = 0; ++ if (name == parent) { ++ number = total = 1; ++ } else if (name.rfind(prefix, 0) == 0) { ++ char extra = 0; ++ if (std::sscanf(name.c_str() + prefix.size(), "%u-of-%u%c", &number, &total, &extra) != 2) { ++ err = "KAR PLE part name is malformed"; ++ close(); ++ return false; ++ } ++ } else { ++ continue; ++ } ++ if (!number || !total || number > total || (declared_parts && declared_parts != total) || ++ t->storage_class != KAR_NESTED || t->source_dtype != KAR_F32 || ++ t->nesting != KAR_TOPDOWN || t->n_dims != 2 || ++ t->dims[0] != PLE_HEAD_DIM || t->row_words != PLE_HEAD_DIM / 32 || ++ t->n_elements % PLE_HEAD_DIM || t->group < 32 || t->group % 32 || ++ level < t->planes_min || level > t->planes_max) { ++ err = "KAR PLE part geometry or precision level differs from the model"; ++ close(); ++ return false; ++ } ++ declared_parts = total; ++ impl_->kar_parts.push_back({number, 0, t}); ++ } ++ std::sort(impl_->kar_parts.begin(), impl_->kar_parts.end(), ++ [](const Impl::KarPart& left, const Impl::KarPart& right) { ++ return left.number < right.number; ++ }); ++ if (!declared_parts || impl_->kar_parts.size() != declared_parts) { ++ err = "KAR PLE parts are absent or incomplete"; ++ close(); ++ return false; ++ } ++ uint64_t rows = 0; ++ for (uint32_t i = 0; i < impl_->kar_parts.size(); ++i) { ++ auto& part = impl_->kar_parts[i]; ++ if (part.number != i + 1 || part.tensor->row_count == 0 || ++ part.tensor->row_count > expected_rows - rows) { ++ err = "KAR PLE parts are out of order or exceed expected rows"; ++ close(); ++ return false; ++ } ++ part.row_base = rows; ++ rows += part.tensor->row_count; ++ } ++ if (rows != expected_rows) { ++ err = "KAR PLE row count differs from the model"; ++ close(); ++ return false; ++ } ++ impl_->n_rows = rows; ++ impl_->kar_level = level; ++ impl_->kar_format = "KAR-L" + std::to_string(level) + "-CPU"; ++ impl_->mode = PleIo::Mmap; ++ return true; ++#endif ++} ++ ++bool PleTable::enable_kar_gpu_cache(uint32_t cache_mib, std::string& err) { ++#if !defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ (void) cache_mib; ++ err = "experimental KAR PLE support is not compiled into this engine"; ++ return false; ++#else ++ if (!impl_->kar || impl_->kar_level != 2 || impl_->kar_gpu_cache) { ++ err = "KAR PLE GPU cache requires an open level-2 archive and no existing cache"; ++ return false; ++ } ++ std::vector parts; ++ parts.reserve(impl_->kar_parts.size()); ++ for (const auto& part : impl_->kar_parts) parts.push_back({part.row_base, part.tensor}); ++ auto cache = std::make_unique(); ++ if (!cache->open(impl_->kar_map, impl_->kar_bytes, parts, cache_mib, 65536, err)) return false; ++ impl_->kar_gpu_cache = std::move(cache); ++ impl_->kar_format = "KAR-L2-GPU-cache"; ++ return true; ++#endif ++} ++ ++bool PleTable::kar_gpu_cache_enabled() const { ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ return impl_->kar_gpu_cache != nullptr; ++#else ++ return false; ++#endif ++} ++ ++bool PleTable::collect_device(float* device_out2560, void* stream, std::string& err) { ++#if !defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ (void) device_out2560; (void) stream; ++ err = "experimental KAR PLE support is not compiled into this engine"; ++ return false; ++#else ++ if (!impl_->kar_gpu_cache || !impl_->pending) { ++ err = "KAR PLE GPU collect requires a cache and an issued token"; ++ return false; ++ } ++ if (!impl_->kar_gpu_cache->enqueue(impl_->rows, PLE_N_HEADS, device_out2560, ++ reinterpret_cast(stream), err)) return false; ++ impl_->pending = false; ++ return true; ++#endif ++} ++ ++bool PleTable::gather_batch_device(const uint32_t* rows, size_t n_tokens, float* device_out, ++ void* stream, std::string& err) { ++#if !defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ (void) rows; (void) n_tokens; (void) device_out; (void) stream; ++ err = "experimental KAR PLE support is not compiled into this engine"; ++ return false; ++#else ++ if (!impl_->kar_gpu_cache || impl_->pending || !rows || !device_out || ++ n_tokens == 0 || n_tokens > 65536) { ++ err = "KAR PLE GPU gather requires a cache, no pending token, and 1..65536 tokens"; ++ return false; ++ } ++ const size_t count = n_tokens * PLE_N_HEADS; ++ const size_t chunk_rows = std::min(65536, impl_->kar_gpu_cache->slots()); ++ for (size_t offset = 0; offset < count; offset += chunk_rows) { ++ const size_t length = std::min(chunk_rows, count - offset); ++ if (!impl_->kar_gpu_cache->enqueue(rows + offset, length, ++ device_out + offset * PLE_HEAD_DIM, ++ reinterpret_cast(stream), err)) return false; ++ } ++ return true; ++#endif ++} ++ + bool PleTable::open(const std::string& gguf_path, std::string& err) { + return open(gguf_path, err, PleIoOptions{}); + } +@@ -450,6 +751,19 @@ void PleTable::prefetch_rows(const uint32_t* rows16) { + + void PleTable::close() { + wait_prefetches(); ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ impl_->kar_gpu_cache.reset(); ++ if (impl_->kar_map) munmap(const_cast(impl_->kar_map), impl_->kar_bytes); ++ impl_->kar_map = nullptr; ++ impl_->kar_bytes = 0; ++ if (impl_->kar_fd >= 0) ::close(impl_->kar_fd); ++ impl_->kar_fd = -1; ++ if (impl_->kar) kar_close(impl_->kar); ++ impl_->kar = nullptr; ++ impl_->kar_parts.clear(); ++ impl_->kar_level = 0; ++ impl_->kar_format.clear(); ++#endif + impl_->reader.close(); + impl_->pending = false; + impl_->locked = false; // the unmap below releases the lock +@@ -464,15 +778,32 @@ void PleTable::close() { + impl_->bytes_read = 0; + } + +-bool PleTable::is_open() const { return impl_->data != nullptr || impl_->reader.is_open(); } ++bool PleTable::is_open() const { ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ if (impl_->kar) return true; ++#endif ++ return impl_->data != nullptr || impl_->reader.is_open(); ++} + bool PleTable::locked() const { return impl_->locked; } +-const char* PleTable::format() const { return impl_->fmt->name; } ++const char* PleTable::format() const { ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ if (impl_->kar) return impl_->kar_format.c_str(); ++#endif ++ return impl_->fmt->name; ++} + PleIo PleTable::mode() const { return impl_->mode; } + uint64_t PleTable::rows() const { return impl_->n_rows; } + uint64_t PleTable::bytes_read() const { return impl_->bytes_read; } + + void PleTable::read_row(uint32_t row, float* out160) const { + std::lock_guard lk(impl_->mu); ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ if (impl_->kar) { ++ if (row >= impl_->n_rows) std::memset(out160, 0, (size_t) PLE_HEAD_DIM * sizeof(float)); ++ else impl_->decode_kar_row(row, out160); ++ return; ++ } ++#endif + if (impl_->mode == PleIo::Direct && impl_->reader.is_open()) { + uint8_t raw[PLE_ROW_BYTES_MAX]; + std::string err; +@@ -620,6 +951,21 @@ bool PleTable::gather_batch(const uint32_t* rows, size_t n_tokens, float* out, s + void PleTable::set_injected_delay_us(double us) { impl_->reader.set_injected_delay_us(us); } + + std::string PleTable::io_report() const { ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ if (impl_->kar_gpu_cache) { ++ const auto s = impl_->kar_gpu_cache->stats(); ++ char buf[300]; ++ std::snprintf(buf, sizeof buf, ++ "PLE GPU cache: %llu hits, %llu misses (%.2f%% hit), %u slots (%.1f MiB compressed), " ++ "%llu compressed bytes, %llu H2D argument bytes", ++ (unsigned long long) s.hits, (unsigned long long) s.misses, ++ s.hits + s.misses ? 100.0 * double(s.hits) / double(s.hits + s.misses) : 0.0, ++ impl_->kar_gpu_cache->slots(), double(impl_->kar_gpu_cache->slots()) * 64.0 / 1048576.0, ++ (unsigned long long) s.compressed_bytes, ++ (unsigned long long) s.host_to_device_bytes); ++ return buf; ++ } ++#endif + if (impl_->mode != PleIo::Direct || !impl_->reader.is_open()) return {}; + const strata::ngram::ReaderStats s = impl_->reader.snapshot(); + char buf[400]; +diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu +index a4f56f10..c549feb3 100644 +--- a/src/prefill/kernels.cu ++++ b/src/prefill/kernels.cu +@@ -2175,8 +2175,9 @@ __global__ void kv_append_kernel(const float* __restrict__ K, const float* __res + uint16_t* v_pool, int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale, + strata::kernels::KvHostPools host, strata::kernels::KvHostPools stage) { + const int64_t t = blockIdx.x; +- const int kvh = blockIdx.y, g = blockIdx.z >> 1; +- const bool is_v = (blockIdx.z & 1) != 0; ++ const bool value_only = k_pool == nullptr && k_q == nullptr; ++ const int kvh = blockIdx.y, g = value_only ? blockIdx.z : blockIdx.z >> 1; ++ const bool is_v = value_only || (blockIdx.z & 1) != 0; + const int d = g * 64 + threadIdx.x; + const float x = (is_v ? V : K)[t * 512 + kvh * 256 + d]; + const int64_t pos = pos0 + t; +@@ -2204,11 +2205,11 @@ __global__ void kv_append_kernel(const float* __restrict__ K, const float* __res + (is_v ? v_q : k_q)[row * 256 + d] = (int8_t) q; + if (threadIdx.x == 0) (is_v ? v_scale : k_scale)[row * 4 + g] = sb; + } +- if (host.k_q != nullptr) { ++ if ((is_v ? host.v_q : host.k_q) != nullptr) { + (is_v ? host.v_q : host.k_q)[row_id * 256 + d] = (int8_t) q; + if (threadIdx.x == 0) (is_v ? host.v_scale : host.k_scale)[row_id * 4 + g] = sb; + } +- if (stage.k_q != nullptr) { ++ if ((is_v ? stage.v_q : stage.k_q) != nullptr) { + (is_v ? stage.v_q : stage.k_q)[row_id * 256 + d] = (int8_t) q; + if (threadIdx.x == 0) (is_v ? stage.v_scale : stage.k_scale)[row_id * 4 + g] = sb; + } +@@ -2443,7 +2444,7 @@ void kv_append(const float* K, const float* V, int64_t T, int64_t pos0, const in + uint16_t* k_pool, uint16_t* v_pool, int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale, + void* stream, const strata::kernels::KvHostPools* host, const strata::kernels::KvHostPools* stage) { + if (T <= 0) return; +- kv_append_kernel<<>>( ++ kv_append_kernel<<>>( + K, V, pos0, page_table, page_size, k_pool, v_pool, k_q, v_q, k_scale, v_scale, + host ? *host : strata::kernels::KvHostPools{}, stage ? *stage : strata::kernels::KvHostPools{}); + check("kv_append"); +diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp +index 6cb888e5..6dbf4156 100644 +--- a/src/prefill/prefill.cpp ++++ b/src/prefill/prefill.cpp +@@ -30,10 +30,12 @@ + #include "strata/kernels/cpu/expert_layout.hpp" + #include "strata/kernels/cpu/hadamard.hpp" + #include "strata/kernels/qsa.hpp" ++#include "strata/kernels/mrope.hpp" + #include "strata/kernels/kv_stream.hpp" + #include "strata/kernels/cvec.hpp" + #include "strata/kernels/kv_q4.hpp" + #include "strata/core/layer.hpp" ++#include "strata/core/keyless.hpp" + #include "strata/core/native_dense.hpp" + #include "strata/core/native_head.hpp" + #include "strata/kernels/verify_kernels.hpp" +@@ -65,6 +67,8 @@ + #include + #include + #include ++#include ++#include + + #ifndef STRATA_PREFILL_MMQ + // A build without the llama.cpp sources (no STRATA_NATIVE_EXPERTS): no MMQ, the FP16 expert path everywhere. +@@ -1035,9 +1039,9 @@ void take_stage(Alloc& o_borrowed, const core::SessionState& ss, const strata::k + st.k_q4 = o.take(rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), ok); + st.v_q4 = o.take(rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), ok); + } else if (q0.kv_int8) { +- st.k_q = o.take(rows * s.head_dim, ok); ++ if (!q0.without_key) st.k_q = o.take(rows * s.head_dim, ok); + st.v_q = o.take(rows * s.head_dim, ok); +- st.k_scale = o.take(rows * (s.head_dim / 64), ok); ++ if (!q0.without_key) st.k_scale = o.take(rows * (s.head_dim / 64), ok); + st.v_scale = o.take(rows * (s.head_dim / 64), ok); + } else { + st.k_pool = o.take(rows * s.head_dim, ok); +@@ -2594,6 +2598,21 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri + const core::ModelGeometry& g = *m.g; + core::SessionState& ss = *m.ss; + const auto t_start = Clock::now(); ++ // Offline teacher capture for fitting only the paper's query-routing parameters. ++ // Explicitly bounded and prohibited in serving; this path never predicts or stores K in V-only mode. ++ std::ofstream keyless_trace; ++ if (const char* path = std::getenv("STRATA_KEYLESS_PREFILL_TRACE")) { ++ if (!*path || n > 4096 || pos0 != 0 || ss.qsa_states[0].without_key || std::filesystem::exists(path)) { ++ err = "keyless teacher trace requires a new private file, ordinary K+V and at most 4096 prompt tokens"; ++ return false; ++ } ++ keyless_trace.open(path, std::ios::binary); ++ if (!keyless_trace) { err = "cannot open keyless teacher trace"; return false; } ++ std::filesystem::permissions(path, std::filesystem::perms::owner_read | std::filesystem::perms::owner_write); ++ keyless_trace.write("SKLTRACE", 8); ++ const uint32_t header[5] = {1, (uint32_t)g.n_qsa_layers(), (uint32_t)g.n_head, (uint32_t)g.n_head_kv, (uint32_t)g.head_dim}; ++ keyless_trace.write((const char*)header, sizeof(header)); ++ } + const int64_t LB = stage_lb_, LE = stage_le_; + // The direct successor's future lives on the Prefill object. Intermediate + // stages therefore do not drain the complete remaining GPU chain here. +@@ -2667,6 +2686,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri + // after this one is read on a thread while the GPU runs this one, into the other of two buffers. The rows + // depend only on the tokens (the two before a position name its n-grams), so this is the same data. + const bool ple_on = ss.ple.ready() && LB <= 1 && 1 < LE; ++ const bool ple_gpu_cache = ple_on && ss.ple.table->kar_gpu_cache_enabled(); + // the PLE block batched over the chunk: the pinned postops and a BF16 or GGUF-native key (else token by token); + // STRATA_PLE_BATCH=0 keeps the per-token block (the A/B) + static const bool ple_batch_env = [] { +@@ -2677,7 +2697,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri + (ss.ple.w.key_bf16 != nullptr || ss.ple.w.key_native_data != nullptr) && + m.region_bytes / ((uint64_t) (3 * strata::kernels::NG_HC_DIM + N + 4) * 4 + (uint64_t) N * 2 + 4096) >= 64; + const int32_t prev0[2] = {prev[0], prev[1]}; +- auto ple_gather = [&m, &ss, tokens, n, prev0, C](int64_t c0, int buf, std::string& e) -> bool { ++ auto ple_gather = [&m, &ss, tokens, n, prev0, C, ple_gpu_cache](int64_t c0, int buf, std::string& e) -> bool { + const int64_t T = std::min(C, n - c0); + auto at = [&](int64_t i) { return i < 2 ? prev0[i] : (int32_t) tokens[i - 2]; }; // prev0, then the tokens + int32_t pv[2] = {at(c0), at(c0 + 1)}; +@@ -2688,7 +2708,8 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri + pv[0] = pv[1]; + pv[1] = tok; + } +- return ss.ple.table->gather_batch(m.ple_rows[buf].data(), (size_t) T, m.ple_emb_host[buf], e); ++ return ple_gpu_cache || ss.ple.table->gather_batch(m.ple_rows[buf].data(), (size_t) T, ++ m.ple_emb_host[buf], e); + }; + std::string ple_next_err; + std::future ple_next; // declared after everything it reads: an early return waits for it +@@ -2838,31 +2859,38 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri + if (!ple_pending) return true; + ple_pending = false; + const auto tp = Clock::now(); +- if (!ple_next.get()) { +- err = ple_next_err; +- return false; +- } +- // #1996: the pageable fallback (no RAM to pin) goes up through a pinned slot; the pinned buffers as before +- if ((m.ple_pageable[ple_buf].empty() +- ? cudaMemcpyAsync(m.ple_emb, m.ple_emb_host[ple_buf], (size_t) T * N * 4, cudaMemcpyHostToDevice, m.cs) +- : m.up_ring.h2d(m.ple_emb, m.ple_emb_host[ple_buf], (size_t) T * N * 4, m.cs)) != +- cudaSuccess || +- cudaEventRecord(m.ple_copied[ple_buf], m.cs) != cudaSuccess) { +- err = std::string("prefill: the PLE rows' upload failed: ") + cudaGetErrorString(cudaGetLastError()); +- return false; +- } +- if (c0 + C < n) { +- // the other buffer's upload (a chunk ago) is done before the SSD thread refills it +- if (cudaEventSynchronize(m.ple_copied[ple_buf ^ 1]) != cudaSuccess) { ++ if (ple_gpu_cache) { // local KAR PLE GPU row cache (default off): ple_gather only computed the n-gram rows ++ if (!ple_next.get()) { ++ err = ple_next_err; ++ return false; ++ } ++ if (!ss.ple.table->gather_batch_device(m.ple_rows[0].data(), (size_t) T, m.ple_emb, m.cs, err)) return false; ++ } else { ++ if (!ple_next.get()) { ++ err = ple_next_err; ++ return false; ++ } ++ // #1996: the pageable fallback (no RAM to pin) goes up through a pinned slot; the pinned buffers as before ++ if ((m.ple_pageable[ple_buf].empty() ++ ? cudaMemcpyAsync(m.ple_emb, m.ple_emb_host[ple_buf], (size_t) T * N * 4, cudaMemcpyHostToDevice, m.cs) ++ : m.up_ring.h2d(m.ple_emb, m.ple_emb_host[ple_buf], (size_t) T * N * 4, m.cs)) != ++ cudaSuccess || ++ cudaEventRecord(m.ple_copied[ple_buf], m.cs) != cudaSuccess) { + err = std::string("prefill: the PLE rows' upload failed: ") + cudaGetErrorString(cudaGetLastError()); + return false; + } +- ple_next = std::async(std::launch::async, [&ple_gather, &ple_next_err, c1 = c0 + C, b = ple_buf ^ 1] { +- strata::aux_cpus::pin_current_thread(); +- return ple_gather(c1, b, ple_next_err); +- }); ++ if (c0 + C < n) { ++ // the other buffer's upload (a chunk ago) is done before the SSD thread refills it ++ if (cudaEventSynchronize(m.ple_copied[ple_buf ^ 1]) != cudaSuccess) { ++ err = std::string("prefill: the PLE rows' upload failed: ") + cudaGetErrorString(cudaGetLastError()); ++ return false; ++ } ++ ple_next = std::async(std::launch::async, [&ple_gather, &ple_next_err, c1 = c0 + C, b = ple_buf ^ 1] { ++ strata::aux_cpus::pin_current_thread(); ++ return ple_gather(c1, b, ple_next_err); ++ }); ++ } + } +- ple_buf ^= 1; + stats_.ms_ple += ms_since(tp); + return true; + }; +@@ -3291,13 +3319,13 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri + *wikn = need(v, "indexer.k_norm.weight", err); + if (!wq || !wk || !wv || !wo || !wik || !wiq || !wqn || !wkn || !wiqn || !wikn) return false; + pt.mark(kPfQsa, cs); +- if (!native_proj(m.gemm, wk, m.mixed_h, m.Kc, T, v.name("attn_k.weight"), err)) return false; ++ if (!st.without_key && !native_proj(m.gemm, wk, m.mixed_h, m.Kc, T, v.name("attn_k.weight"), err)) return false; + if (!native_proj(m.gemm, wv, m.mixed_h, m.Vc, T, v.name("attn_v.weight"), err)) return false; + if (!native_proj(m.gemm, wq, m.mixed_h, m.Qf, T, v.name("attn_q.weight"), err)) return false; + if (!bf16_proj(m.gemm, wik, m.mixed_bf, m.idx_raw, T, v.name("indexer.k_proj.weight"), err, 0, m.mixed_bf_lo)) return false; + if (!bf16_proj(m.gemm, wiq, m.mixed_bf, m.q_idx, T, v.name("indexer.q_proj.weight"), err, 0, m.mixed_bf_lo)) return false; +- rms_rows(m.Kc, (const float*) wkn->data, T * 2, 256, 256, EPS, m.cs); +- rope(m.Kc, T, 2, 256, 512, p0, strata::kernels::rope_scaling(), m.cs); ++ if (!st.without_key) rms_rows(m.Kc, (const float*) wkn->data, T * 2, 256, 256, EPS, m.cs); ++ if (!st.without_key) rope(m.Kc, T, 2, 256, 512, p0, strata::kernels::rope_scaling(), m.cs); + // KV streaming: this layer's cells [0, p0) come in from the host copy to the staging pool, and the + // chunk's cells go to the host copy, the staging pool, and the VRAM slots of resident blocks + const bool staged = st.kv_mode == 1; +@@ -3360,6 +3388,19 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri + if (staged) pf_step("reading the prompt (batched, step sync): the K/V append at layer", l); + split_q(m.Qf, m.q, T, m.cs); + rms_rows(m.q, (const float*) wqn->data, T * 24, 256, 256, EPS, m.cs); ++ if (keyless_trace.is_open()) { ++ const int32_t record[3] = {(int32_t)l, (int32_t)p0, (int32_t)T}; ++ keyless_trace.write((const char*)record, sizeof(record)); ++ for (const auto& tensor : std::vector>{ ++ {m.q,(size_t)T*24*256}, {m.Kc,(size_t)T*2*256}, {m.Vc,(size_t)T*2*256}}) { ++ std::vector host(tensor.second); ++ if (cudaMemcpyAsync(host.data(), tensor.first, host.size()*sizeof(float), cudaMemcpyDeviceToHost, cs) != cudaSuccess || ++ cudaStreamSynchronize(cs) != cudaSuccess) { err="keyless teacher readback failed"; return false; } ++ keyless_trace.write((const char*)host.data(), host.size()*sizeof(float)); ++ } ++ if (!keyless_trace) { err="keyless teacher trace write failed"; return false; } ++ } ++ if (st.without_key) strata::kernels::keyless_route_query(m.q, core::keyless_routing(l), T, 24, 256, m.cs); + rope(m.q, T, 24, 256, 6144, p0, strata::kernels::rope_scaling(), m.cs); + if (st.kv_rot) strata::kernels::fwht256_inplace_cuda(m.q, T * 24, m.cs); + rms_rows(m.q_idx, (const float*) wiqn->data, T * 4, 128, 128, EPS, m.cs); +@@ -3495,15 +3536,17 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri + } + } + } +- const strata::kernels::QsaAttnPools pools = staged ? pools_of(m.stage, m.ident_table) ++ strata::kernels::QsaAttnPools pools = staged ? pools_of(m.stage, m.ident_table) + : core::qsa_attn_pools(st); ++ pools.without_key = st.without_key; ++ pools.keyless_cos = st.cos_tab; pools.keyless_sin = st.sin_tab; pools.keyless_n_rot = 64; pools.keyless_mrope = strata::kernels::mrope_table(); + pt.mark(kPfQsaAttn, cs); + // perf-review D-1: the whole chunk on tensor cores, one block per (query, KV head), FP32-level + // accuracy but not bitwise (qsa_prompt_attn.hpp). Q4_0 KV, or STRATA_PROMPT_ATTN_OLD=1: the + // decode kernel, 32 queries at a time (K8V4 runs the tensor kernel's mode 3: INT8 K, + // V dequantized from its q4_0 blocks to fp16 at gather) + static const bool old_attn = std::getenv("STRATA_PROMPT_ATTN_OLD") != nullptr; +- if (old_attn || !strata::kernels::qsa_prompt_attn_batch(m.q, pools, m.sel_ids, m.steps_dev, m.cap, s, ++ if (st.without_key || old_attn || !strata::kernels::qsa_prompt_attn_batch(m.q, pools, m.sel_ids, m.steps_dev, m.cap, s, + m.attn, T, m.cs)) + for (int64_t t0 = 0; t0 < T; t0 += m.attn_batch) { + const int64_t nb = std::min(m.attn_batch, T - t0); +diff --git a/src/program/generate.cpp b/src/program/generate.cpp +index d381227d..370e310f 100644 +--- a/src/program/generate.cpp ++++ b/src/program/generate.cpp +@@ -31,6 +31,9 @@ + #include "strata/core/conversation_memory.hpp" + #include "strata/core/coupled_draft.hpp" + #include "strata/core/expert_source.hpp" ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) ++#include "kar_expert_miss.hpp" ++#endif + #include "strata/core/foresight_swap.hpp" + #include "strata/core/pinned.hpp" + #include "strata/core/pin_budget.hpp" +@@ -76,6 +79,7 @@ + #include "strata/prefill/moe_mmq.hpp" + #endif + #include "strata/core/native_dense.hpp" ++#include "strata/core/keyless.hpp" + #include "strata/program/batch_read.hpp" + #include "strata/program/logits_selection.hpp" + #include "strata/program/conv_cache.hpp" +@@ -479,6 +483,9 @@ struct Options { + std::string embd_gguf; + /// Plan v0.3 P2: how the n-gram table is read. Direct (default) = unbuffered SSD reads, table never in RAM. + std::string ple_io = "direct"; ++ std::string ple_kar; ///< experimental PLE-only KAR quality arm; all other weights stay native ++ uint32_t ple_kar_level = 2; ++ uint32_t ple_kar_gpu_cache_mib = 0; ///< opt-in bounded compressed GPU PLE cache; 0 keeps CPU gather + bool ple_io_explicit = false; ///< --ple-io was given: the engine only warns when direct measures slow + int64_t ple_row_cache = 1 << 20; ///< bounded row cache (rows of 90 B); 0 disables + int ple_inflight = 256; // the prompt path reads a chunk's rows at once: 64 left the SSD half idle (32K: 303 -> 189 ms) +@@ -818,6 +825,9 @@ void usage() { + " so a caller never has to export environment variables\n" + " --ple-gguf PATH required PLE table (original second GGUF shard); with --native, the model's\n" + " shard that holds per_layer_token_embd.weight when not given\n" ++ " --ple-kar PATH experimental PLE-only KAR CPU quality arm (requires a KAR-enabled build)\n" ++ " --ple-kar-level N precision of the experimental PLE KAR arm (default 2)\n" ++ " --ple-kar-gpu-cache-mib N experimental compressed PLE row cache in VRAM (1..1024; level 2)\n" + " --no-ple explicit diagnostic ablation of the PLE layer\n" + " --ple-io direct|mmap|ram n-gram table reads (plan v0.3 P2). direct (default): unbuffered SSD\n" + " reads, the table never enters RAM or the file cache; mmap: A/B arm;\n" +@@ -2476,6 +2486,29 @@ int main(int argc, char** argv) { + else if (a == "--dump-halves") o.dump_halves = next("--dump-halves"); + else if (a == "--dump-routing") o.dump_routing = next("--dump-routing"); + else if (a == "--ple-gguf") o.ple_gguf = next("--ple-gguf"); ++ else if (a == "--ple-kar") o.ple_kar = next("--ple-kar"); ++ else if (a == "--ple-kar-level") { ++ const std::string value = next("--ple-kar-level"); ++ unsigned level = 0; ++ const auto parsed = std::from_chars(value.data(), value.data() + value.size(), level); ++ if (parsed.ec != std::errc{} || parsed.ptr != value.data() + value.size() || ++ level < 1 || level > 8) { ++ std::fprintf(stderr, "strata generate: --ple-kar-level must be an integer from 1 to 8\n"); ++ return 2; ++ } ++ o.ple_kar_level = level; ++ } ++ else if (a == "--ple-kar-gpu-cache-mib") { ++ const std::string value = next("--ple-kar-gpu-cache-mib"); ++ unsigned mib = 0; ++ const auto parsed = std::from_chars(value.data(), value.data() + value.size(), mib); ++ if (parsed.ec != std::errc{} || parsed.ptr != value.data() + value.size() || ++ mib < 1 || mib > 1024) { ++ std::fprintf(stderr, "strata generate: --ple-kar-gpu-cache-mib must be 1..1024\n"); ++ return 2; ++ } ++ o.ple_kar_gpu_cache_mib = mib; ++ } + else if (a == "--no-ple") o.no_ple = true; + else if (a == "--ple-io") { o.ple_io = next("--ple-io"); o.ple_io_explicit = true; } + else if (a == "--ple-row-cache") o.ple_row_cache = std::atoll(next("--ple-row-cache")); +@@ -2895,6 +2928,10 @@ int main(int argc, char** argv) { + } + #endif + strata::core::set_coupled_draft(o.coupled_draft); ++ if ((std::getenv("STRATA_KEYLESS_TRACE") || std::getenv("STRATA_KEYLESS_PREFILL_TRACE")) && (o.serve || o.max_new > 512)) { ++ std::fprintf(stderr, "strata generate: STRATA_KEYLESS_TRACE is offline only and needs --max-new <= 512\n"); ++ return 2; ++ } + { // --host-core / STRATA_HOST_CORE, before the pool and the session pin any thread + std::string hc = o.host_core; + if (hc.empty()) +@@ -3193,6 +3230,11 @@ int main(int argc, char** argv) { + std::fprintf(stderr, "strata generate: --kv must be fp16, int8, q4_0 or k8v4\n"); + return 2; + } ++ const char* keyless_path = std::getenv("STRATA_KEYLESS_ROUTING"); ++ if (keyless_path && (!*keyless_path || o.kv != "int8" || o.gpu_stages || !o.dump_halves.empty() || std::getenv("STRATA_KEYLESS_TRACE") || std::getenv("STRATA_KEYLESS_PREFILL_TRACE") || (std::getenv("STRATA_KV_ROT") && std::getenv("STRATA_KV_ROT")[0] == '1'))) { ++ std::fprintf(stderr, "strata: keyless requires INT8, no Hadamard rotation, one GPU stage and no diagnostic dumps\n"); return 2; ++ } ++ strata::core::qsa_set_without_key(keyless_path != nullptr); + strata::core::qsa_set_kv_int8(o.kv == "int8"); + strata::core::qsa_set_kv_q4(o.kv == "q4_0"); // PR #21: 4-bit codes after a Hadamard rotation (kv_q4.hpp) + // STRATA_KV_ROT=1: INT8 K/V through the Hadamard rotation --kv q4_0 already uses. Opt-in: first-token KL to +@@ -3296,6 +3338,15 @@ int main(int argc, char** argv) { + std::fprintf(stderr, "strata generate: --no-ple and --ple-gguf are mutually exclusive\n"); + return 2; + } ++ if ((o.no_ple && !o.ple_kar.empty()) || (o.ple_kar.empty() && o.ple_kar_level != 2) || ++ (!o.ple_kar.empty() && (o.ple_kar_level < 1 || o.ple_kar_level > 8 || o.ple_io != "direct"))) { ++ std::fprintf(stderr, "strata generate: --ple-kar requires PLE, level 1..8, and default --ple-io\n"); ++ return 2; ++ } ++ if (o.ple_kar_gpu_cache_mib && (o.ple_kar.empty() || o.ple_kar_level != 2)) { ++ std::fprintf(stderr, "strata generate: --ple-kar-gpu-cache-mib requires --ple-kar at level 2\n"); ++ return 2; ++ } + if (o.native_ple_postops && o.no_ple) { + std::fprintf(stderr, "strata generate: --native-ple-postops requires PLE enabled\n"); + return 2; +@@ -3755,6 +3806,37 @@ int main(int argc, char** argv) { + rope_cfg.type == RST::YaRN ? "YaRN" : "--yarn-attn-factor", rope_cfg.mscale()); + } + } ++ const char* kar_expert_archive = std::getenv("STRATA_NEXT_KAR_EXPERTS_ARCHIVE"); ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) ++ strata::kar::ExpertMiss kar_expert_miss; ++ if (kar_expert_archive != nullptr) { ++ const char* level_text = std::getenv("STRATA_NEXT_KAR_EXPERTS_LEVEL"); ++ if (!native_pack || o.no_pool || !split_devs.empty() || remote_caches || ++ !level_text || std::strlen(level_text) != 1 || level_text[0] < '1' || level_text[0] > '8' || ++ g.n_embd != strata::kernels::cpu::H) { ++ std::fprintf(stderr, "strata generate: experimental KAR misses require a native pack, one GPU, " ++ "the expert pool and explicit STRATA_NEXT_KAR_EXPERTS_LEVEL=1..8\n"); ++ return 2; ++ } ++ for (const auto& f : strata::kernels::cpu::expert_layout().fmt) ++ if (f.n_embd != strata::kernels::cpu::H || f.n_ff != strata::kernels::cpu::FF) { ++ std::fprintf(stderr, "strata generate: unsupported KAR expert geometry\n"); return 2; ++ } ++ if (!kar_expert_miss.open(kar_expert_archive, (uint32_t) g.n_layers, (uint32_t) g.n_expert, ++ (uint32_t) g.n_embd, strata::kernels::cpu::FF, ++ (uint32_t) (level_text[0] - '0'), err)) { ++ std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; ++ } ++ // Native resident hits are the baseline. Route all otherwise CPU/PCIe ++ // misses to the explicit experimental arm; use pcie-frac=0 in its baseline. ++ o.pcie_frac = 0; ++ } ++#else ++ if (kar_expert_archive != nullptr) { ++ std::fprintf(stderr, "strata generate: this build has no experimental KAR expert support\n"); ++ return 2; ++ } ++#endif + strata::core::NativeEmbed native_embed; + if (native_pack) { + if (o.native_preset.empty() || o.spec < 2 || o.keep_canonical || +@@ -3978,6 +4060,10 @@ int main(int argc, char** argv) { + return 2; + } + ++ if (keyless_path && !strata::core::keyless_load(keyless_path, wt, g, err)) { ++ std::fprintf(stderr, "strata: keyless routing: %s\n", err.c_str()); return 1; ++ } ++ if (keyless_path) std::fprintf(stderr, "strata: experimental V-only QSA query routing; indexer and MTP keys retained; quality gate pending\n"); + strata::core::SessionState ss; + void* sbuf = nullptr; // allocated after the layer-split search, sized to CUDA0's own layer range (the carve) + // **THE ENGINE RAN ON THE LEGACY DEFAULT STREAM, WHICH ON WDDM IS THE SLOW PATH.** All four session +@@ -4054,13 +4140,19 @@ int main(int argc, char** argv) { + pio.keepalive_window_s = kw != nullptr && *kw ? std::clamp(std::atof(kw), 1.0, 86400.0) : 60.0; + if (pio.mode != strata::kernels::PleIo::Direct || !pio.io_thread) pio.keepalive_ms = 0; + } +- if (!ple_table.open(o.ple_gguf, err, pio)) { ++ const bool ple_open = o.ple_kar.empty() ? ple_table.open(o.ple_gguf, err, pio) ++ : ple_table.open_kar(o.ple_kar, o.ple_kar_level, err); ++ if (!ple_open) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } ++ if (o.ple_kar_gpu_cache_mib && !ple_table.enable_kar_gpu_cache(o.ple_kar_gpu_cache_mib, err)) { ++ std::fprintf(stderr, "strata generate: PLE GPU cache: %s\n", err.c_str()); ++ return 1; ++ } + // Recommend, never force: when the default direct reads measure slow, switch to the mapped reads (40-100x + // faster on the reporters' drives); an explicit --ple-io direct is kept and only warned about. +- if (pio.mode == strata::kernels::PleIo::Direct && std::getenv("STRATA_PLE_PROBE") == nullptr) { ++ if (o.ple_kar.empty() && pio.mode == strata::kernels::PleIo::Direct && std::getenv("STRATA_PLE_PROBE") == nullptr) { // (not for the local KAR PLE arm) + constexpr double kSlowRowsPerS = 15000.0; // ~60 MB/s of 4 KiB pages; a healthy NVMe is >100k + const double rps = ple_direct_rows_per_s(ple_table); + if (rps >= kSlowRowsPerS) +@@ -4109,7 +4201,12 @@ int main(int argc, char** argv) { + std::fprintf(stderr, "strata generate: PLE table %s (--ple-io ram) in %.1f s\n", + ple_table.locked() ? "locked in RAM" : "loaded (not locked)", + std::chrono::duration(Clock::now() - tpl).count()); +- if (pio.keepalive_ms > 0) ++ if (!o.ple_kar.empty()) ++ std::fprintf(stderr, "strata generate: experimental PLE KAR %s arm at level %u%s\n", ++ o.ple_kar_gpu_cache_mib ? "bounded GPU-cache" : "CPU quality", ++ o.ple_kar_level, ++ o.ple_kar_gpu_cache_mib ? " (prefill/decode CUDA, speculative verification CPU)" : ""); ++ else if (pio.keepalive_ms > 0) + std::fprintf(stderr, "strata generate: the SSD is kept awake while rows are read: one page of the table after " + "%.0f ms without a read, until %.0f s after the last request " + "(STRATA_SSD_KEEPALIVE=0 turns it off)\n", pio.keepalive_ms, pio.keepalive_window_s); +@@ -5245,7 +5342,8 @@ int main(int argc, char** argv) { + return 1; + } + std::fprintf(stderr, "strata generate: PLE on, table %llu rows of %s\n", +- (unsigned long long) ple_table.rows(), o.ple_gguf.c_str()); ++ (unsigned long long) ple_table.rows(), ++ o.ple_kar.empty() ? o.ple_gguf.c_str() : o.ple_kar.c_str()); + } + } + mem_mark("the session (KV, GDN state, PLE history)"); +@@ -6773,6 +6871,12 @@ int main(int argc, char** argv) { + + if (remote_opt && !remote_opt->init(err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } + Drive drive; ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) ++ if (kar_expert_archive != nullptr) { ++ drive.d.experimental_miss = &strata::kar::ExpertMiss::dispatch; ++ drive.d.experimental_miss_user = &kar_expert_miss; ++ } ++#endif + // #731 (opt-in, STRATA_DISJOINT_ADAPT=1): the adaptive tiers leave an expert a helper GPU holds out of the primary's + // promotion candidates (it would sit in both caches). Asked live, from the helper's own cache (RemoteExperts::holds, + // #854), so an expert the helper's tier swaps in or out later is followed - never a copy taken at load. +@@ -12402,6 +12506,10 @@ int main(int argc, char** argv) { + // unknown keys are skipped: the ids start at the first token without '=' + } + } ++ if (kar_expert_archive != nullptr && req_pcie_frac != 0.0) { ++ std::printf("ERR experimental KAR misses require pcie_frac=0\n"); ++ continue; ++ } + strata::prefill::Prefill::set_pipe_request(req_pipe); // every request sets it: none carries over + std::vector req_bias; + std::string bias_error; +@@ -15376,6 +15484,8 @@ 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 if (st.without_key) { ++ a = {{h ? st.host.v_q : st.v_q, kvb}, {h ? st.host.v_scale : st.v_scale, scb}}; + } 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}}; +@@ -15579,6 +15689,11 @@ int main(int argc, char** argv) { + 100.0 * (double) req_hits / (double) req_look, + (long long) req_hits, (long long) req_look, off); + } ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) ++ if (kar_expert_archive != nullptr) ++ std::fprintf(stderr, "strata serve: KAR verifier entries computed since startup: %llu\n", ++ (unsigned long long) kar_expert_miss.computed()); ++#endif + if (drive.d.tail_experts > 0) // STRATA_ROUTE_TAIL_SKIP, cumulative + std::fprintf(stderr, "strata serve: route tail skip: %lld missed experts skipped (%lld entries) since the " + "start\n", (long long) drive.d.tail_experts, (long long) drive.d.tail_skipped); +@@ -15745,6 +15860,8 @@ int main(int argc, char** argv) { + helper_bytes_before = bytes; + } + } ++ if (o.stats && ple_table.kar_gpu_cache_enabled()) ++ std::fprintf(stderr, "strata serve: %s\n", ple_table.io_report().c_str()); + save_profile("exit"); // #477: QUIT, or the server closed stdin + #if defined(STRATA_GPU_METAL) + // the stdin reader (detached above) may still take in_mu when the server closes the pipe after QUIT; on macOS diff --git a/engine/strata/.gitattributes b/engine/strata/.gitattributes index 466d97e8..e9e15ba7 100644 --- a/engine/strata/.gitattributes +++ b/engine/strata/.gitattributes @@ -4,6 +4,24 @@ bench/prompts/** -text # launchers keep their platform line endings wherever the repository is cloned *.sh text eol=lf *.bat text eol=crlf +*.cmd text eol=crlf +*.ps1 text eol=crlf +bin/strata text eol=lf # copies of real packs' native_experts.txt, parsed byte for byte by tests/core/expert_layout_test.cpp tests/data/native_experts/** -text + +# the quant yardstick's text set: tokenized byte for byte (set.ids.json), never convert its line endings +data/quant_quality/** -text + +# the license text is shipped and checked as LF text on every checkout +LICENSE text eol=lf + +# container scripts run in Linux: always LF +docker/*.sh text eol=lf +Dockerfile text eol=lf +docker/Dockerfile text eol=lf +docker/compose/* text eol=lf + +# Apple tools (codesign, plutil) read these: LF only, wherever the repository is cloned +*.plist text eol=lf diff --git a/engine/strata/.github/ISSUE_TEMPLATE/benchmark.yml b/engine/strata/.github/ISSUE_TEMPLATE/benchmark.yml new file mode 100644 index 00000000..2d2514b7 --- /dev/null +++ b/engine/strata/.github/ISSUE_TEMPLATE/benchmark.yml @@ -0,0 +1,26 @@ +name: Benchmark +description: Share measurements from your machine, or report a problem with the benchmark tools +title: "[Benchmark] " +labels: ["benchmark"] +body: + - type: markdown + value: | + The title must start with **[Benchmark]**. Keep it, and add the GPU and model after it. + + To share a full report, follow the [community benchmark guide](https://github.com/Niko1221/Strata/blob/main/docs/COMMUNITY_BENCHMARKS.md) and open a results-only pull request. The standard protocol is a [draft](https://github.com/Niko1221/Strata/blob/main/docs/BENCHMARK_PROTOCOL.md); existing tools do not implement it yet. Include poor results and failed requests. + - type: textarea + id: what + attributes: + label: What did you measure, or what went wrong + description: Hardware (GPU and VRAM, CPU, RAM, OS), Strata version, model and quantization, the exact command, and the numbers. Paste the report or link the pull request. + validations: + required: true + - type: dropdown + id: reproduction-status + attributes: + label: Reproduction status + options: + - Measured locally + - Unconfirmed (I did not run it) + validations: + required: true diff --git a/engine/strata/.github/ISSUE_TEMPLATE/bug_report.yml b/engine/strata/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 00000000..77692fbe --- /dev/null +++ b/engine/strata/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,101 @@ +name: Bug report +description: Something in Strata doesn't work as documented +title: "[Area] " +labels: ["bug"] +body: + - type: markdown + value: | + Thanks for the report. Please read [CONTRIBUTING.md](https://github.com/Niko1221/Strata/blob/main/CONTRIBUTING.md) first. + + Search the [open and closed issues](https://github.com/Niko1221/Strata/issues?q=is%3Aissue) first: this may already be tracked, and new evidence belongs in that thread. + + Write only what you saw. Do not guess at steps, errors, hardware or severity. + + **The title must start with its area:** [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other]. Choose the same one below. + - type: dropdown + id: area + attributes: + label: Area + description: Start the issue title with the same area in square brackets, for example "[Engine] decode stops after 2 minutes". Pick Other if none fits. + options: + - "[Engine] (speed, kernels, models, the server and API)" + - "[GUI] (the desktop app)" + - "[TUI] (the Terminal: strata launch, connect, monitor)" + - "[Benchmark] (measurements and reports)" + - "[Docs] (documentation)" + - "[Other] (anything else, including setup and installation)" + validations: + required: true + - type: dropdown + id: how + attributes: + label: Desktop app, Terminal or source? + options: + - Desktop app (Windows, Linux or Mac) + - Terminal (the `strata` command) + - Source (START-HERE.bat, setup.sh or a build) + - Docker + - Other + validations: + required: true + - type: textarea + id: what + attributes: + label: What happened + description: What you did, what you got, and what you expected instead. Paste the exact error text if there is one. + validations: + required: true + - type: textarea + id: reproduce + attributes: + label: Smallest steps or command that reproduce it + description: The shortest list of steps that shows the problem. If you cannot make it happen again, say so here. + validations: + required: false + - type: dropdown + id: reproduction-status + attributes: + label: Reproduction status + options: + - Reproduced locally + - Unconfirmed static analysis (I read code or ran a scanner; I did not see it fail) + validations: + required: true + - type: input + id: version + attributes: + label: Strata version + description: "In the app: Settings > About. In the Terminal: `strata --version`. From source: the About tab of the web page, or `engine` in `GET /v1/status`, or the git commit." + placeholder: "Strata 0.2.5 · engine 0.1.50" + validations: + required: true + - type: input + id: hardware + attributes: + label: Graphics card, memory and system + description: The card and its VRAM, the RAM of the PC, and the operating system. + placeholder: "RTX 5070 12 GB · 64 GB RAM · Windows 11" + validations: + required: true + - type: input + id: model + attributes: + label: Model, size and settings + description: The model and size you started, the context, and whether pictures were on. Write what is relevant. + placeholder: "Qwen3.8-Flash-Next IQ2_XS · 128K context · pictures on" + validations: + required: false + - type: textarea + id: log + attributes: + label: Logs + description: | + The app: Settings > Engine > Diagnostics > View logs > Save logs, then drag the file in. The Terminal: paste the output of `strata doctor`. From source: drag in `strata-.log` from your Strata folder. + Remove API keys, passwords and private text first. + validations: + required: false + - type: markdown + value: | + A couple of extras that help a lot: + + - Check the [troubleshooting page](https://github.com/Niko1221/Strata/blob/main/docs/TROUBLESHOOTING.md) first, many reports are already solved there. diff --git a/engine/strata/.github/ISSUE_TEMPLATE/config.yml b/engine/strata/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 00000000..be9cdf2e --- /dev/null +++ b/engine/strata/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: true +contact_links: + - name: Troubleshooting and known issues + url: https://github.com/Niko1221/Strata/blob/main/docs/TROUBLESHOOTING.md + about: Symptom-to-fix table for crashes, out of memory, hangs, and port problems. \ No newline at end of file diff --git a/engine/strata/.github/ISSUE_TEMPLATE/feature_request.yml b/engine/strata/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 00000000..8a2b375e --- /dev/null +++ b/engine/strata/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,41 @@ +name: Feature request +description: Suggest something new or an improvement +title: "[Area] " +labels: ["enhancement"] +body: + - type: markdown + value: | + Explain what you want in plain language. For a large feature, a change to a default or a refactor, please agree the scope here first. Read [CONTRIBUTING.md](https://github.com/Niko1221/Strata/blob/main/CONTRIBUTING.md). + + **The title must start with its area:** [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other]. Choose the same one below. + - type: dropdown + id: area + attributes: + label: Area + description: Start the issue title with the same area in square brackets, for example "[Engine] decode stops after 2 minutes". Pick Other if none fits. + options: + - "[Engine] (speed, kernels, models, the server and API)" + - "[GUI] (the desktop app)" + - "[TUI] (the Terminal: strata launch, connect, monitor)" + - "[Benchmark] (measurements and reports)" + - "[Docs] (documentation)" + - "[Other] (anything else, including setup and installation)" + validations: + required: true + - type: textarea + id: idea + attributes: + label: What do you want to do? + description: Describe the goal rather than the implementation. Say who needs it and why. + validations: + required: true + - type: textarea + id: workaround + attributes: + label: What do you do today instead? + description: The workaround you use now, if there is one. + validations: + required: false + - type: markdown + value: | + All of this counts: model and architecture support, the server and API, the app and the Terminal, multi-GPU and layer split, images and vision, MCP servers, setup and installation, and performance. diff --git a/engine/strata/.github/ISSUE_TEMPLATE/question.yml b/engine/strata/.github/ISSUE_TEMPLATE/question.yml new file mode 100644 index 00000000..345bf512 --- /dev/null +++ b/engine/strata/.github/ISSUE_TEMPLATE/question.yml @@ -0,0 +1,45 @@ +name: Question +description: Ask how to use Strata, or share a result +title: "[Area] " +labels: ["question"] +body: + - type: markdown + value: | + Not sure how to do something, or want to share numbers from your machine? Ask here. To share a full benchmark, see [CONTRIBUTING.md](https://github.com/Niko1221/Strata/blob/main/CONTRIBUTING.md#share-a-benchmark). + + **The title must start with its area:** [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other]. Choose the same one below. + - type: dropdown + id: area + attributes: + label: Area + description: Start the issue title with the same area in square brackets, for example "[Engine] decode stops after 2 minutes". Pick Other if none fits. + options: + - "[Engine] (speed, kernels, models, the server and API)" + - "[GUI] (the desktop app)" + - "[TUI] (the Terminal: strata launch, connect, monitor)" + - "[Benchmark] (measurements and reports)" + - "[Docs] (documentation)" + - "[Other] (anything else, including setup and installation)" + validations: + required: true + - type: textarea + id: question + attributes: + label: Your question + description: What you're trying to do. Include your version, GPU, and OS if it affects the answer. + validations: + required: true + - type: textarea + id: tried + attributes: + label: What you tried + description: What you already did and where you got stuck. + validations: + required: false + - type: textarea + id: numbers + attributes: + label: Results (optional) + description: Only if you ran a benchmark or measured speed. Model, quant, context, and the tok/s you get. + validations: + required: false diff --git a/engine/strata/.github/pull_request_template.md b/engine/strata/.github/pull_request_template.md new file mode 100644 index 00000000..688f7aba --- /dev/null +++ b/engine/strata/.github/pull_request_template.md @@ -0,0 +1,30 @@ +**The title must start with its area: [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other], for example "[Engine] fix decode stop on long prompts" or "[GUI] keep the model list after a tab switch".** + + + +## Problem and result + + +## Related discussion + + +## Approach + + +## Validation + + +**Passed:** + + +**Failed:** + + +**Not run:** + + +## Limits + diff --git a/engine/strata/.github/scripts/item-check.js b/engine/strata/.github/scripts/item-check.js new file mode 100644 index 00000000..b07b6350 --- /dev/null +++ b/engine/strata/.github/scripts/item-check.js @@ -0,0 +1,218 @@ +'use strict'; +// Format check for issues and pull requests (see CONTRIBUTING.md and .github/ISSUE_TEMPLATE/*.yml). +// Pure functions only: no network, no filesystem. Used by intake.yml and reopen.yml through reset-bot.js. + +const AREAS = ['Engine', 'GUI', 'TUI', 'Benchmark', 'Docs', 'Other']; +const TITLE_RE = new RegExp('^\\[(' + AREAS.join('|') + ')\\] \\S'); +const NO_ANSWER = /^(_no response_|none|n\/a|na|-|todo|tbd|\.|\?)$/i; +const NOT_RUN_LABELS = /^\*\*(passed|failed|not run)\s*:?\*\*\s*:?/gim; + +// Version the reopened work must be tested on. +const CURRENT_VERSION_RE = /\b0\.2\.\d+|0\.2\.0-beta/i; +// Any version or commit. +const ANY_VERSION_RE = /\bv?\d+\.\d+(\.\d+)*(-[a-z0-9.]+)?\b|\b[0-9a-f]{7,40}\b|\bcommit\b/i; +const HARDWARE_RE = /\b(rtx|gtx|geforce|quadro|tesla|radeon|rx ?\d|instinct|arc|a\d{3,4}|b\d{2,3}|apple|m[1-5]( pro| max| ultra)?|nvidia|amd|intel|gpu|cpu|vram|\d+ ?gb|ram|windows|linux|ubuntu|debian|fedora|arch|macos|mac os|wsl)\b/i; +const REVISION_RE = /0\.2\.\d|beta|\bmain\b|\b[0-9a-f]{7,40}\b/i; + +function stripComments(text) { + return String(text || '').replace(//g, ''); +} + +function hasAreaPrefix(title) { + return TITLE_RE.test(String(title || '')); +} + +// Issue forms render as "### Label\n\nvalue". Returns { label: value } for those headings. +function parseSections(body) { + const out = {}; + let cur = null; + for (const line of stripComments(body).split(/\r?\n/)) { + const m = /^#{1,6}\s+(.+?)\s*#*\s*$/.exec(line); + if (m) { + cur = m[1].trim(); + out[cur] = ''; + } else if (cur !== null) { + out[cur] += line + '\n'; + } + } + for (const k of Object.keys(out)) out[k] = out[k].trim(); + return out; +} + +function realText(value) { + const t = String(value || '').replace(NOT_RUN_LABELS, '').replace(/\s+/g, ' ').trim(); + return NO_ANSWER.test(t) ? '' : t; +} + +function findSection(sections, re) { + for (const k of Object.keys(sections)) if (re.test(k)) return { key: k, value: sections[k] }; + return null; +} + +// Required parts of each issue form: [display name, heading regex, minimum characters of real text]. +const FORMS = { + bug: { + detect: /what happened/i, + parts: [ + ['Area', /^area$/i, 2], + ['Desktop app, Terminal or source?', /desktop app, terminal or source/i, 2], + ['What happened', /what happened/i, 20], + ['Reproduction status', /reproduction status/i, 2], + ['Strata version', /strata version/i, 3], + ['Graphics card, memory and system', /graphics card|memory and system/i, 3], + ], + needsCurrentVersion: 'Strata version', + }, + feature: { + detect: /what do you want to do/i, + parts: [ + ['Area', /^area$/i, 2], + ['What do you want to do?', /what do you want to do/i, 20], + ], + }, + question: { + detect: /your question/i, + parts: [ + ['Area', /^area$/i, 2], + ['Your question', /your question/i, 15], + ], + }, + benchmark: { + detect: /what did you measure/i, + parts: [ + ['What did you measure, or what went wrong', /what did you measure/i, 30], + ['Reproduction status', /reproduction status/i, 2], + ], + needsCurrentVersionInBody: true, + }, +}; + +function checkIssue({ title, body, labels = [], mode = 'intake' }) { + const missing = []; + if (!hasAreaPrefix(title)) { + missing.push('Start the title with its area: [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other], then a short description. Example: "[Engine] decode stops after 2 minutes".'); + } + const text = stripComments(body); + const sections = parseSections(text); + const labelSet = new Set(labels.map((l) => String(l).toLowerCase())); + const needCurrent = mode === 'reopen'; + + let formKey = null; + for (const [key, f] of Object.entries(FORMS)) { + if (findSection(sections, f.detect)) { formKey = key; break; } + } + + if (formKey) { + const form = FORMS[formKey]; + for (const [name, re, min] of form.parts) { + const s = findSection(sections, re); + if (!s || realText(s.value).length < min) missing.push('Fill in "' + name + '".'); + } + if (needCurrent && form.needsCurrentVersion) { + const s = findSection(sections, /strata version/i); + if (s && realText(s.value) && !CURRENT_VERSION_RE.test(s.value)) { + missing.push('Re-test on Strata 0.2.0-beta and put that version in "' + form.needsCurrentVersion + '". If it no longer happens, say so in a comment instead.'); + } + } + if (needCurrent && form.needsCurrentVersionInBody && !CURRENT_VERSION_RE.test(text)) { + missing.push('Say which Strata version you measured on. Re-measure on 0.2.0-beta if you can.'); + } + return { ok: missing.length === 0, missing, kind: formKey }; + } + + // Free-form text (older issues, blank issues). + const plain = realText(text); + const lenient = labelSet.has('enhancement') || labelSet.has('question'); + if (plain.length < (lenient ? 40 : 80)) { + missing.push('Describe it in the issue body: what happened, what you expected, and the exact error if there is one. The issue forms (New issue > Bug report) list what to include.'); + } + if (!lenient) { + if (!ANY_VERSION_RE.test(text)) missing.push('Add the Strata version (Settings > About, or `strata --version`).'); + else if (needCurrent && !CURRENT_VERSION_RE.test(text)) missing.push('Re-test on Strata 0.2.0-beta and name that version in the issue. If it no longer happens, say so in a comment instead.'); + if (!HARDWARE_RE.test(text)) missing.push('Add your graphics card with its VRAM, your RAM and your operating system.'); + } + return { ok: missing.length === 0, missing, kind: 'free-form' }; +} + +function checkPull({ title, body, mode = 'intake' }) { + const missing = []; + if (!hasAreaPrefix(title)) { + missing.push('Start the title with its area: [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other], then a short description. Example: "[Engine] fix decode stop on long prompts".'); + } + const text = stripComments(body); + const sections = parseSections(text); + const problem = findSection(sections, /problem|result|summary|what.*change/i); + const validation = findSection(sections, /validation|testing|tests?\b|how.*tested/i); + + let valText = ''; + if (problem || validation) { + if (!problem || realText(problem.value).length < 20) missing.push('Fill in "Problem and result": what triggered the change, and how it behaves before and after.'); + if (!validation || realText(validation.value).length < 20) { + missing.push('Fill in "Validation": the exact commands, the revision and environment tested, what you saw. Keep Passed, Failed and Not run apart.'); + } else { + valText = validation.value; + } + } else { + const plain = realText(text); + if (plain.length < 150) { + missing.push('Describe the pull request: the problem and the result. The pull request template shows the parts (Problem and result, Related discussion, Approach, Validation, Limits).'); + } + if (!/(problem|result|before|after|fix|because|bug)/i.test(plain)) missing.push('Add "Problem and result": what triggered the change, and how it behaves before and after.'); + if (!/(validat|tested|passed|ran |built|build|not run)/i.test(plain)) missing.push('Add "Validation": the exact commands, the revision and environment tested, and what you saw.'); + valText = plain; + } + if (mode === 'reopen' && valText && !REVISION_RE.test(valText)) { + missing.push('Say in Validation which revision you tested: rebase on main (or 0.2.0-beta) and re-run your checks.'); + } + return { ok: missing.length === 0, missing, kind: 'pull' }; +} + +function checkItem({ isPull, ...rest }) { + return isPull ? checkPull(rest) : checkIssue(rest); +} + +function checklist(missing) { + return missing.map((m) => '- [ ] ' + m).join('\n'); +} + +const CONTRIB = 'https://github.com/Niko1221/Strata/blob/main/CONTRIBUTING.md'; + +function intakeComment(isPull, missing) { + return [ + 'Thanks for the ' + (isPull ? 'pull request' : 'issue') + '. To keep the tracker readable, every item needs an area prefix in the title and the parts of the ' + (isPull ? 'pull request template' : 'issue form') + ' filled in. This one is missing:', + '', + checklist(missing), + '', + 'Edit the ' + (isPull ? 'pull request' : 'issue') + ' (title and description) and this note goes away on its own. If it is still missing parts in 5 days it will be closed, which is not a rejection: fix it and comment `/reopen`.', + '', + 'Details: [CONTRIBUTING.md](' + CONTRIB + ')', + ].join('\n'); +} + +function reopenMissingComment(isPull, missing) { + return [ + 'Not reopened yet. Still missing:', + '', + checklist(missing), + '', + 'Edit the ' + (isPull ? 'pull request' : 'issue') + ' and comment `/reopen` again. Details: [CONTRIBUTING.md](' + CONTRIB + ')', + ].join('\n'); +} + +function reopenOkComment(isPull) { + return 'Reopened, thank you. A maintainer will pick it up from here.' + (isPull ? ' If it conflicts with main, rebase it first; that speeds up review.' : ''); +} + +function staleComment(isPull) { + return [ + 'Closing this ' + (isPull ? 'pull request' : 'issue') + ' because it still did not follow the format after 5 days. That is housekeeping, not a rejection.', + '', + 'To bring it back: fix the title (area prefix) and the missing parts, then comment `/reopen`. A check runs and reopens it, or tells you what is still missing. See [CONTRIBUTING.md](' + CONTRIB + ').', + ].join('\n'); +} + +module.exports = { + AREAS, TITLE_RE, hasAreaPrefix, parseSections, stripComments, realText, + checkIssue, checkPull, checkItem, checklist, + intakeComment, reopenMissingComment, reopenOkComment, staleComment, +}; diff --git a/engine/strata/.github/scripts/item-check.test.js b/engine/strata/.github/scripts/item-check.test.js new file mode 100644 index 00000000..c870f144 --- /dev/null +++ b/engine/strata/.github/scripts/item-check.test.js @@ -0,0 +1,192 @@ +'use strict'; +const test = require('node:test'); +const assert = require('node:assert'); +const c = require('./item-check'); +const bot = require('./reset-bot'); + +const bugForm = (over = {}) => { + const f = { + 'Area': '[Engine] (speed, kernels, models, the server and API)', + 'Desktop app, Terminal or source?': 'Terminal (the `strata` command)', + 'What happened': 'Decode stops after two minutes with "CUDA error 700". I expected it to continue.', + 'Smallest steps or command that reproduce it': '_No response_', + 'Reproduction status': 'Reproduced locally', + 'Strata version': 'Strata 0.2.0-beta · engine 0.1.45.3', + 'Graphics card, memory and system': 'RTX 5070 12 GB · 64 GB RAM · Windows 11', + ...over, + }; + return Object.entries(f).map(([k, v]) => `### ${k}\n\n${v}`).join('\n\n'); +}; + +test('title prefix', () => { + assert.ok(c.hasAreaPrefix('[Engine] fix decode')); + assert.ok(c.hasAreaPrefix('[Docs] x')); + assert.ok(!c.hasAreaPrefix('Engine fix')); + assert.ok(!c.hasAreaPrefix('[engine] fix')); + assert.ok(!c.hasAreaPrefix('[Engine]')); + assert.ok(!c.hasAreaPrefix('[Engine] ')); + assert.ok(!c.hasAreaPrefix('[Area] foo')); + assert.ok(!c.hasAreaPrefix('')); + assert.ok(!c.hasAreaPrefix(undefined)); +}); + +test('filled bug form passes in both modes', () => { + for (const mode of ['intake', 'reopen']) { + const r = c.checkIssue({ title: '[Engine] decode stops', body: bugForm(), labels: ['bug'], mode }); + assert.deepStrictEqual(r.missing, []); + assert.strictEqual(r.kind, 'bug'); + } +}); + +test('bug form: missing parts are named', () => { + const r = c.checkIssue({ title: 'decode stops', body: bugForm({ 'Strata version': '_No response_', 'What happened': 'bad' }) }); + assert.ok(!r.ok); + assert.ok(r.missing.some((m) => /title/i.test(m))); + assert.ok(r.missing.some((m) => m.includes('What happened'))); + assert.ok(r.missing.some((m) => m.includes('Strata version'))); +}); + +test('reopen needs a 0.2 version, intake does not', () => { + const body = bugForm({ 'Strata version': 'Strata 0.1.44' }); + assert.ok(c.checkIssue({ title: '[Engine] x y', body, mode: 'intake' }).ok); + const r = c.checkIssue({ title: '[Engine] x y', body, mode: 'reopen' }); + assert.ok(!r.ok); + assert.ok(r.missing.some((m) => m.includes('0.2.0-beta'))); +}); + +test('html comments and placeholders do not count', () => { + const r = c.checkIssue({ title: '[Engine] x y', body: bugForm({ 'What happened': '' }) }); + assert.ok(r.missing.some((m) => m.includes('What happened'))); +}); + +test('feature and question forms', () => { + const f = '### Area\n\n[GUI] (the desktop app)\n\n### What do you want to do?\n\nLet me pin a model to the top of the list in the app.'; + assert.ok(c.checkIssue({ title: '[GUI] pin models', body: f, mode: 'reopen' }).ok); + assert.ok(!c.checkIssue({ title: '[GUI] pin models', body: '### Area\n\n[GUI]\n\n### What do you want to do?\n\n_No response_' }).ok); + const q = '### Area\n\n[Other]\n\n### Your question\n\nHow do I move the model folder to another drive?'; + assert.ok(c.checkIssue({ title: '[Other] model folder', body: q }).ok); +}); + +test('free-form issue', () => { + const good = 'Strata 0.2.0-beta on an RTX 3060 12 GB with 32 GB RAM on Linux: the server hangs when I send two requests at once. Expected both to finish.'; + assert.ok(c.checkIssue({ title: '[Engine] hang on two requests', body: good, mode: 'reopen' }).ok); + assert.ok(!c.checkIssue({ title: '[Engine] hang', body: 'it crashes', mode: 'intake' }).ok); + const old = good.replace('0.2.0-beta', '0.1.40'); + assert.ok(c.checkIssue({ title: '[Engine] hang', body: old, mode: 'intake' }).ok); + assert.ok(!c.checkIssue({ title: '[Engine] hang', body: old, mode: 'reopen' }).ok); + assert.ok(c.checkIssue({ title: '[Other] idea', body: 'It would help if the app remembered my last model between runs, today I pick it again.', labels: ['enhancement'], mode: 'reopen' }).ok); +}); + +const prBody = (over = {}) => { + const p = { + problem: 'Decode stopped on prompts above 8k because the stop check read the wrong length. Now it continues.', + validation: '**Passed:** `ctest -R decode`, commit abcdef1, RTX 3060, 12 of 12.\n\n**Failed:** none observed\n\n**Not run:** HIP build', + ...over, + }; + return `## Problem and result\n\n${p.problem}\n\n## Related discussion\nnone\n\n## Approach\nFix the length.\n\n## Validation\n${p.validation}\n\n## Limits\nnone`; +}; + +test('filled PR passes', () => { + assert.deepStrictEqual(c.checkPull({ title: '[Engine] fix stop', body: prBody(), mode: 'reopen' }).missing, []); +}); + +test('untouched PR template fails', () => { + const tpl = '## Problem and result\n\n\n## Validation\n\n\n**Passed:**\n\n\n**Failed:**\n\n**Not run:**\n'; + const r = c.checkPull({ title: '[Engine] fix stop', body: tpl }); + assert.ok(!r.ok); + assert.ok(r.missing.some((m) => m.includes('Problem and result'))); + assert.ok(r.missing.some((m) => m.includes('Validation'))); +}); + +test('PR: empty body and bad title', () => { + const r = c.checkPull({ title: 'fix', body: null }); + assert.ok(!r.ok); + assert.ok(r.missing.length >= 2); +}); + +test('PR reopen needs a revision', () => { + const body = prBody({ validation: '**Passed:** I tried it and it worked for me on my machine, looked fine.' }); + assert.ok(c.checkPull({ title: '[Engine] x y', body, mode: 'intake' }).ok); + assert.ok(!c.checkPull({ title: '[Engine] x y', body, mode: 'reopen' }).ok); +}); + +test('free-form PR', () => { + const body = 'This fixes a crash when the context is above 8k, because the length was read from the wrong field. Before it aborted, after it continues. I built it on CUDA and ran the decode test, passed.'; + assert.ok(c.checkPull({ title: '[Engine] fix crash', body }).ok); + assert.ok(!c.checkPull({ title: '[Engine] fix crash', body: 'fixes stuff' }).ok); +}); + +test('messages', () => { + const m = c.intakeComment(false, ['a', 'b']); + assert.ok(m.includes('- [ ] a') && m.includes('/reopen') && m.includes('CONTRIBUTING.md')); + assert.ok(c.staleComment(true).includes('/reopen')); +}); + +// handlers with a fake GitHub client +function fake(calls, extra = {}) { + const rest = { + issues: { + getLabel: async () => ({}), + createLabel: async (a) => calls.push(['createLabel', a.name]), + addLabels: async (a) => calls.push(['addLabels', a.labels]), + removeLabel: async (a) => calls.push(['removeLabel', a.name]), + createComment: async (a) => calls.push(['comment', a.body]), + update: async (a) => calls.push(['update', a.state]), + get: async () => ({ data: extra.live }), + listEvents: async () => {}, + listForRepo: async () => {}, + }, + pulls: { get: async () => ({ data: { mergeable_state: 'clean' } }) }, + }; + return { rest, paginate: async (fn) => (fn === rest.issues.listEvents ? (extra.events || []) : (extra.items || [])) }; +} +const core = { info() {} }; +const repo = { owner: 'o', repo: 'r' }; + +test('intake labels and comments once', async () => { + const calls = []; + const item = { number: 1, title: 'bad', body: '', labels: [], user: { type: 'User' }, author_association: 'NONE' }; + await bot.intake({ github: fake(calls), context: { repo, payload: { action: 'opened', issue: item } }, core }); + assert.deepStrictEqual(calls.map((c) => c[0]), ['addLabels', 'comment']); + calls.length = 0; + item.labels = [{ name: 'needs-format' }]; + await bot.intake({ github: fake(calls), context: { repo, payload: { action: 'edited', issue: item } }, core }); + assert.deepStrictEqual(calls, []); +}); + +test('intake clears the label when edited into shape', async () => { + const calls = []; + const item = { number: 1, title: '[Engine] x y', body: bugForm(), labels: [{ name: 'needs-format' }], user: { type: 'User' } }; + await bot.intake({ github: fake(calls), context: { repo, payload: { action: 'edited', issue: item } }, core }); + assert.deepStrictEqual(calls.map((c) => c[0]), ['removeLabel', 'comment']); +}); + +test('reopen: ignores strangers, reopens the author when it passes', async () => { + const issue = { number: 5, state: 'closed', user: { login: 'amy' }, labels: [] }; + let calls = []; + const comment = { body: '/reopen', user: { login: 'bob', type: 'User' }, author_association: 'NONE' }; + await bot.reopen({ github: fake(calls), context: { repo, payload: { issue, comment } }, core }); + assert.deepStrictEqual(calls, []); + + const live = { number: 5, title: '[Engine] x y', body: bugForm(), labels: [] }; + comment.user.login = 'amy'; + await bot.reopen({ github: fake(calls, { live }), context: { repo, payload: { issue, comment } }, core }); + assert.deepStrictEqual(calls.map((c) => c[0]), ['update', 'removeLabel', 'comment']); + assert.strictEqual(calls[0][1], 'open'); + + calls = []; + live.title = 'no prefix'; + await bot.reopen({ github: fake(calls, { live }), context: { repo, payload: { issue, comment } }, core }); + assert.deepStrictEqual(calls.map((c) => c[0]), ['comment']); + assert.ok(calls[0][1].includes('Not reopened')); +}); + +test('sweep closes only old flagged items', async () => { + const calls = []; + const old = new Date(Date.now() - 6 * 86400000).toISOString(); + const fresh = new Date(Date.now() - 1 * 86400000).toISOString(); + const mk = (n, created) => ({ number: n, title: 'bad', body: '', labels: [{ name: 'needs-format' }], created_at: created }); + const gh = fake(calls, { items: [mk(1, old), mk(2, fresh)] }); + await bot.sweep({ github: gh, context: { repo }, core }); + assert.deepStrictEqual(calls.map((c) => c[0]), ['comment', 'update']); +}); diff --git a/engine/strata/.github/scripts/reset-bot.js b/engine/strata/.github/scripts/reset-bot.js new file mode 100644 index 00000000..11eb63ae --- /dev/null +++ b/engine/strata/.github/scripts/reset-bot.js @@ -0,0 +1,164 @@ +'use strict'; +// GitHub-side handlers for intake.yml, reopen.yml and the 5-day sweep. +// They take the actions/github-script objects ({ github, context, core }) and never touch PR code: +// everything comes from the event payload and the REST API. + +const check = require('./item-check'); + +const LABEL = 'needs-format'; +const STALE_DAYS = 5; +const MAINTAINER = new Set(['OWNER', 'MEMBER', 'COLLABORATOR']); +// Items a maintainer closed on purpose stay closed. +const BLOCK_LABELS = new Set(['wontfix', 'invalid', 'duplicate', 'declined']); + +function labelNames(item) { + return (item.labels || []).map((l) => (typeof l === 'string' ? l : l.name)); +} + +async function ensureLabel(github, context) { + const { owner, repo } = context.repo; + try { + await github.rest.issues.getLabel({ owner, repo, name: LABEL }); + } catch (e) { + if (e.status !== 404) throw e; + await github.rest.issues.createLabel({ + owner, repo, name: LABEL, color: 'fbca04', + description: 'Title or description does not follow CONTRIBUTING.md yet', + }); + } +} + +async function removeLabel(github, context, number) { + const { owner, repo } = context.repo; + try { + await github.rest.issues.removeLabel({ owner, repo, issue_number: number, name: LABEL }); + } catch (e) { + if (e.status !== 404) throw e; + } +} + +function itemFromPayload(context) { + const p = context.payload; + return p.pull_request || p.issue; +} + +function isPullItem(item, context) { + return Boolean(context.payload.pull_request || item.pull_request); +} + +// issues: opened/edited/reopened, pull_request_target: opened/edited/reopened +async function intake({ github, context, core }) { + const { owner, repo } = context.repo; + const item = itemFromPayload(context); + if (!item || (item.user && item.user.type === 'Bot')) return; + if (MAINTAINER.has(item.author_association) && context.payload.action === 'opened') { + // Maintainer items are not nagged on creation. + return; + } + const isPull = isPullItem(item, context); + const labels = labelNames(item); + const hasLabel = labels.includes(LABEL); + const res = check.checkItem({ isPull, title: item.title, body: item.body, labels, mode: 'intake' }); + core.info('check ' + (isPull ? 'PR' : 'issue') + ' #' + item.number + ': ' + (res.ok ? 'ok' : res.missing.join(' | '))); + + if (res.ok) { + if (hasLabel) { + await removeLabel(github, context, item.number); + await github.rest.issues.createComment({ owner, repo, issue_number: item.number, body: 'Thanks, this follows the format now.' }); + } + return; + } + if (context.payload.action === 'edited' && !hasLabel) return; // edits only matter for items already flagged + if (hasLabel) return; // one note only + await ensureLabel(github, context); + await github.rest.issues.addLabels({ owner, repo, issue_number: item.number, labels: [LABEL] }); + await github.rest.issues.createComment({ owner, repo, issue_number: item.number, body: check.intakeComment(isPull, res.missing) }); +} + +// issue_comment created, body starts with /reopen +async function reopen({ github, context, core }) { + const { owner, repo } = context.repo; + const comment = context.payload.comment; + const issue = context.payload.issue; + if (!/^\s*\/reopen\b/.test(comment.body || '')) return; + if (comment.user.type === 'Bot') return; + const isAuthor = comment.user.login === issue.user.login; + const isMaint = MAINTAINER.has(comment.author_association); + if (!isAuthor && !isMaint) { + core.info('ignored /reopen from ' + comment.user.login + ' (not the author or a maintainer)'); + return; + } + const isPull = Boolean(issue.pull_request); + const say = (body) => github.rest.issues.createComment({ owner, repo, issue_number: issue.number, body }); + const labels = labelNames(issue); + const wasOpen = issue.state === 'open'; + + if (labels.some((l) => BLOCK_LABELS.has(l.toLowerCase())) && !isMaint) { + await say('This one was closed on purpose (' + labels.filter((l) => BLOCK_LABELS.has(l.toLowerCase())).join(', ') + '). Please add your new evidence in a comment and a maintainer will decide.'); + return; + } + if (wasOpen && !labels.includes(LABEL)) { + core.info('already open, nothing to do'); + return; + } + + // The bot reads the live item, not the possibly stale event copy. + const live = (await github.rest.issues.get({ owner, repo, issue_number: issue.number })).data; + const res = check.checkItem({ isPull, title: live.title, body: live.body, labels: labelNames(live), mode: 'reopen' }); + core.info('reopen check #' + live.number + ': ' + (res.ok ? 'ok' : res.missing.join(' | '))); + + if (!res.ok) { + await say(check.reopenMissingComment(isPull, res.missing)); + return; + } + if (!wasOpen) { + try { + await github.rest.issues.update({ owner, repo, issue_number: live.number, state: 'open' }); + } catch (e) { + await say('The check passed, but GitHub would not reopen it (' + (e.message || e.status) + '). ' + (isPull ? 'If the branch was deleted, restore it or open a new pull request and link this one.' : 'Please open a new issue and link this one.')); + return; + } + } + await removeLabel(github, context, live.number); + let extra = ''; + if (isPull) { + try { + const pr = (await github.rest.pulls.get({ owner, repo, pull_number: live.number })).data; + if (pr.mergeable_state === 'dirty') extra = '\n\nIt has conflicts with main now: please rebase it.'; + } catch (e) { /* best effort */ } + } + await say(check.reopenOkComment(isPull) + extra); +} + +async function labelTime(github, owner, repo, number, fallback) { + const events = await github.paginate(github.rest.issues.listEvents, { owner, repo, issue_number: number, per_page: 100 }); + let t = null; + for (const e of events) { + if (e.event === 'labeled' && e.label && e.label.name === LABEL) t = e.created_at; + } + return t || fallback; +} + +// scheduled: close items that kept the needs-format label for more than 5 days +async function sweep({ github, context, core }) { + const { owner, repo } = context.repo; + const cutoff = Date.now() - STALE_DAYS * 86400 * 1000; + const items = await github.paginate(github.rest.issues.listForRepo, { owner, repo, state: 'open', labels: LABEL, per_page: 100 }); + core.info(items.length + ' open items with ' + LABEL); + for (const item of items) { + const since = new Date(await labelTime(github, owner, repo, item.number, item.created_at)).getTime(); + if (since > cutoff) continue; + const isPull = Boolean(item.pull_request); + // Re-check first: an edit that fixed it should have cleared the label already; do not close good items. + const res = check.checkItem({ isPull, title: item.title, body: item.body, labels: labelNames(item), mode: 'intake' }); + if (res.ok) { + await removeLabel(github, context, item.number); + continue; + } + await github.rest.issues.createComment({ owner, repo, issue_number: item.number, body: check.staleComment(isPull) }); + await github.rest.issues.update({ owner, repo, issue_number: item.number, state: 'closed', state_reason: 'not_planned' }); + core.info('closed #' + item.number); + } +} + +module.exports = { intake, reopen, sweep, LABEL, STALE_DAYS }; diff --git a/engine/strata/.github/workflows/docker-images.yml b/engine/strata/.github/workflows/docker-images.yml new file mode 100644 index 00000000..e72c8e99 --- /dev/null +++ b/engine/strata/.github/workflows/docker-images.yml @@ -0,0 +1,114 @@ +name: Docker images + +# Builds the Strata container images of one release from its engine packages and pushes them to ghcr.io. +# Run by hand only (Actions tab -> Docker images -> Run workflow). Nothing starts it on its own. +# +# For each flavor the job downloads the engine package from the release and checks it against the signed update feed +# (docker/fetch-engines.py: the feed's Ed25519 signature, the archive's SHA-256, the manifest hash, the package signature, +# every file's hash), builds the image with docker/build.sh and, only when "push" is on, pushes +# ghcr.io/niko1221/strata:- and ghcr.io/niko1221/strata:latest- +# The first run with "push" off builds everything without publishing it (a dry run). + +on: + workflow_dispatch: + inputs: + release_tag: + description: 'Release tag whose engine packages go into the images (for example v0.2.3)' + required: true + type: string + flavors: + description: 'Flavors to build, comma separated (empty: every flavor the release has a package for)' + required: false + default: '' + type: string + push: + description: 'Push the images to ghcr.io (off: build only, nothing is published)' + required: true + default: false + type: boolean + latest: + description: 'Also move the latest- tags (turn off for a pre-release or a test)' + required: true + default: true + type: boolean + source_ref: + description: 'Git ref of the Dockerfile and the Terminal sources (empty: the release tag)' + required: false + default: '' + type: string + +permissions: + contents: read + +env: + IMAGE: ghcr.io/niko1221/strata + +jobs: + plan: + runs-on: ubuntu-24.04 + outputs: + flavors: ${{ steps.list.outputs.flavors }} + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ inputs.source_ref || inputs.release_tag }} + - name: Which flavors does the release have a package for + id: list + env: + WANT: ${{ inputs.flavors }} + TAG: ${{ inputs.release_tag }} + run: | + set -eu + args="--release-tag $TAG --list --skip-missing" + [ -n "$WANT" ] && args="$args --flavors $WANT" + python3 docker/fetch-engines.py $args > list.tsv + cat list.tsv + flavors=$(awk -F'\t' '$3 != "SKIP" {printf "%s\"%s\"", (n++ ? "," : ""), $1}' list.tsv) + [ -n "$flavors" ] || { echo "the release has no engine package for any requested flavor"; exit 1; } + echo "flavors=[$flavors]" >> "$GITHUB_OUTPUT" + + image: + needs: plan + runs-on: ubuntu-24.04 + timeout-minutes: 120 + permissions: + contents: read + packages: write + strategy: + fail-fast: false + max-parallel: 3 + matrix: + flavor: ${{ fromJSON(needs.plan.outputs.flavors) }} + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ inputs.source_ref || inputs.release_tag }} + - name: Free disk space (the runner has about 14 GB; a package plus its image needs about 10 GB) + run: | + sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache/CodeQL || true + docker system prune -af >/dev/null 2>&1 || true + df -h / + - name: Log in to ghcr.io + if: ${{ inputs.push }} + env: + REGISTRY_TOKEN: ${{ secrets.GITHUB_TOKEN }} + REGISTRY_USER: ${{ github.actor }} + run: printf '%s' "$REGISTRY_TOKEN" | docker login ghcr.io -u "$REGISTRY_USER" --password-stdin + - name: Fetch, verify, build (and push when push is on) + env: + TAG: ${{ inputs.release_tag }} + FLAVOR: ${{ matrix.flavor }} + PUSH: ${{ inputs.push && '--push' || '' }} + LATEST: ${{ !inputs.latest && '--no-latest' || '' }} + run: | + docker/publish.sh --release-tag "$TAG" --flavors "$FLAVOR" --image "$IMAGE" $PUSH $LATEST + - name: Summary + if: ${{ always() }} + run: | + { + echo "### ${{ matrix.flavor }}" + echo "- release: ${{ inputs.release_tag }}, pushed: ${{ inputs.push }}" + echo "- image: \`$IMAGE:${INPUT_TAG#v}-${{ matrix.flavor }}\`" + } >> "$GITHUB_STEP_SUMMARY" + env: + INPUT_TAG: ${{ inputs.release_tag }} diff --git a/engine/strata/.github/workflows/intake.yml b/engine/strata/.github/workflows/intake.yml new file mode 100644 index 00000000..326a0d92 --- /dev/null +++ b/engine/strata/.github/workflows/intake.yml @@ -0,0 +1,58 @@ +name: Intake + +# New issues and pull requests that do not follow CONTRIBUTING.md get the needs-format label and one friendly note. +# Items that keep the label for 5 days are closed by the daily sweep, with a note on how to /reopen. +# +# pull_request_target is used instead of pull_request on purpose: a pull request from a fork gets a read-only +# GITHUB_TOKEN under pull_request, so it could not be labelled or commented on. It is safe here because this +# workflow never checks out or runs the pull request's code. It checks out the default branch only (the bot +# scripts) and reads the title and description from the event payload and the REST API. + +on: + issues: + types: [opened, edited] + pull_request_target: + types: [opened, edited] + schedule: + - cron: '17 4 * * *' + workflow_dispatch: + +permissions: + contents: read + issues: write + pull-requests: write + +concurrency: + group: intake-${{ github.event.issue.number || github.event.pull_request.number || 'sweep' }} + cancel-in-progress: false + +jobs: + check: + if: github.event_name == 'issues' || github.event_name == 'pull_request_target' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.repository.default_branch }} + sparse-checkout: .github/scripts + persist-credentials: false + - uses: actions/github-script@v7 + with: + script: | + const bot = require('./.github/scripts/reset-bot.js'); + await bot.intake({ github, context, core }); + + sweep: + if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.repository.default_branch }} + sparse-checkout: .github/scripts + persist-credentials: false + - uses: actions/github-script@v7 + with: + script: | + const bot = require('./.github/scripts/reset-bot.js'); + await bot.sweep({ github, context, core }); diff --git a/engine/strata/.github/workflows/metal-build.yml b/engine/strata/.github/workflows/metal-build.yml new file mode 100644 index 00000000..7a69696f --- /dev/null +++ b/engine/strata/.github/workflows/metal-build.yml @@ -0,0 +1,51 @@ +name: Metal build + +# Compile and link the Metal engine on a macOS runner (no GPU needed: the kernels are compiled at run time). The shared host files +# (src/core/verify.cpp, src/prefill, src/program/generate.cpp) call kernel entry points that exist only for CUDA / HIP until Metal gets a +# stub or an implementation; a missing one is a link error here, not on a user's Mac (owner round 9, G6). + +on: + pull_request: + paths: + - 'src/**' + - 'include/**' + - 'metal/**' + - 'third_party/**' + - 'CMakeLists.txt' + - '.github/workflows/metal-build.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + metal-link: + runs-on: macos-14 + timeout-minutes: 45 + env: + # setup.py's LLAMA_CPP_COMMIT and metal/setup_mac.py's metal-cpp pin + LLAMA_CPP_COMMIT: 3cf03257f219afbe7334045ff7c6a06ac68c627d + METAL_CPP_URL: https://developer.apple.com/metal/cpp/files/metal-cpp_26.zip + METAL_CPP_SHA256: 4df3c078b9aadcb516212e9cb03004cbc5ce9a3e9c068fa3144d021db585a3a4 + steps: + - uses: actions/checkout@v4 + - name: Tools + run: brew install ninja + - name: metal-cpp + run: | + curl -fsSL "$METAL_CPP_URL" -o metal-cpp.zip + echo "$METAL_CPP_SHA256 metal-cpp.zip" | shasum -a 256 -c - + unzip -q metal-cpp.zip -d _mcpp + - name: llama.cpp (ggml) at the pinned commit + run: | + mkdir llama.cpp && cd llama.cpp + git init -q + git remote add origin https://github.com/ggml-org/llama.cpp.git + git fetch -q --depth 1 origin "$LLAMA_CPP_COMMIT" + git checkout -q FETCH_HEAD + - name: Configure + run: | + cmake -S metal -B build-metal -G Ninja -DCMAKE_BUILD_TYPE=Release \ + -DMETAL_CPP_DIR="$PWD/_mcpp/metal-cpp" -DSTRATA_GGML_DIR="$PWD/llama.cpp" + - name: Build and link the engine + run: cmake --build build-metal --target strata diff --git a/engine/strata/.github/workflows/reopen.yml b/engine/strata/.github/workflows/reopen.yml new file mode 100644 index 00000000..ff7c10f9 --- /dev/null +++ b/engine/strata/.github/workflows/reopen.yml @@ -0,0 +1,38 @@ +name: Reopen + +# An author comments /reopen on their closed issue or pull request. The check runs and the item is reopened, +# or the bot replies with what is still missing. GitHub does not let authors reopen items a maintainer closed, +# so this workflow does it for them. +# +# issue_comment always runs the workflow file from the default branch with a write-capable token, which is what +# we need for fork authors too. It never checks out or executes the pull request's code: it reads the live +# title and description through the REST API. Only the author of the item or a maintainer can trigger it. + +on: + issue_comment: + types: [created] + +permissions: + contents: read + issues: write + pull-requests: write + +concurrency: + group: reopen-${{ github.event.issue.number }} + cancel-in-progress: false + +jobs: + reopen: + if: startsWith(github.event.comment.body, '/reopen') && github.event.comment.user.type != 'Bot' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.repository.default_branch }} + sparse-checkout: .github/scripts + persist-credentials: false + - uses: actions/github-script@v7 + with: + script: | + const bot = require('./.github/scripts/reset-bot.js'); + await bot.reopen({ github, context, core }); diff --git a/engine/strata/.github/workflows/scripts-test.yml b/engine/strata/.github/workflows/scripts-test.yml new file mode 100644 index 00000000..97b5de9c --- /dev/null +++ b/engine/strata/.github/workflows/scripts-test.yml @@ -0,0 +1,21 @@ +name: Scripts test + +on: + pull_request: + paths: + - '.github/scripts/**' + - '.github/workflows/intake.yml' + - '.github/workflows/reopen.yml' + +permissions: + contents: read + +jobs: + node-test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - run: node --test .github/scripts/item-check.test.js diff --git a/engine/strata/.github/workflows/terminal-minimal-server.yml b/engine/strata/.github/workflows/terminal-minimal-server.yml new file mode 100644 index 00000000..e2c75316 --- /dev/null +++ b/engine/strata/.github/workflows/terminal-minimal-server.yml @@ -0,0 +1,65 @@ +name: Minimal serving runtime + +on: + push: + paths: + - .github/workflows/terminal-minimal-server.yml + - requirements.txt + - strata.py + - strata_cli/** + - strata_control/** + - serve/** + - tests/terminal/test_runtime.py + - tools/minimal_server_smoke.py + - tools/strata_tokenizer.py + pull_request: + paths: + - .github/workflows/terminal-minimal-server.yml + - requirements.txt + - strata.py + - strata_cli/** + - strata_control/** + - serve/** + - tests/terminal/test_runtime.py + - tools/minimal_server_smoke.py + - tools/strata_tokenizer.py + workflow_dispatch: + +permissions: + contents: read + +jobs: + fake-engine: + name: Linux / runtime requirements only + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + - uses: actions/setup-python@v7 + with: + python-version: '3.11' + - name: Install only pinned runtime requirements + shell: bash + run: | + python -m venv "$RUNNER_TEMP/strata-runtime-venv" + "$RUNNER_TEMP/strata-runtime-venv/bin/python" -m pip install -r requirements.txt + - name: Check fake-engine serving without terminal packages + shell: bash + run: | + python - <<'PY' + import os + import subprocess + from pathlib import Path + + report = Path(os.environ['RUNNER_TEMP']) / 'minimal-server-smoke.json' + python = str(Path(os.environ['RUNNER_TEMP']) / 'strata-runtime-venv' / 'bin' / 'python') + subprocess.run([python, 'tools/minimal_server_smoke.py', + '--report', str(report)], check=True) + print(report.read_text()) + PY + - name: Run full server suite without terminal packages + shell: bash + run: | + "$RUNNER_TEMP/strata-runtime-venv/bin/python" -m unittest discover -s serve -p 'test_*.py' diff --git a/engine/strata/.github/workflows/terminal-portable-monitor.yml b/engine/strata/.github/workflows/terminal-portable-monitor.yml new file mode 100644 index 00000000..905e7c40 --- /dev/null +++ b/engine/strata/.github/workflows/terminal-portable-monitor.yml @@ -0,0 +1,115 @@ +name: Portable monitor client + +on: + push: + paths: + - .github/workflows/terminal-portable-monitor.yml + - packaging/monitor_bundle.py + - strata.py + - strata_cli/** + - strata_control/** + - tools/minimal_cli_smoke.py + - tools/portable_monitor_smoke.py + - tools/portable_monitor_pty_smoke.py + - requirements-monitor.txt + - LICENSE + pull_request: + paths: + - .github/workflows/terminal-portable-monitor.yml + - packaging/monitor_bundle.py + - strata.py + - strata_cli/** + - strata_control/** + - tools/minimal_cli_smoke.py + - tools/portable_monitor_smoke.py + - tools/portable_monitor_pty_smoke.py + - requirements-monitor.txt + - LICENSE + workflow_dispatch: + +permissions: + contents: read + +jobs: + client: + name: ${{ matrix.os }} / Python ${{ matrix.python }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest] + python: ['3.10', '3.11'] + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + - uses: actions/setup-python@v7 + with: + python-version: ${{ matrix.python }} + - name: Check source CLI without optional packages + shell: bash + run: | + python - <<'PY' + import os + import subprocess + import sys + from pathlib import Path + + report = Path(os.environ['RUNNER_TEMP']) / 'minimal-cli-smoke.json' + subprocess.run([sys.executable, 'tools/minimal_cli_smoke.py', + '--report', str(report)], check=True) + print(report.read_text()) + PY + - name: Build and smoke test without site packages + shell: bash + run: | + python - <<'PY' + import os + import subprocess + import sys + from pathlib import Path + + bundle = Path(os.environ['RUNNER_TEMP']) / 'strata-monitor.pyz' + report = bundle.with_name('monitor-stdlib-smoke.json') + subprocess.run([sys.executable, 'packaging/monitor_bundle.py', + 'build', str(bundle)], check=True) + subprocess.run([sys.executable, 'tools/portable_monitor_smoke.py', + '--bundle', str(bundle), '--report', str(report)], check=True) + print(report.read_text()) + PY + - name: Install optional Textual dependency + if: matrix.python == '3.11' + run: python -m pip install -r requirements-monitor.txt + - name: Smoke test packaged interactive Overview + if: matrix.python == '3.11' + shell: bash + run: | + python - <<'PY' + import os + import subprocess + import sys + from pathlib import Path + + bundle = Path(os.environ['RUNNER_TEMP']) / 'strata-monitor.pyz' + report = bundle.with_name('monitor-interactive-smoke.json') + subprocess.run([sys.executable, 'tools/portable_monitor_smoke.py', + '--bundle', str(bundle), '--interactive', + '--report', str(report)], check=True) + print(report.read_text()) + PY + - name: Check POSIX terminal restoration + if: matrix.os == 'ubuntu-latest' && matrix.python == '3.11' + shell: bash + run: | + python - <<'PY' + import os + import subprocess + import sys + from pathlib import Path + + bundle = Path(os.environ['RUNNER_TEMP']) / 'strata-monitor.pyz' + report = bundle.with_name('monitor-pty-smoke.json') + subprocess.run([sys.executable, 'tools/portable_monitor_pty_smoke.py', + '--bundle', str(bundle), '--report', str(report)], check=True) + print(report.read_text()) + PY diff --git a/engine/strata/.github/workflows/title-area.yml b/engine/strata/.github/workflows/title-area.yml new file mode 100644 index 00000000..6c5779f0 --- /dev/null +++ b/engine/strata/.github/workflows/title-area.yml @@ -0,0 +1,28 @@ +name: Title area + +# Checks that a pull request or issue title starts with its area: [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other]. +# It reads the title only: no checkout, no labels, no comments, no write access. + +on: + pull_request: + types: [opened, edited, reopened, synchronize] + issues: + types: [opened, edited, reopened] + +permissions: {} + +jobs: + title: + runs-on: ubuntu-latest + steps: + - name: Check the title + env: + TITLE: ${{ github.event.pull_request.title || github.event.issue.title }} + run: | + case "$TITLE" in + "[Engine] "?*|"[GUI] "?*|"[TUI] "?*|"[Benchmark] "?*|"[Docs] "?*|"[Other] "?*) + echo "Title OK: $TITLE" ;; + *) + echo "::error::The title must start with its area and then a short description. Allowed areas: [Engine], [GUI], [TUI], [Benchmark], [Docs], [Other]. Example: \"[Engine] fix decode stop on long prompts\". Your title: $TITLE" + exit 1 ;; + esac diff --git a/engine/strata/.gitignore b/engine/strata/.gitignore index cb6477db..c6cfb336 100644 --- a/engine/strata/.gitignore +++ b/engine/strata/.gitignore @@ -37,17 +37,51 @@ td.log /strata-*.json /strata-*.log /build-strata.bat +/build-strata-cuda12.bat +/build-cuda12/ /.strata-mcp/ # image encoder (setup.py --vision): build output and the generated build script build-vision*/ build-vision.bat +build-vision-cuda12.bat # setup.py outputs (engine, downloads) and release builds /engine/ +/engine-sycl/ +/engine-cuda12/ /build-release*/ /dist/ *.done /third_party/*.zip +# IDEs +.vscode/ +.idea/ +.cursor/ + +/.ccache/ /.rocm-win/ + +# local Windows HIP packaging output +dist-hip/ + +# Terminal / Desktop split: local venvs, build output and archives never enter git +.terminal-venv/ +.terminal-test-venv/ +node_modules/ +*.dmg +/release/artifacts/ +/apps/host/dist/ +/apps/desktop/src-tauri/target/ +/apps/desktop/src-tauri/resources/node/* +!/apps/desktop/src-tauri/resources/node/.gitignore +# the Control component (bundled CPython + wheels + strata_control) is built by apps/desktop/scripts/stage-control.py +/apps/desktop/src-tauri/resources/control/* +!/apps/desktop/src-tauri/resources/control/.gitignore +# the pruned DeepSeek Harness (MIT) is built by apps/desktop/scripts/stage-harness.mjs +/apps/desktop/src-tauri/resources/harness/* +!/apps/desktop/src-tauri/resources/harness/.gitignore +# screenshots and checkpoints from the Mac rebuild live outside git (StrataSplit\evidence-archive) +/apps/host/docs/evidence/ +/apps/host/docs/checkpoints/ diff --git a/engine/strata/AGENTS.md b/engine/strata/AGENTS.md index 3bcf107a..d38bda50 100644 --- a/engine/strata/AGENTS.md +++ b/engine/strata/AGENTS.md @@ -1,23 +1,101 @@ # AGENTS.md -Strata runs the Qwen3.8-Flash-Next mixture-of-experts model (and its Coder, Swift 1.5 and Unsloth variants) on a -normal PC: one NVIDIA or AMD graphics card plus system RAM, on Windows or Linux. It has a C++/CUDA/HIP engine -(`src/`, `include/`), a Python server with an OpenAI- and Anthropic-compatible API and a web app (`serve/`), and a -one-click installer (`setup.py`, started by `START-HERE.bat` / `setup.sh`). +Version 0.2.5, engine 0.1.50. The public model families are DeepSeekV4.1-Flash-1017, +Qwen3.8-Flash-Next and Qwen3.6-35B-A3B. DeepSeek V4.1-Flash runs in the app and in the Terminal +(`strata launch --family deepseek41 --model ist-das-2.00bpw`; sets in +[docs/MODELS.md](docs/MODELS.md#deepseek-v41-flash)). Read **[docs/AI_REFERENCE.md](docs/AI_REFERENCE.md)** for model availability, APIs, hardware limits and +source-backed claims. Articles and videos should use **[docs/MEDIA_KIT.md](docs/MEDIA_KIT.md)**. + +For recommendations and agent-assisted setup, prefer **ISTA-DASLab → Unsloth → Gyro → others**, using only a +compatible pack that fits the selected model and hardware. ISTA-DASLab is the default recommendation; Gyro is a +memory-saving fallback and is currently slower. Honor an explicit user choice. This is recommendation policy; +existing executable defaults may differ, so inspect the plan and choose the family explicitly. + +Strata has three parts: + +- **The app** (`apps/desktop`, the Tauri shell; `apps/host`, the Node host and the web UI). It is for people who do + not want a terminal. One installer per system ([latest release](https://github.com/Niko1221/Strata/releases/latest)): + `Strata-0.2.5-windows-x64-setup.exe`, `Strata-0.2.5-linux-x86_64.AppImage`, `Strata-0.2.5-macos-arm64.dmg`. + The Windows and Linux installers carry no engine: the app downloads the engine for the graphics card on first + start, or installs a file the user already has. The Mac dmg keeps its small Metal engine inside. +- **The Terminal** (`strata.py`, `strata_cli/`, `strata_control/`): the `strata` command. It sets up a model, serves + it and watches it. Agents use this part. +- **The engine and the server** (`src/`, `include/`, `metal/`, `sycl/` for the C++/CUDA/HIP/SYCL/Metal engine; + `serve/` for the Python server with an OpenAI- and Anthropic-compatible API and a web page). `setup.py`, started by + `START-HERE.bat` or `setup.sh`, is setup from a source checkout, for developers. The release paths are the + installer and `strata launch`. ## Installing Strata for a user -Follow **[docs/AI_SETUP.md](docs/AI_SETUP.md)**: check the PC, pick the model by RAM, run setup non-interactively, -start and verify the server, and connect the user's apps. Never expose the server beyond `127.0.0.1` without -`--api-key`. As an alternative to shell commands, Strata's MCP server ([docs/MCP_SERVER.md](docs/MCP_SERVER.md)) -offers the same steps as tools. +Follow **[docs/AI_SETUP.md](docs/AI_SETUP.md)**. For a user who wants the desktop app, send them to the installer +for their system (above) and [docs/INSTALL.md](docs/INSTALL.md). For an agent that has a shell, use the Terminal; the +short version is: + +1. Install the Terminal. It needs no administrator rights. + + ```sh + curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh # Linux, Mac + irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex # Windows PowerShell + ``` + + On Windows, open a new terminal afterwards so that `strata` is on the PATH. +2. Check what would happen. Nothing is changed: + + ```sh + strata launch --plan --family qwen --model q2_0 + ``` + +3. Set up and serve without questions. It downloads the engine for the card and the model (tens of GB), starts the + server, prints the addresses and returns. The server keeps running. + + ```sh + strata launch --family qwen --model q2_0 --yes --no-tui + ``` + + Useful flags (all of them: `strata launch --help`): `--family`, `--model-path` (files the user already has), + `--data-dir`, `--context 32k|64k|128k`, `--vision off|on|gpu|cpu`, `--parallel N`, `--gpu 0,1`, + `--access local|lan|cloudflare|tailscale`, `--port`, `--api-key-env NAME`, `--new-key`, `--save-preset NAME`, + `--speed faster|full` (DeepSeek), `--output json`. `strata launch --status` shows what is serving, `strata launch --stop` stops it, and + `strata launch --show-key` prints the API key. +4. Connect the user's apps: `strata connect` lists them, `strata connect --check` sends one prompt and one tool + call the way that app does. + +Keep the server on `127.0.0.1` unless the user asks for more. Beyond it an API key is recommended: `--access lan` makes one for you, and `--no-api-key` serves without one (a warning, never a refusal; on a public tunnel the warning is stronger). Source setup (`START-HERE.bat`, `setup.sh`) is the fallback for a developer or for a system with no release package; it is +documented in [docs/SOURCE_INSTALL.md](docs/SOURCE_INSTALL.md). Those wrappers exist in a source checkout, not in the +released app. Do not tell an app user to find a `.bat` file. +Source setup does not make an unsupported model or backend compatible. Strata's MCP server ([docs/MCP_SERVER.md](docs/MCP_SERVER.md)) offers the same steps as tools. ## Working on the code - How the engine works, every measured number, the API and all settings: [docs/DETAILS.md](docs/DETAILS.md) and the [paper](docs/paper/Strata-Paper.pdf). -- AMD (HIP) build and validation: [docs/AMD_HIP.md](docs/AMD_HIP.md); multi-GPU: [docs/MULTI_GPU.md](docs/MULTI_GPU.md). -- Setup's own tests run without a GPU or downloads: `python tools/test_setup_.py` (for example - `tools/test_setup_amd.py`, `tools/test_setup_choices.py`). -- Keep the docs' style: plain words, measured numbers with what they were measured on, no claims without a - measurement. +- The Terminal: [docs/TERMINAL.md](docs/TERMINAL.md) and [docs/TERMINAL_LAUNCH.md](docs/TERMINAL_LAUNCH.md). The app, + the packages and the update feed: [packaging/README.md](packaging/README.md) and [packaging/UPDATES.md](packaging/UPDATES.md). +- AMD (HIP) build and validation: [docs/AMD_HIP.md](docs/AMD_HIP.md); multi-GPU: [docs/MULTI_GPU.md](docs/MULTI_GPU.md); + Mac (Metal): [docs/MAC.md](docs/MAC.md). +- Tests: the Terminal and Control tests are in `tests/terminal` (`python -m pytest tests/terminal`). The app's UI + tests run with `npm test` in `apps/host`. Setup's own tests run without a GPU or downloads: + `python tools/test_setup_.py` (for example `tools/test_setup_amd.py`, `tools/test_setup_choices.py`). +- Keep the docs' style: plain words, short sentences, written for non-technical users first. Give measured numbers + with what they were measured on. Make no claim without a measurement. + +## Contributing a change or report + +The rules are in **[CONTRIBUTING.md](CONTRIBUTING.md)**. Read it before you open an issue or a pull request, and +follow it whether a person or an agent writes the text. The short version: + +- Start every issue and pull request title with its area: `[Engine]`, `[GUI]`, `[TUI]`, `[Benchmark]`, `[Docs]` or + `[Other]`, for example `[Engine] fix …`. A check on GitHub fails a pull request whose title has no area. +- Search the open and closed issues and pull requests first, and add to a thread that already covers your point. +- Agree the scope in an issue before a large feature, a refactor or a change to a default. +- One problem per pull request. Lead with the problem and the result, then the approach, then the validation + (passed, failed and not run, kept apart) and the limits. +- A new feature is opt-in, and the default path stays byte-identical to the last release. Say how you checked. +- Build every backend a file touches (CUDA, HIP, SYCL) before asking for review. +- Change a default only where you measured it faster, and show the numbers with what they were measured on. +- Never submit measurements, logs or reproduction steps you did not produce. Mark a finding from reading code as + unconfirmed static analysis. +- A report from hardware the maintainers do not have is welcome. Follow + [docs/COMMUNITY_BENCHMARKS.md](docs/COMMUNITY_BENCHMARKS.md), compare against a same-day run of the build you are + testing, and say what you did not test. +- Open test requests and the hardware that is wanted are listed in [docs/TEST_REQUESTS.md](docs/TEST_REQUESTS.md). diff --git a/engine/strata/BENCH.bat b/engine/strata/BENCH.bat new file mode 100644 index 00000000..f54bc90d --- /dev/null +++ b/engine/strata/BENCH.bat @@ -0,0 +1,19 @@ +@echo off +rem Benchmark this Strata install the way it is used and write a report you can share (docs/COMMUNITY_BENCHMARKS.md). +rem It starts the model with your settings (or uses the one already running), takes about 10 minutes and changes nothing. +rem Options: --clients 4 (several requests at once), --long (a 32K prompt), --compare . +rem This is the quick speed check. The standard benchmark (docs/BENCHMARK_PROTOCOL.md), whose results other people can compare with, is `strata bench run`. +setlocal +title Strata - benchmark +cd /d "%~dp0" +if not exist ".venv\Scripts\python.exe" ( + echo Strata is not set up here yet: run START-HERE.bat first. + pause + exit /b 1 +) +echo Quick speed check. For results other people can compare with (the standard benchmark, a few minutes), run: .venv\Scripts\python.exe strata.py bench run +echo. +".venv\Scripts\python.exe" tools\strata_bench.py %* +set "RC=%ERRORLEVEL%" +pause +exit /b %RC% diff --git a/engine/strata/CMakeLists.txt b/engine/strata/CMakeLists.txt index 4d9f2ca1..ef1a1aec 100644 --- a/engine/strata/CMakeLists.txt +++ b/engine/strata/CMakeLists.txt @@ -1,4 +1,4 @@ -# Strata Engine - top-level build (P1.S1). +# Strata Engine - top-level build (P1.S1). # # Targets (phase-1 §P1.S1): `strata_artifact` (no CUDA dependency), `tests`. `strata_plan` and the C++ # `strata-pack` are added when their sources exist - a target with no sources would make the build graph @@ -8,7 +8,18 @@ # below refuses anything older: silently building for a pre-Ampere arch would produce a binary that runs # and is wrong about its own performance, which is the worst of both outcomes. cmake_minimum_required(VERSION 3.24) -project(strata VERSION 0.1.35 LANGUAGES CXX) +project(strata VERSION 0.1.50 LANGUAGES CXX) +# EXPERIMENTAL: the Intel Arc engine, the SYCL port in sycl/ (PR #423; icpx + oneMKL, docs/INTEL_ARC.md). It is its +# own project that takes the unported sources from src/; with this on, nothing below is configured. +option(STRATA_ENABLE_SYCL "EXPERIMENTAL: build the Intel Arc (SYCL) engine from sycl/ - docs/INTEL_ARC.md" OFF) +if(STRATA_ENABLE_SYCL) + if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) + message(FATAL_ERROR "STRATA_ENABLE_SYCL is a separate backend; leave STRATA_ENABLE_CUDA and STRATA_ENABLE_HIP off") + endif() + message(WARNING "STRATA_ENABLE_SYCL: the Intel Arc engine is experimental (community port, docs/INTEL_ARC.md)") + add_subdirectory(sycl) + return() +endif() add_compile_definitions(STRATA_VERSION="${PROJECT_VERSION}") # issue #31: release builds keep a PDB beside the exe (not shipped in it), so a minidump from a stalled engine can # be read back to the exact source line @@ -21,10 +32,33 @@ endif() # instead of this machine's (Strata's own AVX-512 kernels are per-file and chosen at run time either way), and # the MSVC runtime linked in, so no Visual C++ redistributable is needed. option(STRATA_PORTABLE "build for other PCs: AVX2 baseline, static MSVC runtime" OFF) +# EXPERIMENTAL, opt-in: an engine for CPUs without AVX2 (#394, #595, #623), compiled on that PC. ggml-cpu, which then +# computes every CPU expert row, is built for this floor instead of AVX2 or the build host: "avx" (Sandy/Ivy Bridge: +# AVX, no FMA/F16C/AVX2) or "none" (SSE4.2 + POPCNT: Nehalem/Westmere). Strata's own AVX2/AVX-512 kernels stay in the +# binary behind their CPU checks; the router lookahead gets an AVX1 kernel. Empty (the default) changes nothing. +set(STRATA_ISA_FLOOR "" CACHE STRING "experimental older-CPU build: empty (default, AVX2 floor), avx, or none (SSE4.2)") +set_property(CACHE STRATA_ISA_FLOOR PROPERTY STRINGS "" avx none) +if(NOT STRATA_ISA_FLOOR STREQUAL "" AND NOT STRATA_ISA_FLOOR STREQUAL "avx" AND NOT STRATA_ISA_FLOOR STREQUAL "none") + message(FATAL_ERROR "STRATA_ISA_FLOOR must be empty, avx or none (got '${STRATA_ISA_FLOOR}')") +endif() +if(STRATA_ISA_FLOOR AND STRATA_PORTABLE) + message(FATAL_ERROR "STRATA_ISA_FLOOR (an older-CPU build) and STRATA_PORTABLE (the AVX2 release build) exclude each other") +endif() if(STRATA_PORTABLE AND MSVC) set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded") endif() +# #3202: Windows hands a program its command line in the system's ANSI code page (cp1251 / cp866 on a Russian Windows, cp1252 on an +# English one), but the engine reads every path as UTF-8 (the run configs and the server write UTF-8). A model folder with +# Cyrillic letters arrived as other bytes, or as "?" where the page has no such letter, and the model did not open. This manifest +# makes the process's ANSI code page UTF-8 (Windows 10 1903 and newer; older Windows ignores it and nothing changes), so the +# command line, fopen and std::ifstream all take UTF-8. +function(strata_utf8_manifest target) + if(MSVC) + target_sources(${target} PRIVATE ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/cmake/strata-utf8.manifest) + endif() +endfunction() + set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) @@ -33,10 +67,22 @@ if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) endif() option(STRATA_ENABLE_CUDA "Build the CUDA targets (Phase 2+)" OFF) -option(STRATA_ENABLE_HIP "Build the HIP targets for wave32 AMD GPUs (gfx1100, gfx1201; gfx1030 unvalidated)" OFF) +# AMD gfx906 (MI50, wave64): the same .cu sources compiled as HIP through the gfx906 compat layer. The CUDA runtime and +# cuBLAS names are mapped by the headers in include/strata/platform/hip_compat/, which go first on the include path, +# and CUDA::cudart / CUDA::cublas become aliases of HIP's targets, so every CUDA target below stays as it is. This is +# separate from STRATA_ENABLE_HIP (the wave32 RDNA backend): with it on, STRATA_ENABLE_CUDA is on and +# STRATA_ENABLE_HIP stays off, so every "CUDA" branch of the tree is the one taken. +option(STRATA_HIP_GFX906 "Build the CUDA targets for AMD gfx906 through HIP (wave64 compat layer)" OFF) +if(STRATA_HIP_GFX906) + if(STRATA_ENABLE_HIP) + message(FATAL_ERROR "STRATA_HIP_GFX906 and STRATA_ENABLE_HIP are separate backends; enable only one") + endif() + set(STRATA_ENABLE_CUDA ON CACHE BOOL "" FORCE) +endif() +option(STRATA_ENABLE_HIP "Build the HIP targets for wave32 AMD GPUs (gfx1100, gfx1201; gfx1012/gfx1030 unvalidated)" OFF) option(STRATA_CUDA_STATIC "Linux GNU engine: static CUDA toolkit and C++ runtimes (host glibc and NVIDIA driver required)" OFF) if(STRATA_CUDA_STATIC) - if(NOT STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP OR NOT CMAKE_SYSTEM_NAME STREQUAL "Linux" + if(NOT STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP OR STRATA_HIP_GFX906 OR NOT CMAKE_SYSTEM_NAME STREQUAL "Linux" OR NOT CMAKE_CXX_COMPILER_ID STREQUAL "GNU") message(FATAL_ERROR "STRATA_CUDA_STATIC requires Linux, GNU C++, and STRATA_ENABLE_CUDA=ON (HIP disabled)") endif() @@ -44,15 +90,35 @@ if(STRATA_CUDA_STATIC) set(CMAKE_CUDA_RUNTIME_LIBRARY Static) endif() option(STRATA_PREFILL_MMQ "Build the optional GGML MMQ prefill path for HIP" OFF) -# CUDA: MMQ prompt kernels for Q4_K / Q5_K / Q5_1 (Unsloth's UD-Q4_K_XL experts). Off by default: the engine loads -# every kernel when it starts (CUDA_MODULE_LOADING=EAGER), so these took ~5 MB of VRAM - 1-3 expert slots - from every -# model, and the UD-Q4_K_XL prompt is SSD-bound with or without them (docs/UNSLOTH_Q4.md) -option(STRATA_MMQ_KQUANTS "Build the CUDA MMQ prompt kernels for Q4_K / Q5_K / Q5_1 experts" OFF) +# MMQ prompt kernels for Q4_K / Q5_K / Q5_1 / Q6_K (Unsloth's UD-Q4/Q5/Q6_K_XL experts; on HIP also the dense GGUF +# projections, STRATA_DENSE_MMQ). On by default since MODEL-UPDATE Phase 1: on CUDA they are their own library +# (strata_kq, loaded only for a model with these formats: the engine loads every kernel of its own binary at start, +# CUDA_MODULE_LOADING=EAGER, and these took ~3.8 MB of VRAM - 3 IQ3_XXS expert slots on a P100 - from every model); on +# HIP a code object loads on first use, so they cost other models nothing there (R9700: the same slots). Used at run +# time with STRATA_MMQ_KQ=1 (opt-in: it changes the prompt's rounding against the FP16 path). +option(STRATA_MMQ_TQ_OVERLAY "Gyro trellis MMQ prompt kernels on an upstream llama.cpp: an overlay of its ggml-cuda headers written at configure time (cmake/strata_ggml_tq_overlay.cmake)" ON) +option(STRATA_MMQ_KQUANTS "Build the MMQ prompt kernels for Q4_K / Q5_K / Q5_1 / Q6_K: the experts of Unsloth's K-quant files, and on HIP the dense GGUF projections (STRATA_DENSE_MMQ)" ON) +# Q6_K gate/up in the grouped expert kernels (Unsloth's UD-Q6_K_XL, and layer 2 of UD-Q5_K_XL; docs/QUANTS.md). On by +# default since MODEL-UPDATE Phase 1: one more instance per grouped kernel in iq_kernels.cu, +19 KB of sm_60 code, +# measured to leave every expert-cache slot count as it was (P100, R9700). -DSTRATA_Q6K_EXPERTS=OFF drops it. +option(STRATA_Q6K_EXPERTS "Build the Q6_K gate/up grouped expert kernels (UD-Q6_K_XL, UD-Q5_K_XL)" ON) +if(STRATA_Q6K_EXPERTS) + add_compile_definitions(STRATA_Q6K_EXPERTS=1) +endif() option(STRATA_ORCA_Q4KS_MMQ "Build the GGML Q5_0 MMQ instance for OrcaRouter Q4_K_S" OFF) +# CUDA: the pointer-table MMQ behind STRATA_MMQ_DIRECT=1 (the prompt path's MMQ reads resident experts in their cache +# slots through a Strata-side copy of llama.cpp's MMQ scheduler, src/prefill/moe_mmq_tab.cuh). Off by default, like +# the K-quant options above: the engine loads every kernel when it starts (CUDA_MODULE_LOADING=EAGER), and these nine +# instances (+15 MB of binary) take 36-38 MiB of VRAM per GPU on sm_86 - expert slots every model would lose, with +# STRATA_MMQ_DIRECT unset too. They also add ~70% of the upstream MMQ instances' compile time per CUDA arch (175 s +# of CPU for the nine at sm_86 alone). Off, the build's device code is byte for byte the one without this feature. CUDA +# only (not HIP, not gfx906); switched off at configure time when the llama.cpp tree's mmq.cuh is not one the copy +# was verified against. +option(STRATA_MMQ_TAB "Build the pointer-table prompt MMQ for STRATA_MMQ_DIRECT=1 (CUDA; ~37 MiB VRAM per GPU)" OFF) if(STRATA_PREFILL_MMQ AND NOT STRATA_ENABLE_HIP) message(FATAL_ERROR "STRATA_PREFILL_MMQ requires STRATA_ENABLE_HIP=ON") endif() -if(STRATA_ENABLE_CUDA AND STRATA_ENABLE_HIP) +if(STRATA_ENABLE_CUDA AND STRATA_ENABLE_HIP AND NOT STRATA_HIP_GFX906) message(FATAL_ERROR "STRATA_ENABLE_CUDA and STRATA_ENABLE_HIP are separate backends; enable only one") endif() if(STRATA_ENABLE_HIP) @@ -66,18 +132,57 @@ 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) +# #2027: defined here, before the GPU section reads it to register the native-expert tests (it was defined at the +# native-experts section far below, so a first configure registered four tests fewer than the second) +option(STRATA_NATIVE_EXPERTS "Native (IQ) expert support through ggml-cpu" ON) 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_split_failure_test src/core/conversation_split_failure_test.cpp) + target_include_directories(conversation_split_failure_test PRIVATE include) + add_test(NAME conversation_split_failure_test COMMAND conversation_split_failure_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) + add_executable(conversation_file_test src/core/conversation_file_test.cpp src/core/conversation_file.cpp) + target_include_directories(conversation_file_test PRIVATE include) + add_test(NAME conversation_file_test COMMAND conversation_file_test) + add_executable(session_save_reclaim_test src/core/session_save_reclaim_test.cpp src/core/conversation_file.cpp) + target_include_directories(session_save_reclaim_test PRIVATE include) + add_test(NAME session_save_reclaim_test COMMAND session_save_reclaim_test) endif() -if(STRATA_ENABLE_CUDA) +if(STRATA_HIP_GFX906) + if(NOT DEFINED CMAKE_HIP_ARCHITECTURES) + set(CMAKE_HIP_ARCHITECTURES gfx906 CACHE STRING "HIP architectures" FORCE) + endif() + enable_language(HIP) + find_package(hip REQUIRED) + find_package(hipblas REQUIRED) + add_library(CUDA::cudart INTERFACE IMPORTED) + target_link_libraries(CUDA::cudart INTERFACE hip::host) + target_compile_definitions(CUDA::cudart INTERFACE STRATA_HIP_GFX906=1 __HIP_PLATFORM_AMD__=1) + target_include_directories(CUDA::cudart BEFORE INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include/strata/platform/hip_compat) + add_library(CUDA::cublas INTERFACE IMPORTED) + target_link_libraries(CUDA::cublas INTERFACE roc::hipblas CUDA::cudart) + set(CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES ${CMAKE_CURRENT_SOURCE_DIR}/include/strata/platform/hip_compat) + include_directories(BEFORE ${CMAKE_CURRENT_SOURCE_DIR}/include/strata/platform/hip_compat) + add_compile_definitions(STRATA_HIP_GFX906=1) + message(STATUS "Strata: HIP (gfx906 compat) enabled, arch ${CMAKE_HIP_ARCHITECTURES}") + set(_strata_gpu_runtime_target CUDA::cudart) + set(_strata_gpu_blas_target CUDA::cublas) + set(_strata_gpu_include_directories ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) +elseif(STRATA_ENABLE_CUDA) + # #585: CMake links CUDA code with the STATIC runtime by default, and the targets below also link CUDA::cudart (the + # DLL's import library). MSVC with a CUDA 12.x toolkit - the experimental Pascal/Volta build - then fails with + # LNK1169 (every cudart symbol defined twice); GNU ld lets it pass. That build links the shared runtime alone. The + # ready-made engine (CUDA 13, no STRATA_EXPERIMENTAL_SM60) is unchanged; -DCMAKE_CUDA_RUNTIME_LIBRARY overrides. + if(MSVC AND STRATA_EXPERIMENTAL_SM60 AND NOT DEFINED CMAKE_CUDA_RUNTIME_LIBRARY) + set(CMAKE_CUDA_RUNTIME_LIBRARY Shared) + endif() enable_language(CUDA) # `enable_language(CUDA)` gives the .cu compile rules but NOT the imported targets, so `CUDA::cudart` has to # be brought in explicitly for the host-side tests that call cudaMalloc themselves. @@ -116,6 +221,11 @@ if(STRATA_ENABLE_CUDA) "CUDA 12.8 crashed on long prompts on these cards (issues #220, #224). Use CUDA 13.0 or newer.") endif() endforeach() + if(STRATA_EXPERIMENTAL_SM60) + # every target sees it: the Pascal / Volta code paths (the Volta prompt attention, PR #600) are compiled into this + # build only, so the ready-made engine (sm_75+) keeps exactly the code it had + add_compile_definitions(STRATA_EXPERIMENTAL_SM60=1) + endif() message(STATUS "Strata: CUDA enabled, arch ${CMAKE_CUDA_ARCHITECTURES}") set(_strata_gpu_runtime_target CUDA::cudart) set(_strata_gpu_blas_target CUDA::cublas) @@ -132,7 +242,7 @@ if(STRATA_ENABLE_CUDA) set(_strata_gpu_include_directories ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) elseif(STRATA_ENABLE_HIP) set(_strata_gpu_runtime_target strata_hip_runtime) - set(_strata_gpu_blas_target roc::hipblas) + set(_strata_gpu_blas_target ${STRATA_HIP_BLAS_TARGETS}) set(_strata_gpu_include_directories ${STRATA_HIP_COMPAT_INCLUDE_DIR}) endif() @@ -175,6 +285,12 @@ target_link_libraries(strata-dequant PRIVATE strata_artifact) # this file is now nothing but the CLI entry point, and its inherited guard spells that as a "selftest" target_compile_definitions(strata-dequant PRIVATE STRATA_DEQUANT_SELFTEST) if(STRATA_BUILD_TESTS) + add_executable(batch_telemetry_test src/core/batch_telemetry_test.cpp) + target_include_directories(batch_telemetry_test PRIVATE include) + add_test(NAME batch_telemetry_test COMMAND batch_telemetry_test) + add_executable(logit_bias_test src/core/logit_bias_test.cpp) + target_include_directories(logit_bias_test PRIVATE include) + add_test(NAME logit_bias_test COMMAND logit_bias_test) # the reader refuses a duplicate tensor name at open, naming it (a synthetic GGUF: no model, no GPU) add_executable(gguf_reader_test src/artifact/gguf_reader_test.cpp) target_link_libraries(gguf_reader_test PRIVATE strata_artifact) @@ -183,6 +299,44 @@ if(STRATA_BUILD_TESTS) add_executable(gguf_split_test tests/core/gguf_split_test.cpp) target_link_libraries(gguf_split_test PRIVATE strata_artifact) add_test(NAME gguf_split_test COMMAND gguf_split_test) + # the model families (qwen4exp, qwen35moe): the guards, the geometry from metadata, the layout tables (synthetic) + add_executable(model_family_test tests/core/model_family_test.cpp) + target_link_libraries(model_family_test PRIVATE strata_artifact) + add_test(NAME model_family_test COMMAND model_family_test) + # how --batch cuts a prompt read into pieces (a layer split with no slot decoding must still reach a BYIELD) + add_executable(batch_read_test tests/program/batch_read_test.cpp) + target_include_directories(batch_read_test PRIVATE include) + add_test(NAME batch_read_test COMMAND batch_read_test) + # the model's geometry from its metadata, and the check against the kernels' compiled shape (synthetic) + add_executable(gguf_geometry_test tests/core/gguf_geometry_test.cpp) + target_link_libraries(gguf_geometry_test PRIVATE strata_artifact) + add_test(NAME gguf_geometry_test COMMAND gguf_geometry_test) + + # the hipBLASLt tuning header's architecture gate: RDNA4 siblings share solution IDs, RDNA3 siblings share + # theirs, cross-family pairs and version mismatches stay rejected (synthetic tables: no model, no GPU) + add_executable(tuning_header_arch_family_test tests/prefill/tuning_header_arch_family_test.cpp) + target_include_directories(tuning_header_arch_family_test PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src/prefill") + add_test(NAME tuning_header_arch_family_test COMMAND tuning_header_arch_family_test) + + # the auto layer split's minimum stage size (#1616): header-only rule, no GPU + add_executable(split_rules_test tests/program/split_rules_test.cpp) + target_include_directories(split_rules_test PRIVATE include) + add_test(NAME split_rules_test COMMAND split_rules_test) + + # the prompt planner's host-memory model (#2824): header-only, no GPU + add_executable(prefill_plan_test tests/program/prefill_plan_test.cpp) + target_include_directories(prefill_plan_test PRIVATE include) + add_test(NAME prefill_plan_test COMMAND prefill_plan_test) + + # the default CPU prefill share is not armed when every expert is resident (#1595): header-only rule, no GPU + add_executable(share_rules_test tests/prefill/share_rules_test.cpp) + target_include_directories(share_rules_test PRIVATE include) + add_test(NAME share_rules_test COMMAND share_rules_test) + + # the Windows HIP auto prefill chunk cap (#1630) and the commit-limit verdict (#1607): header-only, no GPU + add_executable(host_limits_test tests/platform/host_limits_test.cpp) + target_include_directories(host_limits_test PRIVATE include) + add_test(NAME host_limits_test COMMAND host_limits_test) endif() # ---- strata_plan ---------------------------------------------------------- @@ -201,6 +355,8 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_library(strata_core STATIC src/core/device.cu src/core/pinned.cu src/platform/memory.cpp src/core/graph.cpp src/core/weights.cpp src/core/layout.cpp) target_include_directories(strata_core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) + # the DFlash2 drafter (src/core/dflash2.cpp, src/kernels/cuda/dflash2.cu) exists in the CUDA and HIP builds; the Metal and SYCL builds compile without it + target_compile_definitions(strata_core PUBLIC STRATA_HAVE_DFLASH2=1) if(STRATA_ENABLE_CUDA AND STRATA_EXPERIMENTAL_SM60) # the runtime device check (src/core/device.cu) admits the cards this build was made for (#236) target_compile_definitions(strata_core PRIVATE STRATA_EXPERIMENTAL_SM60=1) @@ -241,6 +397,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) # reference is the whole point - a kernel checked against another copy of itself proves nothing. add_library(strata_kernels STATIC src/kernels/cuda/dequant_s2.cu src/kernels/cuda/s2_gemv.cu src/kernels/cuda/s_gemv.cu + src/kernels/cuda/s_gemv_pair.cu src/kernels/cuda/s2_gemv_quads.cu src/kernels/cuda/s2_gemv_fast.cu src/kernels/cuda/router_top10.cu @@ -262,6 +419,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) src/kernels/cuda/native_gdn.cu src/kernels/cuda/native_gr_postops.cu src/kernels/cuda/native_router.cu + src/kernels/cuda/route_prior.cu src/kernels/cuda/native_gdn_preprocess.cu src/kernels/cuda/native_qsa.cu src/kernels/cuda/native_rope.cu @@ -282,6 +440,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) src/kernels/cuda/dequant_bf16.cu src/kernels/cuda/qsa_select.cu src/kernels/cuda/verify_kernels.cu + src/kernels/cuda/dflash2.cu src/kernels/cuda/iq_kernels.cu src/kernels/ngram.cpp src/ngram/ple_reader.cpp @@ -316,6 +475,21 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_executable(strata_next_kar_ple_probe "${STRATA_NEXT_KAR_DIR}/src/kar_ple_cpu_probe.cpp") target_link_libraries(strata_next_kar_ple_probe PRIVATE strata_kernels) endif() + # Exact gfx1100 prompt scorer (PR1825 method port): optional standalone test, + # also available where the published source omits tests/. + option(STRATA_PARITY_GFX1100_QSA_SCORES "Build the exact gfx1100 QSA score/ID check" OFF) + if(STRATA_ENABLE_HIP AND (STRATA_BUILD_TESTS OR STRATA_PARITY_GFX1100_QSA_SCORES)) + set_source_files_properties(src/kernels/cuda/qsa_scores_gfx1100_test.cu + src/kernels/qsa_scores_gfx1100_parity.cpp PROPERTIES LANGUAGE HIP) + add_executable(qsa_scores_gfx1100_parity src/kernels/qsa_scores_gfx1100_parity.cpp + src/kernels/cuda/qsa_scores_gfx1100_test.cu) + target_include_directories(qsa_scores_gfx1100_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(qsa_scores_gfx1100_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + enable_testing() + add_test(NAME qsa_scores_gfx1100_parity COMMAND qsa_scores_gfx1100_parity --full) + set_tests_properties(qsa_scores_gfx1100_parity PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 180 + ENVIRONMENT "STRATA_SCORES_THREAD=1;STRATA_SCORES_THREAD_TRACE=1") + endif() # perf-review D-1: the tensor-core prompt attention vs the FP32 kernel and FP64 (GPU, synthetic, no model); with # the tests, or alone with -DSTRATA_PARITY_PROMPT_ATTN=ON. CUDA only: HIP compiles the tensor-core kernel out. if((STRATA_BUILD_TESTS OR STRATA_PARITY_PROMPT_ATTN) AND STRATA_ENABLE_CUDA) @@ -323,6 +497,56 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_include_directories(qsa_prompt_attn_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) target_link_libraries(qsa_prompt_attn_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) endif() + # PR #600: the Volta (sm_70) prompt attention's latency pipeline against the FP32 kernel it replaces. Only in the + # experimental sm_60/sm_70 build, where prompt_attn_v70_kernel is compiled in. + if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA AND STRATA_EXPERIMENTAL_SM60) + add_executable(qsa_prompt_attn_sm70_bench bench/qsa_prompt_attn_sm70_bench.cpp) + target_include_directories(qsa_prompt_attn_sm70_bench PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) + target_link_libraries(qsa_prompt_attn_sm70_bench PRIVATE strata_kernels CUDA::cudart) + endif() + # #512: the top-k's active-block bound (Turing's dispatch, forced on any card by STRATA_TOPK_ACTIVE_ANY) against + # the capacity rule, selected ids bitwise + if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA) + add_executable(qsa_topk_active_parity src/kernels/qsa_topk_active_parity.cpp) + target_include_directories(qsa_topk_active_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) + target_link_libraries(qsa_topk_active_parity PRIVATE strata_kernels CUDA::cudart) + add_test(NAME qsa_topk_active_parity COMMAND qsa_topk_active_parity) + set_tests_properties(qsa_topk_active_parity PROPERTIES SKIP_RETURN_CODE 77) + # STRATA_QSA_SLOTS: a batch window's scores, top-k and attention as one launch over rows of different slots + # against one call per row, bitwise (synthetic, no model) + add_executable(qsa_slots_parity src/kernels/qsa_slots_parity.cpp) + target_include_directories(qsa_slots_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) + target_link_libraries(qsa_slots_parity PRIVATE strata_kernels CUDA::cudart) + add_test(NAME qsa_slots_parity COMMAND qsa_slots_parity) + add_test(NAME qsa_slots_parity_lanecell COMMAND qsa_slots_parity) + set_tests_properties(qsa_slots_parity qsa_slots_parity_lanecell PROPERTIES SKIP_RETURN_CODE 77) + set_tests_properties(qsa_slots_parity_lanecell PROPERTIES ENVIRONMENT "STRATA_ATTN_LANECELL=1") + # fork: the Daily's decode attention (STRATA_ATTN_DAILY=1: PR #540's chunk kernel on every card and the bounded + # merge) against upstream's kernels, bitwise; the production entries checked with the variable off and on + add_executable(qsa_merge_daily_parity src/kernels/qsa_merge_daily_parity.cpp) + target_include_directories(qsa_merge_daily_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) + target_link_libraries(qsa_merge_daily_parity PRIVATE strata_kernels CUDA::cudart) + add_test(NAME qsa_merge_daily_parity_default COMMAND qsa_merge_daily_parity) + add_test(NAME qsa_merge_daily_parity_daily COMMAND qsa_merge_daily_parity) + set_tests_properties(qsa_merge_daily_parity_default PROPERTIES ENVIRONMENT "STRATA_ATTN_DAILY=0" + SKIP_RETURN_CODE 77) + set_tests_properties(qsa_merge_daily_parity_daily PROPERTIES ENVIRONMENT "STRATA_ATTN_DAILY=1" + SKIP_RETURN_CODE 77) + # the prompt path's block scores on the thread-per-head kernel (Turing) against the warp kernel, bitwise + add_executable(qsa_scores_parity src/kernels/qsa_scores_parity.cpp) + target_include_directories(qsa_scores_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) + target_link_libraries(qsa_scores_parity PRIVATE strata_kernels CUDA::cudart) + add_test(NAME qsa_scores_parity COMMAND qsa_scores_parity) + set_tests_properties(qsa_scores_parity PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "STRATA_SCORES_THREAD=1") + endif() + # QSAROWS (docs/QSAROWS.md): what the T rows of a verification window cost in a QSA layer's decode kernels at a long + # context (block scores, top-k, attention over each row's selection, indexer append), row by row; GPU, synthetic, no + # model. Not in the default build: `cmake --build --target qsa_rows_bench`. + if(STRATA_ENABLE_CUDA) + add_executable(qsa_rows_bench EXCLUDE_FROM_ALL src/kernels/qsa_rows_bench.cpp) + target_include_directories(qsa_rows_bench PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) + target_link_libraries(qsa_rows_bench PRIVATE strata_kernels CUDA::cudart) + endif() # the QSA selection (block scores on the warp kernel and the tensor-core one, top-k): a GPU bench with a # scorer-vs-scorer comparison and an FP64 accuracy gate (synthetic, no model); the ctest runs a 32K context under a # 262144-cell capacity (the top-k dispatch follows the capacity) and exits non-zero on a failed gate @@ -331,6 +555,24 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) set_source_files_properties(src/kernels/qsa_select_bench.cpp PROPERTIES LANGUAGE HIP) target_link_libraries(qsa_select_bench PRIVATE strata_kernels strata_hip_runtime) add_test(NAME qsa_select_bench COMMAND qsa_select_bench 32768 256 3 262144) + # the FP32 tiled scorer (STRATA_SELECT_SIMT=1) on HIP: FP64 gate and selections against the warp kernel at 131K + add_test(NAME qsa_select_bench_fp32_tiled COMMAND qsa_select_bench 131072 256 3 262144) + set_tests_properties(qsa_select_bench_fp32_tiled PROPERTIES ENVIRONMENT "STRATA_SELECT_SIMT=1") + endif() + # the same on CUDA: the tensor-core scorer (sm_80+) or the FP32 tiled one (below sm_80, and forced on any card by + # STRATA_QSA_WARP=1 in the second test) against the warp kernel and FP64, at 32K and 131K + if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA) + add_executable(qsa_select_bench src/kernels/qsa_select_bench.cpp) + target_include_directories(qsa_select_bench PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) + target_link_libraries(qsa_select_bench PRIVATE strata_kernels CUDA::cudart) + add_test(NAME qsa_select_bench COMMAND qsa_select_bench 32768 256 3 262144) + add_test(NAME qsa_select_bench_fp32_tiled COMMAND qsa_select_bench 131072 256 3 262144) + set_tests_properties(qsa_select_bench_fp32_tiled PROPERTIES ENVIRONMENT "STRATA_QSA_WARP=1;STRATA_SELECT_SIMT=1") + endif() + if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA) # the prompt attention on a recorded selection (STRATA_QSA_DUMP) + add_executable(pa_bench tests/cuda/pa_bench.cpp) + target_include_directories(pa_bench PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) + target_link_libraries(pa_bench PRIVATE strata_kernels CUDA::cudart) endif() # plan v0.3 P6: llama.cpp's block layouts and codebook grids for the i-quant formats (MIT, third_party/ggml) target_include_directories(strata_kernels PRIVATE third_party/ggml) @@ -349,7 +591,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) src/kernels/cuda/native_flash_attn.cu src/kernels/cuda/native_qsa_indexer.cu src/kernels/cuda/native_qsa_score.cu - PROPERTIES COMPILE_OPTIONS "--use_fast_math") + PROPERTIES COMPILE_OPTIONS "$,,--use_fast_math>") elseif(STRATA_ENABLE_HIP) # Keep Q8_K's multiply and magic-bias rounding as separate FP32 operations on HIP; contraction to an # FMA changes tie results. The embedding gather also relies on separately rounded operations. @@ -388,10 +630,36 @@ 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/keyless.cpp 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/conversation_snapshot.cpp src/core/conversation_state.cpp src/core/conversation_memory.cpp) + src/core/remote_expert_opt.cu + 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/dflash2.cpp + src/core/conversation_snapshot.cpp src/core/conversation_state.cpp src/core/conversation_memory.cpp src/core/peer_experts.cpp + src/core/arch_defaults.cpp src/core/nv_defaults.cpp src/core/vmm.cpp src/core/conversation_file.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(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA AND NOT STRATA_HIP_GFX906) + add_executable(host_graph_launch_test tests/core/host_graph_launch_test.cu) + target_include_directories(host_graph_launch_test PRIVATE include) + target_link_libraries(host_graph_launch_test PRIVATE CUDA::cudart Threads::Threads) + add_test(NAME host_graph_launch_test COMMAND host_graph_launch_test) + set_tests_properties(host_graph_launch_test PROPERTIES TIMEOUT 30) + endif() + if(STRATA_BUILD_TESTS AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/exchange_storage_test.cpp") + add_executable(exchange_storage_test tests/core/exchange_storage_test.cpp) + target_include_directories(exchange_storage_test PRIVATE include) + target_link_libraries(exchange_storage_test PRIVATE Threads::Threads) + add_test(NAME exchange_storage_test COMMAND exchange_storage_test) + set_tests_properties(exchange_storage_test PROPERTIES TIMEOUT 60) + endif() + + # available_host_bytes(): MemAvailable, cgroup limits and the operator's --memory-limit-mib cap on fixture directories + # - no GPU, no CUDA + if(STRATA_BUILD_TESTS AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/memory_guard_test.cpp") + add_executable(memory_guard_test tests/core/memory_guard_test.cpp src/core/conversation_memory.cpp) + target_include_directories(memory_guard_test PRIVATE include) + add_test(NAME memory_guard_test COMMAND memory_guard_test) + set_tests_properties(memory_guard_test PROPERTIES TIMEOUT 60) + endif() + option(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS "Build the opt-in KAR native decode cache-miss arm" OFF) if(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) if(NOT STRATA_ENABLE_CUDA OR NOT CMAKE_SYSTEM_NAME STREQUAL "Linux") @@ -422,6 +690,41 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(file_expert_source_test PRIVATE strata_engine) add_test(NAME file_expert_source_test COMMAND file_expert_source_test) set_tests_properties(file_expert_source_test PROPERTIES TIMEOUT 60) + add_executable(vmm_test tests/core/vmm_test.cpp) + target_link_libraries(vmm_test PRIVATE strata_engine) + add_test(NAME vmm_test COMMAND vmm_test) + set_tests_properties(vmm_test PROPERTIES TIMEOUT 60) + # The resident RAM mode with a layer split: the copy keeps each stage's lend region, and the experts the + # prompt path borrows are served from RAM (the file source reads none of them). The device calls are + # wrapped - conversation_transfer_test's pattern - and `pin = false` keeps the copy pageable, so this + # runs on a CPU-only PC. + if(NOT STRATA_ENABLE_HIP AND UNIX AND NOT APPLE AND CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") + add_executable(split_lend_complement_test tests/core/split_lend_complement_test.cpp) + target_link_libraries(split_lend_complement_test PRIVATE strata_engine) + target_link_options(split_lend_complement_test PRIVATE + -Wl,--wrap=cudaMalloc -Wl,--wrap=cudaFree -Wl,--wrap=cudaMemset -Wl,--wrap=cudaMemcpy + -Wl,--wrap=cudaMemcpyAsync -Wl,--wrap=cudaStreamSynchronize -Wl,--wrap=cudaDeviceSynchronize + -Wl,--wrap=cudaGetLastError -Wl,--wrap=cudaGetDevice -Wl,--wrap=cudaSetDevice + -Wl,--wrap=cudaMemGetInfo -Wl,--wrap=cudaHostAlloc -Wl,--wrap=cudaFreeHost) + add_test(NAME split_lend_complement_test COMMAND split_lend_complement_test) + set_tests_properties(split_lend_complement_test PROPERTIES ENVIRONMENT "CUDA_VISIBLE_DEVICES=-1" TIMEOUT 120) + endif() + endif() + # #477: the learned expert profile (--expert-profile-save): its order and make_profile.py's file format (CPU only) + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/expert_profile_save_test.cpp") + enable_testing() + add_executable(expert_profile_save_test tests/core/expert_profile_save_test.cpp) + target_link_libraries(expert_profile_save_test PRIVATE strata_engine) + add_test(NAME expert_profile_save_test COMMAND expert_profile_save_test) + set_tests_properties(expert_profile_save_test PROPERTIES TIMEOUT 60) + endif() + # the profile header's version is enforced: a version other than 1 is refused by its number (CPU only) + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/expert_profile_version_test.cpp") + enable_testing() + add_executable(expert_profile_version_test tests/core/expert_profile_version_test.cpp) + target_link_libraries(expert_profile_version_test PRIVATE strata_engine) + add_test(NAME expert_profile_version_test COMMAND expert_profile_version_test) + set_tests_properties(expert_profile_version_test PROPERTIES TIMEOUT 60) endif() if(STRATA_BUILD_TESTS AND STRATA_NATIVE_EXPERTS) # native_experts.txt v2-v4 (the real packs' copies and the per-role shard column) and the arena filled from @@ -440,6 +743,16 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(expert_cache_per_layer_test PRIVATE strata_engine) add_test(NAME expert_cache_per_layer_test COMMAND expert_cache_per_layer_test) set_tests_properties(expert_cache_per_layer_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + add_executable(expert_cache_segmented_test tests/core/expert_cache_segmented_test.cpp) + target_link_libraries(expert_cache_segmented_test PRIVATE strata_engine) + add_test(NAME expert_cache_segmented_test COMMAND expert_cache_segmented_test) + set_tests_properties(expert_cache_segmented_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + # STRATA_MMQ_DIRECT: slot_guard / slot_room / slot_tail on the uniform and the sized cache, and the default + # (no guard) sized layout unchanged + add_executable(expert_cache_slot_guard_test tests/core/expert_cache_slot_guard_test.cpp) + target_link_libraries(expert_cache_slot_guard_test PRIVATE strata_engine) + add_test(NAME expert_cache_slot_guard_test COMMAND expert_cache_slot_guard_test) + set_tests_properties(expert_cache_slot_guard_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) endif() if(STRATA_BUILD_CONVERSATION_TESTS) add_executable(keyless_stream_parity src/kernels/kv_stream_parity.cpp) @@ -458,7 +771,9 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) 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) + -Wl,--wrap=cudaMemcpy -Wl,--wrap=cudaMemcpyAsync -Wl,--wrap=cudaStreamSynchronize + -Wl,--wrap=cudaGetDevice -Wl,--wrap=cudaStreamCreateWithFlags + -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) @@ -470,8 +785,17 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) # against llama.cpp on the SAME ids and a tokenizer on one side of that comparison is a second variable. # plan v0.3 P5: batched prompt processing (tensor-core GEMMs through cuBLAS). add_library(strata_prefill STATIC src/prefill/gemm.cu src/prefill/kernels.cu src/prefill/prefill.cpp) + if(STRATA_ENABLE_HIP) + # #313: the RDNA3 WMMA GEMMs include hip_runtime.h: AMD builds only (a CUDA build never sees this file) + target_sources(strata_prefill PRIVATE src/prefill/wmma_gemm.cu) + endif() target_include_directories(strata_prefill PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories}) target_link_libraries(strata_prefill PUBLIC strata_engine ${_strata_gpu_blas_target} ${_strata_gpu_runtime_target}) + if(STRATA_ENABLE_CUDA) + # v100/gdn-chunk: the chunked Volta GDN prompt recurrence. The dispatch (src/prefill/kernels.cu) is + # Volta-only (cc 7.0) and gated on STRATA_EXPERIMENTAL_SM60; the path itself stays opt-in (STRATA_GDN_CHUNK). + target_sources(strata_prefill PRIVATE src/prefill/gdn_chunk.cu) + endif() if(STRATA_ENABLE_HIP AND STRATA_HIPBLASLT_AVAILABLE) target_compile_definitions(strata_prefill PRIVATE STRATA_HIPBLASLT_AVAILABLE=1) target_link_libraries(strata_prefill PRIVATE roc::hipblaslt) @@ -479,18 +803,201 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_executable(tune_hipblaslt tools/hip/tune_hipblaslt.cpp) target_link_libraries(tune_hipblaslt PRIVATE hip::host roc::hipblas roc::hipblaslt) endif() + if(STRATA_ENABLE_HIP AND STRATA_ROCBLAS_AVAILABLE) + # the prompt path's rocBLAS solution table (STRATA_ROCBLAS_TUNING; tools/hip/tune_rocblas makes one) + target_compile_definitions(strata_prefill PRIVATE STRATA_ROCBLAS_AVAILABLE=1) + target_link_libraries(strata_prefill PRIVATE roc::rocblas) + + add_executable(tune_rocblas tools/hip/tune_rocblas.cpp) + target_link_libraries(tune_rocblas PRIVATE hip::host roc::rocblas) + endif() + + # DFlash2 drafter tools (not built by default: cmake --build --target dflash2_parity dflash2_gemm_bench dflash2_attn_bench): the drafter against + # the torch port on a synthetic case (needs the pack and a case file, tools/dflash2/mk_parity_case.py), and the timing of its Q8 GEMM and attention + add_executable(dflash2_parity EXCLUDE_FROM_ALL src/core/dflash2_parity.cpp) + target_include_directories(dflash2_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(dflash2_parity PRIVATE strata_engine strata_kernels ${_strata_gpu_runtime_target}) + add_executable(dflash2_gemm_bench EXCLUDE_FROM_ALL src/core/dflash2_gemm_bench.cpp) + target_include_directories(dflash2_gemm_bench PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(dflash2_gemm_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_executable(dflash2_launch_bench EXCLUDE_FROM_ALL src/core/dflash2_launch_bench.cu) + target_include_directories(dflash2_launch_bench PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(dflash2_launch_bench PRIVATE ${_strata_gpu_runtime_target}) + add_executable(dflash2_bw_bench EXCLUDE_FROM_ALL src/core/dflash2_bw_bench.cu) + target_include_directories(dflash2_bw_bench PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(dflash2_bw_bench PRIVATE ${_strata_gpu_runtime_target}) + add_executable(dflash2_small_bench EXCLUDE_FROM_ALL src/core/dflash2_small_bench.cpp) + target_include_directories(dflash2_small_bench PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(dflash2_small_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_executable(dflash2_attn_bench EXCLUDE_FROM_ALL src/core/dflash2_attn_bench.cpp) + target_include_directories(dflash2_attn_bench PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(dflash2_attn_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_executable(strata src/program/generate.cpp) + strata_utf8_manifest(strata) target_include_directories(strata PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(strata PRIVATE strata_engine strata_prefill strata_spec ${_strata_gpu_runtime_target}) if(STRATA_CUDA_STATIC) target_link_options(strata PRIVATE -static-libstdc++ -static-libgcc) set_target_properties(strata PROPERTIES SKIP_BUILD_RPATH TRUE INSTALL_RPATH "") endif() + if(WIN32 AND STRATA_ENABLE_HIP) + # 0.2.1.2: the ROCm math libraries live in \rocm\bin, which is on PATH only when the launcher starts the engine; load them on first + # use (main() adds that folder to the DLL search first) so `strata.exe --version` works from the package folder. amdhip64_7.dll and the + # C++ runtime sit beside the exe (tools/hip/package_windows.py) and stay normal imports. + target_link_libraries(strata PRIVATE delayimp) + target_link_options(strata PRIVATE "LINKER:/DELAYLOAD:hipblas.dll" "LINKER:/DELAYLOAD:libhipblaslt.dll" "LINKER:/DELAYLOAD:rocblas.dll") + endif() + + # NEW-MODELS-PLAN.md T1: Qwen3.6-35B-A3B's reference path (one GPU, the model resident, plain kernels), checked + # against llama.cpp by tools/qwen35/; the engine itself does not run the family yet + add_executable(strata-q36ref src/qwen35/q36ref.cu) + target_include_directories(strata-q36ref PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories}) + target_link_libraries(strata-q36ref PRIVATE strata_kernels strata_warnings ${_strata_gpu_runtime_target}) + # the engine path for the same family (serve protocol, prompt chunks, decode graph): src/qwen35/q36_engine.cu, a + # library that `strata` switches to for a qwen35moe model (the family switch at the top of its main) and that + # strata-q36 wraps on its own. Not on gfx906 (#3172, #3271): it calls cuBLAS entry points the wave64 compat layer does + # not map (cublasSgemm, cublasGemmStridedBatchedEx) and its kernels assume 32-lane warps; main() guards every use with + # STRATA_HAVE_QWEN35, so a gfx906 build links and runs the Qwen3.8 family, and `strata --families` says so + if(NOT STRATA_HIP_GFX906) + add_library(strata_qwen35 STATIC src/qwen35/q36_engine.cu) + target_include_directories(strata_qwen35 PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(strata_qwen35 PRIVATE strata_prefill strata_kernels strata_warnings ${_strata_gpu_runtime_target}) + if(STRATA_NATIVE_EXPERTS) + # the hybrid mode (experts that do not all fit in VRAM): the CPU expert pool on ggml-cpu's arithmetic + target_link_libraries(strata_qwen35 PRIVATE strata_kernels_cpu) + target_compile_definitions(strata_qwen35 PRIVATE STRATA_Q36_CPU_POOL=1) + endif() + add_executable(strata-q36 src/qwen35/q36_main.cpp) + strata_utf8_manifest(strata-q36) + target_link_libraries(strata-q36 PRIVATE strata_qwen35 ${_strata_gpu_runtime_target}) + target_link_libraries(strata PRIVATE strata_qwen35) + target_compile_definitions(strata PRIVATE STRATA_HAVE_QWEN35=1) + endif() + + # DeepSeek-V4.1-Flash: the third engine path (src/dsv41, from Project Maya's maya-ds4, MIT, third_party/project-maya). + # Its own executable for now (strata-dsv41); a family switch in `strata` comes after first light. OFF by default: it + # changes no existing target (the vendored kernels live in strata::dsv41k, so no symbol is shared with strata_kernels). + option(STRATA_BUILD_DSV41 "Build the DeepSeek-V4.1 engine path (strata-dsv41)" OFF) + if(STRATA_BUILD_DSV41 AND NOT STRATA_HIP_GFX906) + add_library(strata_dsv41_kernels STATIC src/dsv41/vendor/exl3.cu src/dsv41/vendor/sampler.cu src/dsv41/vendor/moe_win.cu + src/dsv41/vendor/exl3_cpu.cpp) + if(NOT STRATA_ENABLE_HIP) # (the pre-sm_80 NVIDIA decode kernels exl3.cu dispatches to) + target_sources(strata_dsv41_kernels PRIVATE src/dsv41/vendor/exl3_legacy.cu) + endif() + target_include_directories(strata_dsv41_kernels PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories}) + target_link_libraries(strata_dsv41_kernels PUBLIC ${_strata_gpu_runtime_target}) + add_executable(strata-dsv41 src/dsv41/ds4_main.cpp src/dsv41/ds4_model.cu src/dsv41/ds4_kernels.cu src/dsv41/ds4_vision.cu + src/dsv41/ds4_gguf.cu src/dsv41/ds4_gguf_cpu.cpp src/dsv41/ds4_iq.cu src/dsv41/ds4_iq_cpu.cpp + src/dsv41/ds4_tq.cu src/dsv41/ds4_tq_cpu.cpp src/dsv41/ds4_gg_cpu.cpp src/dsv41/ds4_packinfo.cpp) + # the commit the binary was built from, readable with --version (set -DSTRATA_BUILD_ID=... for a tree without .git) + if(NOT STRATA_BUILD_ID AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/BUILD_ID) # (a git archive has no .git: the packer writes the commit here) + file(STRINGS ${CMAKE_CURRENT_SOURCE_DIR}/BUILD_ID STRATA_BUILD_ID LIMIT_COUNT 1) + endif() + if(NOT STRATA_BUILD_ID) + execute_process(COMMAND git -C ${CMAKE_CURRENT_SOURCE_DIR} rev-parse --short=9 HEAD OUTPUT_VARIABLE STRATA_BUILD_ID + OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET) + endif() + if(NOT STRATA_BUILD_ID) + set(STRATA_BUILD_ID unknown) + endif() + set_source_files_properties(src/dsv41/ds4_main.cpp PROPERTIES COMPILE_DEFINITIONS "DS4_BUILD_ID=\"${STRATA_BUILD_ID}\"") + target_include_directories(strata-dsv41 PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories} + ${CMAKE_CURRENT_SOURCE_DIR}/third_party/ggml) + target_link_libraries(strata-dsv41 PRIVATE strata_dsv41_kernels ${_strata_gpu_runtime_target} ${_strata_gpu_blas_target}) + find_package(Threads REQUIRED) + target_link_libraries(strata-dsv41 PRIVATE Threads::Threads) + if(WIN32 AND STRATA_ENABLE_HIP) # cudaMemGetInfo is the DXGI-budgeted hip_compat::mem_get_info (src/core/device.cu): on a Strix Halo the + # carve-out is not all the GPU may use, and the engine sizes its expert tiers by what the budget says is free + target_link_libraries(strata-dsv41 PRIVATE strata_core) + endif() + if(STRATA_NATIVE_EXPERTS) # Strata's CPU trellis kernels (tq_cpu.hpp) for the trellis experts on the CPU lane + target_link_libraries(strata-dsv41 PRIVATE strata_kernels_cpu) + target_compile_definitions(strata-dsv41 PRIVATE STRATA_DSV41_TQ_CPU=1) + endif() + if(STRATA_NATIVE_EXPERTS) + # the CPU lane's ggml-type rows: ggml-cpu's dots against Strata's AVX2 i-quant rows (bits and GB/s); no GPU, no model + add_executable(ds4_gg_bench tests/dsv41/gg_dot_bench.cpp src/dsv41/ds4_gg_cpu.cpp) + target_include_directories(ds4_gg_bench PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_SOURCE_DIR}/src/dsv41 + ${CMAKE_CURRENT_SOURCE_DIR}/third_party/ggml) + target_link_libraries(ds4_gg_bench PRIVATE strata_kernels_cpu Threads::Threads) + target_compile_definitions(ds4_gg_bench PRIVATE STRATA_DSV41_TQ_CPU=1) + endif() + if(STRATA_NATIVE_EXPERTS) + # the trellis experts (device kernels ds4_tq.cu, CPU lane ds4_tq_cpu.cpp) against a double reference; needs a GPU, no model + # both test .cpp files launch kernels, so they compile as HIP on the AMD backend and as CUDA on the NVIDIA one + if(STRATA_ENABLE_HIP) + set(_ds4_test_lang HIP) + elseif(STRATA_ENABLE_CUDA) + set(_ds4_test_lang CUDA) + else() + set(_ds4_test_lang CXX) + endif() + set_source_files_properties(tests/dsv41/tq_expert_test.cpp PROPERTIES LANGUAGE ${_ds4_test_lang}) + add_executable(ds4_tq_test tests/dsv41/tq_expert_test.cpp src/dsv41/ds4_tq.cu src/dsv41/ds4_iq.cu src/dsv41/ds4_tq_cpu.cpp + src/dsv41/ds4_iq_cpu.cpp src/dsv41/ds4_gg_cpu.cpp tools/trellis/tqenc.cpp) + target_include_directories(ds4_tq_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories} + ${CMAKE_CURRENT_SOURCE_DIR}/third_party/ggml ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/cpu) + target_link_libraries(ds4_tq_test PRIVATE strata_kernels_cpu ${_strata_gpu_runtime_target} Threads::Threads) + target_compile_definitions(ds4_tq_test PRIVATE STRATA_DSV41_TQ_CPU=1) + # the same with the plain-FMA tile instead of the gfx12 WMMA one (what CUDA and gfx11 builds run) + add_executable(ds4_tq_test_portable tests/dsv41/tq_expert_test.cpp src/dsv41/ds4_tq.cu src/dsv41/ds4_iq.cu src/dsv41/ds4_tq_cpu.cpp + src/dsv41/ds4_iq_cpu.cpp src/dsv41/ds4_gg_cpu.cpp tools/trellis/tqenc.cpp) + target_include_directories(ds4_tq_test_portable PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories} + ${CMAKE_CURRENT_SOURCE_DIR}/third_party/ggml ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/cpu) + target_link_libraries(ds4_tq_test_portable PRIVATE strata_kernels_cpu ${_strata_gpu_runtime_target} Threads::Threads) + target_compile_definitions(ds4_tq_test_portable PRIVATE STRATA_DSV41_TQ_CPU=1 DS4_TQ_PORTABLE=1) + if(STRATA_ENABLE_HIP) + target_compile_options(ds4_tq_test_portable PRIVATE "$<$:SHELL:-include ${CMAKE_CURRENT_SOURCE_DIR}/include/strata/dsv41/hip_extra.h>") + endif() + if(STRATA_ENABLE_HIP) + target_compile_options(ds4_tq_test PRIVATE "$<$:SHELL:-include ${CMAKE_CURRENT_SOURCE_DIR}/include/strata/dsv41/hip_extra.h>") + endif() + # the i-quant experts (ds4_iq.cu) against ggml's own decode of the same blocks + a double reference, device and CPU + # lane, for every type the device takes: the gate a new type (IQ2_XS ..) has to pass before the engine uses it + set_source_files_properties(tests/dsv41/iq_expert_test.cpp PROPERTIES LANGUAGE ${_ds4_test_lang}) + add_executable(ds4_iq_test tests/dsv41/iq_expert_test.cpp src/dsv41/ds4_iq.cu src/dsv41/ds4_iq_cpu.cpp + src/dsv41/ds4_gg_cpu.cpp src/dsv41/ds4_tq.cu src/dsv41/ds4_tq_cpu.cpp) + target_include_directories(ds4_iq_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories} + ${CMAKE_CURRENT_SOURCE_DIR}/third_party/ggml ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/cpu) + target_link_libraries(ds4_iq_test PRIVATE strata_kernels_cpu ${_strata_gpu_runtime_target} Threads::Threads) + target_compile_definitions(ds4_iq_test PRIVATE STRATA_DSV41_TQ_CPU=1) + if(STRATA_ENABLE_HIP) + target_compile_options(ds4_iq_test PRIVATE "$<$:SHELL:-include ${CMAKE_CURRENT_SOURCE_DIR}/include/strata/dsv41/hip_extra.h>") + endif() + # the kept conversations' .meta file and prefix matching (ds4_slotmeta.hpp): no GPU, no model + add_executable(ds4_slot_test tests/dsv41/slot_test.cpp) + target_include_directories(ds4_slot_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/dsv41) + target_compile_features(ds4_slot_test PRIVATE cxx_std_17) + add_executable(ds4_experts_rule_test tests/dsv41/experts_rule_test.cpp) + target_include_directories(ds4_experts_rule_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/dsv41) + target_compile_features(ds4_experts_rule_test PRIVATE cxx_std_17) + add_executable(ds4_pick_rule_test tests/dsv41/pick_rule_test.cpp) + target_include_directories(ds4_pick_rule_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/dsv41) + target_compile_features(ds4_pick_rule_test PRIVATE cxx_std_17) + endif() + if(STRATA_ENABLE_HIP) + foreach(_t strata_dsv41_kernels strata-dsv41) + target_compile_options(${_t} PRIVATE "$<$:SHELL:-include ${CMAKE_CURRENT_SOURCE_DIR}/include/strata/dsv41/hip_extra.h>") + endforeach() + endif() + endif() if(STRATA_ENABLE_HIP) enable_testing() set(_strata_hip_tests) + add_executable(hip_prefill_gemm tests/hip/prefill_gemm.cpp) + target_link_libraries(hip_prefill_gemm PRIVATE strata_prefill strata_hip_runtime) + add_test(NAME hip_prefill_gemm COMMAND hip_prefill_gemm) + list(APPEND _strata_hip_tests hip_prefill_gemm) + add_executable(hip_gemm_f16_io_parity tests/hip/gemm_f16_io_parity.cpp) + target_link_libraries(hip_gemm_f16_io_parity PRIVATE strata_prefill strata_hip_runtime) + add_test(NAME hip_gemm_f16_io_parity COMMAND hip_gemm_f16_io_parity) + list(APPEND _strata_hip_tests hip_gemm_f16_io_parity) + add_executable(hip_q2_zero tests/hip/q2_zero.cpp) + target_link_libraries(hip_q2_zero PRIVATE strata_kernels strata_hip_runtime) + add_test(NAME hip_q2_zero COMMAND hip_q2_zero) + list(APPEND _strata_hip_tests hip_q2_zero) add_executable(hip_expert_cache_staging tests/hip/expert_cache_staging.cpp) target_link_libraries(hip_expert_cache_staging PRIVATE strata_engine) add_test(NAME hip_expert_cache_staging COMMAND hip_expert_cache_staging) @@ -528,6 +1035,33 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_test(NAME hip_prefill_native_batch COMMAND hip_prefill_native_batch) list(APPEND _strata_hip_tests hip_prefill_native_batch) endif() + # Aurora: the prompt GDN recurrence's per-head kernel against the column-split + norm kernels, bitwise + add_executable(hip_gdn_rec_head tests/hip/gdn_rec_head.cpp) + target_link_libraries(hip_gdn_rec_head PRIVATE strata_prefill strata_hip_runtime) + add_test(NAME hip_gdn_rec_head COMMAND hip_gdn_rec_head) + list(APPEND _strata_hip_tests hip_gdn_rec_head) + add_executable(hip_gdn_chunked tests/hip/gdn_chunked.cpp) + target_link_libraries(hip_gdn_chunked PRIVATE strata_prefill strata_hip_runtime) + add_test(NAME hip_gdn_chunked COMMAND hip_gdn_chunked) + add_test(NAME hip_gdn_chunked_off COMMAND hip_gdn_chunked --off) + add_test(NAME hip_gdn_chunked_default COMMAND hip_gdn_chunked --default) + list(APPEND _strata_hip_tests hip_gdn_chunked hip_gdn_chunked_off hip_gdn_chunked_default) + # #313: the RDNA3 / RDNA3.5 WMMA dense GEMMs (opt-in STRATA_WMMA_GEMM=1) against a reference + add_executable(hip_prefill_wmma_gemm_parity tests/hip/prefill_wmma_gemm_parity.cpp) + target_include_directories(hip_prefill_wmma_gemm_parity PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src/prefill") + target_link_libraries(hip_prefill_wmma_gemm_parity PRIVATE strata_prefill strata_hip_runtime) + add_test(NAME hip_prefill_wmma_gemm_parity COMMAND hip_prefill_wmma_gemm_parity) + set_tests_properties(hip_prefill_wmma_gemm_parity PROPERTIES SKIP_RETURN_CODE 77) # no matrix cores: skipped + list(APPEND _strata_hip_tests hip_prefill_wmma_gemm_parity) + # S (STRATA_HCD_EXACT): the exact HC down kernel against hipBLASLt solution 1176 / 1177 (needs STRATA_HIPBLASLT_TUNING; exit 77 else) + add_executable(hip_prefill_hcd_exact_parity tests/hip/prefill_hcd_exact_parity.cpp) + target_link_libraries(hip_prefill_hcd_exact_parity PRIVATE strata_prefill strata_hip_runtime) + add_test(NAME hip_prefill_hcd_exact_parity COMMAND hip_prefill_hcd_exact_parity) + set_tests_properties(hip_prefill_hcd_exact_parity PROPERTIES SKIP_RETURN_CODE 77) + list(APPEND _strata_hip_tests hip_prefill_hcd_exact_parity) + # the HC write-back kernel timed at the prompt path's shapes with an output checksum (not a ctest; STRATA_GRW_V picks a variant) + add_executable(hip_prefill_gr_write_bench tests/hip/prefill_gr_write_bench.cpp) + target_link_libraries(hip_prefill_gr_write_bench PRIVATE strata_prefill strata_hip_runtime) # S6: the AMD fast router against the portable kernel, bitwise add_executable(hip_router_fast tests/hip/router_fast.cpp) target_link_libraries(hip_router_fast PRIVATE strata_kernels strata_hip_runtime) @@ -547,6 +1081,15 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) set_tests_properties(hip_prefill_hipblaslt_gemm PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) list(APPEND _strata_hip_tests hip_prefill_hipblaslt_gemm) endif() + if(STRATA_ROCBLAS_AVAILABLE) + # the rocBLAS solution table of the FP16-out prompt GEMMs (gfx103x): opt-in, skips without STRATA_ROCBLAS_TUNING + add_executable(hip_prefill_rocblas_gemm tests/hip/prefill_rocblas_gemm.cpp) + target_include_directories(hip_prefill_rocblas_gemm PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src/prefill") + target_link_libraries(hip_prefill_rocblas_gemm PRIVATE strata_prefill strata_hip_runtime roc::rocblas roc::hipblas) + add_test(NAME hip_prefill_rocblas_gemm COMMAND hip_prefill_rocblas_gemm) + set_tests_properties(hip_prefill_rocblas_gemm PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + list(APPEND _strata_hip_tests hip_prefill_rocblas_gemm) + endif() if(_strata_hip_tests) set_tests_properties(${_strata_hip_tests} PROPERTIES TIMEOUT 60) endif() @@ -556,6 +1099,9 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) if(TARGET hip_prefill_hipblaslt_gemm) set_tests_properties(hip_prefill_hipblaslt_gemm PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endif() + if(TARGET hip_prefill_rocblas_gemm) + set_tests_properties(hip_prefill_rocblas_gemm PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endif() endif() add_executable(dequant_s2_parity src/kernels/dequant_s2_parity.cpp) @@ -624,6 +1170,34 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_include_directories(mmvq_multi_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(mmvq_multi_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME mmvq_multi_parity COMMAND mmvq_multi_parity) + if(STRATA_HIP_GFX906) # the CUDA layout, where the negative control has power (the wave64 one is exact at every T) + add_test(NAME mmvq_multi_parity_cuda_layout COMMAND mmvq_multi_parity) + set_tests_properties(mmvq_multi_parity_cuda_layout PROPERTIES ENVIRONMENT "STRATA_MMVQ_WAVE=0") + endif() + endif() + if(STRATA_ENABLE_CUDA) + # fork F4: the 2-4 column dense projections from the interleaved q8_1 copy, bitwise vs native_mmvq (GPU, synthetic) + add_executable(mmvq_il_parity src/kernels/mmvq_il_parity.cpp) + target_include_directories(mmvq_il_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(mmvq_il_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME mmvq_il_parity COMMAND mmvq_il_parity) + # the wide dequant kernels (a thread per 8 values; sm_61's default), bitwise vs the per-group ones (GPU, synthetic, + # no model; --bench adds old/new timings) + add_executable(dequant_wide_parity src/kernels/dequant_wide_parity.cpp) + target_include_directories(dequant_wide_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(dequant_wide_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME dequant_wide_parity COMMAND dequant_wide_parity) + endif() + # programmatic dependent launch (pdl.hpp) in a captured verify-shaped chain: bitwise vs ordinary launches over + # replays with poisoned buffers, and only kernel-to-kernel programmatic edges (GPU, synthetic, no model; the edges + # are only made on sm_90+, elsewhere it checks that there are none). NVIDIA only: PDL is a CUDA feature. + if(STRATA_ENABLE_CUDA AND NOT STRATA_HIP_GFX906) + add_executable(pdl_parity src/kernels/pdl_parity.cpp) + target_include_directories(pdl_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(pdl_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME pdl_parity COMMAND pdl_parity) + # PDL is opt-in (STRATA_DF_PDL); the test checks the opted-in path, whose PDL capture forces programmatic launches + set_tests_properties(pdl_parity PROPERTIES ENVIRONMENT "STRATA_DF_PDL=1") endif() # the IQ kernels that decode a weight part once for every column/entry, bitwise vs the per-column ones # (GPU, synthetic, no model; --bench adds old/new timings) @@ -631,11 +1205,107 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_include_directories(iq_multi_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(iq_multi_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME iq_multi_parity COMMAND iq_multi_parity) + # the Gyro trellis decode kernels (TQ2_T / TQK6 / TQK7) on synthetic blocks: decode-once vs per-column bitwise, output + # checksums to compare two builds byte for byte, --bench for timings (GPU, no model) + add_executable(tq_pascal_bench src/kernels/tq_pascal_bench.cpp) + target_include_directories(tq_pascal_bench PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(tq_pascal_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME tq_pascal_bench COMMAND tq_pascal_bench) + set_tests_properties(iq_multi_parity PROPERTIES ENVIRONMENT "STRATA_KQ_SPLIT=1") # the Q4_K / Q5_K / Q8_0 Split path against the old kernels + # the same Split path on the other routes it can meet: the generic multi kernels (no V2K) and the fused gate/up + SwiGLU kernel, and the sub-16-row + # gate/up route switched off (a K-quant row has 160 dots, not the 80 the sub-16 rows assume: STRATA_KQ_SPLIT=1 must stay bitwise on all of them) + add_test(NAME iq_multi_parity_kq_nov2k COMMAND iq_multi_parity) + set_tests_properties(iq_multi_parity_kq_nov2k PROPERTIES ENVIRONMENT "STRATA_KQ_SPLIT=1;STRATA_EXPERT_V2K=0") + add_test(NAME iq_multi_parity_kq_swiglu COMMAND iq_multi_parity) + set_tests_properties(iq_multi_parity_kq_swiglu PROPERTIES ENVIRONMENT "STRATA_KQ_SPLIT=1;STRATA_GU_SWIGLU=1") + add_test(NAME iq_multi_parity_kq_nosub16 COMMAND iq_multi_parity) + set_tests_properties(iq_multi_parity_kq_nosub16 PROPERTIES ENVIRONMENT "STRATA_KQ_SPLIT=1;STRATA_NO_SUB16_GU=1") + # the prompt path's DeltaNet recurrence: gdn_rec_kh_kernel against gdn_rec_cols_pipe_kernel, bitwise (GPU, + # synthetic, no model; --bench adds timings). NVIDIA only: cp.async and the CUDA occupancy API (not on gfx906) + if(STRATA_ENABLE_CUDA AND NOT STRATA_HIP_GFX906) + # Independent pinned expert uploads: byte parity and stream/event ordering. + add_executable(dma_batch_parity tests/core/dma_batch_parity.cu) + target_include_directories(dma_batch_parity PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include) + target_link_libraries(dma_batch_parity PRIVATE ${_strata_gpu_runtime_target}) + add_test(NAME dma_batch_parity COMMAND dma_batch_parity) + set_tests_properties(dma_batch_parity PROPERTIES TIMEOUT 120) + if(WIN32) + add_test(NAME dma_batch_registered_parity COMMAND dma_batch_parity --registered) + set_tests_properties(dma_batch_registered_parity PROPERTIES TIMEOUT 120) + endif() + add_executable(gdn_rec_parity src/prefill/gdn_rec_parity.cu) + target_link_libraries(gdn_rec_parity PRIVATE ${_strata_gpu_runtime_target}) + add_test(NAME gdn_rec_parity COMMAND gdn_rec_parity) + # the prompt path's BF16 products against cuBLAS's own BF16 GEMM, within fp32 rounding (sm_7x runs them on the + # FP16 tensor cores; GPU, synthetic, no model; --bench adds timings) + add_executable(gemm_bf16_parity src/prefill/gemm_bf16_parity.cu) + target_link_libraries(gemm_bf16_parity PRIVATE strata_prefill ) + add_test(NAME gemm_bf16_parity COMMAND gemm_bf16_parity) + # Pascal, opt-in STRATA_DENSE_F32=1: the dense projections' FP16 GEMMs as cublasSgemm on FP32 copies, bitwise vs + # the cuBLAS FP16 call over a sweep of chunk sizes (GPU, synthetic, no model; --full sweeps every size, --bench + # adds timings). Not a ctest: whether the two agree is a property of the cuBLAS build, which this checks. + add_executable(gemm_f32_parity src/prefill/gemm_f32_parity.cu) + target_link_libraries(gemm_f32_parity PRIVATE strata_prefill ) + # the hyper-connection read's fused up projection + mix (gr_upmix, STRATA_HC_UPMIX) against cuBLAS + gr_mix_r, + # bitwise where cuBLAS sums K in the same order, else within FP32 rounding and as close to FP64 (GPU, synthetic, + # no model; --bench adds timings) + add_executable(gr_upmix_parity src/prefill/gr_upmix_parity.cu) + target_link_libraries(gr_upmix_parity PRIVATE strata_prefill ) + add_test(NAME gr_upmix_parity COMMAND gr_upmix_parity) + set_tests_properties(gr_upmix_parity PROPERTIES SKIP_RETURN_CODE 77) + endif() + # native_expert_grouped's group stride and fused SwiGLU + q8_1, bitwise vs the launches before them (GPU, synthetic, + # no model; --bench adds v1/new timings of a window's 48 calls in a graph) + add_executable(native_grouped_parity src/kernels/native_grouped_parity.cpp) + target_include_directories(native_grouped_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(native_grouped_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME native_grouped_parity COMMAND native_grouped_parity) + add_executable(mmvf_rows_parity src/kernels/mmvf_rows_parity.cpp) + target_include_directories(mmvf_rows_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(mmvf_rows_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME mmvf_rows_parity COMMAND mmvf_rows_parity) + set_tests_properties(mmvf_rows_parity PROPERTIES ENVIRONMENT "STRATA_MMVF_ROWS=1" TIMEOUT 120) + if(STRATA_HIP_GFX906) + add_test(NAME native_grouped_fused_parity COMMAND native_grouped_parity) + set_tests_properties(native_grouped_fused_parity PROPERTIES + ENVIRONMENT "STRATA_HIP_SWIGLU_FUSED=1;STRATA_EXP_MODE=7" TIMEOUT 120) + add_executable(gfx906_gdn_rec_head tests/hip/gdn_rec_head.cpp) + target_include_directories(gfx906_gdn_rec_head PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(gfx906_gdn_rec_head PRIVATE strata_prefill ${_strata_gpu_runtime_target}) + add_test(NAME gfx906_gdn_rec_head COMMAND gfx906_gdn_rec_head) + set_tests_properties(gfx906_gdn_rec_head PROPERTIES TIMEOUT 120) + endif() + if(STRATA_ENABLE_CUDA) + # the Volta prompt experts (gemm_iq_f16_grouped, STRATA_PF_WMMA) against a double reference; skipped below sm_70 + add_executable(pf_wmma_parity src/kernels/pf_wmma_parity.cpp) + target_include_directories(pf_wmma_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(pf_wmma_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME pf_wmma_parity COMMAND pf_wmma_parity) + set_tests_properties(pf_wmma_parity PROPERTIES SKIP_RETURN_CODE 77) + endif() add_executable(shared_expert_parity src/kernels/shared_expert_parity.cpp) target_include_directories(shared_expert_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(shared_expert_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME shared_expert_parity COMMAND shared_expert_parity --selftest) - + # the split / batched verify-window kernels (from eddoursul's fork), bitwise vs the kernels they replace; CUDA only + if(STRATA_ENABLE_CUDA) + add_executable(verify_parity src/kernels/verify_parity.cpp) + target_include_directories(verify_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(verify_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME verify_parity COMMAND verify_parity --selftest) + endif() + add_executable(fused_gr_bench src/kernels/fused_gr_bench.cpp) + target_include_directories(fused_gr_bench PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(fused_gr_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_executable(router_chain_bench src/kernels/router_chain_bench.cpp) + target_include_directories(router_chain_bench PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(router_chain_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + # B6: the dense projections' time per verify row at the model's shapes, default vs STRATA_B6_MMVQ_ROWS, bitwise + if(STRATA_ENABLE_CUDA) + add_executable(b6_mmvq_bench src/kernels/b6_mmvq_bench.cpp) + target_include_directories(b6_mmvq_bench PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(b6_mmvq_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + endif() add_executable(gr_parity src/kernels/gr_parity.cpp) target_include_directories(gr_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(gr_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) @@ -646,6 +1316,22 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(gdn_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME gdn_parity COMMAND gdn_parity --selftest) + # v100/gdn-chunk: the chunked GDN prompt recurrence vs the token recurrence and a host reference (GPU, + # synthetic, no model). The chunked path changes the summation order - FP32-level, not bit-exact - so the + # test asserts measured error bounds, and --selftest pins them. + if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA) + add_executable(gdn_chunk_parity src/kernels/gdn_chunk_parity.cpp) + target_include_directories(gdn_chunk_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(gdn_chunk_parity PRIVATE strata_prefill ${_strata_gpu_runtime_target}) + add_test(NAME gdn_chunk_parity COMMAND gdn_chunk_parity --selftest) + set_tests_properties(gdn_chunk_parity PROPERTIES SKIP_RETURN_CODE 77) + + # v100/gdn-chunk: the micro benchmark (CUDA events, real GDN shapes): chunked vs recurrent prompt path. + add_executable(gdn_chunk_bench bench/gdn_chunk_bench.cpp) + target_include_directories(gdn_chunk_bench PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(gdn_chunk_bench PRIVATE strata_prefill ${_strata_gpu_runtime_target}) + endif() + add_executable(s2_gemv_q8_parity src/kernels/s2_gemv_q8_parity.cpp) target_include_directories(s2_gemv_q8_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(s2_gemv_q8_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) @@ -656,11 +1342,25 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(sampler_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME sampler_parity COMMAND sampler_parity --selftest) set_tests_properties(sampler_parity PROPERTIES ENVIRONMENT "STRATA_OLD_SAMPLER=0;STRATA_SAMPLER_ONE_BLOCK=0") + # the GPU verifier of probabilistic draft acceptance against the host reference (STRATA_SPEC_PROB) + add_executable(spec_verify_parity src/kernels/spec_verify_parity.cpp) + target_include_directories(spec_verify_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(spec_verify_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME spec_verify_parity COMMAND spec_verify_parity) + set_tests_properties(spec_verify_parity PROPERTIES ENVIRONMENT "STRATA_OLD_SAMPLER=0;STRATA_SAMPLER_ONE_BLOCK=0") # the same fixtures on the other two sampled paths: the one-block kernel and the 0.1.20 kernel add_test(NAME sampler_parity_one_block COMMAND sampler_parity --selftest) set_tests_properties(sampler_parity_one_block PROPERTIES ENVIRONMENT "STRATA_OLD_SAMPLER=0;STRATA_SAMPLER_ONE_BLOCK=1") add_test(NAME sampler_parity_old COMMAND sampler_parity --selftest) set_tests_properties(sampler_parity_old PROPERTIES ENVIRONMENT "STRATA_OLD_SAMPLER=1;STRATA_SAMPLER_ONE_BLOCK=0") + # S19: the decode QSA top-k and the greedy argmax on thread-block clusters (sm_90+) vs the one-CTA kernels, bitwise, + # captured in a graph too (GPU, synthetic, no model; skips below sm_90); --bench: per-call times + if(STRATA_ENABLE_CUDA) + add_executable(decode_cluster_parity src/kernels/decode_cluster_parity.cpp) + target_include_directories(decode_cluster_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(decode_cluster_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME decode_cluster_parity COMMAND decode_cluster_parity --selftest) + endif() add_executable(rope_parity src/kernels/rope_parity.cpp) target_include_directories(rope_parity PRIVATE ${_strata_gpu_include_directories}) @@ -672,10 +1372,57 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(quantize_act_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME quantize_act_parity COMMAND quantize_act_parity --selftest) + # the verify window's routing in one multi-column BF16 projection + one top-k, bitwise the per-token calls + add_executable(route_window_parity src/kernels/route_window_parity.cpp) + target_include_directories(route_window_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(route_window_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME route_window_parity COMMAND route_window_parity) + + # STRATA_ROUTE_RESIDENT's swap: the warp-per-token kernel against a scalar reference of the same semantics, + # bitwise on the ids, the weights and the four counters (GPU, synthetic, no model) + add_executable(route_resident_parity src/kernels/route_resident_parity.cu) + target_include_directories(route_resident_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(route_resident_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME route_resident_parity COMMAND route_resident_parity) + set_tests_properties(route_resident_parity PROPERTIES TIMEOUT 120) + add_executable(router_top10_parity src/kernels/router_top10_parity.cpp) target_include_directories(router_top10_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(router_top10_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME router_top10_parity COMMAND router_top10_parity --selftest) + # #783 PR-c: the multi-token router and the k = 10 float4 combine, bitwise against the single-token contracts + add_executable(native_multi_parity src/kernels/native_multi_parity.cpp) + target_include_directories(native_multi_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(native_multi_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME native_multi_parity COMMAND native_multi_parity) + # #783 PR-d: the batched K/V append (INT8, Q4_0, the hybrid fold) against the per-cell appends, memcmp + add_executable(kv_steps_parity src/kernels/kv_steps_parity.cpp) + target_include_directories(kv_steps_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(kv_steps_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME kv_steps_parity COMMAND kv_steps_parity) + # #783 PR-e: the device-built expert plan (parallel grouping + prefix scan) against a host replay of its contract + add_executable(resident_plan_parity src/kernels/resident_plan_parity.cpp) + target_include_directories(resident_plan_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(resident_plan_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME resident_plan_parity COMMAND resident_plan_parity) + # #783 PR-g: the multi-token hyper-connection read/write (exact-T projections under them) against the single-token calls + add_executable(gr_multi_parity src/kernels/gr_multi_parity.cpp) + target_include_directories(gr_multi_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(gr_multi_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME gr_multi_parity COMMAND gr_multi_parity) + # STRATA_HC_PERSIST=1: the persistent hyper-connection read against the default multi read (bounded, two runs bitwise), + # and with the variable unset it never runs (a skip where the card cannot hold its 80 blocks, and on CUDA) + add_executable(hc_persist_parity src/kernels/hc_persist_parity.cpp) + target_include_directories(hc_persist_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(hc_persist_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME hc_persist_parity COMMAND hc_persist_parity) + add_test(NAME hc_persist_default_off COMMAND hc_persist_parity --off) + if(STRATA_HIP_GFX906) + # the S6 router (STRATA_HIP_ROUTER_FAST=1 on gfx906) against the portable kernel, bitwise, on wave64 + add_executable(hip_router_fast tests/hip/router_fast.cpp) + target_include_directories(hip_router_fast PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(hip_router_fast PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + endif() add_executable(s_gemv_parity src/kernels/s_gemv_parity.cpp) target_include_directories(s_gemv_parity PRIVATE ${_strata_gpu_include_directories}) @@ -692,6 +1439,16 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(bf16_gemv_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME bf16_gemv_parity COMMAND bf16_gemv_parity --selftest) + # the V100 fusion work: every fused kernel against its unfused pipeline, bitwise, and the before/after + # CUDA-event timings at decode shapes (`--bench`). It is a .cu because it carries the unfused reference + # kernels it compares against. + if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA) + add_executable(fusions_parity bench/micro/fusions_parity.cu) + target_include_directories(fusions_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(fusions_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME fusions_parity COMMAND fusions_parity) + endif() + add_executable(s_gemv_q8k_parity src/kernels/s_gemv_q8k_parity.cpp) target_include_directories(s_gemv_q8k_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(s_gemv_q8k_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) @@ -702,6 +1459,16 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(qsa_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME qsa_parity COMMAND qsa_parity --selftest) + # the QSA top-k the engine dispatches against the original kernel: identical ids on both sides of the register + # kernel's reach, with tied and with equal scores (synthetic, no model) + add_executable(qsa_topk_parity src/kernels/qsa_topk_parity.cpp) + target_include_directories(qsa_topk_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(qsa_topk_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME qsa_topk_parity COMMAND qsa_topk_parity --selftest) + # the register kernel from the smallest prompt batch (the line gfx1151 moves to 4096 blocks): same ids at every case + add_test(NAME qsa_topk_parity_reg_always COMMAND qsa_topk_parity --selftest) + set_tests_properties(qsa_topk_parity_reg_always PROPERTIES ENVIRONMENT "STRATA_TOPK_REG_MIN_BLOCKS=0") + # ---- P2.S4: the PLE n-gram hash, the IQ4_NL table read, and the PLE block ---- # `ngram.cpp` is host-only but lives in `strata_kernels` because `ple.cu` shares its geometry constants, and # splitting them across two libraries would only add a layer. @@ -731,6 +1498,13 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(kv_stream_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME kv_stream_parity COMMAND kv_stream_parity) + # #2403: the verify window's KV calls on a streamed layer and on a ring (steps appends with the host copy, batched + # resolve + attention, plain launches and graph replays), q4_0 / int8 / K8V4 (GPU, synthetic, no model). + add_executable(kv_window_parity src/kernels/kv_window_parity.cpp) + target_include_directories(kv_window_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(kv_window_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME kv_window_parity COMMAND kv_window_parity) + # PR #120: the hybrid K8V4 KV (INT8 K + rotated Q4_0 V) vs host references (GPU, synthetic, no model). add_executable(kv_hybrid_parity src/kernels/kv_hybrid_parity.cpp) target_include_directories(kv_hybrid_parity PRIVATE ${_strata_gpu_include_directories}) @@ -741,6 +1515,17 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_include_directories(kv_q4_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(kv_q4_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME kv_q4_parity COMMAND kv_q4_parity) + # the verify window's one-launch forms (hyper-connection write, PLE post-ops with the commit's + # history snapshots) vs the per-token launches they replace, bitwise (GPU, synthetic, no model) + add_executable(verify_batch_parity src/kernels/verify_batch_parity.cpp) + target_include_directories(verify_batch_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(verify_batch_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME verify_batch_parity COMMAND verify_batch_parity) + # #2234: the batch window's one-launch-for-all-rows kernels vs the per-row launches, bitwise (GPU, synthetic) + add_executable(batch_rows_parity src/kernels/batch_rows_parity.cpp) + target_include_directories(batch_rows_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(batch_rows_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME batch_rows_parity COMMAND batch_rows_parity) add_executable(cvec_parity src/kernels/cvec_parity.cpp) target_include_directories(cvec_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(cvec_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) @@ -766,6 +1551,11 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(platform_memory_test PRIVATE strata_core ${_strata_gpu_runtime_target}) add_test(NAME platform_memory_test COMMAND platform_memory_test) + # The pinned-memory headroom (pin_budget.hpp) against a simulated ceiling; skips without a GPU. + add_executable(pin_budget_test src/core/pin_budget_test.cpp) + target_link_libraries(pin_budget_test PRIVATE strata_core ${_strata_gpu_runtime_target}) + add_test(NAME pin_budget_test COMMAND pin_budget_test) + if(CMAKE_SYSTEM_NAME STREQUAL "Linux") add_executable(pinned_shared_test src/core/pinned_shared_test.cpp) target_link_libraries(pinned_shared_test PRIVATE strata_core ${_strata_gpu_runtime_target}) @@ -828,9 +1618,19 @@ endif() # worse opt-out. `cpu_require_expert_support()` therefore refuses at startup on a CPU without the # features, and the fallback exists for tests, exactly as P2.S3 specifies. # Plan v0.3 P6: speculation components that need no GPU. -add_library(strata_spec STATIC src/spec/suffix_drafter.cpp src/spec/controller.cpp src/spec/draft_policy.cpp) +add_library(strata_spec STATIC src/spec/suffix_drafter.cpp src/spec/controller.cpp src/spec/draft_policy.cpp + src/spec/draft_source.cpp) target_include_directories(strata_spec PUBLIC include) if(STRATA_BUILD_TESTS) + add_executable(arch_defaults_test src/core/arch_defaults_test.cpp src/core/arch_defaults.cpp) + target_include_directories(arch_defaults_test PRIVATE include) + add_test(NAME arch_defaults_test COMMAND arch_defaults_test) + add_executable(adapt_async_default_test src/core/adapt_async_default_test.cpp) + target_include_directories(adapt_async_default_test PRIVATE include) + add_test(NAME adapt_async_default_test COMMAND adapt_async_default_test) + add_executable(uma_cache_test src/core/uma_cache_test.cpp) + target_include_directories(uma_cache_test PRIVATE include) + add_test(NAME uma_cache_test COMMAND uma_cache_test) add_executable(suffix_drafter_test src/spec/suffix_drafter_test.cpp) target_link_libraries(suffix_drafter_test PRIVATE strata_spec) add_test(NAME suffix_drafter_test COMMAND suffix_drafter_test) @@ -840,24 +1640,54 @@ 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) + add_executable(spec_start_test src/spec/spec_start_test.cpp) + target_include_directories(spec_start_test PRIVATE include) + add_test(NAME spec_start_test COMMAND spec_start_test) endif() if(STRATA_BUILD_TESTS OR STRATA_BUILD_CONVERSATION_TESTS) + add_executable(message_boundary_test src/program/message_boundary_test.cpp) + target_include_directories(message_boundary_test PRIVATE include) + add_test(NAME message_boundary_test COMMAND message_boundary_test) + # a layer split's ring override and the lend slots sized with it: the RAM copy must keep every borrowed slot (CPU) + add_executable(split_ring_test src/program/split_ring_test.cpp) + target_include_directories(split_ring_test PRIVATE include) + add_test(NAME split_ring_test COMMAND split_ring_test) # 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) add_test(NAME conv_cache_test COMMAND conv_cache_test) + # which path computes the draft layer's prompt K/V, and STRATA_SPLIT_MTP_BATCH's parsing (header-only, CPU) + add_executable(draft_kv_plan_test src/program/draft_kv_plan_test.cpp) + target_include_directories(draft_kv_plan_test PRIVATE include) + add_test(NAME draft_kv_plan_test COMMAND draft_kv_plan_test) # coupled draft sampling's counter and penalty-ring arithmetic (header-only, CPU) add_executable(coupled_draft_test src/core/coupled_draft_test.cpp) target_include_directories(coupled_draft_test PRIVATE include) add_test(NAME coupled_draft_test COMMAND coupled_draft_test) + # probabilistic draft acceptance (STRATA_SPEC_PROB): rejection sampling preserves p - chi-square over 2M trials per case (CPU) + add_executable(spec_prob_test src/core/spec_prob_test.cpp) + target_include_directories(spec_prob_test PRIVATE include) + add_test(NAME spec_prob_test COMMAND spec_prob_test) + # the per-card window cap of --draft dflash2 (header-only, CPU) + add_executable(draft_cap_test src/core/draft_cap_test.cpp) + target_include_directories(draft_cap_test PRIVATE include) + add_test(NAME draft_cap_test COMMAND draft_cap_test) # the f32 -> bf16 rounding against ggml's, NaN included, over every f32 bit pattern (header-only, CPU) add_executable(bf16_bits_test src/kernels/bf16_bits_test.cpp) target_include_directories(bf16_bits_test PRIVATE include) add_test(NAME bf16_bits_test COMMAND bf16_bits_test) + # the batch window's row layout (a slot's group of proposed rows, the layer split's hand-off capacity; header-only, CPU) + add_executable(batch_rows_test tests/core/batch_rows_test.cpp) + target_include_directories(batch_rows_test PRIVATE include) + add_test(NAME batch_rows_test COMMAND batch_rows_test) + # how many pipelined slot groups --batch runs with: the 0.1.41 default, and --batch-mtp keeping it serial (header-only, CPU) + add_executable(batch_groups_test src/program/batch_groups_test.cpp) + target_include_directories(batch_groups_test PRIVATE include) + add_test(NAME batch_groups_test COMMAND batch_groups_test) endif() add_library(strata_kernels_cpu STATIC src/kernels/cpu/expert.cpp src/kernels/cpu/pool.cpp - src/kernels/cpu/expert_layout.cpp src/kernels/cpu/q2_avx2.cpp) + src/kernels/cpu/expert_layout.cpp src/kernels/cpu/q2_avx2.cpp src/kernels/cpu/hadamard.cpp) target_include_directories(strata_kernels_cpu PUBLIC include) # Plan v0.3 P6: only the kernel files get the AVX-512 / AVX2 flags; the pool and the probe run on any x86-64, # and the engine picks the kernels at run time (cpu_avx512_ok). @@ -870,6 +1700,34 @@ else() PROPERTIES COMPILE_OPTIONS "-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx512vbmi;-mf16c;-mfma") set_source_files_properties(src/kernels/cpu/q2_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") endif() +# AVX-VNNI (Alder Lake, Sapphire Rapids and later): the AVX-2 expert kernels' vpdpwssd / vpdpbusd copies (q2_avx2.cpp, +# iq_avx2.cpp; *_rows.inl), taken at run time where cpu_avxvnni_ok(). GCC and Clang compile only those functions with +# target("avxvnni") - never -mavxvnni on a file, which would let the compiler use it anywhere - and MSVC takes the +# intrinsics under /arch:AVX2. A compiler without them (GCC < 11, Clang < 12) builds the files without the copies. +include(CheckCXXSourceCompiles) +if(MSVC) + set(CMAKE_REQUIRED_FLAGS "/arch:AVX2") +else() + set(CMAKE_REQUIRED_FLAGS "-mavx2 -mfma -mf16c") +endif() +check_cxx_source_compiles([=[ +#include +#if defined(__GNUC__) || defined(__clang__) +__attribute__((target("avxvnni"))) +#endif +static __m256i dots(__m256i a, __m256i b) { return _mm256_dpbusd_avx_epi32(_mm256_dpwssd_avx_epi32(a, a, b), a, b); } +int main() { + volatile int x = 1; + return _mm256_extract_epi32(dots(_mm256_set1_epi32(x), _mm256_set1_epi32(x)), 0) == 0; +} +]=] STRATA_HAVE_AVXVNNI_INTRINSICS) +unset(CMAKE_REQUIRED_FLAGS) +if(STRATA_HAVE_AVXVNNI_INTRINSICS) + set(_strata_avxvnni STRATA_AVXVNNI=1) +else() + set(_strata_avxvnni STRATA_AVXVNNI=0) +endif() +set_property(SOURCE src/kernels/cpu/q2_avx2.cpp APPEND PROPERTY COMPILE_DEFINITIONS ${_strata_avxvnni}) find_package(Threads REQUIRED) target_link_libraries(strata_kernels_cpu PUBLIC Threads::Threads) @@ -878,7 +1736,6 @@ target_link_libraries(strata_kernels_cpu PUBLIC Threads::Threads) # The CPU computes a native expert with ggml-cpu's own dot products (`ggml_get_type_traits_cpu`), so an IQ # weight means exactly what it means in llama.cpp. ggml is built static from a llama.cpp checkout: a local one # with -DSTRATA_GGML_DIR=..., otherwise the pinned upstream commit (third_party/ggml/VERSION.txt). -option(STRATA_NATIVE_EXPERTS "Native (IQ) expert support through ggml-cpu" ON) set(STRATA_GGML_DIR "" CACHE PATH "llama.cpp checkout to take ggml from (empty: fetch the pinned commit)") if(STRATA_PREFILL_MMQ AND NOT STRATA_NATIVE_EXPERTS) message(FATAL_ERROR "STRATA_PREFILL_MMQ requires STRATA_NATIVE_EXPERTS=ON for GGML sources") @@ -900,6 +1757,29 @@ if(STRATA_NATIVE_EXPERTS) foreach(_f GGML_AVX GGML_AVX2 GGML_FMA GGML_F16C GGML_BMI2) set(${_f} ON CACHE BOOL "" FORCE) endforeach() + # The DeepSeek engine (STRATA_BUILD_DSV41) builds ggml-cpu with BMI2 OFF: ggml's IQ1_S / IQ1_M dots use _pdep_u64 with it, and AMD + # Zen 1/2 run PDEP in microcode (EPYC 7452, IQ1_M one-token dot 1.8 GB/s against 32 GB/s without it; IQ1_S 2.3 against 37). The + # results are bit-identical either way (ds4_gg_bench --dump, types 19 and 29, 1-16 tokens). Other engines keep BMI2 until their + # next rebuild is looked at: no Qwen package changes with this commit. + if(STRATA_BUILD_DSV41) + set(GGML_BMI2 OFF CACHE BOOL "" FORCE) + endif() + elseif(STRATA_ISA_FLOOR) + # the experimental older-CPU build (STRATA_ISA_FLOOR above): one ggml-cpu for the floor, ggml's "sandybridge" + # feature set (SSE4.2 + AVX) or SSE4.2 alone - not the build host's, which may be newer than the PC it runs on. + # From the Strata_Dirigo fork (rwkeyes). ggml's defaults turn the rest on when GGML_NATIVE is off: all off here. + set(GGML_NATIVE OFF CACHE BOOL "" FORCE) + set(GGML_CPU_ALL_VARIANTS OFF CACHE BOOL "" FORCE) + set(GGML_SSE42 ON CACHE BOOL "" FORCE) + if(STRATA_ISA_FLOOR STREQUAL "avx") + set(GGML_AVX ON CACHE BOOL "" FORCE) + else() + set(GGML_AVX OFF CACHE BOOL "" FORCE) + endif() + foreach(_f GGML_AVX2 GGML_FMA GGML_F16C GGML_BMI2 GGML_AVX_VNNI GGML_AVX512 GGML_AVX512_VBMI GGML_AVX512_VNNI + GGML_AVX512_BF16 GGML_AMX_TILE GGML_AMX_INT8 GGML_AMX_BF16) + set(${_f} OFF CACHE BOOL "" FORCE) + endforeach() else() set(GGML_NATIVE ON CACHE BOOL "" FORCE) endif() @@ -920,21 +1800,135 @@ if(STRATA_NATIVE_EXPERTS) # part of strata_kernels_cpu (the pool calls these and they call its CPU probe: one library, so GNU ld's # one-pass static linking has no cycle to resolve) target_sources(strata_kernels_cpu PRIVATE src/kernels/cpu/native_expert.cpp src/kernels/cpu/iq_avx512.cpp - src/kernels/cpu/iq_avx2.cpp src/kernels/cpu/kq_avx2.cpp) + src/kernels/cpu/iq_avx2.cpp src/kernels/cpu/kq_avx2.cpp + src/kernels/cpu/kq_avx1.cpp src/kernels/cpu/q2_avx1.cpp src/kernels/cpu/iq_avx1.cpp + src/kernels/cpu/nvfp4_avx512.cpp src/kernels/cpu/nvfp4_avx2.cpp + src/kernels/cpu/tq_cpu.cpp src/kernels/cpu/tq_avx2.cpp src/kernels/cpu/tq_avx512.cpp) target_include_directories(strata_kernels_cpu PRIVATE third_party/ggml) if(MSVC) - set_source_files_properties(src/kernels/cpu/iq_avx512.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX512") + set_source_files_properties(src/kernels/cpu/iq_avx512.cpp src/kernels/cpu/nvfp4_avx512.cpp + PROPERTIES COMPILE_OPTIONS "/arch:AVX512") set_source_files_properties(src/kernels/cpu/iq_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2") set_source_files_properties(src/kernels/cpu/kq_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2") + set_source_files_properties(src/kernels/cpu/nvfp4_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2") + set_source_files_properties(src/kernels/cpu/tq_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2") + set_source_files_properties(src/kernels/cpu/tq_avx512.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX512") + # the router lookahead's AVX1 dot (older CPUs; called behind cpu_avx1_ok): no FMA, no 256-bit integer ops + set_source_files_properties(src/kernels/cpu/kq_avx1.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX") + # the older CPUs' Q2_0 rows and activation quantizer (q2_avx1.cpp, issue #1699): 128-bit integer lanes, + # no FMA/F16C, its own #error guard; called only behind cpu_avx1_ok() && !cpu_avx2_ok() + set_source_files_properties(src/kernels/cpu/q2_avx1.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX") + # the older CPUs' i-quant expert rows (iq_avx1.hpp): 128-bit SSSE3/SSE2 integer, SSE2 float, no FMA/F16C + set_source_files_properties(src/kernels/cpu/iq_avx1.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX") else() - set_source_files_properties(src/kernels/cpu/iq_avx512.cpp PROPERTIES COMPILE_OPTIONS - "-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx512vbmi;-mf16c;-mfma") + set_source_files_properties(src/kernels/cpu/iq_avx512.cpp src/kernels/cpu/nvfp4_avx512.cpp PROPERTIES COMPILE_OPTIONS + "-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx512vbmi;-mavx512vpopcntdq;-mbmi2;-mf16c;-mfma") set_source_files_properties(src/kernels/cpu/iq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") set_source_files_properties(src/kernels/cpu/kq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") + set_source_files_properties(src/kernels/cpu/nvfp4_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") + # the trellis kernels: AVX2 + FMA, and AVX-512 F/BW/VL/VBMI/VNNI (exactly what cpu_avx512_ok() checks) + set_source_files_properties(src/kernels/cpu/tq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") + set_source_files_properties(src/kernels/cpu/tq_avx512.cpp PROPERTIES COMPILE_OPTIONS + "-mavx512f;-mavx512bw;-mavx512vl;-mavx512vnni;-mavx512vbmi;-mavx2;-mfma;-mf16c") + set_source_files_properties(src/kernels/cpu/kq_avx1.cpp PROPERTIES COMPILE_OPTIONS "-mavx") + # the older CPUs' Q2_0 rows and activation quantizer (q2_avx1.cpp, issue #1699): SSE4.2 + AVX with + # AVX2/FMA/F16C explicitly off, so a -march=native build host cannot leak AVX2 code into the file that + # runs on a Sandy Bridge Xeon + set_source_files_properties(src/kernels/cpu/q2_avx1.cpp PROPERTIES COMPILE_OPTIONS + "-msse4.2;-mavx;-mno-avx2;-mno-fma;-mno-f16c") + # the older CPUs' i-quant expert rows (iq_avx1.hpp): SSE4.2 + AVX with AVX2/FMA/F16C explicitly off, so a + # -march=native build host cannot leak AVX2 code into the file that runs on a Sandy Bridge Xeon + set_source_files_properties(src/kernels/cpu/iq_avx1.cpp PROPERTIES COMPILE_OPTIONS + "-msse4.2;-mavx;-mno-avx2;-mno-fma;-mno-f16c") + endif() + set_property(SOURCE src/kernels/cpu/iq_avx2.cpp APPEND PROPERTY COMPILE_DEFINITIONS ${_strata_avxvnni}) + if(STRATA_ISA_FLOOR STREQUAL "avx") + target_compile_definitions(strata_kernels_cpu PRIVATE STRATA_ISA_FLOOR_AVX=1) + elseif(STRATA_ISA_FLOOR STREQUAL "none") + target_compile_definitions(strata_kernels_cpu PRIVATE STRATA_ISA_FLOOR_NONE=1) endif() target_link_libraries(strata_kernels_cpu PUBLIC ggml-cpu ggml-base) target_compile_definitions(strata_kernels_cpu PUBLIC STRATA_NATIVE_EXPERTS=1) + if(STRATA_BUILD_TESTS) + # the Q5_1 block dequantizer (a Q5_1 PLE table) against ggml's, synthetic blocks: no model, no GPU + add_executable(dequant_q5_1_test tests/core/dequant_q5_1_test.cpp) + target_link_libraries(dequant_q5_1_test PRIVATE strata_artifact ggml-base) + add_test(NAME dequant_q5_1_test COMMAND dequant_q5_1_test) + endif() + # the router lookahead's dot on each rung this CPU has (AVX2, the older CPUs' AVX1) against a double reference + add_executable(router_dot_parity src/kernels/cpu/router_dot_parity.cpp) + target_link_libraries(router_dot_parity PRIVATE strata_kernels_cpu) + if(STRATA_BUILD_TESTS) + add_executable(pool_tasks_test src/kernels/cpu/pool_tasks_test.cpp) + target_link_libraries(pool_tasks_test PRIVATE strata_kernels_cpu) + add_test(NAME pool_tasks_test COMMAND pool_tasks_test) + set_tests_properties(pool_tasks_test PROPERTIES TIMEOUT 180) + add_test(NAME router_dot_parity COMMAND router_dot_parity) + add_test(NAME router_dot_parity_avx COMMAND ${CMAKE_COMMAND} -E env STRATA_FORCE_ISA=avx $) + endif() + # the AVX-2 expert kernels' variants (iq_avx2.cpp, q2_avx2.cpp) bit for bit against each other at 1..8 tokens and + # against ggml-cpu's dot, on random blocks; --bench: ms per expert on one thread, the weights streamed from DRAM + add_executable(iq_avx2_parity src/kernels/cpu/iq_avx2_parity.cpp) + target_link_libraries(iq_avx2_parity PRIVATE strata_kernels_cpu) + # the 512-bit i-quant rows against ggml-cpu's dot: the exact rows bit for bit at 1-4 tokens, the engine's multi-token rows to float + # rounding, with the grid lookups as scalar loads and as gathers (SKIP without AVX-512) + add_executable(iq512_gather_parity src/kernels/cpu/iq512_gather_parity.cpp) + target_link_libraries(iq512_gather_parity PRIVATE strata_kernels_cpu) + if(STRATA_BUILD_TESTS) + add_test(NAME iq512_gather_parity_scalar COMMAND ${CMAKE_COMMAND} -E env STRATA_IQ_GATHER=0 $) + add_test(NAME iq512_gather_parity_gather COMMAND ${CMAKE_COMMAND} -E env STRATA_IQ_GATHER=1 $) + endif() + # MODEL-UPDATE: the pool's expert rows per format on T threads against the RAM bandwidth (a benchmark, no test) + add_executable(kq_cpu_bench src/kernels/cpu/kq_cpu_bench.cpp) + target_link_libraries(kq_cpu_bench PRIVATE strata_kernels_cpu) + if(STRATA_BUILD_TESTS) + add_test(NAME iq_avx2_parity COMMAND iq_avx2_parity) + add_test(NAME iq_avx2_parity_iq3s_mt1 COMMAND ${CMAKE_COMMAND} -E env STRATA_IQ3S_MT1=1 $) + endif() + # the older CPUs' AVX1 expert rows (iq_avx1.cpp) against ggml-cpu's dots and against their own one-token + # rows at every width; --bench: ms per expert, the weights streamed from DRAM. Runs on any AVX CPU: + # on an AVX2 machine it checks the older-CPU path as an AVX-only machine would run it. + add_executable(iq_avx1_parity src/kernels/cpu/iq_avx1_parity.cpp) + target_link_libraries(iq_avx1_parity PRIVATE strata_kernels_cpu) + if(STRATA_BUILD_TESTS) + add_test(NAME iq_avx1_parity COMMAND iq_avx1_parity) + endif() + # the AVX-2 Q8_K activation quantizer against ggml's, byte for byte (--bench: its time) + add_executable(q8k_quant_parity src/kernels/cpu/q8k_quant_parity.cpp) + target_link_libraries(q8k_quant_parity PRIVATE strata_kernels_cpu) + if(STRATA_BUILD_TESTS) + add_test(NAME q8k_quant_parity COMMAND q8k_quant_parity) + add_test(NAME q8k_quant_parity_avx COMMAND ${CMAKE_COMMAND} -E env STRATA_FORCE_ISA=avx $) + endif() set(_strata_mmq_types q2_0 iq2_xxs iq2_xs iq2_s iq3_xxs iq3_s iq4_nl iq4_xs q8_0) + # APR: the agention llama.cpp fork has MMQ instances for its trellis expert types (f62fdead0); any other ggml + # tree leaves them to the FP16 prompt path + if(STRATA_GGML_DIR AND EXISTS "${STRATA_GGML_DIR}/ggml/src/ggml-cuda/template-instances/mmq-instance-tqk6.cu") + list(APPEND _strata_mmq_types tq2_t tqk6 tqk7) + set(_strata_mmq_tq ON) + elseif(STRATA_MMQ_TQ_OVERLAY AND (STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)) + # an upstream llama.cpp: the trellis MMQ instances come from an overlay of the pinned ggml-cuda headers written at + # configure time (cmake/strata_ggml_tq_overlay.cmake); off with a message if the llama.cpp tree is not the pinned one + if(STRATA_GGML_DIR) + set(_strata_tq_llama "${STRATA_GGML_DIR}") + else() + set(_strata_tq_llama "${strata_llamacpp_SOURCE_DIR}") + endif() + include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/strata_ggml_tq_overlay.cmake) + set(_strata_tq_overlay_dir "${CMAKE_BINARY_DIR}/ggml-tq-overlay") + strata_ggml_tq_overlay("${_strata_tq_llama}" "${_strata_tq_overlay_dir}") + if(STRATA_TQ_OVERLAY_OK) + configure_file(third_party/ggml/ggml-common-tq.h "${_strata_tq_overlay_dir}/ggml-common-tq.h" COPYONLY) + configure_file(src/kernels/cuda/tq_lut_i8.cuh "${_strata_tq_overlay_dir}/tq_lut_i8.cuh" COPYONLY) + set(_strata_mmq_tq ON) + set(_strata_mmq_tq_overlay ON) + message(STATUS "trellis MMQ (Gyro prompts): overlay on the pinned ggml-cuda in ${_strata_tq_overlay_dir}") + if(STRATA_BUILD_TESTS) + add_test(NAME ggml_tq_overlay COMMAND ${CMAKE_COMMAND} -DLLAMA=${_strata_tq_llama} + -DOUT=${CMAKE_BINARY_DIR}/ggml-tq-overlay-test -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/ggml_tq_overlay_test.cmake) + endif() + endif() + endif() # #296: OrcaRouter Q4_K_S's Q5_0 experts (Q4_K and Q5_1 come with STRATA_MMQ_KQUANTS on CUDA, S5's branch) if(STRATA_ORCA_Q4KS_MMQ) list(APPEND _strata_mmq_types q5_0) @@ -949,39 +1943,189 @@ if(STRATA_NATIVE_EXPERTS) set(_strata_gg ${strata_llamacpp_SOURCE_DIR}/ggml) endif() set(_strata_mmq ${_strata_gg}/src/ggml-cuda) - add_library(strata_mmq STATIC src/prefill/moe_mmq.cu src/prefill/ggml_cuda_host.cu ${_strata_mmq}/quantize.cu) + set(_strata_quantize_cu ${_strata_mmq}/quantize.cu) # the overlay's copy when the trellis overlay is on: it includes mmq.cuh + if(_strata_mmq_tq_overlay) + set(_strata_quantize_cu ${_strata_tq_overlay_dir}/quantize.cu) + endif() + # #136: the Q2_0 pack's prompt experts on Strata's own int8 kernels (moe_fused.cu, opt-in STRATA_PF_FUSED=1; CUDA + # only: the HIP branch below keeps MMQ, and an sm_75 device or an sm_75-only build reports them unavailable) + add_library(strata_mmq STATIC src/prefill/moe_mmq.cu src/prefill/moe_fused.cu src/prefill/moe_fused_iq.cu + src/prefill/mmq_nvfp4_w4a8.cu + src/prefill/ggml_cuda_host.cu ${_strata_quantize_cu}) # q8_0: the drafter's matrices (E-9); STRATA_ORCA_Q4KS_MMQ adds q5_0 (#296, in _strata_mmq_types), and - # STRATA_MMQ_KQUANTS q4_k q5_k q5_1, the experts of Unsloth's UD-Q4_K_XL (docs/UNSLOTH_Q4.md; the dispatch - # follows eddoursul/Strata 7706c1b) + # STRATA_MMQ_KQUANTS q4_k q5_k q5_1 q6_k, the experts of Unsloth's UD-Q4/Q5/Q6_K_XL (docs/QUANTS.md; the dispatch + # follows eddoursul/Strata 7706c1b). MODEL-UPDATE Phase 1: on CUDA they are a library of their own, strata_kq + # (below), loaded only for a model with these experts: the engine loads every kernel of its own binary at start + # (CUDA_MODULE_LOADING=EAGER), and these four took ~3.8 MB of VRAM (3 expert slots of IQ3_XXS on a P100) from every + # model. gfx906 (HIP: code objects load on first use) keeps them in strata_mmq. set(_strata_mmq_cuda_types ${_strata_mmq_types}) - if(STRATA_MMQ_KQUANTS) - list(APPEND _strata_mmq_cuda_types q4_k q5_k q5_1) + set(_strata_kq_types q4_k q5_k q5_1 q6_k) + set(_strata_kq_dso OFF) + if(STRATA_MMQ_KQUANTS AND STRATA_HIP_GFX906) + list(APPEND _strata_mmq_cuda_types ${_strata_kq_types}) + elseif(STRATA_MMQ_KQUANTS) + set(_strata_kq_dso ON) endif() foreach(_t IN LISTS _strata_mmq_cuda_types) target_sources(strata_mmq PRIVATE ${_strata_mmq}/template-instances/mmq-instance-${_t}.cu) endforeach() + if(_strata_mmq_tq_overlay) + foreach(_t tq2_t tqk6 tqk7) + target_sources(strata_mmq PRIVATE ${_strata_tq_overlay_dir}/template-instances/mmq-instance-${_t}.cu) + endforeach() + # first on the include path: the patched mmq.cuh / ggml.h shadow the pinned ones for this target only + target_include_directories(strata_mmq BEFORE PRIVATE ${_strata_tq_overlay_dir} ${_strata_tq_overlay_dir}/include) + endif() + # NVFP4: W4A8 (default) in mmq_nvfp4_w4a8.cu with the plain architectures; the opt-in W4A4 needs RTX 50's FP4 MMA, + # which exists only in the arch-specific target, so its one unit alone is built with 12x -> 12xa (the default + # binary is unchanged and runs on sm_121; a card without that image falls back to W4A8 at run time) + set(_strata_w4a4_archs ${CMAKE_CUDA_ARCHITECTURES}) + # (two steps: CMake before 3.29 rejects a \2 whose optional group did not match, "120" alone) + list(TRANSFORM _strata_w4a4_archs REPLACE "^(12[0-9])$" "\\1a") + list(TRANSFORM _strata_w4a4_archs REPLACE "^(12[0-9])-(real|virtual)$" "\\1a-\\2") + add_library(strata_mmq_w4a4 STATIC src/prefill/mmq_nvfp4_w4a4.cu) + set_target_properties(strata_mmq_w4a4 PROPERTIES CUDA_ARCHITECTURES "${_strata_w4a4_archs}") + target_include_directories(strata_mmq_w4a4 PRIVATE ${_strata_gg}/include ${_strata_gg}/src ${_strata_mmq}) + target_compile_options(strata_mmq_w4a4 PRIVATE $<$:--extended-lambda -use_fast_math>) + if(MSVC) + target_compile_options(strata_mmq_w4a4 PRIVATE $<$:-Xcompiler=/bigobj>) + endif() + target_link_libraries(strata_mmq_w4a4 PUBLIC ggml-base ${_strata_gpu_runtime_target}) + target_link_libraries(strata_mmq PRIVATE strata_mmq_w4a4) + # STRATA_MMQ_TAB: the pointer-table copy of MMQ's scheduler mirrors mmq.cuh from mul_mat_q_process_tile through + # mul_mat_q_case (struct mmq_args included). A fingerprint of that text instead of a compile probe: nothing is + # compiled at configure time, and a llama.cpp tree with another scheduler turns the feature off instead of + # failing the build. _strata_mmq_tab_known: the hashes moe_mmq_tab.cuh was verified against (3cf03257, the + # fetched pin; the vendored third_party/llama.cpp tree has the same mmq.cuh). + set(_strata_mmq_tab_on OFF) + if(STRATA_MMQ_TAB AND NOT STRATA_HIP_GFX906) # gfx906 compiles no .cu from here (its HIP glob): no tab at all + set(_strata_mmq_tab_known 36e4dc716c504470ec09cc0852d29a6ac5eace257f6e5e72db3805ca4f043eb0) + set(_strata_mmq_tab_hash "") + if(EXISTS ${_strata_mmq}/mmq.cuh) + file(READ ${_strata_mmq}/mmq.cuh _strata_mmq_src) + string(REPLACE "\r\n" "\n" _strata_mmq_src "${_strata_mmq_src}") + string(FIND "${_strata_mmq_src}" "static __device__ __forceinline__ void mul_mat_q_process_tile" _strata_tab_a) + string(FIND "${_strata_mmq_src}" "#define DECL_MMQ_CASE" _strata_tab_b) + if(_strata_tab_a GREATER -1 AND _strata_tab_b GREATER _strata_tab_a) + math(EXPR _strata_tab_len "${_strata_tab_b} - ${_strata_tab_a}") + string(SUBSTRING "${_strata_mmq_src}" ${_strata_tab_a} ${_strata_tab_len} _strata_tab_region) + string(SHA256 _strata_mmq_tab_hash "${_strata_tab_region}") + endif() + unset(_strata_mmq_src) + unset(_strata_tab_region) + endif() + if(_strata_mmq_tab_hash AND _strata_mmq_tab_hash IN_LIST _strata_mmq_tab_known) + set(_strata_mmq_tab_on ON) + else() + message(STATUS "STRATA_MMQ_TAB off: mmq.cuh differs from the mirrored scheduler (${_strata_mmq_tab_hash})") + endif() + endif() + if(_strata_mmq_tab_on) + set(_strata_tab_cuh ${CMAKE_CURRENT_SOURCE_DIR}/src/prefill/moe_mmq_tab.cuh) + # the native packs' nine types, the ones prefill_mmq_tab_test checks bit for bit; the optional Q5_0 / K-quant + # instances (STRATA_ORCA_Q4KS_MMQ, STRATA_MMQ_KQUANTS) get no pointer table and keep the gather + set(_strata_mmq_tab_types q2_0 iq2_xxs iq2_xs iq2_s iq3_xxs iq3_s iq4_nl iq4_xs q8_0) + foreach(_t IN LISTS _strata_mmq_tab_types) + string(TOUPPER ${_t} _strata_tab_T) + configure_file(src/prefill/mmq_tab_instance.cu.in ${CMAKE_BINARY_DIR}/mmq_tab/mmq-tab-${_t}.cu @ONLY) + target_sources(strata_mmq PRIVATE ${CMAKE_BINARY_DIR}/mmq_tab/mmq-tab-${_t}.cu) + endforeach() + target_compile_definitions(strata_mmq PRIVATE STRATA_MMQ_TAB=1) + message(STATUS "STRATA_MMQ_TAB on: pointer-table MMQ for ${_strata_mmq_tab_types}") + endif() target_include_directories(strata_mmq PRIVATE ${_strata_gg}/include ${_strata_gg}/src ${_strata_mmq} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) target_compile_options(strata_mmq PRIVATE $<$:--extended-lambda -use_fast_math>) if(MSVC) target_compile_options(strata_mmq PRIVATE $<$:-Xcompiler=/bigobj>) endif() + # GGML's CUDA error reporting calls cuGetErrorString from the driver API. target_link_libraries(strata_mmq PUBLIC ggml-base ${_strata_gpu_runtime_target}) + if(TARGET CUDA::cuda_driver) # not in the HIP (gfx906) build, whose CUDA::cudart is a stand-in + target_link_libraries(strata_mmq PUBLIC CUDA::cuda_driver) + endif() if(STRATA_MMQ_KQUANTS) target_compile_definitions(strata_mmq PRIVATE STRATA_MMQ_KQUANTS=1) endif() + if(_strata_kq_dso) + # strata_kq: the K-quant MMQ instances with their own copy of ggml_cuda_host.cu's symbols and the static CUDA + # runtime, next to the engine (libstrata_kq.so / strata_kq.dll); moe_mmq.cu opens it when a model asks for one + # of these formats (STRATA_MMQ_KQ=1). Without the file the engine runs them on the FP16 prompt path, as before. + target_compile_definitions(strata_mmq PRIVATE STRATA_KQ_DSO=1) + target_sources(strata_mmq PRIVATE src/prefill/mmq_kq_loader.cpp) + if(NOT WIN32) + target_link_libraries(strata_mmq PUBLIC ${CMAKE_DL_LIBS}) + endif() + add_library(strata_kq SHARED src/prefill/mmq_kq_lib.cu src/prefill/ggml_cuda_host.cu) + foreach(_t IN LISTS _strata_kq_types) + target_sources(strata_kq PRIVATE ${_strata_mmq}/template-instances/mmq-instance-${_t}.cu) + endforeach() + target_include_directories(strata_kq PRIVATE ${_strata_gg}/include ${_strata_gg}/src ${_strata_mmq} + ${CMAKE_CURRENT_SOURCE_DIR}/include) + target_compile_options(strata_kq PRIVATE $<$:--extended-lambda -use_fast_math>) + if(MSVC) + target_compile_options(strata_kq PRIVATE $<$:-Xcompiler=/bigobj>) + endif() + set_target_properties(strata_kq PROPERTIES CUDA_RUNTIME_LIBRARY Static POSITION_INDEPENDENT_CODE ON + CXX_VISIBILITY_PRESET hidden CUDA_VISIBILITY_PRESET hidden) + # ggml-base is static: position-independent so a shared library can hold it (the same code otherwise) + set_target_properties(ggml-base PROPERTIES POSITION_INDEPENDENT_CODE ON) + target_link_libraries(strata_kq PRIVATE ggml-base) + if(TARGET CUDA::cuda_driver) + target_link_libraries(strata_kq PRIVATE CUDA::cuda_driver) + endif() + add_dependencies(strata_mmq strata_kq) + endif() if(STRATA_ORCA_Q4KS_MMQ) target_compile_definitions(strata_mmq PRIVATE STRATA_ORCA_Q4KS_MMQ=1) endif() + if(_strata_mmq_tq) + target_compile_definitions(strata_mmq PRIVATE STRATA_MMQ_TQ=1) + endif() target_link_libraries(strata_prefill PUBLIC strata_mmq) - target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_MMQ=1) + target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_MMQ=1 STRATA_PREFILL_FUSED=1) + if(STRATA_BUILD_TESTS) + # #136: the fused int8 experts against a double-precision reference and the MMQ path (exit 77 below sm_80) + add_executable(prefill_fused_moe_test tests/cuda/prefill_fused_moe_test.cpp) + target_link_libraries(prefill_fused_moe_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) + add_test(NAME prefill_fused_moe_test COMMAND prefill_fused_moe_test) + set_tests_properties(prefill_fused_moe_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300) + # #136: the same for the native packs' formats (IQ2_XXS IQ2_XS IQ2_S IQ3_XXS IQ3_S IQ4_XS, down Q2_0 IQ4_NL) + add_executable(prefill_fused_iq_test tests/cuda/prefill_fused_iq_test.cpp) + target_link_libraries(prefill_fused_iq_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) + add_test(NAME prefill_fused_iq_test COMMAND prefill_fused_iq_test) + set_tests_properties(prefill_fused_iq_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600) + # the MoE input quantized per token and scattered to its rows (mmq::quantize_scatter) against the per-row + # gather: the same q8_1 bytes for every MMQ layout (--bench: both at 2K, 8K and 32K tokens) + add_executable(prefill_mmq_scatter_test tests/cuda/prefill_mmq_scatter_test.cpp) + target_link_libraries(prefill_mmq_scatter_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) + add_test(NAME prefill_mmq_scatter_test COMMAND prefill_mmq_scatter_test) + set_tests_properties(prefill_mmq_scatter_test PROPERTIES TIMEOUT 120) + endif() + if(STRATA_BUILD_TESTS AND _strata_mmq_tab_on) + # STRATA_MMQ_DIRECT: the pointer-table MMQ bit for bit against the gathered MMQ (exit 77 below sm_80) + add_executable(prefill_mmq_tab_test tests/cuda/prefill_mmq_tab_test.cu) + target_link_libraries(prefill_mmq_tab_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) + add_test(NAME prefill_mmq_tab_test COMMAND prefill_mmq_tab_test) + set_tests_properties(prefill_mmq_tab_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600) + endif() if(STRATA_BUILD_TESTS AND STRATA_MMQ_KQUANTS) # the UD-Q4_K_XL expert formats through MMQ against ggml's dequantized weights (synthetic, a few seconds) add_executable(prefill_mmq_kquant_test tests/cuda/prefill_mmq_kquant_test.cpp) target_link_libraries(prefill_mmq_kquant_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) add_test(NAME prefill_mmq_kquant_test COMMAND prefill_mmq_kquant_test) - set_tests_properties(prefill_mmq_kquant_test PROPERTIES TIMEOUT 120) + # the K-quant MMQ is opt-in at run time (STRATA_MMQ_KQ=1), and on CUDA it is strata_kq next to the test + set_tests_properties(prefill_mmq_kquant_test PROPERTIES TIMEOUT 120 ENVIRONMENT STRATA_MMQ_KQ=1) endif() + # the NVFP4 expert products (w4a8 / w4a4, STRATA_PREFILL_NVFP4) against a double-precision reference + add_executable(mmq_nvfp4_parity src/prefill/mmq_nvfp4_parity.cpp) + target_link_libraries(mmq_nvfp4_parity PRIVATE strata_mmq ggml-base CUDA::cudart) + if(NOT MSVC) # its FP16 rounding helper uses the F16C intrinsics (GCC/Clang need the target flag) + target_compile_options(mmq_nvfp4_parity PRIVATE $<$:-mf16c>) + endif() + # the routed-expert products (MMQ) timed at the prompt path's shapes (16 experts a launch) + add_executable(mmq_expert_bench src/prefill/mmq_expert_bench.cpp) + target_link_libraries(mmq_expert_bench PRIVATE strata_mmq ggml-base CUDA::cudart) elseif(STRATA_PREFILL_MMQ) # Compile only the pinned GGML MMQ and activation-quantizer sources used by prefill. This uses # common.cuh's native HIP path without enabling a second GGML HIP backend. @@ -991,28 +2135,74 @@ if(STRATA_NATIVE_EXPERTS) set(_strata_gg "${strata_llamacpp_SOURCE_DIR}/ggml") endif() set(_strata_mmq "${_strata_gg}/src/ggml-cuda") + set(_strata_quantize_cu "${_strata_mmq}/quantize.cu") # the overlay's copy when the trellis overlay is on: it includes mmq.cuh + if(_strata_mmq_tq_overlay) + set(_strata_quantize_cu "${_strata_tq_overlay_dir}/quantize.cu") + endif() if(NOT EXISTS "${_strata_mmq}/common.cuh" OR NOT EXISTS "${_strata_mmq}/quantize.cu") message(FATAL_ERROR "The selected GGML source is missing the ggml-cuda MMQ sources: ${_strata_mmq}") endif() + # Aurora: moe_fused.cu's gfx11 and moe_fused_iq.cu's gfx11 / gfx12 WMMA kernels for the prompt experts (opt-in STRATA_PF_FUSED=1) set(_strata_mmq_sources src/prefill/moe_mmq.cu + src/prefill/moe_fused.cu + src/prefill/moe_fused_iq.cu + src/prefill/moe_f16_kq.cu src/prefill/ggml_cuda_host.cu - "${_strata_mmq}/quantize.cu") + "${_strata_quantize_cu}") + if(STRATA_MMQ_KQUANTS) + # the same K-quant instances as the CUDA branch: on HIP they serve the dense GGUF projections + # of Gemm::native (STRATA_DENSE_MMQ=1), the mixed-quant packs' attention/PLE tensors + list(APPEND _strata_mmq_types q4_k q5_k q5_1 q6_k) + endif() foreach(_t IN LISTS _strata_mmq_types) list(APPEND _strata_mmq_sources "${_strata_mmq}/template-instances/mmq-instance-${_t}.cu") endforeach() + if(_strata_mmq_tq_overlay) + foreach(_t tq2_t tqk6 tqk7) + list(APPEND _strata_mmq_sources "${_strata_tq_overlay_dir}/template-instances/mmq-instance-${_t}.cu") + endforeach() + endif() set_source_files_properties(${_strata_mmq_sources} PROPERTIES LANGUAGE HIP) + # moe_fused.cu is Strata's own CUDA-shaped source: it takes the HIP compat headers, ggml's MMQ sources do not + set_source_files_properties(src/prefill/moe_fused.cu src/prefill/moe_fused_iq.cu src/prefill/moe_f16_kq.cu + PROPERTIES INCLUDE_DIRECTORIES "${STRATA_HIP_COMPAT_INCLUDE_DIR}") add_library(strata_mmq STATIC ${_strata_mmq_sources}) target_include_directories(strata_mmq PRIVATE "${_strata_gg}/include" "${_strata_gg}/src" "${_strata_mmq}" PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) + if(_strata_mmq_tq_overlay) + target_include_directories(strata_mmq BEFORE PRIVATE ${_strata_tq_overlay_dir} ${_strata_tq_overlay_dir}/include) + endif() target_compile_definitions(strata_mmq PRIVATE GGML_USE_HIP=1) + if(STRATA_MMQ_KQUANTS) + target_compile_definitions(strata_mmq PRIVATE STRATA_MMQ_KQUANTS=1) + endif() if(STRATA_ORCA_Q4KS_MMQ) target_compile_definitions(strata_mmq PRIVATE STRATA_ORCA_Q4KS_MMQ=1) endif() + if(_strata_mmq_tq) + target_compile_definitions(strata_mmq PRIVATE STRATA_MMQ_TQ=1) + endif() target_link_libraries(strata_mmq PUBLIC ggml-base hip::host roc::hipblas) target_link_libraries(strata_prefill PUBLIC strata_mmq) - target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_MMQ=1) + target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_MMQ=1 STRATA_PREFILL_FUSED=1) + # Aurora: the gfx11 fused experts against the FP64 reference and MMQ (tests/cuda's test; exit 77 off gfx11) + add_executable(hip_prefill_fused_moe tests/cuda/prefill_fused_moe_test.cpp) + target_include_directories(hip_prefill_fused_moe PRIVATE "${_strata_gg}/include") + target_link_libraries(hip_prefill_fused_moe PRIVATE strata_mmq ggml-base strata_hip_runtime) + add_test(NAME hip_prefill_fused_moe COMMAND hip_prefill_fused_moe) + set_tests_properties(hip_prefill_fused_moe PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300) + list(APPEND _strata_hip_tests hip_prefill_fused_moe) + add_executable(hip_prefill_fused_iq tests/cuda/prefill_fused_iq_test.cpp) + target_include_directories(hip_prefill_fused_iq PRIVATE "${_strata_gg}/include") + target_link_libraries(hip_prefill_fused_iq PRIVATE strata_mmq ggml-base strata_hip_runtime) + add_test(NAME hip_prefill_fused_iq COMMAND hip_prefill_fused_iq) + set_tests_properties(hip_prefill_fused_iq PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600) + # the same binary on F16 weights (gfx11: the covered formats take moe_f16_kq.cu / native_f16_kernel; elsewhere it is the default run again) + add_test(NAME hip_prefill_fused_iq_f16 COMMAND hip_prefill_fused_iq) + set_tests_properties(hip_prefill_fused_iq_f16 PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600 ENVIRONMENT "STRATA_PF_F16=1;STRATA_PF_F16_KQ=1") + list(APPEND _strata_hip_tests hip_prefill_fused_iq) # Numerical diagnostic: synthetic layouts by default, optional first-expert IQ3_XXS/IQ4_NL check with a pack. add_executable(hip_prefill_mmq_parity tests/hip/prefill_mmq_parity.cpp) @@ -1027,24 +2217,73 @@ if(STRATA_NATIVE_EXPERTS) add_executable(hip_ple_iq4 tests/hip/ple_iq4.cpp) target_link_libraries(hip_ple_iq4 PRIVATE strata_kernels strata_hip_runtime ggml-base) endif() + # the NVFP4 AVX-512 and AVX2 rows vs ggml-cpu's vec_dot, and their speed (CPU only; optional arg: a pack's experts.bin) + add_executable(nvfp4_avx512_parity src/kernels/cpu/nvfp4_avx512_parity.cpp) + target_link_libraries(nvfp4_avx512_parity PRIVATE strata_kernels_cpu) + add_test(NAME nvfp4_cpu_parity COMMAND nvfp4_avx512_parity) # random blocks; the AVX2 rows bit-equal to ggml's + set_tests_properties(nvfp4_cpu_parity PROPERTIES TIMEOUT 120) + if(STRATA_ENABLE_CUDA) # the NVFP4 decode kernels vs ggml's reference + add_executable(nvfp4_expert_gpu_parity src/kernels/nvfp4_expert_gpu_parity.cpp) + target_link_libraries(nvfp4_expert_gpu_parity PRIVATE strata_kernels ggml-base CUDA::cudart) + # the decode experts' weight bandwidth on random blobs of a format pair, and an output hash (bit-for-bit checks) + add_executable(nvfp4_decode_bench src/kernels/nvfp4_decode_bench.cpp) + target_link_libraries(nvfp4_decode_bench PRIVATE strata_kernels CUDA::cudart) + endif() if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_executable(native_expert_parity src/kernels/native_expert_parity.cpp) target_include_directories(native_expert_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(native_expert_parity PRIVATE strata_kernels strata_kernels_cpu strata_artifact ${_strata_gpu_runtime_target}) + # strata_engine: the --load-check mode runs the engine's start-up checks (NativeDense, check_experts_gguf) + target_link_libraries(native_expert_parity PRIVATE strata_engine strata_kernels strata_kernels_cpu strata_artifact ${_strata_gpu_runtime_target}) + add_executable(native_expert_bench src/kernels/native_expert_bench.cpp) + target_include_directories(native_expert_bench PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(native_expert_bench PRIVATE strata_kernels strata_kernels_cpu strata_artifact ${_strata_gpu_runtime_target}) + # MODEL-UPDATE: the dense Q8_0 GEMVs at the engine's shapes against the memory bandwidth (a benchmark, no test) + add_executable(q8_gemv_bench src/kernels/q8_gemv_bench.cpp) + target_include_directories(q8_gemv_bench PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(q8_gemv_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + if(STRATA_ENABLE_CUDA) + # EXPDEC (docs/EXPERTDEC.md): the grouped experts' default kernels against STRATA_EXPDEC=1 at T = 1..4, bit for bit + # and in microseconds, on synthetic blobs read cold from DRAM + add_executable(expdec_bench EXCLUDE_FROM_ALL src/kernels/expdec_bench.cpp) + target_include_directories(expdec_bench PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(expdec_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + endif() if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA) # Unsloth UD-Q4_K_XL's three expert pairs (and Q8_0 alone, its embedding) on synthetic ggml-quantized weights - # at 2560/640: GPU and CPU experts against the float reference, GPU dequantizers against to_float - foreach(_pair q4_K/q5_1 q4_K/q8_0 q5_K/q8_0 q8_0/q8_0) + # at 2560/640: GPU and CPU experts against the float reference, GPU dequantizers against to_float. + # q4_K/q5_0 and q5_0/q8_0: a plain llama-quantize "_M" tier GGUF (not Unsloth's dynamic method) commonly + # puts Q5_0 on down-projections (sometimes gate/up too) where this model's native_experts.txt had no GPU + # kernel for it before; q5_0/q5_0 (both roles Q5_0) is left out of this list since stacking the same + # lower-precision format on both roles pushes the GPU path over this test's 3% threshold (quantization + # noise, not a kernel bug -- see the PR). + # q4_0/q4_0 and q4_0/q4_1: a plain llama-quantize Q4_0 file (bartowski's Qwen3.8-Flash-Next-Q4_0: gate/up Q4_0, + # down Q4_0 on 42 layers and Q4_1 on 6) + # q6_K/q8_0: Unsloth UD-Q6_K_XL gate/up Q6_K with Q8_0 down (docs/UNSLOTH_Q6.md). Layer 2 is q8_0/q8_0, already listed. + set(_strata_parity_pairs q4_K/q5_1 q4_K/q8_0 q5_K/q8_0 q8_0/q8_0 q4_K/q5_0 q5_0/q8_0 q4_0/q4_0 q4_0/q4_1) + if(STRATA_Q6K_EXPERTS) + list(APPEND _strata_parity_pairs q6_K/q8_0) + else() # a pair without GPU kernels (Q6_K gate/up) is refused by native_expert_supported, not run + add_test(NAME native_expert_parity_refuses_q6_K COMMAND native_expert_parity --synthetic q6_K/q8_0) + set_tests_properties(native_expert_parity_refuses_q6_K PROPERTIES WILL_FAIL TRUE) + endif() + foreach(_pair ${_strata_parity_pairs}) string(REPLACE "/" "_" _name "${_pair}") add_test(NAME native_expert_parity_${_name} COMMAND native_expert_parity --synthetic ${_pair}) set_tests_properties(native_expert_parity_${_name} PROPERTIES TIMEOUT 120) endforeach() add_test(NAME native_expert_parity_q5_1_min COMMAND native_expert_parity --q5_1-min) + # APR: the trellis expert types and the Hadamard activation rotation, when ggml comes from the agention fork + # (the only tree with these types; marked by its ggml-cuda/tq.cuh) + if(STRATA_GGML_DIR AND EXISTS "${STRATA_GGML_DIR}/ggml/src/ggml-cuda/tq.cuh") + foreach(_pair tqk6/tqk7 tq2_t/tq2_t) + string(REPLACE "/" "_" _name "${_pair}") + add_test(NAME native_expert_parity_${_name} COMMAND native_expert_parity --synthetic ${_pair}) + add_test(NAME native_expert_parity_hadamard_${_name} COMMAND native_expert_parity --synthetic-hadamard ${_pair}) + set_tests_properties(native_expert_parity_${_name} native_expert_parity_hadamard_${_name} PROPERTIES TIMEOUT 300) + endforeach() + endif() # #290: the BF16 token embedding (--embd-gguf) gathered and dequantized bit for bit add_test(NAME native_expert_parity_bf16_embd COMMAND native_expert_parity --bf16-embd) - # a pair without GPU kernels (Q6_K gate/up) is refused by native_expert_supported, not run - add_test(NAME native_expert_parity_refuses_q6_K COMMAND native_expert_parity --synthetic q6_K/q8_0) - set_tests_properties(native_expert_parity_refuses_q6_K PROPERTIES WILL_FAIL TRUE) endif() endif() # #296's real-weight checks (OrcaRouter Q4_K_S files; docs/ORCA_Q4_K_S.md) - test programs, not part of a release @@ -1066,6 +2305,15 @@ if(STRATA_ENABLE_CUDA AND STRATA_BUILD_TESTS AND EXISTS "${CMAKE_CURRENT_SOURCE_ endif() if(STRATA_BUILD_TESTS) + if(WIN32) + add_executable(pool_affinity_test src/kernels/cpu/pool_affinity_test.cpp) + target_link_libraries(pool_affinity_test PRIVATE strata_kernels_cpu) + add_test(NAME pool_affinity_test COMMAND pool_affinity_test) + elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux") + add_executable(pool_affinity_test src/kernels/cpu/pool_affinity_linux_test.cpp) + target_link_libraries(pool_affinity_test PRIVATE strata_kernels_cpu) + add_test(NAME pool_affinity_test COMMAND pool_affinity_test) + endif() # Plan v0.3 P6: one expert applied to several tokens, bitwise vs the single-token kernel (synthetic, CPU only). # plan v0.3 P5: the device dequantizers vs the artifact's CPU dequantizers on the real shards (not a ctest: needs # the 38 GB model; run it by hand or from tools/gpu_session.py) @@ -1077,6 +2325,31 @@ if(STRATA_BUILD_TESTS) add_executable(expert_multi_test src/kernels/cpu/expert_multi_test.cpp) target_link_libraries(expert_multi_test PRIVATE strata_kernels_cpu) add_test(NAME expert_multi_test COMMAND expert_multi_test) + set_tests_properties(expert_multi_test PROPERTIES SKIP_RETURN_CODE 77) # no AVX-512: skipped + + # PR #706: the opt-in AVX-2 Q2_0 bit-plane kernel (STRATA_Q2_BITPLANE=1) against the legacy one, bitwise alone/window + if(STRATA_BUILD_TESTS AND CMAKE_SYSTEM_PROCESSOR MATCHES "AMD64|x86_64|x64|X86") + add_executable(q2_bitplane_parity src/kernels/cpu/q2_bitplane_parity.cpp) + target_link_libraries(q2_bitplane_parity PRIVATE strata_kernels_cpu) + add_test(NAME q2_bitplane_parity COMMAND q2_bitplane_parity) + set_tests_properties(q2_bitplane_parity PROPERTIES ENVIRONMENT "STRATA_Q2_BITPLANE=1") + endif() + + if(STRATA_NATIVE_EXPERTS) + # APR port: a Hadamard-folded trellis expert (TQ2_T / TQK6 / TQK7) on the CPU path vs llama.cpp's graph for the + # same weights (synthetic; needs STRATA_GGML_DIR = a ggml with the trellis types, else it reports and fails) + add_executable(native_hadamard_test src/kernels/cpu/native_hadamard_test.cpp) + target_link_libraries(native_hadamard_test PRIVATE strata_kernels_cpu strata_artifact) + add_test(NAME native_hadamard_test COMMAND native_hadamard_test) + set_tests_properties(native_hadamard_test PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + # the CPU trellis kernels (tq_cpu.hpp): AVX2 / AVX-512 vs the scalar kernel bit for bit, vs ggml-cpu's vec_dot + # and to_float, plain and with the Hadamard rotation; `tq_cpu_parity --bench` is the micro-benchmark + add_executable(tq_cpu_parity src/kernels/cpu/tq_cpu_parity.cpp) + target_link_libraries(tq_cpu_parity PRIVATE strata_kernels_cpu) + add_test(NAME tq_cpu_parity COMMAND tq_cpu_parity) + add_test(NAME tq_cpu_parity_avx2 COMMAND ${CMAKE_COMMAND} -E env STRATA_FORCE_AVX2=1 $) + set_tests_properties(tq_cpu_parity tq_cpu_parity_avx2 PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endif() add_executable(expert_parity src/kernels/cpu/expert_parity.cpp) target_link_libraries(expert_parity PRIVATE strata_kernels_cpu) @@ -1088,17 +2361,74 @@ if(STRATA_BUILD_TESTS) add_executable(pool_test src/kernels/cpu/pool_test.cpp) target_link_libraries(pool_test PRIVATE strata_kernels_cpu) add_test(NAME pool_test COMMAND pool_test --selftest WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) + # where the workers are placed (one per physical core by default) and --pool-cores (real pools, no model) + add_executable(pool_cores_test src/kernels/cpu/pool_cores_test.cpp) + target_link_libraries(pool_cores_test PRIVATE strata_kernels_cpu) + add_test(NAME pool_cores_test COMMAND pool_cores_test) + # the default CPU expert worker count on mock CPUs (8c/16t, 16c/32t, 64c/128t, 2-socket 128c/256t, ...) + add_executable(pool_plan_test src/kernels/cpu/pool_plan_test.cpp) + target_include_directories(pool_plan_test PRIVATE include) + add_test(NAME pool_plan_test COMMAND pool_plan_test) + # 0.2.2: when the pool splits per NUMA node by itself (a fake sysfs node folder, mock cores; STRATA_NUMA_POOL=0, one node = unchanged) + add_executable(numa_pool_test src/kernels/cpu/numa_pool_test.cpp) + target_include_directories(numa_pool_test PRIVATE include) + target_compile_features(numa_pool_test PRIVATE cxx_std_17) + add_test(NAME numa_pool_test COMMAND numa_pool_test) + # #3204: when the HIP start-up warm-up of hipBLAS may run (pure policy, no GPU) + add_executable(warm_policy_test src/prefill/warm_policy_test.cpp) + target_include_directories(warm_policy_test PRIVATE include) + add_test(NAME warm_policy_test COMMAND warm_policy_test) # issue #29: tiny batches with sleeping workers, as on a big-VRAM card; a hang fails it add_executable(pool_stress src/kernels/cpu/pool_stress.cpp) target_link_libraries(pool_stress PRIVATE strata_kernels_cpu) add_test(NAME pool_stress COMMAND pool_stress 20) + # #795: nothing an AVX2-only CPU can reach may hold AVX-512 / AVX-VNNI-class instructions. (1) the linked test binary + # (every CPU kernel file plus ggml-cpu; on Linux, the kernel library) is disassembled and any function with such instructions must be a kernel of + # a wide-ISA file, not a weak / COMDAT copy and not a probe or helper that every CPU runs; (2) with -DSTRATA_SDE= + # (Intel SDE) the CPU tests run on an emulated AVX2-only Haswell and on an Alder Lake (AVX-VNNI, no AVX-512): SDE stops + # at the first instruction the chip does not have. + if(TARGET iq_avx2_parity) + find_package(Python3 QUIET COMPONENTS Interpreter) + if(Python3_Interpreter_FOUND) + if(MSVC) + target_link_options(iq_avx2_parity PRIVATE /MAP) + add_test(NAME isa_guard_check COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tools/check_isa_guard.py + $ --map $/iq_avx2_parity.map) + else() + # the library, not the binary: a Linux source build compiles ggml-cpu for the build machine on purpose + add_test(NAME isa_guard_check COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tools/check_isa_guard.py + $) + endif() + set_tests_properties(isa_guard_check PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600) + endif() + endif() + set(STRATA_SDE "" CACHE FILEPATH "Intel SDE (sde / sde64): also run the CPU tests on an emulated AVX2-only and an AVX-VNNI-only CPU") + if(STRATA_SDE AND TARGET iq_avx2_parity) + foreach(_chip hsw adl) + foreach(_t iq_avx2_parity q8k_quant_parity router_dot_parity pool_tasks_test q2_bitplane_parity) + if(TARGET ${_t}) + add_test(NAME sde_${_chip}_${_t} COMMAND ${STRATA_SDE} -${_chip} -- $) + set_tests_properties(sde_${_chip}_${_t} PROPERTIES TIMEOUT 900) + endif() + endforeach() + if(TARGET q2_bitplane_parity) + set_tests_properties(sde_${_chip}_q2_bitplane_parity PROPERTIES ENVIRONMENT "STRATA_Q2_BITPLANE=1") + endif() + endforeach() + endif() + if(UNIX AND NOT APPLE) add_executable(direct_file_async_test tests/platform/direct_file_async.cpp src/platform/direct_file.cpp) target_include_directories(direct_file_async_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include) target_link_libraries(direct_file_async_test PRIVATE Threads::Threads) add_test(NAME direct_file_async_test COMMAND direct_file_async_test) endif() + # --aux-cpus: the CPU-set derivation (pure) and the placement of live threads; header-only, no GPU + add_executable(aux_cpus_test tests/platform/aux_cpus_test.cpp) + target_include_directories(aux_cpus_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include) + target_link_libraries(aux_cpus_test PRIVATE Threads::Threads) + add_test(NAME aux_cpus_test COMMAND aux_cpus_test) endif() if(STRATA_BUILD_TESTS) @@ -1108,3 +2438,53 @@ if(STRATA_BUILD_TESTS) add_subdirectory(tests) endif() endif() + +# ---- HIP gfx906: every CUDA source of the tree (and the ggml-cuda MMQ sources) is compiled as HIP ---- +if(STRATA_HIP_GFX906) + file(GLOB_RECURSE _strata_cu CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src/*.cu ${CMAKE_CURRENT_SOURCE_DIR}/bench/micro/*.cu + ${CMAKE_CURRENT_SOURCE_DIR}/tools/vision/*.cu) + if(_strata_mmq) + file(GLOB _strata_mmq_cu ${_strata_mmq}/*.cu ${_strata_mmq}/template-instances/*.cu) + list(APPEND _strata_cu ${_strata_mmq_cu}) + target_compile_definitions(strata_mmq PRIVATE GGML_USE_HIP) + # #3172: strata_mmq_w4a4 is built from llama.cpp's headers too; without GGML_USE_HIP its common.cuh took the CUDA vendor header + # (cuda.h, cuda_bf16.h: not found). Here it only reports that W4A4 (RTX 50's FP4 MMA) is not available. + if(TARGET strata_mmq_w4a4) + target_compile_definitions(strata_mmq_w4a4 PRIVATE GGML_USE_HIP) + endif() + # #3271: three more link errors of a 0.1.44+ gfx906 build, all sources that strata_mmq lists but the glob above never saw: + # the trellis overlay's quantize.cu and instances (they are generated into the build tree, so the glob missed them: CMake drops a + # .cu source whose language is not enabled) and moe_f16_kq.cu, which moe_fused_iq.cu calls (a stub here: no gfx11 device code, so + # f16kq::covers() answers false and the int8 kernels run, as on every other card) + if(_strata_mmq_tq_overlay) + set(_strata_tq_hip ${_strata_tq_overlay_dir}/quantize.cu) + foreach(_t tq2_t tqk6 tqk7) + list(APPEND _strata_tq_hip ${_strata_tq_overlay_dir}/template-instances/mmq-instance-${_t}.cu) + endforeach() + list(APPEND _strata_cu ${_strata_tq_hip}) + endif() + target_sources(strata_mmq PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/prefill/moe_f16_kq.cu) + endif() + set_source_files_properties(${_strata_cu} PROPERTIES LANGUAGE HIP) +endif() + +if(STRATA_HIP_GFX906) + add_executable(gfx906_qsa_query_swizzle_probe bench/gfx906_qsa_query_swizzle_probe.cpp) + target_link_libraries(gfx906_qsa_query_swizzle_probe PRIVATE strata_kernels ${_strata_gpu_runtime_target}) +endif() + +# ---- DeepSeek-V4.1 on a box with no GPU toolkit ------------------------------------------------ +# The whole DSV41 block above lives inside if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP), so with neither backend on +# -DSTRATA_BUILD_DSV41=ON was silently unused and the host-side benchmark could not be built at all (found on p1004, +# 2026-10-23: the CPU lane is exactly what a box without a usable GPU needs to measure). This branch builds the one target +# that has no device code, so the CPU-lane A/B runs anywhere. +if(STRATA_BUILD_DSV41 AND NOT STRATA_ENABLE_CUDA AND NOT STRATA_ENABLE_HIP AND NOT STRATA_HIP_GFX906) + message(STATUS "STRATA_BUILD_DSV41: no GPU backend, building the host-side benchmark only (ds4_gg_bench)") + if(STRATA_NATIVE_EXPERTS) + add_executable(ds4_gg_bench tests/dsv41/gg_dot_bench.cpp src/dsv41/ds4_gg_cpu.cpp) + target_include_directories(ds4_gg_bench PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_SOURCE_DIR}/src/dsv41 + ${CMAKE_CURRENT_SOURCE_DIR}/third_party/ggml) + target_link_libraries(ds4_gg_bench PRIVATE strata_kernels_cpu Threads::Threads) + target_compile_definitions(ds4_gg_bench PRIVATE STRATA_DSV41_TQ_CPU=1) + endif() +endif() diff --git a/engine/strata/CONTRIBUTING.md b/engine/strata/CONTRIBUTING.md new file mode 100644 index 00000000..4efd7dd6 --- /dev/null +++ b/engine/strata/CONTRIBUTING.md @@ -0,0 +1,122 @@ +# Contributing to Strata + +**AI assistance is welcome. The contributor is responsible for understanding the change and supplying real evidence.** + +These rules apply to issues, pull requests, benchmark reports, and the agents helping prepare them. +You should be able to explain every changed line and answer review questions about it. + +## Before starting + +1. Search [issues](https://github.com/Niko1221/Strata/issues) and + [pull requests](https://github.com/Niko1221/Strata/pulls), including closed discussions. Add new evidence to an + existing thread when it covers your problem. +2. Read [AGENTS.md](AGENTS.md) and the documentation for the component you want to change. +3. Get maintainer agreement on scope before substantial features, refactors, architecture changes, or changes to + defaults. Describe the user problem, proposed behavior, and tradeoffs in an issue first. Agreement on scope + does not guarantee a merge. Focused fixes and benchmark reports can go straight to a PR. +4. Keep one problem per PR. Update that PR after feedback; do not open competing attempts for the same change. + +Do not resubmit a declined proposal under a different title or through another agent. If new evidence changes +the situation, bring it to the original discussion and let a maintainer decide whether to reopen it. + +## Report a problem people can investigate + +Use the matching [issue form](https://github.com/Niko1221/Strata/issues/new/choose). A bug report should include: + +- The smallest steps or command that reproduce the problem, and the expected and actual behavior. +- Strata version or commit, OS, GPU and VRAM, and relevant model, quantization, and configuration. +- The exact error and relevant logs, with credentials and private content removed. +- Whether you reproduced it yourself. Label a finding based only on reading code or a scanner as + **unconfirmed static analysis**, and explain the suspected path without presenting it as an observed failure. + +Do not invent reproduction steps, errors, affected hardware, or severity. If you cannot reproduce something, +say what you inspected and what would verify the hypothesis. Feature requests should explain a concrete user +need and the current workaround. Questions should say what you tried and where you got stuck. + +Example structure, with placeholders to replace with actual observations: + +```text +Problem: +Environment: +Reproduce: +Expected: +Actual: +Evidence: +Reproduction status: +``` + +## Titles + +Every issue and pull request title starts with its area in square brackets, then a short description: `[Engine]`, `[GUI]`, `[TUI]`, +`[Benchmark]`, `[Docs]` or `[Other]`. For example `[Engine] fix decode stop on long prompts` or `[GUI] keep the model list after a tab +switch`. The issue forms ask for the area and a check on the title fails when the prefix is missing. + +## Prepare a focused pull request + +Lead with the problem and resulting behavior. Explain why the approach is needed, the important limits, and +any compatibility effects. Link the issue and scope agreement when applicable. A file-by-file narration or +an AI-generated summary of the diff is not a substitute for this explanation. + +- Keep unrelated formatting, cleanup, dependency changes, and speculative abstractions out of the PR. +- Add documentation where it changes what a user or developer needs to know. Avoid repeated summaries, + speculative roadmaps, and generated documentation with no actionable information. +- Preserve existing behavior outside the intended change. New features are opt-in; follow the default-path + and performance requirements in [AGENTS.md](AGENTS.md). +- Read the complete diff, including generated files, before submitting. Remove debugging output, secrets, + private paths, and accidental files. +- Prefer a small relevant regression check over tests that only restate the implementation. Documentation-only + changes need link, example, and consistency checks; they do not require GPU builds. + +## Show the validation you actually performed + +List exact commands, the revision and environment tested, and observed outcomes. Keep **passed**, **failed**, +and **not run** separate. Include relevant output or a log attachment. A command you suggest running is not +evidence that it passed; a CI run on a different revision is not validation of the submitted code. + +Build every backend a code change touches, including CUDA, HIP, and SYCL where applicable, before requesting +review. For changes that need hardware execution, report that execution separately from compilation. A mock, +static check, or successful build does not establish hardware correctness. If you lack a required environment, +keep the PR as a draft, identify the missing checks, and ask for targeted help in the same thread. Do not claim +compatibility you have not tested. + +Performance claims need before/after runs on the same hardware and workload, with every changed setting +identified. Preserve the individual runs, failures, and variability. Follow the +[community measurement guide](docs/COMMUNITY_BENCHMARKS.md); standard submissions will use the +[benchmark protocol](docs/BENCHMARK_PROTOCOL.md) once it is activated. One fast run does not justify changing a +default or claiming a speedup for other machines. + +Example PR body; placeholders are not test results: + +```text +Problem and result: +Related discussion: +Approach: +Validation: + Passed: + Failed: + Not run: +Limits: +``` + +## Rules for AI-assisted work + +Use agents to help investigate, implement, and explain work that you can review. Before submitting, verify +their claims against the source, actual command output, or a cited primary reference. + +Never submit fabricated measurements, invented test results, fake logs, or copied claims you have not checked. +Do not turn a repository scan into a batch of speculative issues or PRs. Consolidate related findings, establish +their effect, and submit the useful evidence. Do not present an agent's confidence or another model's approval +as validation. Keep review replies concise and address the requested change or evidence directly. + +Maintainers may request a smaller change, return a PR to draft, or close a submission that lacks evidence, +duplicates existing work, or ignores agreed scope. A smaller, understandable contribution with honest limits +is easier to review and maintain. + +## Share a benchmark + +A results-only PR should contain the human report, raw measurements, sanitized configuration, and supporting +logs. Keep it separate from engine changes and include poor results and failed requests. + +The [current community benchmark guide](docs/COMMUNITY_BENCHMARKS.md) remains available for measurements made +with today's tools. The [new protocol](docs/BENCHMARK_PROTOCOL.md) defines the draft standard and future approval +workflow. Its draft status must remain visible: existing reports are not automatically standard or approved. diff --git a/engine/strata/Dockerfile b/engine/strata/Dockerfile index 6b62dae0..82f096cf 100644 --- a/engine/strata/Dockerfile +++ b/engine/strata/Dockerfile @@ -1,115 +1,110 @@ -# syntax=docker/dockerfile:1 +# Strata, built FROM SOURCE (NVIDIA CUDA 13). The engine is compiled here, packaged as an engine component package and then +# installed into the same runtime image as the ready-made ones (docker/Dockerfile): same Terminal, same entrypoint, same /data volume. # -# Strata: Qwen3.8-Flash-Next on NVIDIA GPUs (RTX 30/40/50, 12+ GB VRAM; two or -# three cards can share one model, 8 GB each - docs/MULTI_GPU.md). +# Most people want the ready-made images instead (nothing compiled): docs/DOCKER.md. # -# The engine is compiled during docker build, so the first container start only -# downloads the model (~70 GB) and starts the server. docker build has no GPU, -# so the CUDA architectures are fixed here instead of read from nvidia-smi: the -# engine is a fat binary with a cubin per listed arch, and the runtime picks the -# one matching your card. Narrow CUDA_ARCHITECTURES to your card for a faster -# build; a card outside the set needs a rebuild with its own arch. +# docker build -t strata:src . # RTX 20/30/40/50 (compiles for each, ~25 min) +# docker build -t strata:src --build-arg CUDA_ARCHITECTURES=86 . # one card only (faster); 86 = RTX 30, 89 = RTX 40, 120 = RTX 50 +# docker build -t strata:src-cuda12 --build-arg CUDA_IMAGE=nvidia/cuda:12.9.1-devel-ubuntu24.04 \ +# --build-arg CUDA_ARCHITECTURES="60;61;70;75;80;86;89" --build-arg BUILD_VISION=0 . # GTX 10 / P100 / V100 (driver 575+) +# docker run --rm --gpus all -p 127.0.0.1:8080:8080 --ulimit memlock=-1 --shm-size 2g --stop-timeout 120 \ +# -v strata-data:/data -e MODEL=IQ3_XXS -e API_KEY=change-me-please-123 strata:src # -# Build: -# docker build -t strata . -# docker build -t strata --build-arg CUDA_ARCHITECTURES=89 . # RTX 40 only +# docker build has no GPU, so the CUDA architectures are given here instead of read from nvidia-smi. The engine is a fat binary with +# a machine-code part per listed architecture (plus PTX for the newest, which later cards can JIT), and the runtime picks the one +# matching your card. Narrow CUDA_ARCHITECTURES to your card for a faster build. Native code for the CPU that builds the image is NOT +# used (STRATA_PORTABLE=ON), so the image runs on any x86-64 CPU with AVX2. # -# Run (host needs an NVIDIA driver >= 580 and nvidia-container-toolkit): -# docker run --rm --gpus all \ -# -p 8080:8080 \ -# --ulimit memlock=-1 \ -# -v strata-data:/data \ -# -e MODEL=IQ2_XS \ -# strata -# -# Setup choices are env vars, read by docker-entrypoint.sh: FAMILY, MODEL, CONTEXT, -# VISION (no | yes | cpu), KV (int8 | q4_0 | k8v4), GPU (one card) or GPUS ("0,2" -# or "all", with LAYER_SPLIT), LOW_RAM (auto | on | off), HOST, PORT, API_KEY. -# -# Only the model files, the prepared pack, the MTP layer and the install config -# live in the /data volume; the engine is part of the image. Strata loads 32-62 GB -# into RAM, so a capped container needs -e LOW_RAM=on: setup.py reads the RAM from -# /proc/meminfo, which here is the host's total, not the container's limit. Add an -# API key before exposing the port to a network: -e API_KEY=. Pass -# -e REINSTALL=1 to change the model settings later. -# -# --gpus all on a host with two usable cards: setup takes both (the layer split is -# its recommended default). Pin one card with -e GPU=0, or name them with -# -e GPUS=0,2. A volume set up for one card switches to the pair on its first start -# on a two-card host unless GPU or GPUS pins it. LOW_RAM=on runs on one card. +# Plain legacy-builder features only (no heredocs, no --mount). AMD (HIP) and Intel (SYCL) source builds: docs/AMD_HIP.md, docs/INTEL.md. -FROM nvidia/cuda:13.0.0-devel-ubuntu24.04 - -# STRATA_EXECV=1: setup.py replaces itself with the server, so the server is PID 1 -# and docker stop's SIGTERM reaches it (see setup.start). Normal Linux starts, which -# don't set it, keep spawning the server as a child. -ENV DEBIAN_FRONTEND=noninteractive PYTHONUNBUFFERED=1 LANG=C.UTF-8 STRATA_EXECV=1 +ARG CUDA_IMAGE=nvidia/cuda:13.0.0-devel-ubuntu24.04 +ARG RUNTIME_BASE=ubuntu:24.04 +# ---- 1. compile the engine and make its component package +FROM ${CUDA_IMAGE} AS engine-build +ENV DEBIAN_FRONTEND=noninteractive PYTHONUNBUFFERED=1 PATH=/venv/bin:$PATH RUN apt-get update && apt-get install -y --no-install-recommends \ - build-essential ca-certificates curl git libatomic1 libgomp1 \ - python3 python3-pip python3-venv unzip \ + build-essential ca-certificates git libgomp1 libatomic1 python3 python3-pip python3-venv unzip \ && rm -rf /var/lib/apt/lists/* - -WORKDIR /opt/strata +WORKDIR /src COPY . . - -# RTX 20 (75), RTX 30 (86), RTX 40 (89), RTX 50 (120), plus 80 for A-series. CMakeLists -# refuses anything below 75. BUILD_VISION=0 skips the image encoder build. -ARG CUDA_ARCHITECTURES=75;80;86;89;120 +ARG CUDA_ARCHITECTURES="75;80;86;89;120" ARG BUILD_VISION=1 +ARG ENGINE_VERSION= +RUN python3 -m venv /venv && /venv/bin/pip install --no-cache-dir -r requirements.txt -r requirements-build.txt +# llama.cpp at the pinned commit (ggml for the engine, mtmd for pictures), exactly as setup.py fetches it +RUN /venv/bin/python -c "import setup; print(setup.get_llama_cpp())" +RUN set -e; \ + real=""; for a in $(echo "$CUDA_ARCHITECTURES" | tr ';,' ' '); do real="$real;${a}-real"; done; real=${real#;}; \ + last=$(echo "$CUDA_ARCHITECTURES" | tr ';,' ' ' | awk '{print $NF}'); \ + sm60=OFF; for a in $(echo "$CUDA_ARCHITECTURES" | tr ';,' ' '); do if [ "$a" -lt 75 ]; then sm60=ON; fi; done; \ + /venv/bin/cmake -G Ninja -S . -B build -DCMAKE_BUILD_TYPE=Release -DSTRATA_ENABLE_CUDA=ON -DSTRATA_BUILD_TESTS=OFF \ + -DSTRATA_EXPERIMENTAL_SM60=$sm60 \ + -DSTRATA_NATIVE_EXPERTS=ON -DSTRATA_PORTABLE=ON -DSTRATA_Q6K_EXPERTS=ON -DSTRATA_MMQ_KQUANTS=ON \ + "-DCMAKE_CUDA_ARCHITECTURES=${real};${last}-virtual" -DSTRATA_GGML_DIR=/src/third_party/llama.cpp; \ + /venv/bin/cmake --build build --target strata strata_kq -j "$(nproc)"; \ + if [ "$BUILD_VISION" = "1" ]; then \ + /venv/bin/cmake -G Ninja -S tools/vision -B build-vision -DCMAKE_BUILD_TYPE=Release -DLLAMA_DIR=/src/third_party/llama.cpp \ + -DSTRATA_VISION_CUDA=ON -DSTRATA_PORTABLE=ON -DGGML_CUDA_NCCL=OFF "-DCMAKE_CUDA_ARCHITECTURES=${real};${last}-virtual"; \ + /venv/bin/cmake --build build-vision --target strata-vision -j "$(nproc)"; \ + fi +RUN set -e; \ + mkdir -p /stage /engine; \ + cp build/strata /stage/; \ + [ -f build/libstrata_kq.so ] && cp build/libstrata_kq.so /stage/ || true; \ + [ -f build-vision/bin/strata-vision ] && cp build-vision/bin/strata-vision /stage/ || true; \ + ver="${ENGINE_VERSION:-$(sed -n 's/^[[:space:]]*project([^)]*VERSION[[:space:]]*\([0-9][0-9.]*\).*/\1/p' CMakeLists.txt | head -1)}"; \ + cudafull=$(nvcc --version | sed -n 's/.*release \([0-9][0-9]*\.[0-9][0-9]*\).*/\1/p' | head -1); cudamajor=${cudafull%%.*}; \ + if [ "$cudamajor" = 13 ]; then mindriver=580.65; else mindriver=575.51; fi; \ + vision_archs=""; [ -f /stage/strata-vision ] && vision_archs=", \"vision_archs\": \"$CUDA_ARCHITECTURES\""; \ + echo "{\"version\": \"$ver\", \"source\": \"docker build\", \"archs\": \"$CUDA_ARCHITECTURES\", \"cuda\": \"$cudafull\", \"portable\": true${vision_archs}}" > /stage/BUILD.json; \ + python3 packaging/collect_libs.py --binary build/strata --search /usr/local/cuda/lib64 --out /stage --also 'libcublasLt.so*'; \ + archs=""; for a in $(echo "$CUDA_ARCHITECTURES" | tr ';,' ' '); do archs="$archs --arch sm_$a"; done; \ + last=$(echo "$CUDA_ARCHITECTURES" | tr ';,' ' ' | awk '{print $NF}'); \ + python3 packaging/package_engine.py --src /stage --backend cuda --version "$ver" --out /engine $archs --arch "compute_$last" \ + --min-driver nvidia=$mindriver --variant cuda$cudamajor --platform linux-x86_64 --build-id "docker-source-${ver}-cuda${cudafull}" --include SYSTEM-LIBS.txt --include 'libstrata_kq*' \ + --include strata-vision; \ + for d in /engine/*/; do python3 packaging/package_engine.py --verify "$d"; python3 packaging/binary_deps.py "$d"; done -RUN python3 -m venv .venv \ - && .venv/bin/pip install --no-cache-dir --upgrade pip \ - && .venv/bin/pip install --no-cache-dir -r requirements.txt \ - && chmod +x setup.sh docker-entrypoint.sh - -# llama.cpp at the pinned commit, then the engine and the image encoder, built -# exactly the way setup.py builds them. BUILD.json is what setup.py reads to -# decide whether an engine is current: source=local with a matching src hash -# means the first start reuses it instead of recompiling. -RUN .venv/bin/python - <<'PYEOF' -import json, os, pathlib, shutil -import setup - -llama = setup.get_llama_cpp() -nvcc, _ = setup.find_nvcc() -arch = os.environ.get("CUDA_ARCHITECTURES", "75;80;86;89;120").strip().strip('"').replace(",", ";") -vision = "gpu" if os.environ.get("BUILD_VISION", "1") == "1" else "none" - -setup.cmake_build(setup.ROOT, setup.ROOT / "build", "strata", - ["-DSTRATA_ENABLE_CUDA=ON", "-DSTRATA_BUILD_TESTS=OFF", - f"-DCMAKE_CUDA_ARCHITECTURES={arch}", f"-DCMAKE_CUDA_COMPILER={nvcc}", - f"-DSTRATA_GGML_DIR={llama}"], None, "build-strata.bat") -if vision != "none": - setup.cmake_build(setup.ROOT / "tools" / "vision", setup.ROOT / "build-vision", "strata-vision", - [f"-DLLAMA_DIR={llama}", "-DSTRATA_VISION_CUDA=ON", - f"-DCMAKE_CUDA_ARCHITECTURES={arch}", f"-DCMAKE_CUDA_COMPILER={nvcc}"], None, "build-vision.bat") - -eng = setup.ROOT / "engine" -eng.mkdir(exist_ok=True) -shutil.copy2(setup.ROOT / "build" / setup.EXE, eng / setup.EXE) -if vision != "none": - shutil.copy2(setup.ROOT / "build-vision" / "bin" / setup.VEXE, eng / setup.VEXE) -bindir = pathlib.Path(nvcc).parent -meta = {"source": "local", "version": setup.source_version(), - "archs": [int(a.split("-")[0]) for a in arch.split(";") if a.split("-")[0].isdigit()], "vision": vision, - "cuda_dirs": [str(d) for d in (bindir, bindir / "x64", bindir.parent / "lib64") if d.is_dir()], - "src": setup.source_hash(setup.ENGINE_SOURCES), - "vision_src": setup.source_hash(setup.VISION_SOURCES) if vision != "none" else None} -(eng / "BUILD.json").write_text(json.dumps(meta, indent=1)) -PYEOF - -# the cmake trees are build-time only; the engine itself is what the container needs -RUN rm -rf build build-vision +# ---- 2. the Terminal (the release archive, built here) +FROM ${RUNTIME_BASE} AS terminal +ENV DEBIAN_FRONTEND=noninteractive +RUN apt-get update && apt-get install -y --no-install-recommends python3 ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY . /src/ +RUN python3 /src/packaging/package_terminal.py --out /out --cache /cache \ + && mkdir -p /opt/strata \ + && tar -xzf /out/strata-terminal-*-linux-x86_64.tar.gz -C /opt/strata \ + && mv /opt/strata/strata-terminal-* /opt/strata/terminal \ + && /opt/strata/terminal/bin/strata --version +# llama.cpp at the commit setup.py pins: fetched here, so the first start does not depend on GitHub. Only gguf-py (the model preparation +# tools) and the file setup.py looks for (ggml/CMakeLists.txt) are kept: 170 MB become a few +RUN cd /opt/strata/terminal && STRATA_CONTROL_INSTALL=1 STRATA_INSTALL_DIR=/opt/strata/seed PYTHONNOUSERSITE=1 \ + /opt/strata/terminal/python/bin/python3 -c "import setup; print(setup.get_llama_cpp())" \ + && rm -rf /opt/strata/seed/third_party/*.zip* \ + && cd /opt/strata/seed/third_party/llama.cpp \ + && find . -mindepth 1 -maxdepth 1 ! -name gguf-py ! -name ggml ! -name 'LICENSE*' -exec rm -rf {} + \ + && find ggml -mindepth 1 -depth ! -type d ! -name CMakeLists.txt -delete && find ggml -mindepth 1 -type d -empty -delete \ + && du -sh /opt/strata/seed +# ---- 3. the runtime image (the same as docker/Dockerfile's, FLAVOR=cuda) +FROM ${RUNTIME_BASE} +ARG STRATA_VERSION=dev +ENV DEBIAN_FRONTEND=noninteractive +RUN apt-get update && apt-get install -y --no-install-recommends tini ca-certificates libgomp1 libatomic1 libnuma1 zlib1g \ + && rm -rf /var/lib/apt/lists/* /var/cache/apt/* +COPY --from=terminal /opt/strata/terminal /opt/strata/terminal +COPY --from=terminal /opt/strata/seed /opt/strata/seed +COPY --from=engine-build /engine/ /opt/strata/components/engine/ +COPY docker/entrypoint.sh docker/healthcheck.sh /opt/strata/ +COPY docker/strata-wrapper.sh /usr/local/bin/strata +RUN chmod 0755 /opt/strata/entrypoint.sh /opt/strata/healthcheck.sh /usr/local/bin/strata +ENV STRATA_COMPONENTS_DIR=/opt/strata/components STRATA_INSTALL_DIR=/data/install XDG_STATE_HOME=/data/state \ + XDG_CONFIG_HOME=/data/config HOME=/data/home PORT=8080 LANG=C.UTF-8 PYTHONUNBUFFERED=1 PYTHONNOUSERSITE=1 STRATA_IN_DOCKER=1 \ + NVIDIA_VISIBLE_DEVICES=all NVIDIA_DRIVER_CAPABILITIES=compute,utility VOLUME ["/data"] EXPOSE 8080 - -# /health is answered before the API key gate, so it works with or without one. -# The port only opens after the model loads (1-3 minutes, longer on a first run), -# so the start period is generous: a too short one marks a still-loading container -# unhealthy and a restart policy would kill it mid-download. -HEALTHCHECK --interval=30s --timeout=5s --start-period=600s --retries=3 \ - CMD curl -fs "http://127.0.0.1:${PORT:-8080}/health" || exit 1 - -ENTRYPOINT ["./docker-entrypoint.sh"] +LABEL org.opencontainers.image.title="Strata" com.strata.flavor="cuda" com.strata.build="from-source" org.opencontainers.image.version="${STRATA_VERSION}" +HEALTHCHECK --interval=30s --timeout=8s --start-period=2h --retries=3 CMD ["/opt/strata/healthcheck.sh"] +STOPSIGNAL SIGTERM +ENTRYPOINT ["/usr/bin/tini", "--", "/opt/strata/entrypoint.sh"] +CMD ["run"] diff --git a/engine/strata/README.de.md b/engine/strata/README.de.md new file mode 100644 index 00000000..070c03f3 --- /dev/null +++ b/engine/strata/README.de.md @@ -0,0 +1,188 @@ +

+ + + Strata + +

+ +

Leistungsstarke KI auf deinem eigenen Computer.

+

Chatten, programmieren und mit Bildern arbeiten, lokal.

+ +

+ Modelle · Installation · + Hardware · Tools · + Hilfe · Unterstützen +

+ +

+ Strata herunterladen + MIT-Lizenz + Strata auf Buy Me a Coffee unterstützen +

+ +

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português

+ +**Kostenlos, Open Source und ganz in deiner Hand.** Nutze Strata auf dem Desktop oder mit deinen liebsten Coding-Tools. Kein Konto nötig. + +## Modelle + +Wir empfehlen **zuerst ISTA-DASLab**, danach **Unsloth** und andere Anbieter, soweit ein passendes Modell in deinen Speicher passt. + +
+  Qwen3.8-Flash-Next + +| Anbieter | Auswahl | +| --- | --- | +| **ISTA-DASLab · empfohlen** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S. [Coder: IQ1\_M](docs/MODELS.md#coder) zum Programmieren. | +| **Unsloth** | UD-IQ4\_XS, UD-Q4\_K\_XL, UD-Q5\_K\_XL, UD-Q6\_K\_XL, Q8\_0 | +| **Gyro · agentionai** | [Gyro-S, Gyro-M](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF). Geringerer Speicherbedarf, aber langsamer. | +| **Weitere Optionen** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) | + +[Größen, Speicherbedarf und Kompatibilität vergleichen](docs/MODELS.md). + +
+ +
+  Qwen3.6-35B-A3B + +**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0. Das sind die derzeit dokumentierten Pakete für dieses Modell. + +[Modellanleitung und Kompatibilität](docs/QWEN36.md). + +
+ +
+  DeepSeekV4.1-Flash-1017 + +In der **Desktop-App** und im **Terminal**. Was nicht in den Arbeitsspeicher passt, wird von deiner SSD gelesen. Darum brauchst du viel freien Speicherplatz. + +| Set (IST-DAS) | Download | Freier Speicherplatz nötig | +| --- | ---: | ---: | +| 1.75 bpw | 239 GB | etwa 245 GB | +| 2.00 bpw | 257 GB | etwa 265 GB | +| 2.25 bpw | 274 GB | etwa 280 GB | + +Läuft auf NVIDIA RTX 30, 40 und 50 (Windows und Linux) und auf AMD Radeon AI PRO R9700 (Linux). Das Setup lädt die Dateien und die DeepSeek-Engine herunter und startet dann das Modell. + +```sh +strata launch --family deepseek41 --model ist-das-2.00bpw --plan +``` + +Gemessen mit dem 2.00-bpw-Set auf Strata 0.2.5. „Ausgabe“ ist das Tempo der Antwort, „Prompt“ zeigt, wie schnell Strata deine Eingabe liest. + +| Hardware | Ausgabe | Prompt | +| --- | ---: | ---: | +| RTX 5070 12 GB, 64 GB RAM | 4 bis 6 Token/s | etwa 110 Token/s (4K) | +| RTX 3060 12 GB, 46 GB RAM | 9 bis 11 Token/s | etwa 155 Token/s (4K) | +| 1x Radeon AI PRO R9700, 251 GB RAM | 21 bis 25 Token/s | 320 bis 360 Token/s (8K) | +| 4x Radeon AI PRO R9700 | 74 bis 77 Token/s | 400 bis 450 Token/s (8K) | + +[Speicher, Festplatte und Details](docs/DEEPSEEK41.md) · [Versionshinweise](https://github.com/Niko1221/Strata/releases) + +
+ + + +Unsicher, was passt? [Wähle ein Modell für deinen Computer](docs/MODELS.md#pick-by-memory). + +## Installation + + + +### Desktop-App + +**[Strata für Windows, Linux oder Mac herunterladen →](https://github.com/Niko1221/Strata/releases/latest)** + +Installiere die App, wähle ein Modell und leg mit dem Chat los. Es gibt einen Installer pro System. Beim ersten Start lädt die App die Engine für deine Grafikkarte herunter. [Hilfe zum Installer](docs/INSTALL.md#the-app). + +Dateien: `Strata-0.2.5-windows-x64-setup.exe` · `Strata-0.2.5-linux-x86_64.AppImage` · `Strata-0.2.5-macos-arm64.dmg` + +

+ Strata-Desktop-App mit Chat und Live-Codevorschau nebeneinander +
Chat, Dateien und Live-Vorschau in einem Fenster. +

+ + + +### Terminal-App + +Lieber im Terminal? Installiere Strata und starte dann **`strata launch`**. + +
+Installationsbefehle + +**Linux / Mac** + +```sh +curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh +``` + +**Windows PowerShell** + +```powershell +irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex +``` + +Öffne unter Windows danach ein neues Terminal. Dann: + +```sh +strata launch +``` + +Folge den Anweisungen, um ein Modell herunterzuladen und zu starten. [Terminal-Anleitung](docs/TERMINAL_LAUNCH.md). + +
+ +

+ Strata-Terminal-App mit Modellaktivität, Tempo, Speicher und letzten Anfragen +
Behalte Modell und Hardware im Blick, während es läuft. +

+ + + +[Aus dem Quellcode bauen](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [Vollständige Installationsanleitung](docs/INSTALL.md) + + + +## Hardware + +| Unterstützte Hardware | Anleitung | +| --- | --- | +| **NVIDIA GeForce RTX 20 / 30 / 40 / 50** | [NVIDIA-Setup](docs/INSTALL.md#what-you-need) | +| **AMD Radeon RX 7700 / 7800 / 7900, RX 9060 / 9070, AI PRO R9700** | [AMD-Setup](docs/AMD_HIP.md) | +| **AMD Radeon RX 6800 / 6900 · experimentell** | [RX-6000-Setup](docs/AMD_HIP.md#rdna2-gfx1030) | +| **Intel Arc · Linux** | [Intel-Setup](docs/INTEL_ARC.md) | +| **Apple Silicon · M1 oder neuer** | [Mac-Setup](docs/MAC.md) | +| **AMD Ryzen AI Max · Strix Halo** | [Strix-Halo-Setup](docs/STRIX_HALO.md) | + + + +## Tools + +**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw**, und weitere über die OpenAI- und Anthropic-kompatiblen APIs. + +Führe **`strata connect`** aus, um die Einrichtung für dein Tool zu sehen. [Verbindungsanleitung](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect). + + + + + + +## Hilfe + +[Alle Anleitungen](docs) · [Fehlerbehebung](docs/TROUBLESHOOTING.md) · [Fehler melden](https://github.com/Niko1221/Strata/issues/new/choose) · +[Benchmarks](docs/COMMUNITY_BENCHMARKS.md) · [So funktioniert es](docs/HOW_IT_WORKS.md) · [Mitmachen](CONTRIBUTING.md) + +## Strata unterstützen + +**Hilf mit, lokale KI für alle offen zu halten.** Ein Kaffee hilft, Entwicklung und Tests auf mehr Hardware zu finanzieren. + +Buy Me a Coffee: Strata unterstützen + +[MIT-Lizenz](LICENSE) · [Danksagung und Modelllizenzen](docs/HOW_IT_WORKS.md#credits) · [Datenschutz](docs/SAFETY.md) + + + +Für KI-Tools und automatische Leser: technische Referenz · Setup-Anleitung. + +**Sponsoring, Hardware-Partnerschaften oder Zusammenarbeit:** [niko.veit@outlook.com](mailto:niko.veit@outlook.com). diff --git a/engine/strata/README.es.md b/engine/strata/README.es.md new file mode 100644 index 00000000..e9efd723 --- /dev/null +++ b/engine/strata/README.es.md @@ -0,0 +1,188 @@ +

+ + + Strata + +

+ +

IA potente en tu propio ordenador.

+

Chatea, programa y trabaja con imágenes, en local.

+ +

+ Modelos · Instalación · + Hardware · Herramientas · + Ayuda · Apoyar +

+ +

+ Descargar Strata + Licencia MIT + Apoya Strata en Buy Me a Coffee +

+ +

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português

+ +**Gratis, de código abierto y tuyo para ejecutar.** Usa Strata en tu escritorio o con tus herramientas de programación favoritas. No necesitas cuenta. + +## Modelos + +Recomendamos **primero ISTA-DASLab**, después **Unsloth** y otros proveedores, siempre que haya un modelo compatible que quepa en tu memoria. + +
+  Qwen3.8-Flash-Next + +| Proveedor | Opciones | +| --- | --- | +| **ISTA-DASLab · recomendado** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S. [Coder: IQ1\_M](docs/MODELS.md#coder) para programar. | +| **Unsloth** | UD-IQ4\_XS, UD-Q4\_K\_XL, UD-Q5\_K\_XL, UD-Q6\_K\_XL, Q8\_0 | +| **Gyro · agentionai** | [Gyro-S, Gyro-M](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF). Usa menos memoria, pero es más lento. | +| **Otras opciones** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) | + +[Compara tamaños, necesidades de memoria y compatibilidad](docs/MODELS.md). + +
+ +
+  Qwen3.6-35B-A3B + +**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0. Son los paquetes documentados actualmente para este modelo. + +[Guía del modelo y compatibilidad](docs/QWEN36.md). + +
+ +
+  DeepSeekV4.1-Flash-1017 + +En la **aplicación de escritorio** y en el **Terminal**. Lo que no cabe en la memoria se lee desde tu SSD, así que hace falta mucho espacio libre en disco. + +| Conjunto (IST-DAS) | Descarga | Espacio libre necesario | +| --- | ---: | ---: | +| 1.75 bpw | 239 GB | unos 245 GB | +| 2.00 bpw | 257 GB | unos 265 GB | +| 2.25 bpw | 274 GB | unos 280 GB | + +Funciona en NVIDIA RTX 30, 40 y 50 (Windows y Linux) y en AMD Radeon AI PRO R9700 (Linux). La instalación descarga los archivos y el motor de DeepSeek, y después inicia el modelo. + +```sh +strata launch --family deepseek41 --model ist-das-2.00bpw --plan +``` + +Medido con el conjunto de 2.00 bpw en Strata 0.2.5. «Salida» es la velocidad de la respuesta; «Prompt» es la rapidez con la que Strata lee tu texto. + +| Hardware | Salida | Prompt | +| --- | ---: | ---: | +| RTX 5070 12 GB, 64 GB de RAM | 4 a 6 tokens/s | unos 110 tokens/s (4K) | +| RTX 3060 12 GB, 46 GB de RAM | 9 a 11 tokens/s | unos 155 tokens/s (4K) | +| 1x Radeon AI PRO R9700, 251 GB de RAM | 21 a 25 tokens/s | 320 a 360 tokens/s (8K) | +| 4x Radeon AI PRO R9700 | 74 a 77 tokens/s | 400 a 450 tokens/s (8K) | + +[Memoria, disco y detalles](docs/DEEPSEEK41.md) · [Notas de la versión](https://github.com/Niko1221/Strata/releases) + +
+ + + +¿No sabes qué cabe? [Elige un modelo para tu ordenador](docs/MODELS.md#pick-by-memory). + +## Instalación + + + +### Aplicación de escritorio + +**[Descargar Strata para Windows, Linux o Mac →](https://github.com/Niko1221/Strata/releases/latest)** + +Instala la aplicación, elige un modelo y empieza a chatear. Hay un instalador por sistema. En el primer arranque, la aplicación descarga el motor para tu tarjeta gráfica. [Ayuda con el instalador](docs/INSTALL.md#the-app). + +Archivos: `Strata-0.2.5-windows-x64-setup.exe` · `Strata-0.2.5-linux-x86_64.AppImage` · `Strata-0.2.5-macos-arm64.dmg` + +

+ Aplicación de escritorio de Strata con un chat y una vista previa del código en vivo, una junto a otra +
Chat, archivos y vista previa en vivo en una sola ventana. +

+ + + +### Aplicación de Terminal + +¿Prefieres la terminal? Instala Strata y ejecuta **`strata launch`**. + +
+Comandos de instalación + +**Linux / Mac** + +```sh +curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh +``` + +**Windows PowerShell** + +```powershell +irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex +``` + +En Windows, abre una terminal nueva después. Luego: + +```sh +strata launch +``` + +Sigue las indicaciones para descargar e iniciar un modelo. [Guía del Terminal](docs/TERMINAL_LAUNCH.md). + +
+ +

+ Aplicación de Terminal de Strata con la actividad del modelo, la velocidad, la memoria y las peticiones recientes +
Observa tu modelo y tu hardware mientras se ejecuta. +

+ + + +[Compilar desde el código fuente](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [Guía de instalación completa](docs/INSTALL.md) + + + +## Hardware + +| Hardware compatible | Guía | +| --- | --- | +| **NVIDIA GeForce RTX 20 / 30 / 40 / 50** | [Instalación en NVIDIA](docs/INSTALL.md#what-you-need) | +| **AMD Radeon RX 7700 / 7800 / 7900, RX 9060 / 9070, AI PRO R9700** | [Instalación en AMD](docs/AMD_HIP.md) | +| **AMD Radeon RX 6800 / 6900 · experimental** | [Instalación en RX 6000](docs/AMD_HIP.md#rdna2-gfx1030) | +| **Intel Arc · Linux** | [Instalación en Intel](docs/INTEL_ARC.md) | +| **Apple Silicon · M1 o posterior** | [Instalación en Mac](docs/MAC.md) | +| **AMD Ryzen AI Max · Strix Halo** | [Instalación en Strix Halo](docs/STRIX_HALO.md) | + + + +## Herramientas + +**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw**, y más, mediante las API compatibles con OpenAI y Anthropic. + +Ejecuta **`strata connect`** para ver las instrucciones de tu herramienta. [Guía de conexión](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect). + + + + + + +## Ayuda + +[Todas las guías](docs) · [Solución de problemas](docs/TROUBLESHOOTING.md) · [Informar de un error](https://github.com/Niko1221/Strata/issues/new/choose) · +[Benchmarks](docs/COMMUNITY_BENCHMARKS.md) · [Cómo funciona](docs/HOW_IT_WORKS.md) · [Contribuir](CONTRIBUTING.md) + +## Apoya Strata + +**Ayuda a mantener la IA local abierta a todos.** Un café ayuda a financiar el desarrollo y las pruebas en más hardware. + +Buy Me a Coffee: apoya Strata + +[Licencia MIT](LICENSE) · [Créditos y licencias de los modelos](docs/HOW_IT_WORKS.md#credits) · [Privacidad](docs/SAFETY.md) + + + +Para herramientas de IA y lectores automáticos: referencia técnica · instrucciones de instalación. + +**Patrocinios, alianzas de hardware o colaboraciones:** [niko.veit@outlook.com](mailto:niko.veit@outlook.com). diff --git a/engine/strata/README.fr.md b/engine/strata/README.fr.md new file mode 100644 index 00000000..eb4e6723 --- /dev/null +++ b/engine/strata/README.fr.md @@ -0,0 +1,188 @@ +

+ + + Strata + +

+ +

Une IA puissante sur votre propre ordinateur.

+

Discutez, programmez et travaillez avec des images, en local.

+ +

+ Modèles · Installation · + Matériel · Outils · + Aide · Soutenir +

+ +

+ Télécharger Strata + Licence MIT + Soutenir Strata sur Buy Me a Coffee +

+ +

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português

+ +**Gratuit, open source, et à vous de l'exécuter.** Utilisez Strata sur votre bureau ou avec vos outils de programmation préférés. Aucun compte nécessaire. + +## Modèles + +Nous recommandons **d'abord ISTA-DASLab**, puis **Unsloth** et d'autres fournisseurs, lorsqu'un modèle compatible tient en mémoire. + +
+  Qwen3.8-Flash-Next + +| Fournisseur | Choix | +| --- | --- | +| **ISTA-DASLab · recommandé** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S. [Coder : IQ1\_M](docs/MODELS.md#coder) pour programmer. | +| **Unsloth** | UD-IQ4\_XS, UD-Q4\_K\_XL, UD-Q5\_K\_XL, UD-Q6\_K\_XL, Q8\_0 | +| **Gyro · agentionai** | [Gyro-S, Gyro-M](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF). Utilise moins de mémoire, mais plus lent. | +| **Autres options** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) | + +[Comparer les tailles, la mémoire nécessaire et la compatibilité](docs/MODELS.md). + +
+ +
+  Qwen3.6-35B-A3B + +**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0. Ce sont les paquets actuellement documentés pour ce modèle. + +[Guide du modèle et compatibilité](docs/QWEN36.md). + +
+ +
+  DeepSeekV4.1-Flash-1017 + +Dans l'**application de bureau** et dans le **Terminal**. Ce qui ne tient pas en mémoire est lu depuis votre SSD : il faut donc beaucoup d'espace disque libre. + +| Jeu (IST-DAS) | Téléchargement | Espace disque libre nécessaire | +| --- | ---: | ---: | +| 1.75 bpw | 239 GB | environ 245 GB | +| 2.00 bpw | 257 GB | environ 265 GB | +| 2.25 bpw | 274 GB | environ 280 GB | + +Fonctionne sur les NVIDIA RTX 30, 40 et 50 (Windows et Linux) et sur l'AMD Radeon AI PRO R9700 (Linux). L'installation télécharge les fichiers et le moteur DeepSeek, puis démarre le modèle. + +```sh +strata launch --family deepseek41 --model ist-das-2.00bpw --plan +``` + +Mesuré avec le jeu 2.00 bpw sur Strata 0.2.5. « Sortie » est la vitesse de la réponse, « Prompt » la vitesse à laquelle Strata lit votre texte. + +| Matériel | Sortie | Prompt | +| --- | ---: | ---: | +| RTX 5070 12 GB, 64 GB de RAM | 4 à 6 tokens/s | environ 110 tokens/s (4K) | +| RTX 3060 12 GB, 46 GB de RAM | 9 à 11 tokens/s | environ 155 tokens/s (4K) | +| 1x Radeon AI PRO R9700, 251 GB de RAM | 21 à 25 tokens/s | 320 à 360 tokens/s (8K) | +| 4x Radeon AI PRO R9700 | 74 à 77 tokens/s | 400 à 450 tokens/s (8K) | + +[Mémoire, disque et détails](docs/DEEPSEEK41.md) · [Notes de version](https://github.com/Niko1221/Strata/releases) + +
+ + + +Vous ne savez pas ce qui tient ? [Choisir un modèle pour votre ordinateur](docs/MODELS.md#pick-by-memory). + +## Installation + + + +### Application de bureau + +**[Télécharger Strata pour Windows, Linux ou Mac →](https://github.com/Niko1221/Strata/releases/latest)** + +Installez l'application, choisissez un modèle et commencez à discuter. Il y a un seul installateur par système. Au premier lancement, l'application télécharge le moteur de votre carte graphique. [Aide pour l'installateur](docs/INSTALL.md#the-app). + +Fichiers: `Strata-0.2.5-windows-x64-setup.exe` · `Strata-0.2.5-linux-x86_64.AppImage` · `Strata-0.2.5-macos-arm64.dmg` + +

+ Application de bureau Strata avec une discussion et un aperçu du code en direct côte à côte +
Discussion, fichiers et aperçu en direct dans une seule fenêtre. +

+ + + +### Application Terminal + +Vous préférez le terminal ? Installez Strata, puis lancez **`strata launch`**. + +
+Commandes d'installation + +**Linux / Mac** + +```sh +curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh +``` + +**Windows PowerShell** + +```powershell +irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex +``` + +Sous Windows, ouvrez ensuite un nouveau terminal. Puis : + +```sh +strata launch +``` + +Suivez les invites pour télécharger et démarrer un modèle. [Guide du Terminal](docs/TERMINAL_LAUNCH.md). + +
+ +

+ Application Terminal de Strata affichant l'activité du modèle, la vitesse, la mémoire et les requêtes récentes +
Suivez votre modèle et votre matériel pendant qu'il tourne. +

+ + + +[Compiler depuis les sources](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [Guide d'installation complet](docs/INSTALL.md) + + + +## Matériel + +| Matériel pris en charge | Guide | +| --- | --- | +| **NVIDIA GeForce RTX 20 / 30 / 40 / 50** | [Installation NVIDIA](docs/INSTALL.md#what-you-need) | +| **AMD Radeon RX 7700 / 7800 / 7900, RX 9060 / 9070, AI PRO R9700** | [Installation AMD](docs/AMD_HIP.md) | +| **AMD Radeon RX 6800 / 6900 · expérimental** | [Installation RX 6000](docs/AMD_HIP.md#rdna2-gfx1030) | +| **Intel Arc · Linux** | [Installation Intel](docs/INTEL_ARC.md) | +| **Apple Silicon · M1 ou plus récent** | [Installation sur Mac](docs/MAC.md) | +| **AMD Ryzen AI Max · Strix Halo** | [Installation Strix Halo](docs/STRIX_HALO.md) | + + + +## Outils + +**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw**, et d'autres via les API compatibles OpenAI et Anthropic. + +Lancez **`strata connect`** pour voir la configuration de votre outil. [Guide de connexion](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect). + + + + + + +## Aide + +[Tous les guides](docs) · [Dépannage](docs/TROUBLESHOOTING.md) · [Signaler un bogue](https://github.com/Niko1221/Strata/issues/new/choose) · +[Benchmarks](docs/COMMUNITY_BENCHMARKS.md) · [Comment ça marche](docs/HOW_IT_WORKS.md) · [Contribuer](CONTRIBUTING.md) + +## Soutenir Strata + +**Aidez à garder l'IA locale ouverte à tous.** Un café aide à financer le développement et les tests sur davantage de matériel. + +Buy Me a Coffee : soutenir Strata + +[Licence MIT](LICENSE) · [Crédits et licences des modèles](docs/HOW_IT_WORKS.md#credits) · [Confidentialité](docs/SAFETY.md) + + + +Pour les outils d'IA et les lecteurs automatiques : référence technique · instructions d'installation. + +**Parrainages, partenariats matériel ou collaborations :** [niko.veit@outlook.com](mailto:niko.veit@outlook.com). diff --git a/engine/strata/README.ja.md b/engine/strata/README.ja.md new file mode 100644 index 00000000..4a180076 --- /dev/null +++ b/engine/strata/README.ja.md @@ -0,0 +1,188 @@ +

+ + + Strata + +

+ +

あなた自身のパソコンで、高性能な AI を。

+

チャット、コーディング、画像の処理を、すべてローカルで。

+ +

+ モデル · インストール · + ハードウェア · ツール · + ヘルプ · 支援 +

+ +

+ Strata をダウンロード + MIT ライセンス + Buy Me a Coffee で Strata を支援する +

+ +

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português

+ +**無料でオープンソース。自分の環境で動かせます。** デスクトップで、またはお好みのコーディングツールと一緒に Strata を使えます。アカウントは不要です。 + +## モデル + +まず **ISTA-DASLab** をおすすめします。次に **Unsloth** などの提供元です。メモリに収まる互換モデルがある場合に選べます。 + +
+  Qwen3.8-Flash-Next + +| 提供元 | 選択肢 | +| --- | --- | +| **ISTA-DASLab · おすすめ** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S。[Coder: IQ1\_M](docs/MODELS.md#coder)(コーディング向け)。 | +| **Unsloth** | UD-IQ4\_XS, UD-Q4\_K\_XL, UD-Q5\_K\_XL, UD-Q6\_K\_XL, Q8\_0 | +| **Gyro · agentionai** | [Gyro-S, Gyro-M](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF)。メモリ使用量は少ないですが、動作は遅くなります。 | +| **その他の選択肢** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) | + +[サイズ、必要なメモリ、互換性を比べる](docs/MODELS.md)。 + +
+ +
+  Qwen3.6-35B-A3B + +**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0。現在、このモデルで文書化されているパックです。 + +[モデルガイドと互換性](docs/QWEN36.md)。 + +
+ +
+  DeepSeekV4.1-Flash-1017 + +**デスクトップアプリ**と**ターミナル**で使えます。メモリに収まらない分は SSD から読み込むため、空きディスク容量がたくさん必要です。 + +| セット(IST-DAS) | ダウンロード | 必要な空き容量 | +| --- | ---: | ---: | +| 1.75 bpw | 239 GB | 約245 GB | +| 2.00 bpw | 257 GB | 約265 GB | +| 2.25 bpw | 274 GB | 約280 GB | + +NVIDIA RTX 30・40・50 シリーズ(Windows と Linux)と、AMD Radeon AI PRO R9700(Linux)で動きます。セットアップがファイルと DeepSeek エンジンをダウンロードし、モデルを起動します。 + +```sh +strata launch --family deepseek41 --model ist-das-2.00bpw --plan +``` + +Strata 0.2.5 で 2.00 bpw のセットを使って測定しました。「出力」は回答の速さ、「プロンプト」は Strata が入力を読み込む速さです。 + +| ハードウェア | 出力 | プロンプト | +| --- | ---: | ---: | +| RTX 5070 12 GB, 64 GB RAM | 4〜6 トークン/秒 | 約 110 トークン/秒 (4K) | +| RTX 3060 12 GB, 46 GB RAM | 9〜11 トークン/秒 | 約 155 トークン/秒 (4K) | +| 1x Radeon AI PRO R9700, 251 GB RAM | 21〜25 トークン/秒 | 320〜360 トークン/秒 (8K) | +| 4x Radeon AI PRO R9700 | 74〜77 トークン/秒 | 400〜450 トークン/秒 (8K) | + +[メモリ、ディスク、詳細](docs/DEEPSEEK41.md) · [リリースノート](https://github.com/Niko1221/Strata/releases) + +
+ + + +どれが動くかわからない場合は、[お使いのパソコンに合うモデルを選ぶ](docs/MODELS.md#pick-by-memory)。 + +## インストール + + + +### デスクトップアプリ + +**[Windows、Linux、Mac 用の Strata をダウンロード →](https://github.com/Niko1221/Strata/releases/latest)** + +アプリをインストールし、モデルを選んで、チャットを始めましょう。インストーラーはシステムごとに1つです。初回起動時に、アプリがお使いのグラフィックスカード用のエンジンをダウンロードします。[インストーラーのヘルプ](docs/INSTALL.md#the-app)。 + +ファイル: `Strata-0.2.5-windows-x64-setup.exe` · `Strata-0.2.5-linux-x86_64.AppImage` · `Strata-0.2.5-macos-arm64.dmg` + +

+ チャットとライブのコードプレビューを並べて表示した Strata デスクトップアプリ +
チャット、ファイル、ライブプレビューを1つのウィンドウで。 +

+ + + +### ターミナルアプリ + +ターミナルのほうが好みですか? Strata をインストールして、**`strata launch`** を実行します。 + +
+インストールコマンド + +**Linux / Mac** + +```sh +curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh +``` + +**Windows PowerShell** + +```powershell +irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex +``` + +Windows では、インストール後に新しいターミナルを開きます。そのあと: + +```sh +strata launch +``` + +画面の案内に従って、モデルをダウンロードして起動します。[ターミナルガイド](docs/TERMINAL_LAUNCH.md)。 + +
+ +

+ モデルの動作、速度、メモリ、最近のリクエストを表示する Strata ターミナルアプリ +
動作中のモデルとハードウェアの状態を確認できます。 +

+ + + +[ソースからビルド](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [インストールガイド(全文)](docs/INSTALL.md) + + + +## ハードウェア + +| 対応ハードウェア | ガイド | +| --- | --- | +| **NVIDIA GeForce RTX 20 / 30 / 40 / 50 シリーズ** | [NVIDIA のセットアップ](docs/INSTALL.md#what-you-need) | +| **AMD Radeon RX 7700 / 7800 / 7900、RX 9060 / 9070、AI PRO R9700** | [AMD のセットアップ](docs/AMD_HIP.md) | +| **AMD Radeon RX 6800 / 6900 · 試験的** | [RX 6000 のセットアップ](docs/AMD_HIP.md#rdna2-gfx1030) | +| **Intel Arc · Linux** | [Intel のセットアップ](docs/INTEL_ARC.md) | +| **Apple Silicon · M1 以降** | [Mac のセットアップ](docs/MAC.md) | +| **AMD Ryzen AI Max · Strix Halo** | [Strix Halo のセットアップ](docs/STRIX_HALO.md) | + + + +## ツール + +**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw**。OpenAI 互換と Anthropic 互換の API を通じて、ほかのツールも使えます。 + +**`strata connect`** を実行すると、お使いのツールの設定方法が表示されます。[接続ガイド](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect)。 + + + + + + +## ヘルプ + +[すべてのガイド](docs) · [トラブルシューティング](docs/TROUBLESHOOTING.md) · [不具合を報告](https://github.com/Niko1221/Strata/issues/new/choose) · +[ベンチマーク](docs/COMMUNITY_BENCHMARKS.md) · [仕組み](docs/HOW_IT_WORKS.md) · [貢献する](CONTRIBUTING.md) + +## Strata を支援する + +**ローカル AI をみんなに開かれたものに。** コーヒー1杯が、開発と、より多くのハードウェアでのテストの支えになります。 + +Buy Me a Coffee: Strata を支援する + +[MIT ライセンス](LICENSE) · [クレジットとモデルのライセンス](docs/HOW_IT_WORKS.md#credits) · [プライバシー](docs/SAFETY.md) + + + +AI ツールと自動リーダー向け: 技術リファレンス · セットアップ手順 + +**スポンサー、ハードウェア提携、共同開発のご相談:** [niko.veit@outlook.com](mailto:niko.veit@outlook.com). diff --git a/engine/strata/README.md b/engine/strata/README.md index 10812dcb..0c9be0d1 100644 --- a/engine/strata/README.md +++ b/engine/strata/README.md @@ -1,184 +1,191 @@ -

Strata

+

+ + + Strata + +

-

Run a 125-billion-parameter AI model on your own gaming PC
-NVIDIA or AMD graphics card (12 GB or more) · Windows or Linux · free and open source

+

Run powerful AI on your own computer.

+

Chat, code and work with images, locally.

-

A voxel pagoda garden that Strata's model wrote, running in the browser
-A voxel pagoda garden, 1 shot prompt running on an RTX 5070 with Strata (IQ3_S, 128K context) · -full video (49 s)

+

+ Models · Install · + Hardware · Tools · + Help · Support +

-Strata runs **[Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next)** - a large, smart AI model that -normally needs a server - on a normal PC. It chats, writes code, reads pictures and works with your apps and coding -agents, and nothing leaves your PC. +

+ Download Strata + MIT license + Support Strata on Buy Me a Coffee +

-## How fast is it? +

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português

-Measured on two ordinary gaming PCs. "Writes answers" is how fast the reply appears in a short chat; "reads your -prompt" is how fast it takes in what you send (a 32K-token document, code or chat history). A token is about ¾ of a -word, so 60 tokens per second is faster than you can read. +**Free, open source, and yours to run.** Use Strata on your desktop or with your favorite coding tools. No account needed. - - - -
NVIDIA: RTX 5070 (12 GB), Ryzen 5 7600, 64 GB RAMAMD: RX 9070 XT (16 GB), Ryzen 9 3900X, 47 GB RAM
+## Models -| Size | Writes answers | Reads your prompt | -| --- | ---: | ---: | -| **Q2_0** | 93 tokens/s | 2,170 tokens/s | -| **IQ2_XS** | 79 tokens/s | 2,090 tokens/s | -| **IQ3_XXS** | 62 tokens/s | 1,750 tokens/s | -| **IQ3_S** | 53 tokens/s | 1,620 tokens/s | -| **Coder** | 55 tokens/s | 2,180 tokens/s | +We recommend **ISTA-DASLab first**, then **Unsloth** and other providers, where a compatible model fits. - +
+  Qwen3.8-Flash-Next -| Size | Writes answers | Reads your prompt | -| --- | ---: | ---: | -| **Q2_0** | 60 tokens/s | 1,160 tokens/s | -| **IQ2_XS** | 52 tokens/s | 1,110 tokens/s | -| **Coder** | 44 tokens/s | 1,420 tokens/s | - -
- -A card with more VRAM is faster: an RTX 3090 (24 GB) should write roughly 100-140 tokens per second. Long chats, -other cards: [speed of each model](docs/MODELS.md#how-fast-is-each-size), [community results](docs/COMMUNITY_BENCHMARKS.md). - -

Buy Me A Coffee
-Strata is free. If it runs well on your PC, a coffee keeps the work on it going.

- -## What you need - -| | | +| Provider | Choices | | --- | --- | -| **Graphics card** | **NVIDIA** GeForce RTX 20, 30, 40 or 50 series, or **AMD** Radeon RX 7900 XT / XTX, RX 7800 XT / 7700 XT, RX 9060 XT, RX 9070 / 9070 XT, Radeon AI PRO R9700 or RX 6800 / 6900 series - with **12 GB of VRAM or more** | -| **RAM** | 32 GB or more - how much decides [which model](#which-model-should-i-pick) fits; 64 GB runs every size | -| **Disk** | about 80 GB free, on an SSD if you can (the first start is much faster) | -| **System** | Windows 10 / 11 or Linux, and a current graphics driver from NVIDIA or AMD | +| **ISTA-DASLab · recommended** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S. [Coder: IQ1\_M](docs/MODELS.md#coder) for coding. | +| **Unsloth** | UD-IQ4\_XS, UD-Q4\_K\_XL, UD-Q5\_K\_XL, UD-Q6\_K\_XL, Q8\_0 | +| **Gyro · agentionai** | [Gyro-S, Gyro-M](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF). Lower memory use but slower. | +| **Other options** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) | -Everything else is installed for you. Two or three cards can share the model ([multi-GPU](docs/MULTI_GPU.md)). -The full list: [docs/INSTALL.md](docs/INSTALL.md#what-you-need). +[Compare sizes, memory needs and compatibility](docs/MODELS.md). + + + +
+  Qwen3.6-35B-A3B + +**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0. These are the currently documented packs for this model. + +[Model guide and compatibility](docs/QWEN36.md). + +
+ +
+  DeepSeekV4.1-Flash-1017 + +In the **desktop app** and the **Terminal**. What does not fit in memory is read from your SSD, so it needs a lot of free +disk space. + +| Set (IST-DAS) | Download | Free disk needed | +| --- | ---: | ---: | +| 1.75 bpw | 239 GB | about 245 GB | +| 2.00 bpw | 257 GB | about 265 GB | +| 2.25 bpw | 274 GB | about 280 GB | + +Runs on NVIDIA RTX 30, 40 and 50 series (Windows and Linux) and AMD Radeon AI PRO R9700 (Linux). Setup downloads the +files and the DeepSeek engine, then starts the model. + +```sh +strata launch --family deepseek41 --model ist-das-2.00bpw --plan +``` + +Measured with the 2.00 bpw set on Strata 0.2.5. Output is the speed of the answer, prompt is how fast Strata reads your input. + +| Hardware | Output | Prompt | +| --- | ---: | ---: | +| RTX 5070 12 GB, 64 GB RAM | 4 to 6 tokens/s | about 110 tokens/s (4K) | +| RTX 3060 12 GB, 46 GB RAM | 9 to 11 tokens/s | about 155 tokens/s (4K) | +| 1x Radeon AI PRO R9700, 251 GB RAM | 21 to 25 tokens/s | 320 to 360 tokens/s (8K) | +| 4x Radeon AI PRO R9700 | 74 to 77 tokens/s | 400 to 450 tokens/s (8K) | + +[Memory, disk and details](docs/DEEPSEEK41.md) · [Release notes](https://github.com/Niko1221/Strata/releases) + +
+ + + +Not sure what fits? [Choose a model for your computer](docs/MODELS.md#pick-by-memory). ## Install -### Let your AI set it up + -Use an AI coding assistant (Claude Code, Cursor, Codex, GitHub Copilot, ...)? Paste this into it: +### Desktop app -```text -Set up Strata on this PC for me: https://github.com/Niko1221/Strata - follow docs/AI_SETUP.md in that repository. +**[Download Strata for Windows, Linux or Mac →](https://github.com/Niko1221/Strata/releases/latest)** + +Install the app, choose a model, and start chatting. There is one installer for each system. On first start the app +downloads the engine for your graphics card. [Help with the installer](docs/INSTALL.md#the-app). + +Files: `Strata-0.2.5-windows-x64-setup.exe` · `Strata-0.2.5-linux-x86_64.AppImage` · `Strata-0.2.5-macos-arm64.dmg` + +

+ Strata desktop app with a chat and live code preview side by side +
Chat, files and a live preview in one window. +

+ + + +### Terminal app + +Prefer the terminal? Install Strata, then run **`strata launch`**. + +
+Install commands + +**Linux / Mac** + +```sh +curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh ``` -It checks your graphics card, RAM and disk, picks the model that fits, installs it, starts it and tells you how to -connect your apps. AI tools can also install, start and stop Strata themselves through its -[MCP server](docs/MCP_SERVER.md). +**Windows PowerShell** -### Or do it yourself +```powershell +irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex +``` -[Download Strata](https://github.com/Niko1221/Strata/archive/refs/heads/main.zip) and unzip it (or `git clone` it). -**Windows:** double-click **`START-HERE.bat`**. **Linux:** run **`./setup.sh`** in the Strata folder. +On Windows, open a new terminal afterwards. Then: -The same steps for NVIDIA and AMD: the installer finds your card and sets up the right engine for it. It asks which -model, which size, how much context (how much text it keeps in mind) and whether it should read pictures - press -Enter each time for the recommended answer. Then it downloads the model (~70 GB; you can stop and it continues where -it left off) and starts it. Your browser opens the Strata app at `http://127.0.0.1:8080`. +```sh +strata launch +``` -> **While the model starts, your PC can be slow or stop responding for 1-3 minutes** (longest the first time): Strata -> loads 35-55 GB into your RAM and locks part of it for the graphics card. That's normal - wait, and don't close the -> window. The window tells you what it is doing. +Follow the prompts to download and start a model. [Terminal guide](docs/TERMINAL_LAUNCH.md). -**Next time**, run `START-HERE.bat` (or `./setup.sh`) again: it starts right away, nothing is downloaded twice. Close -its window to stop the model. Updating, Docker, several cards, where the files go and every option: -[docs/INSTALL.md](docs/INSTALL.md). +
-## Which model should I pick? +

+ Strata terminal app showing model activity, speed, memory and recent requests +
Watch your model and hardware while it runs. +

-The installer recommends one for your RAM. The same model comes in sizes that are compressed more or less: smaller -is faster, larger is a bit smarter. + -| Your RAM | Take | Why | -| --- | --- | --- | -| **32 GB** | **Coder** | it fits 32 GB, and it is made for code (with a 24 GB card, Q2_0 and IQ2_XS run too) | -| **48 GB** | **IQ2_XS** (or Q2_0, the fastest) | the larger sizes do not fit | -| **64 GB** | **IQ2_XS** (recommended), or IQ3_XXS / IQ3_S | every size fits; IQ3_S is the best, and the slowest | -| **96 GB or more** | **IQ3_S**, or Unsloth's 4-bit (experimental) | room for the largest sizes with everything else open | +[Build from source](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [Full install guide](docs/INSTALL.md) -- **[Coder](docs/MODELS.md#coder)** - a coding version with half of the experts removed: 91% of the full model's - SWE-bench Verified score (by its authors), fits 32 GB of RAM. Weaker outside code, including Chinese and other - CJK text (#438): for those, take Q2_0, IQ2_XS or IQ3_S, which keep every expert. -- **[Swift 1.5](docs/MODELS.md#swift-15)** - a fine-tune that thinks much shorter before it answers, so you get the - answer sooner, at about the same quality. -- **[Unsloth UD-Q4_K_XL](docs/MODELS.md#unsloth-ud-q4_k_xl-experimental)** (experimental) - the closest to the full - model, but most of it is read from the SSD while it answers: 7-8.5 tokens/s on a 64 GB PC. -- **[OrcaRouter's Uncensored IQ3_XXS](docs/MODELS.md#orcarouter-uncensored-iq3_xxs)** - a manual setup, not in the - installer's menu. + -Sizes, downloads and what fits where: [docs/MODELS.md](docs/MODELS.md). You can add another model later with -`SETUP.bat` (Linux: `./setup.sh --setup`). +## Hardware -## Using it +| Supported hardware | Guide | +| --- | --- | +| **NVIDIA GeForce RTX 20 / 30 / 40 / 50 series** | [NVIDIA setup](docs/INSTALL.md#what-you-need) | +| **AMD Radeon RX 7700 / 7800 / 7900, RX 9060 / 9070, AI PRO R9700** | [AMD setup](docs/AMD_HIP.md) | +| **AMD Radeon RX 6800 / 6900 · experimental** | [RX 6000 setup](docs/AMD_HIP.md#rdna2-gfx1030) | +| **Intel Arc · Linux** | [Intel setup](docs/INTEL_ARC.md) | +| **Apple Silicon · M1 or newer** | [Mac setup](docs/MAC.md) | +| **AMD Ryzen AI Max · Strix Halo** | [Strix Halo setup](docs/STRIX_HALO.md) | -

The Strata app's Monitor tab next to a coding agent
-The Strata app's Monitor (left) while a coding agent writes the pagoda garden from the video (right)

+ -- **In the browser:** `http://127.0.0.1:8080` - **Chat**, a live **Monitor** of the model and your GPU/CPU/RAM, and - **About** with the settings and addresses. -- **Your apps and coding agents:** add an "OpenAI-compatible" provider with base URL **`http://127.0.0.1:8080/v1`**, - any API key and any model name. Apps that use Anthropic's API: `http://127.0.0.1:8080/v1/messages` (Claude Code: - `ANTHROPIC_BASE_URL=http://127.0.0.1:8080`). -- **Thinking:** choose **off, low, medium or high** in the chat menu or your app's "reasoning effort". Off is - fastest; high is best for hard questions. -- **Pictures:** say yes to "Images?" in setup, then click **Picture** in the chat, or attach them in your app - (AMD cards: on Linux through the processor, not on Windows yet). -- **From your phone or another PC:** `START-HERE.bat --setup --host 0.0.0.0 --api-key ` - always with a key. -- **Good to know:** it answers one request at a time. The first message of a chat is read in full (about 1 minute - per 30,000 tokens); follow-ups start in seconds. +## Tools -More: [where your chats are stored](docs/INSTALL.md#where-things-are-stored), [the API](docs/DETAILS.md#using-it). +**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw**, and more through the OpenAI- and Anthropic-compatible APIs. -## Something went wrong? +Run **`strata connect`** to see setup instructions for your tool. [Connection guide](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect). -- **My PC froze the first time Strata started.** Normal while it loads the model: wait, don't close the window. - Still frozen after 10 minutes? Restart the PC, close other programs and try again, or pick a smaller size. -- **It stopped while downloading or installing.** Run `START-HERE.bat` (or `./setup.sh`) again: it continues where - it stopped. -- **It's very slow and the disk light keeps blinking, or "the engine stopped unexpectedly".** Not enough free RAM: - close other programs (browsers use a lot), or pick a smaller size (Q2_0 or IQ2_XS). -- **It says port 8080 is already in use.** Strata is already running - look for its window. + + + + -More problems and their fixes: [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md). Still stuck? Open an -[issue](https://github.com/Niko1221/Strata/issues) and attach `strata-.log` from the Strata folder. +## Help -## How does it work? - -Models like this one normally run on servers with hundreds of gigabytes of graphics memory. Your graphics card has -12-24 GB. Strata makes it fit by **sharing the work across your whole PC** - like a kitchen, where the things you use -all the time stay on the counter and the rest waits in the pantry. - -

The model's 24,576 experts: the busiest on the graphics card, all of them in RAM, a lookup table on the SSD

- -- **The model is a team of 24,576 small specialists ("experts"),** and each word needs only 10 of them. -- **Your graphics card** keeps the few thousand experts that are asked most often; **your RAM** holds all of them, - and **your processor** works on the rest at the same time. **Your SSD** holds a big lookup table. - -

A small helper guesses the next words; the big model checks them all at once and keeps the right ones

- -- **Guess, then check:** a small helper guesses the next few words and the big model checks them all at once, so - you get the same answer, 1.6-1.8x sooner. -- **Long texts are read in big pieces** (up to 8,192 tokens at a time): over 1,000 tokens per second. - -The longer explanation: [docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md). Every part and its numbers: [the -details](docs/DETAILS.md#how-it-works) and the [paper](docs/paper/Strata-Paper.pdf). - -## Credits and license - -The model is [Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next) by the Qwen team, compressed by -[ISTA-DASLab](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF), UkisAI (Swift 1.5) and Unsloth; -Strata is built with parts of [llama.cpp / ggml](https://github.com/ggml-org/llama.cpp). All credits: -[docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md#credits). Strata is open source under the [MIT License](LICENSE); a few -parts and every model carry their own licenses ([which ones](docs/HOW_IT_WORKS.md#license)). +[All guides](docs) · [Troubleshooting](docs/TROUBLESHOOTING.md) · [Report a bug](https://github.com/Niko1221/Strata/issues/new/choose) · +[Benchmarks](docs/COMMUNITY_BENCHMARKS.md) · [How it works](docs/HOW_IT_WORKS.md) · [Contribute](CONTRIBUTING.md) ## Support Strata -Strata is free and open source. If it is useful to you, you can support its development: +**Help keep local AI open to everyone.** A coffee helps fund development and testing on more hardware. -

Buy Me A Coffee

+Buy Me a Coffee: support Strata + +[MIT license](LICENSE) · [Credits and model licenses](docs/HOW_IT_WORKS.md#credits) · [Privacy](docs/SAFETY.md) + + + +For AI tools and automated readers: technical reference · setup instructions. + +**Sponsorships, hardware partnerships or collaborations:** [niko.veit@outlook.com](mailto:niko.veit@outlook.com). diff --git a/engine/strata/README.pt-BR.md b/engine/strata/README.pt-BR.md new file mode 100644 index 00000000..f268b29a --- /dev/null +++ b/engine/strata/README.pt-BR.md @@ -0,0 +1,188 @@ +

+ + + Strata + +

+ +

IA poderosa no seu próprio computador.

+

Converse, programe e trabalhe com imagens, localmente.

+ +

+ Modelos · Instalação · + Hardware · Ferramentas · + Ajuda · Apoiar +

+ +

+ Baixar o Strata + Licença MIT + Apoie o Strata no Buy Me a Coffee +

+ +

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português

+ +**Gratuito, de código aberto e seu para executar.** Use o Strata no desktop ou com suas ferramentas de programação favoritas. Não precisa de conta. + +## Modelos + +Recomendamos **primeiro a ISTA-DASLab**, depois a **Unsloth** e outros provedores, quando um modelo compatível cabe na memória. + +
+  Qwen3.8-Flash-Next + +| Provedor | Opções | +| --- | --- | +| **ISTA-DASLab · recomendado** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S. [Coder: IQ1\_M](docs/MODELS.md#coder) para programar. | +| **Unsloth** | UD-IQ4\_XS, UD-Q4\_K\_XL, UD-Q5\_K\_XL, UD-Q6\_K\_XL, Q8\_0 | +| **Gyro · agentionai** | [Gyro-S, Gyro-M](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF). Usa menos memória, mas é mais lento. | +| **Outras opções** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) | + +[Compare tamanhos, necessidades de memória e compatibilidade](docs/MODELS.md). + +
+ +
+  Qwen3.6-35B-A3B + +**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0. Esses são os pacotes documentados atualmente para este modelo. + +[Guia do modelo e compatibilidade](docs/QWEN36.md). + +
+ +
+  DeepSeekV4.1-Flash-1017 + +No **aplicativo de desktop** e no **Terminal**. O que não cabe na memória é lido do seu SSD, por isso é preciso muito espaço livre em disco. + +| Conjunto (IST-DAS) | Download | Espaço livre necessário | +| --- | ---: | ---: | +| 1.75 bpw | 239 GB | cerca de 245 GB | +| 2.00 bpw | 257 GB | cerca de 265 GB | +| 2.25 bpw | 274 GB | cerca de 280 GB | + +Roda em NVIDIA RTX 30, 40 e 50 (Windows e Linux) e em AMD Radeon AI PRO R9700 (Linux). A instalação baixa os arquivos e o motor do DeepSeek e depois inicia o modelo. + +```sh +strata launch --family deepseek41 --model ist-das-2.00bpw --plan +``` + +Medido com o conjunto de 2.00 bpw no Strata 0.2.5. “Saída” é a velocidade da resposta; “Prompt” é a rapidez com que o Strata lê o seu texto. + +| Hardware | Saída | Prompt | +| --- | ---: | ---: | +| RTX 5070 12 GB, 64 GB de RAM | 4 a 6 tokens/s | cerca de 110 tokens/s (4K) | +| RTX 3060 12 GB, 46 GB de RAM | 9 a 11 tokens/s | cerca de 155 tokens/s (4K) | +| 1x Radeon AI PRO R9700, 251 GB de RAM | 21 a 25 tokens/s | 320 a 360 tokens/s (8K) | +| 4x Radeon AI PRO R9700 | 74 a 77 tokens/s | 400 a 450 tokens/s (8K) | + +[Memória, disco e detalhes](docs/DEEPSEEK41.md) · [Notas da versão](https://github.com/Niko1221/Strata/releases) + +
+ + + +Não sabe o que cabe? [Escolha um modelo para o seu computador](docs/MODELS.md#pick-by-memory). + +## Instalação + + + +### Aplicativo de desktop + +**[Baixar o Strata para Windows, Linux ou Mac →](https://github.com/Niko1221/Strata/releases/latest)** + +Instale o aplicativo, escolha um modelo e comece a conversar. Há um instalador por sistema. Na primeira vez que abre, o aplicativo baixa o motor da sua placa de vídeo. [Ajuda com o instalador](docs/INSTALL.md#the-app). + +Arquivos: `Strata-0.2.5-windows-x64-setup.exe` · `Strata-0.2.5-linux-x86_64.AppImage` · `Strata-0.2.5-macos-arm64.dmg` + +

+ Aplicativo de desktop do Strata com um chat e uma prévia do código ao vivo lado a lado +
Chat, arquivos e prévia ao vivo em uma só janela. +

+ + + +### Aplicativo de Terminal + +Prefere o terminal? Instale o Strata e execute **`strata launch`**. + +
+Comandos de instalação + +**Linux / Mac** + +```sh +curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh +``` + +**Windows PowerShell** + +```powershell +irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex +``` + +No Windows, abra um novo terminal depois. Em seguida: + +```sh +strata launch +``` + +Siga as instruções para baixar e iniciar um modelo. [Guia do Terminal](docs/TERMINAL_LAUNCH.md). + +
+ +

+ Aplicativo de Terminal do Strata mostrando a atividade do modelo, a velocidade, a memória e as solicitações recentes +
Acompanhe seu modelo e seu hardware enquanto ele roda. +

+ + + +[Compilar a partir do código-fonte](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [Guia de instalação completo](docs/INSTALL.md) + + + +## Hardware + +| Hardware compatível | Guia | +| --- | --- | +| **NVIDIA GeForce RTX 20 / 30 / 40 / 50** | [Instalação para NVIDIA](docs/INSTALL.md#what-you-need) | +| **AMD Radeon RX 7700 / 7800 / 7900, RX 9060 / 9070, AI PRO R9700** | [Instalação para AMD](docs/AMD_HIP.md) | +| **AMD Radeon RX 6800 / 6900 · experimental** | [Instalação para RX 6000](docs/AMD_HIP.md#rdna2-gfx1030) | +| **Intel Arc · Linux** | [Instalação para Intel](docs/INTEL_ARC.md) | +| **Apple Silicon · M1 ou mais novo** | [Instalação para Mac](docs/MAC.md) | +| **AMD Ryzen AI Max · Strix Halo** | [Instalação para Strix Halo](docs/STRIX_HALO.md) | + + + +## Ferramentas + +**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw**, e outras, pelas APIs compatíveis com OpenAI e Anthropic. + +Execute **`strata connect`** para ver as instruções da sua ferramenta. [Guia de conexão](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect). + + + + + + +## Ajuda + +[Todos os guias](docs) · [Solução de problemas](docs/TROUBLESHOOTING.md) · [Relatar um bug](https://github.com/Niko1221/Strata/issues/new/choose) · +[Benchmarks](docs/COMMUNITY_BENCHMARKS.md) · [Como funciona](docs/HOW_IT_WORKS.md) · [Contribuir](CONTRIBUTING.md) + +## Apoie o Strata + +**Ajude a manter a IA local aberta para todos.** Um café ajuda a financiar o desenvolvimento e os testes em mais hardware. + +Buy Me a Coffee: apoie o Strata + +[Licença MIT](LICENSE) · [Créditos e licenças dos modelos](docs/HOW_IT_WORKS.md#credits) · [Privacidade](docs/SAFETY.md) + + + +Para ferramentas de IA e leitores automáticos: referência técnica · instruções de instalação. + +**Patrocínios, parcerias de hardware ou colaborações:** [niko.veit@outlook.com](mailto:niko.veit@outlook.com). diff --git a/engine/strata/README.zh-CN.md b/engine/strata/README.zh-CN.md new file mode 100644 index 00000000..43abda7b --- /dev/null +++ b/engine/strata/README.zh-CN.md @@ -0,0 +1,188 @@ +

+ + + Strata + +

+ +

在你自己的电脑上运行强大的 AI。

+

本地聊天、写代码、处理图片。

+ +

+ 模型 · 安装 · + 硬件 · 工具 · + 帮助 · 支持 +

+ +

+ 下载 Strata + MIT 许可证 + 在 Buy Me a Coffee 上支持 Strata +

+ +

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português

+ +**免费、开源,由你自己运行。** 在桌面上使用 Strata,或搭配你喜欢的编程工具。无需账号。 + +## 模型 + +我们**首先推荐 ISTA-DASLab**,其次是 **Unsloth** 和其他提供方,前提是有内存放得下的兼容模型。 + +
+  Qwen3.8-Flash-Next + +| 提供方 | 可选项 | +| --- | --- | +| **ISTA-DASLab · 推荐** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S。[Coder:IQ1\_M](docs/MODELS.md#coder),适合写代码。 | +| **Unsloth** | UD-IQ4\_XS, UD-Q4\_K\_XL, UD-Q5\_K\_XL, UD-Q6\_K\_XL, Q8\_0 | +| **Gyro · agentionai** | [Gyro-S, Gyro-M](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF)。占用内存更少,但速度更慢。 | +| **其他选项** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) | + +[比较大小、内存需求和兼容性](docs/MODELS.md)。 + +
+ +
+  Qwen3.6-35B-A3B + +**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0。这些是目前文档中收录的该模型的版本。 + +[模型指南和兼容性](docs/QWEN36.md)。 + +
+ +
+  DeepSeekV4.1-Flash-1017 + +可在**桌面应用**和**终端**中使用。内存放不下的部分会从 SSD 读取,所以需要大量空闲磁盘空间。 + +| 版本(IST-DAS) | 下载大小 | 所需空闲磁盘 | +| --- | ---: | ---: | +| 1.75 bpw | 239 GB | 约245 GB | +| 2.00 bpw | 257 GB | 约265 GB | +| 2.25 bpw | 274 GB | 约280 GB | + +支持 NVIDIA RTX 30、40 和 50 系列(Windows 和 Linux),以及 AMD Radeon AI PRO R9700(Linux)。安装程序会下载模型文件和 DeepSeek 引擎,然后启动模型。 + +```sh +strata launch --family deepseek41 --model ist-das-2.00bpw --plan +``` + +以下为 Strata 0.2.5 上 2.00 bpw 版本的实测结果。“输出”是回答的速度,“提示词”是 Strata 读取你输入内容的速度。 + +| 硬件 | 输出 | 提示词 | +| --- | ---: | ---: | +| RTX 5070 12 GB, 64 GB 内存 | 4 到 6 tokens/s | 约 110 tokens/s(4K) | +| RTX 3060 12 GB, 46 GB 内存 | 9 到 11 tokens/s | 约 155 tokens/s(4K) | +| 1x Radeon AI PRO R9700, 251 GB 内存 | 21 到 25 tokens/s | 320 到 360 tokens/s (8K) | +| 4x Radeon AI PRO R9700 | 74 到 77 tokens/s | 400 到 450 tokens/s (8K) | + +[内存、磁盘和详细信息](docs/DEEPSEEK41.md) · [发行说明](https://github.com/Niko1221/Strata/releases) + +
+ + + +不确定哪个放得下?[为你的电脑选择模型](docs/MODELS.md#pick-by-memory)。 + +## 安装 + + + +### 桌面应用 + +**[下载适用于 Windows、Linux 或 Mac 的 Strata →](https://github.com/Niko1221/Strata/releases/latest)** + +安装应用,选择模型,就可以开始聊天。每个系统只有一个安装程序。首次启动时,应用会下载适合你显卡的引擎。[安装程序帮助](docs/INSTALL.md#the-app)。 + +文件: `Strata-0.2.5-windows-x64-setup.exe` · `Strata-0.2.5-linux-x86_64.AppImage` · `Strata-0.2.5-macos-arm64.dmg` + +

+ Strata 桌面应用,聊天和实时代码预览并排显示 +
聊天、文件和实时预览都在一个窗口里。 +

+ + + +### 终端应用 + +更喜欢终端?安装 Strata,然后运行 **`strata launch`**。 + +
+安装命令 + +**Linux / Mac** + +```sh +curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh +``` + +**Windows PowerShell** + +```powershell +irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex +``` + +在 Windows 上,安装后请打开一个新的终端。然后运行: + +```sh +strata launch +``` + +按提示下载并启动模型。[终端指南](docs/TERMINAL_LAUNCH.md)。 + +
+ +

+ Strata 终端应用,显示模型活动、速度、内存和最近的请求 +
模型运行时,随时查看模型和硬件状态。 +

+ + + +[从源码构建](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [完整安装指南](docs/INSTALL.md) + + + +## 硬件 + +| 支持的硬件 | 指南 | +| --- | --- | +| **NVIDIA GeForce RTX 20 / 30 / 40 / 50 系列** | [NVIDIA 安装](docs/INSTALL.md#what-you-need) | +| **AMD Radeon RX 7700 / 7800 / 7900、RX 9060 / 9070、AI PRO R9700** | [AMD 安装](docs/AMD_HIP.md) | +| **AMD Radeon RX 6800 / 6900 · 实验性** | [RX 6000 安装](docs/AMD_HIP.md#rdna2-gfx1030) | +| **Intel Arc · Linux** | [Intel 安装](docs/INTEL_ARC.md) | +| **Apple Silicon · M1 或更新** | [Mac 安装](docs/MAC.md) | +| **AMD Ryzen AI Max · Strix Halo** | [Strix Halo 安装](docs/STRIX_HALO.md) | + + + +## 工具 + +**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw**,也可以通过兼容 OpenAI 和 Anthropic 的 API 使用更多工具。 + +运行 **`strata connect`**,查看你所用工具的设置方法。[连接指南](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect)。 + + + + + + +## 帮助 + +[全部指南](docs) · [故障排查](docs/TROUBLESHOOTING.md) · [报告问题](https://github.com/Niko1221/Strata/issues/new/choose) · +[基准测试](docs/COMMUNITY_BENCHMARKS.md) · [工作原理](docs/HOW_IT_WORKS.md) · [参与贡献](CONTRIBUTING.md) + +## 支持 Strata + +**帮助本地 AI 保持开放。** 一杯咖啡能帮助我们在更多硬件上开发和测试。 + +Buy Me a Coffee:支持 Strata + +[MIT 许可证](LICENSE) · [致谢和模型许可证](docs/HOW_IT_WORKS.md#credits) · [隐私](docs/SAFETY.md) + + + +面向 AI 工具和自动阅读器: 技术参考 · 安装说明 + +**赞助、硬件合作或其他合作:** [niko.veit@outlook.com](mailto:niko.veit@outlook.com). diff --git a/engine/strata/SECURITY.md b/engine/strata/SECURITY.md new file mode 100644 index 00000000..8bd61c84 --- /dev/null +++ b/engine/strata/SECURITY.md @@ -0,0 +1,95 @@ +# Security + +## Reporting a vulnerability + +Please report anything that should not be public until it is fixed **privately**, through GitHub's private +vulnerability reporting: the repository's **Security** tab, **Report a vulnerability** +([direct link](https://github.com/Niko1221/Strata/security/advisories/new)). Say what you found, how to reproduce it +(the request, the config keys involved, the Strata version), and what an attacker gains. We answer there, fix it in +a release, and credit you in the advisory unless you ask us not to. + +Ordinary hardening ideas and findings that are safe to discuss in public are welcome as an +[issue](https://github.com/Niko1221/Strata/issues) (#544 collects audit findings) or as a pull request, which we +review like our own code. + +Supported: the latest release. Fixes go into the next release, not into older ones. + +## What the server exposes + +Strata runs a model on your PC and serves it over HTTP (`serve/server.py`). Out of the box it is reachable from +this PC only. The details and every setting are in [docs/DETAILS.md](docs/DETAILS.md) ("From other devices", +"Host names", "Web pages without an API key", "Tools from MCP servers"). + +- **Where it listens.** `127.0.0.1` by default. `--host 0.0.0.0` (or `"host"` in `strata-.json`) opens it to + your network, and the server then warns when no API key is set. +- **API key.** `"api_key"` in the run config (or `STRATA_API_KEY`) is required on `/v1/*` and on every endpoint + that shows the model's state, requests or answers (`/status`, `/metrics`, `/settings`, `/mcp`, `/props`, `/slots`, + `/api/requests`, `/config`) and on every `POST`. It is compared in constant time. Set one before you open the + server to your network or put a tunnel in front of it. +- **Host check (DNS rebinding, 0.1.38).** Without an API key the server answers only requests whose `Host` is a name + it knows (`localhost`, an IP address, the address it listens on and, when it listens beyond this PC, this PC's + name). Others get 403. `"allowed_hosts"` adds names; with an API key the key decides. +- **Origin check (0.1.38).** Without an API key, a browser `POST` to `/v1/*` from another web site's page (it carries + an `Origin` header) gets 403 unless that origin is Strata's own page, `localhost`, an allowed host, or listed in + `"trusted_origins"` / `"cors_origins"`. Changing settings (`/settings`, and `/config`: the few run config keys the + page's Model settings may change - never the network, key, MCP or program keys), `/load` and `/unload` and the + MCP tools are accepted only as JSON from Strata's own page (or `"trusted_origins"`), so a page elsewhere cannot + change settings or run tools. +- **CORS** is off unless `"cors_origins"` lists origins, and then only for `/v1/*`. +- **MCP tools** are opt-in: only the servers you put in the run config, only for requests from Strata's own page + that ask for them. They run with your user's rights, and the model decides when to call them. +- **The request monitor** (`/api-monitor`, which keeps the last prompts and answers in memory) is off unless + `"api_monitor": true` is set. Apart from it, the server keeps in its process memory the text and tokens of its + last few prompts, whatever `"api_monitor"` says, to encode the next turn faster; no endpoint shows them, and they + are gone when the server stops. + +## The desktop app and the Terminal + +Strata comes in three parts that share one engine: the **desktop app**, the **Terminal** (`strata`) and the **engine** that runs +the model. The section above is about the engine's HTTP server. This is what the other two add. + +- **The app's host listens on this PC only.** The app serves its page from a local host process on `127.0.0.1` (port 8791 unless + changed). A request to its `/api/` endpoints that carries a browser `Origin` from any other site gets 403. The app shell holds a + random secret (32 characters or more, compared in constant time) that is needed to quit the host or tell it which window is open, + and the host gives its own helper processes a second random secret. By default the models the app starts are served on this PC only. +- **Sharing is a separate, key-protected listener.** "Share with other devices" (and the Cloudflare tunnel) will not start until an + API key is set. It opens a different listener that answers only `/v1/models`, `/v1/chat/completions` and `/v1/messages`, never the + app's page or its host endpoints. +- **App and Terminal talk through an owner channel.** One owner process per installation starts and ends the engine, and a second + client (the Terminal) attaches to it. On macOS and Linux that is a private Unix socket in a folder only you can open. On Windows it + is a TCP listener on `127.0.0.1` that answers only requests carrying a 256-bit token kept in an owner-only folder. That is a weaker + guarantee than a socket other users cannot open: on Windows the token is what protects it, as with any loopback service that has a + token (`strata_control/owner_transport.py`). The bridge between the app shell and the host (used for the app update) is also loopback and protected by a token. +- **Starting a model and serving never download anything.** Downloads and updates are one explicit step: `strata update`, or "Update + engine" and "Update Strata" in the app's Settings. Models and saved tuning are never replaced by an update. +- **Updates come from a signed feed.** The release publishes `strata-feed.json` and `strata-feed.json.sig` (Ed25519). An installed + Strata checks the signature against the public key it carries (`strata_control/update_keys.json`), refuses a feed older than the last + one it accepted (a replayed old feed) or expired, and checks every engine package against its SHA-256, its signed manifest and the + card in your PC before it test-starts it and switches to it. Any failure keeps the engine you had. The app installer itself is signed + with a separate key (Tauri's minisign key) that the app and the Terminal both check. The private keys are kept offline by the owner. + See [packaging/UPDATES.md](packaging/UPDATES.md). + +### How far to trust `curl | sh` and `irm | iex` + +The Terminal installs with one line: + +```sh +curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh +irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex +``` + +Piping a script into a shell runs whatever the server sends, so it deserves the same care as running any downloaded program. +What the script does is short and written at its top: it fetches the Terminal archive named in the release's `install-manifest.txt`, +checks its SHA-256, unpacks it into your home folder (no administrator rights, nothing outside your home), checks the release's signed feed +with the Terminal it just unpacked and removes it again if that fails, and puts `strata` on your PATH. + +Those checks have a limit. The checksum comes from the same release as the archive, and the public key that checks the feed arrives inside +that archive, so for the first install all trust rests on HTTPS and on the `Niko1221/Strata` GitHub release itself. The checks catch a +damaged or half-finished download and a feed that was not signed by the release key; they do not protect you if the release has been replaced +by someone who controls it. Later updates are checked against the key already on your PC, which is a stronger position. + +If that is not enough: save the script (`curl -fsSLO https://github.com/Niko1221/Strata/releases/latest/download/install.sh`), read it, and +run it from the file; or install the desktop app or build from source instead and check the code you build. + +Strata has not had an outside security audit yet. +What Strata downloads, when it uses the internet, what stays on your PC and how downloads are checked is written up in [docs/SAFETY.md](docs/SAFETY.md). diff --git a/engine/strata/START-HERE.bat b/engine/strata/START-HERE.bat index dfb92feb..5f255c07 100644 --- a/engine/strata/START-HERE.bat +++ b/engine/strata/START-HERE.bat @@ -2,8 +2,13 @@ rem Strata for Windows: the first run installs everything and starts the model; later runs just start it. rem Needs only an NVIDIA or AMD graphics driver. Python is installed for your user account if it is missing (no admin needed). setlocal +rem Python reads and writes text as UTF-8, not in the Windows code page (cp1251, cp866, ...): a folder or user name with Cyrillic or other letters stays intact (#3202). +set "PYTHONUTF8=1" title Strata cd /d "%~dp0" +rem A bundled Python runtime (the python\ folder of the terminal archive) is used when it is there: nothing to find, +rem install or download. SETUP.bat and UPDATE.bat run this file, so they use it too. +if exist "python\python.exe" goto bundled if exist ".venv\Scripts\python.exe" goto run call :findpy @@ -36,6 +41,14 @@ echo Could not create the Python environment in .venv pause exit /b 1 +:bundled +set "PYTHONNOUSERSITE=1" +set "PYTHONHOME=" +set "PYTHONPATH=" +"python\python.exe" setup.py %* +if errorlevel 1 pause +exit /b + :run ".venv\Scripts\python.exe" setup.py %* if errorlevel 1 pause diff --git a/engine/strata/UPDATE.bat b/engine/strata/UPDATE.bat new file mode 100644 index 00000000..c0fd78a1 --- /dev/null +++ b/engine/strata/UPDATE.bat @@ -0,0 +1,82 @@ +@echo off +rem Update Strata without starting the model (#475): the newest code (git pull, when this folder is a git clone), then +rem what START-HERE.bat does before a start - the engine (a new one when this version needs it), the Python packages, +rem each installed model's settings and draft subset. The model files are not touched. Start the model later with +rem START-HERE.bat. Options are passed on to setup.py. The bundled Python (python\ beside this file) is used when +rem there is one: START-HERE.bat, which this file runs, picks it. +setlocal +title Strata - update +cd /d "%~dp0" +rem All of it in one block: cmd reads a .bat file while it runs it, and the git pull can change this very file. +( + if exist ".git" ( + where git >nul 2>nul || ( + echo This folder is a git clone, but git is not on PATH: install Git for Windows ^(winget install Git.Git^) + echo or run "git pull" here yourself, then run UPDATE.bat again. + pause + exit /b 1 + ) + echo Getting the newest Strata ^(git pull^) ... + git pull --ff-only + if errorlevel 1 ( + rem The history was rewritten on 2026-10-06, see #1276: a clone from before has no commit in common with origin/main. + set "REWR=" + git merge-base HEAD origin/main >nul 2>nul + if errorlevel 1 set "REWR=1" + git rev-parse --is-shallow-repository 2>nul | findstr /x true >nul && set "REWR=" + if defined REWR ( + echo. + echo This clone is on the repository's old history ^(cleaned up on 2026-10-06^): it has no commit in common + echo with origin/main, so it cannot be updated by git pull. + set "DIRTY=" + for /f "delims=" %%i in ('git status --porcelain --untracked-files^=no') do set "DIRTY=1" + if defined DIRTY ( + echo You have local changes to tracked files here, so nothing was touched. To move to the new history + echo yourself ^(your untracked files, models and settings stay where they are^): + echo git branch pre-cleanup-backup + echo git stash push + echo git checkout -B main origin/main + echo then run UPDATE.bat again. + pause + exit /b 1 + ) + set "BK=pre-cleanup-backup" + git rev-parse --verify -q refs/heads/pre-cleanup-backup >nul 2>nul && set "BK=pre-cleanup-backup-%RANDOM%" + set "BR=main" + for /f "delims=" %%i in ('git symbolic-ref --short -q HEAD 2^>nul') do set "BR=%%i" + call git branch %%BK%% HEAD + if errorlevel 1 ( + echo Could not make the backup branch: nothing was updated. + pause + exit /b 1 + ) + call git checkout -q -B %%BR%% origin/main + if errorlevel 1 ( + call git branch -D %%BK%% >nul 2>nul + echo. + echo Could not move to the new history ^(the reason is above^): nothing was updated. By hand: + echo git checkout -B main origin/main + pause + exit /b 1 + ) + call echo Moved to the new history. Your old commits are kept in the branch %%BK%%. + echo Untracked files ^(models, settings, the engine^) were not touched. + ) else ( + echo. + echo git pull did not succeed ^(the reason is above^): nothing was updated. Files you changed here can stop it: + echo "git status" lists them. + pause + exit /b 1 + ) + ) + ) else ( + echo This copy of Strata was not made with git, so it cannot fetch new files itself. Download the newest one: + echo https://github.com/Niko1221/Strata/archive/refs/heads/main.zip + echo unzip it anywhere and run START-HERE.bat ^(or UPDATE.bat^) in it: it finds the model files in Strata-data + echo and sets itself up the same way - nothing big is downloaded again. + echo Checking this copy's engine and settings meanwhile ... + ) + call "%~dp0START-HERE.bat" --update %* + if not errorlevel 1 pause + exit /b +) diff --git a/engine/strata/apps/desktop/package-lock.json b/engine/strata/apps/desktop/package-lock.json new file mode 100644 index 00000000..448060e1 --- /dev/null +++ b/engine/strata/apps/desktop/package-lock.json @@ -0,0 +1,232 @@ +{ + "name": "strata-desktop", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "strata-desktop", + "version": "0.1.0", + "devDependencies": { + "@tauri-apps/cli": "2.12.3" + } + }, + "node_modules/@tauri-apps/cli": { + "version": "2.12.3", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli/-/cli-2.12.3.tgz", + "integrity": "sha512-f7/LsY74SVb1ChmOPw1ajOpxii0GSzDAgmWHRci8JUYuuai04rXsSbFobpmB0sP2DdlvMD/B5ZotEn8GOGMRUg==", + "dev": true, + "license": "Apache-2.0 OR MIT", + "bin": { + "tauri": "tauri.js" + }, + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/tauri" + }, + "optionalDependencies": { + "@tauri-apps/cli-darwin-arm64": "2.12.3", + "@tauri-apps/cli-darwin-x64": "2.12.3", + "@tauri-apps/cli-linux-arm-gnueabihf": "2.12.3", + "@tauri-apps/cli-linux-arm64-gnu": "2.12.3", + "@tauri-apps/cli-linux-arm64-musl": "2.12.3", + "@tauri-apps/cli-linux-riscv64-gnu": "2.12.3", + "@tauri-apps/cli-linux-x64-gnu": "2.12.3", + "@tauri-apps/cli-linux-x64-musl": "2.12.3", + "@tauri-apps/cli-win32-arm64-msvc": "2.12.3", + "@tauri-apps/cli-win32-ia32-msvc": "2.12.3", + "@tauri-apps/cli-win32-x64-msvc": "2.12.3" + } + }, + "node_modules/@tauri-apps/cli-darwin-arm64": { + "version": "2.12.3", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-arm64/-/cli-darwin-arm64-2.12.3.tgz", + "integrity": "sha512-xmVNoJOOKzKLj7GLHXmXLimRby9M42aBIJa0sB80N7o24eKV5JiVmToKTRLVH9yhL05GZ/B6rSSOmbzNFJwBAA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-darwin-x64": { + "version": "2.12.3", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-x64/-/cli-darwin-x64-2.12.3.tgz", + "integrity": "sha512-URd+0usfmUQQyb5kNPiKt2OT8gp7oGU7QR+qOppB6e35mpVBFFVNhWc9oWb3p0u71fDJ09DpF4T6m9xYxoIB8g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-arm-gnueabihf": { + "version": "2.12.3", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm-gnueabihf/-/cli-linux-arm-gnueabihf-2.12.3.tgz", + "integrity": "sha512-0kwUVx2LbmOoTRlwF1oDww7th4/NSluv4ZBQ6KRZsFKg4g0TlTcIiJ0VehqkQYUeC9xIT1Mk6XtF52mI155VSQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-arm64-gnu": { + "version": "2.12.3", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-gnu/-/cli-linux-arm64-gnu-2.12.3.tgz", + "integrity": "sha512-gKSGDx6fx+HBLQmG6guChFdisbrCSdx9Yli+j5teOa64gm1CeM+C6NLru5Pj3ZkkEep05BmCFjxvX+cjqAycZQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-arm64-musl": { + "version": "2.12.3", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.12.3.tgz", + "integrity": "sha512-Yr59qMy/gcvAfBuFdCGlAmGiLsYWMFDbsP4bAI6iNBzcJTGrYWZGeiQhGDo29MQwfF/NUBqyM2qljXu5tZ6wjQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-riscv64-gnu": { + "version": "2.12.3", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-riscv64-gnu/-/cli-linux-riscv64-gnu-2.12.3.tgz", + "integrity": "sha512-jKr0/REBMnLKC0OwPQZkyge0mKDaNZ0b/AbfGwVyCgFfwS730EVLfVDo3nt7MUu6jJaytRq08+xSj5qfy+U1+Q==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-x64-gnu": { + "version": "2.12.3", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-gnu/-/cli-linux-x64-gnu-2.12.3.tgz", + "integrity": "sha512-gTkEqJAGCMROGanxHnzaJzQ+/rXl39HWVg0/hDODS1wDWBGqoceqGC6Qm1+mQbyT11xnsB8mKu/gyVID/YpFIw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-x64-musl": { + "version": "2.12.3", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-musl/-/cli-linux-x64-musl-2.12.3.tgz", + "integrity": "sha512-T2dTxL1svRym71fZtaW4pZYXbthbfFsEJr1NeOUg/p7laWXZbUt/8DMSZf8recu9f7+1F/Lv00HtzsEu6vDO9w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-win32-arm64-msvc": { + "version": "2.12.3", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-arm64-msvc/-/cli-win32-arm64-msvc-2.12.3.tgz", + "integrity": "sha512-eoiQwpEZWbpsVHcM9BAzqqe4TCHszvr3rsM7pUQ4ofLK0lF1i1d/jX0Qo5DYMqcrUtwQuDdDuOCbcT0Izf1VwQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-win32-ia32-msvc": { + "version": "2.12.3", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-ia32-msvc/-/cli-win32-ia32-msvc-2.12.3.tgz", + "integrity": "sha512-kE+KUg6Dbbkgvcw0m99wJVIToFQzJqpMBAXah74WqxaLzssNwSTUccrHp6+QVzMhjQP330tvekFmnQF+0NbE6Q==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-win32-x64-msvc": { + "version": "2.12.3", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-x64-msvc/-/cli-win32-x64-msvc-2.12.3.tgz", + "integrity": "sha512-L7wndWAgX2mLW7alswpL3d1R0P9FN2WYBgHaQkAYEBxHHGkY4vFX9CjcRQ1LAxDAMIJxrY7/aDziFJeChS84NQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + } + } +} diff --git a/engine/strata/apps/desktop/package.json b/engine/strata/apps/desktop/package.json new file mode 100644 index 00000000..e66e5fbc --- /dev/null +++ b/engine/strata/apps/desktop/package.json @@ -0,0 +1,20 @@ +{ + "name": "strata-desktop", + "productName": "Strata", + "version": "0.2.5", + "private": true, + "description": "Strata Desktop - local AI, tuned to one model.", + "scripts": { + "build:ui": "npm --prefix ../host run build", + "typecheck:ui": "npm --prefix ../host run typecheck", + "test:ui": "npm --prefix ../host test", + "tauri": "tauri", + "dev": "npm run build:ui && tauri dev", + "build": "npm run build:ui && tauri build", + "build:app": "npm run build:ui && tauri build --bundles app", + "dmg": "npm run build:ui && tauri build --bundles dmg" + }, + "devDependencies": { + "@tauri-apps/cli": "2.12.3" + } +} diff --git a/engine/strata/apps/desktop/scripts/app-close-matrix.py b/engine/strata/apps/desktop/scripts/app-close-matrix.py new file mode 100644 index 00000000..31e65b98 --- /dev/null +++ b/engine/strata/apps/desktop/scripts/app-close-matrix.py @@ -0,0 +1,361 @@ +#!/usr/bin/env python3 +"""The installed Windows app, closed every way, with a stub engine: nothing may be left running. + + python apps/desktop/scripts/app-close-matrix.py --install [--scenarios all] [--report out.json] + +For each case it starts the REAL installed `strata-desktop.exe` (its window opens), loads a stub engine through the host's API +(profile + `runtime start` under Control's owner runtime, exactly the app's path), records every process of the tree (the app, +the host, Control, the owner host, the server, the engine), ends the app one way, and asserts: + * no process of the tree is left, the engine's port is free, the runtime lease can be taken again; + * the engine got the clean stop where the way of closing allows one (normal close, window X); + * the next load of the same slot works (a lost owner's state is cleaned, not a blocker). +It also proves a second launch focuses the open window and starts nothing, and that one app runs two engines and closes both. +Everything per-user lives under a scratch folder; the stub engine is a script. No real engine ever runs. +""" +from __future__ import annotations + +import argparse +import ctypes +import json +import os +import subprocess +import sys +import tempfile +import time +import urllib.error +import urllib.request +from ctypes import wintypes +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[3] +sys.path.insert(0, str(ROOT)) + +import psutil # noqa: E402 + +from strata_control import procs, runtime # noqa: E402 +from tests.terminal.lifecycle_matrix import install_fake_engine, port_open # noqa: E402 + +if os.name != "nt": + raise SystemExit("this matrix drives the Windows installer's app") + +user32 = ctypes.WinDLL("user32", use_last_error=True) +WM_CLOSE = 0x0010 + + +def main_window(pid: int) -> int | None: + found = [] + + @ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM) + def visit(hwnd, _): + owner = wintypes.DWORD() + user32.GetWindowThreadProcessId(hwnd, ctypes.byref(owner)) + if owner.value == pid and user32.IsWindowVisible(hwnd): + buf = ctypes.create_unicode_buffer(256) + user32.GetWindowTextW(hwnd, buf, 256) + if buf.value.strip() == "Strata": + found.append(hwnd) + return True + user32.EnumWindows(visit, 0) + return found[0] if found else None + + +class Scratch: + def __init__(self, root: Path, install: Path): + self.root, self.install = root, install + self.components = root / "components" + self.models = root / "models" + self.mark = root / "mark" + for d in (self.components, self.models, self.mark, root / "local", root / "home", root / "appdata", root / "webview"): + d.mkdir(parents=True, exist_ok=True) + install_fake_engine(self.components) + from tools.strata_tokenizer import BYTE_TO_UNICODE + tok = self.models / "tokenizer" + tok.mkdir() + tokens = [BYTE_TO_UNICODE[i] for i in range(256)] + ["ab", "<|im_start|>", "<|im_end|>", "<|endoftext|>"] + (tok / "vocab.json").write_text(json.dumps({t: i for i, t in enumerate(tokens)})) + (tok / "merges.txt").write_text("a b") + (tok / "token_type.json").write_text(json.dumps([0] * 257 + [3, 3, 3])) + for name in ("stub", "stub2"): + (self.models / f"strata-{name}.json").write_text(json.dumps({ + "exe": "component:strata-engine", "backend": "cuda", "tokenizer": str(tok), "args": [], "cwd": str(root), + "model_name": name, "host": "127.0.0.1", "port": 0})) + self.env = {**os.environ, "STRATA_COMPONENTS_DIR": str(self.components), "STRATA_PROFILE_DIR": str(root / "profiles"), + "STRATA_RUNTIME_DIR": str(root / "runtime"), "STRATA_INSTALL_DIR": str(self.models), + "STRATA_MODELS_DIR": str(root / "models-unused"), "STRATA_ENGINE_BACKEND": "cuda", + "STRATA_HOME": str(root / "home"), "APPDATA": str(root / "appdata"), "LOCALAPPDATA": str(root / "local"), + "WEBVIEW2_USER_DATA_FOLDER": str(root / "webview"), "FAKE_ENGINE_MARK": str(self.mark), + "FAKE_ENGINE_SLOW_STEPS": "0", "PYTHONDONTWRITEBYTECODE": "1"} + self.env.pop("STRATA_API_KEY", None) + for key in ("STRATA_COMPONENTS_DIR", "STRATA_PROFILE_DIR", "STRATA_RUNTIME_DIR", "LOCALAPPDATA", "STRATA_ENGINE_BACKEND", + "STRATA_NO_ACQUIRE", "FAKE_ENGINE_MARK"): + os.environ[key] = self.env.get(key, "1") # this process reads the same runtime and records folders + + +class App: + def __init__(self, scratch: Scratch): + self.s = scratch + self.proc = subprocess.Popen([str(scratch.install / "strata-desktop.exe")], cwd=scratch.install, env=scratch.env, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + self.base = None + + def host(self): + for child in psutil.Process(self.proc.pid).children(recursive=True): + if child.name().lower() == "node.exe": + return child + return None + + def wait_up(self, seconds=90): + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + if self.proc.poll() is not None: + raise RuntimeError(f"the app exited with {self.proc.returncode}") + try: + host = self.host() + if host: + for c in host.net_connections(kind="tcp"): + if c.status == "LISTEN" and c.laddr.ip == "127.0.0.1": + base = f"http://127.0.0.1:{c.laddr.port}" + try: + if urllib.request.urlopen(base + "/api/health", timeout=2).status == 200 and main_window(self.proc.pid): + self.base = base + return + except OSError: + pass + except psutil.Error: + pass + time.sleep(0.5) + raise RuntimeError("the app did not come up") + + def call(self, path, method="GET", body=None): + req = urllib.request.Request(self.base + path, method=method, data=None if body is None else json.dumps(body).encode(), + headers={"content-type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=120) as r: + return json.loads(r.read() or b"null") + except urllib.error.HTTPError as exc: + raise RuntimeError(f"{method} {path} -> {exc.code} {exc.read()[:300]!r}") from None + + def load(self, model, multiple=False): + self.call("/api/native?refresh=1") + started = self.call("/api/native/operations", "POST", {"kind": "load", "args": {"model": model, **({"multiple": True} if multiple else {})}}) + deadline = time.monotonic() + 180 + while time.monotonic() < deadline: + state = self.call("/api/native") + job = next((j for j in state["jobs"] if j["id"] == started["id"]), None) + if job and job["state"] != "running": + if job["state"] != "done": + raise RuntimeError(f"load {model}: {job['state']} {job.get('error')}") + return state + time.sleep(0.3) + raise RuntimeError("load did not finish") + + +def tree_of(app: App, slots=("app-1",)) -> tuple[list[procs.Ident], list[int]]: + idents, ports = [], [] + members = [psutil.Process(app.proc.pid), *psutil.Process(app.proc.pid).children(recursive=True)] + pids = {p.pid for p in members} + for slot in slots: + state = runtime._read_state(slot) + if state: + pids.add(state["host_pid"]) + for r in procs.records(): + if r.get("profile") in slots: # the app's own slots; a Terminal service is not part of the app's tree + pids.add(r["pid"]) + for pid in pids: + token = procs.start_token(pid) + if token: + idents.append(procs.Ident(pid, token, tuple(procs.command_line(pid) or []))) + return idents, ports + + +def survivors(idents): + return [f"{i.pid} {' '.join(i.cmd)[:80]}" for i in idents if procs.start_token(i.pid) == i.token] + + +def wait_gone(idents, seconds): + deadline = time.monotonic() + seconds + left = survivors(idents) + while left and time.monotonic() < deadline: + time.sleep(0.25) + left = survivors(idents) + return left + + +def lease_free() -> bool: + try: + fd = runtime.acquire_activity_lease(shared=False) + except Exception: # noqa: BLE001 + return False + runtime._unlock_file(fd) + os.close(fd) + return True + + +def control(scratch: Scratch, *argv: str, timeout: int = 300) -> dict: + py = scratch.install / "control" / "python" / "python.exe" + out = subprocess.run([str(py), str(scratch.install / "control" / "strata.py"), *argv, "--output", "json"], + env={**scratch.env, "PYTHONNOUSERSITE": "1", "STRATA_NO_ACQUIRE": "1"}, + capture_output=True, text=True, timeout=timeout) + try: + return json.loads(out.stdout) + except ValueError: + return {"ok": False, "raw": out.stdout[-300:] + out.stderr[-300:]} + + +def stop_cli(scratch: Scratch, slot: str) -> dict: + py = scratch.install / "control" / "python" / "python.exe" + out = subprocess.run([str(py), str(scratch.install / "control" / "strata.py"), "runtime", "stop", "--profile", slot, "--wait", "30", + "--output", "json"], env={**scratch.env, "PYTHONNOUSERSITE": "1", "STRATA_NO_ACQUIRE": "1"}, + capture_output=True, text=True, timeout=120) + try: + return json.loads(out.stdout) + except ValueError: + return {"state": "?", "raw": out.stdout[-200:] + out.stderr[-200:]} + + +def case(name: str, install: Path, how: str) -> dict: + with tempfile.TemporaryDirectory(prefix="strata-app-matrix-", ignore_cleanup_errors=True) as tmp: + saved = dict(os.environ) + scratch = Scratch(Path(tmp), install) + app = App(scratch) + problems, note = [], "" + try: + app.wait_up() + slots = ("app-1", "app-2") if how == "two-engines" else ("app-1",) + terminal = None + if how == "window-x-terminal-engine": + # an engine the Terminal started (its own profile, no tie to the app) must survive the app's close + control(scratch, "profile", "create", "terminal-1", "--from-config", str(scratch.models / "strata-stub2.json")) + terminal = control(scratch, "runtime", "start", "--profile", "terminal-1", "--wait", "60") + if terminal.get("state") != "ready": + raise RuntimeError(f"the Terminal's service did not start: {terminal}") + terminal_pids = {r["pid"] for r in procs.records(profile="terminal-1")} | {runtime._read_state("terminal-1")["host_pid"]} + state = app.load("stub") + if how == "two-engines": + state = app.load("stub2", multiple=True) + engine_ports = [i["port"] for i in state["instances"]] + idents, _ = tree_of(app, slots) + kinds = sorted({("engine" if "engine" in " ".join(i.cmd) else "server" if "serve.server" in " ".join(i.cmd) else + "owner" if "strata_control.runtime" in " ".join(i.cmd) else "app" if "strata-desktop" in i.cmd[0].lower() + else "host" if "node" in i.cmd[0].lower() else "other") for i in idents}) + note = f"tree {len(idents)} processes: {', '.join(kinds)}; engine ports {engine_ports}" + t0 = time.monotonic() + if how == "normal-close": + subprocess.run(["taskkill", "/PID", str(app.proc.pid)], capture_output=True) + elif how in ("window-x", "two-engines", "window-x-terminal-engine"): + hwnd = main_window(app.proc.pid) + if not hwnd: + raise RuntimeError("no main window") + user32.PostMessageW(hwnd, WM_CLOSE, 0, 0) + elif how == "kill-app": + subprocess.run(["taskkill", "/F", "/PID", str(app.proc.pid)], capture_output=True) + elif how == "host-crash": + host = app.host() + subprocess.run(["taskkill", "/F", "/PID", str(host.pid)], capture_output=True) + elif how == "second-launch": + second = subprocess.Popen([str(install / "strata-desktop.exe")], cwd=install, env=scratch.env, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + try: + code = second.wait(timeout=30) + except subprocess.TimeoutExpired: + second.kill() + problems.append("the second launch did not exit") + code = None + time.sleep(2) + hosts = [p for p in psutil.process_iter(["name", "pid"]) if p.info["name"].lower() == "node.exe" + and (p.parent() and p.parent().pid == app.proc.pid)] + apps = [p for p in psutil.process_iter(["name"]) if p.info["name"].lower() == "strata-desktop.exe"] + if app.proc.poll() is not None: + problems.append("the first app went away") + if len(apps) != 1: + problems.append(f"{len(apps)} app processes (want 1)") + if len(hosts) != 1: + problems.append(f"{len(hosts)} hosts under the first app (want 1)") + after, _ = tree_of(app, slots) + new = [i for i in after if i.pid not in {x.pid for x in idents}] + if new: + problems.append(f"the second launch started: {[' '.join(i.cmd)[:60] for i in new]}") + note += f"; second launch exit code {code}, app processes {len(apps)}, hosts {len(hosts)}" + subprocess.run(["taskkill", "/PID", str(app.proc.pid)], capture_output=True) + if how == "host-crash": + # the shell and its window stay (nothing here restarts a dead host); the host, Control's owner, the server and + # the engine must not + idents = [i for i in idents if any(k in " ".join(i.cmd) for k in ("strata_control.runtime", "serve.server", "engine", "node.exe"))] + left = wait_gone(idents, 90) + if left: + problems.append(f"processes left: {left}") + for port in engine_ports: + deadline = time.monotonic() + 10 + while port_open(port) and time.monotonic() < deadline: + time.sleep(0.2) + if port_open(port): + problems.append(f"engine port {port} still open") + if terminal is None and not lease_free(): + problems.append("lease still held") + marks = sorted(p.name for p in scratch.mark.iterdir()) + if terminal is not None: + status = control(scratch, "runtime", "status", "--profile", "terminal-1") + alive_pids = [p for p in terminal_pids if procs.start_token(p)] + if status.get("state") != "ready" or len(alive_pids) != len(terminal_pids): + problems.append(f"closing the app disturbed the Terminal's service: {status.get('state')}, alive {alive_pids} of {sorted(terminal_pids)}") + note += f"; the Terminal's service is {status.get('state')} after the app closed" + stopped = control(scratch, "runtime", "stop", "--profile", "terminal-1", "--wait", "30") + if stopped.get("state") != "stopped" or [p for p in terminal_pids if procs.start_token(p)]: + problems.append(f"the Terminal's service did not stop on request: {stopped}") + time.sleep(1) + if not lease_free(): + problems.append("lease still held after the Terminal's service stopped") + if how in ("normal-close", "window-x", "two-engines", "second-launch", "window-x-terminal-engine") and not ({"quit", "eof"} & set(marks)): + problems.append(f"the engine was not stopped the clean way (marks {marks})") + seconds = round(time.monotonic() - t0, 1) + if how == "host-crash": + subprocess.run(["taskkill", "/PID", str(app.proc.pid)], capture_output=True) + note += "; the app shell stays open after a host crash (by design today)" + # the slot must be usable again: stopping a lost owner's slot cleans its state; nothing blocks the next load + for slot in slots: + res = stop_cli(scratch, slot) + already = "not managed or is stopped" in json.dumps(res) # nothing was left to stop: the clean outcome + if res.get("state") not in ("stopped",) and not already: + problems.append(f"runtime stop {slot} after the close: {res}") + if runtime._read_state(slot) is not None: + problems.append(f"state of {slot} left behind") + return {"name": f"app-{how}", "ok": not problems, "problems": problems, "seconds": seconds, "marks": marks, "note": note} + except Exception as exc: # noqa: BLE001 + return {"name": f"app-{how}", "ok": False, "problems": [f"{type(exc).__name__}: {exc}"] + problems, "note": note} + finally: + for p in psutil.process_iter(["name", "exe"]): + try: + if (p.info["exe"] or "").lower().startswith(str(install).lower()): + p.kill() + except psutil.Error: + pass + for r in procs.records(): + try: + psutil.Process(r["pid"]).kill() + except psutil.Error: + pass + os.environ.clear(); os.environ.update(saved) + + +SCENARIOS = ["normal-close", "window-x", "window-x-terminal-engine", "kill-app", "host-crash", "second-launch", "two-engines"] + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--install", required=True) + ap.add_argument("--scenarios", default="all") + ap.add_argument("--report") + a = ap.parse_args() + names = SCENARIOS if a.scenarios == "all" else a.scenarios.split(",") + results = [] + for how in names: + r = case(how, Path(a.install), how) + results.append(r) + print(("PASS " if r["ok"] else "FAIL ") + r["name"], r.get("seconds", ""), r.get("problems") or "", r.get("note", ""), flush=True) + if a.report: + Path(a.report).write_text(json.dumps({"platform": "windows", "engine": "fake", "results": results}, indent=1), encoding="utf-8") + return 0 if all(r["ok"] for r in results) else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/engine/strata/apps/desktop/scripts/cards-e2e.mjs b/engine/strata/apps/desktop/scripts/cards-e2e.mjs new file mode 100644 index 00000000..fe31a7f4 --- /dev/null +++ b/engine/strata/apps/desktop/scripts/cards-e2e.mjs @@ -0,0 +1,110 @@ +#!/usr/bin/env node +/** + * The Graphics cards choice of the app, end to end on a box with two cards, through the installed app layout (packaged host + bundled Control + a real + * engine component): the model list carries the options (one rule, strata_control/gpu_fit.py), a model that fits one card recommends that card, then + * load with ONE card -> answers, only that card holds the model; load with BOTH cards (the layer split) -> answers, both cards hold the model. + * + * node cards-e2e.mjs --install --components > --work \ + * --family qwen --model IQ3_XXS --data [--smi "nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits"] + */ +import { spawn, spawnSync } from 'node:child_process'; +import { existsSync, mkdirSync, readdirSync } from 'node:fs'; +import { createServer } from 'node:net'; +import { join, resolve } from 'node:path'; + +const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]?.startsWith('--') || all[i + 1] === undefined ? true : all[i + 1]]] : acc), [])); +for (const need of ['install', 'components', 'work', 'model']) if (!args[need]) { console.error('missing --' + need); process.exit(2); } +const install = resolve(args.install), work = resolve(args.work), components = resolve(args.components), family = String(args.family ?? 'qwen'), modelId = String(args.model); +const node = join(install, 'node', 'node'), hostEntry = join(install, 'host', 'server', 'index.mjs'); +const dirs = { models: join(work, 'models'), profiles: join(work, 'profiles'), runtime: join(work, 'runtime'), home: join(work, 'home'), xdg: join(work, 'xdg'), appdata: join(work, 'appdata') }; +for (const d of [dirs.models, dirs.home, dirs.xdg, dirs.appdata]) mkdirSync(d, { recursive: true }); +const delay = ms => new Promise(r => setTimeout(r, ms)); +let failed = false; +const record = (name, ok, detail = '') => { if (!ok) failed = true; console.log(`${ok ? 'ok ' : 'FAIL'} ${name}${detail ? ' ' + String(detail).slice(0, 500) : ''}`); }; +const freePort = async () => { const s = createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; }; +const env = { ...process.env, STRATA_COMPONENTS_DIR: components, STRATA_PROFILE_DIR: dirs.profiles, STRATA_RUNTIME_DIR: dirs.runtime, STRATA_INSTALL_DIR: dirs.models, + STRATA_HOME: dirs.home, STRATA_MODELS_DIR: join(work, 'models-unused'), APPDATA: dirs.appdata, XDG_CONFIG_HOME: dirs.xdg, PYTHONDONTWRITEBYTECODE: '1' }; +delete env.STRATA_API_KEY; +const port = await freePort(); +const base = `http://127.0.0.1:${port}`; +const host = spawn(node, [hostEntry], { cwd: join(install, 'host'), stdio: ['ignore', 'pipe', 'pipe'], + env: { ...env, STRATA_PORT: String(port), STRATA_DIST: join(install, 'host', 'dist'), NODE_ENV: 'production', STRATA_PACKAGED: '1', STRATA_REAL_ENGINE: '1', STRATA_NO_ACQUIRE: '1', + STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()) } }); +let hostLog = ''; +host.stdout.on('data', c => { hostLog += c; }); host.stderr.on('data', c => { hostLog += c; }); +const call = async (path, method = 'GET', body) => { + const response = await fetch(base + path, { method, headers: { 'content-type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) }); + return { status: response.status, body: await response.json().catch(() => null) }; +}; +async function waitJob(id, seconds) { + let last = ''; + for (let i = 0; i < seconds * 2; i++) { + const state = (await call('/api/native')).body; + const job = state.jobs.find(j => j.id === id); + if (job && job.summary !== last) { last = job.summary; console.log(' ... ' + String(last).slice(0, 120)); } + if (job && job.state !== 'running') return { job, state }; + await delay(500); + } + throw new Error('operation did not finish'); +} +const smi = () => { + const cmd = String(args.smi ?? 'nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits').split(' '); + const r = spawnSync(cmd[0], cmd.slice(1), { encoding: 'utf8' }); + return (r.stdout ?? '').split('\n').map(s => Number(s.trim())).filter(Number.isFinite); +}; +async function chatPong(instance) { + const chat = await call('/v1/chat/completions', 'POST', { model: instance?.apiModelId ?? modelId.toLowerCase(), max_tokens: 400, stream: false, temperature: 0, messages: [{ role: 'user', content: 'Reply with exactly one word: pong' }] }); + const m = chat.body?.choices?.[0]?.message ?? {}; + return { ok: chat.status === 200 && /pong/i.test(`${m.content ?? ''}`), text: `${m.content ?? ''}`.slice(0, 60), status: chat.status }; +} +async function main() { + let up = false; + for (let i = 0; i < 200 && !up; i++) { try { up = (await fetch(base + '/api/health')).ok; } catch { /* not yet */ } if (!up) await delay(150); } + record('host healthy', up, up ? base : hostLog.slice(-500)); + if (!up) return; + const packages = existsSync(join(components, 'engine')) ? readdirSync(join(components, 'engine')) : []; + record('an engine component is installed', packages.length > 0, packages.join(', ')); + + // ---- the model list carries the choice + const native = (await call('/api/native?refresh=1')).body; + const gpus = native.hardware?.gpus ?? []; + record('the host sees two or more graphics cards', gpus.filter(g => g.usable !== false).length >= 2, JSON.stringify(gpus.map(g => ({ i: g.index, n: g.name, gb: g.vram_gb })))); + const size = native.catalog?.families?.find(f => f.family === family)?.sizes.find(s => s.model === modelId); + const opt = size?.gpu_options; + record('the model list offers the cards choice for this model', !!opt && opt.options.length >= 2, JSON.stringify(opt?.options?.map(o => ({ key: o.key, cards: o.cards, verdict: o.verdict, rec: o.recommended })))); + record('a model that fits one card recommends the single largest card (the split is offered, not forced)', opt?.recommended === 'single' && opt.options.find(o => o.key === 'split'), `recommended=${opt?.recommended}`); + const single = opt?.options.find(o => o.key === 'single')?.cards ?? [0]; + const both = opt?.options.find(o => o.key === 'split')?.cards ?? [0, 1]; + + // ---- Download and prepare with the recommended card + const values = { family, model: modelId, context: 32768, vision: 'no', gpu: single[0], ...(args.data ? { data_dir: resolve(args.data) } : {}) }; + const started = await call('/api/native/operations', 'POST', { kind: 'install', args: values }); + record('the install operation starts', started.status === 200 || started.status === 202, JSON.stringify(started.body).slice(0, 160)); + const done = await waitJob(started.body.id, 3600); + record('Download and prepare finishes', done.job.state === 'done', `${done.job.state} ${done.job.error ?? done.job.summary}`); + const installed = (await call('/api/native?refresh=1')).body.installed?.models?.find(m => String(m.model).toLowerCase() === modelId.toLowerCase()); + const model = installed?.model ?? modelId.toLowerCase(); + + for (const [label, cards] of [['ONE card', single], ['BOTH cards (layer split)', both]]) { + const before = smi(); + const load = await call('/api/native/operations', 'POST', { kind: 'load', args: { model, gpus: cards } }); + const loaded = await waitJob(load.body.id, 900); + const instance = loaded.state.instances[0]; + record(`load with ${label} starts the engine`, loaded.job.state === 'done' && instance?.status === 'ready', `${loaded.job.state} ${loaded.job.error ?? ''}; instance=${instance?.status}; gpus=${JSON.stringify(instance?.gpus)}`); + record(`the instance runs on exactly the chosen card(s)`, JSON.stringify([...(instance?.gpus ?? [])].sort()) === JSON.stringify([...cards].sort()), `want ${JSON.stringify(cards)} got ${JSON.stringify(instance?.gpus)}`); + await delay(3000); + const used = smi(); + const holding = used.map((mb, i) => (mb - (before[i] ?? 0)) > 1000 ? i : -1).filter(i => i >= 0); + record(`only the chosen card(s) hold the model (graphics memory in use: ${used.join(', ')} MiB)`, JSON.stringify(holding) === JSON.stringify([...cards].sort()), `holding ${JSON.stringify(holding)}`); + const pong = await chatPong(instance); + record(`it answers (${label})`, pong.ok, `${pong.status} ${JSON.stringify(pong.text)}`); + const unloaded = await call(`/api/native/instances/${instance?.id}/unload`, 'POST', {}); + record(`unload (${label})`, unloaded.status === 200, unloaded.status); + await delay(4000); + } +} +try { await main(); } catch (e) { record('run', false, e.stack ?? e); } +host.kill(); +await delay(1500); +console.log(failed ? 'CARDS-E2E FAIL' : 'CARDS-E2E PASS'); +process.exit(failed ? 1 : 0); diff --git a/engine/strata/apps/desktop/scripts/fetch-node.ps1 b/engine/strata/apps/desktop/scripts/fetch-node.ps1 new file mode 100644 index 00000000..2d833a9b --- /dev/null +++ b/engine/strata/apps/desktop/scripts/fetch-node.ps1 @@ -0,0 +1,72 @@ +# Fetch and verify the private Node runtime the Windows desktop bundle ships (win-x64). +# +# The PowerShell twin of fetch-node.sh: same pinned version, same SHA-256 pin, same refusal to +# install anything whose digest does not match. Not committed output: node.exe is a ~90 MB binary. +# +# Usage: +# powershell -NoProfile -ExecutionPolicy Bypass -File apps\desktop\scripts\fetch-node.ps1 +# ... -File fetch-node.ps1 -Check # verify what is already installed +# ... -File fetch-node.ps1 -FromFile node.zip # verify and install a zip you already have (offline) +# +# The Node version must satisfy the App Host's own engines.node (>= 24.12.0). +[CmdletBinding()] +param( + [switch]$Check, + [string]$FromFile = '', + [string]$Dest = '' +) +$ErrorActionPreference = 'Stop' + +$NodeVersion = if ($env:STRATA_NODE_VERSION) { $env:STRATA_NODE_VERSION } else { '24.12.0' } +$Target = 'win-x64' +# SHA-256 of node-v24.12.0-win-x64.zip from nodejs.org's SHASUMS256.txt; keep equal to fetch-node.sh. +$Expected = '9c125f61ae947b52e779095830f9cac267846a043ef7192183c84016aaad2812' +if (-not $Dest) { $Dest = Join-Path $PSScriptRoot '..\src-tauri\resources\node' } +$Installed = Join-Path $Dest 'node.exe' + +function Fail([string]$Message) { [Console]::Error.WriteLine("fetch-node: $Message"); exit 1 } + +if ($Check) { + if (-not (Test-Path -LiteralPath $Installed)) { Fail "not installed at $Installed" } + $got = (& $Installed --version).Trim() + Write-Output "fetch-node: $Installed is $got" + if ($got -ne "v$NodeVersion") { Fail "expected v$NodeVersion" } + exit 0 +} + +$Archive = "node-v$NodeVersion-$Target.zip" +$Work = Join-Path ([IO.Path]::GetTempPath()) ("strata-node-" + [Guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory -Path $Work | Out-Null +try { + $Zip = Join-Path $Work $Archive + if ($FromFile) { + Copy-Item -LiteralPath $FromFile -Destination $Zip + } else { + $Url = "https://nodejs.org/dist/v$NodeVersion/$Archive" + Write-Output "fetch-node: $Url" + [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 + $ProgressPreference = 'SilentlyContinue' + Invoke-WebRequest -UseBasicParsing -Uri $Url -OutFile $Zip + } + $Actual = (Get-FileHash -Algorithm SHA256 -LiteralPath $Zip).Hash.ToLowerInvariant() + if ($NodeVersion -ne '24.12.0') { + # another version has no recorded digest: say so rather than implying a verification + [Console]::Error.WriteLine("fetch-node: WARNING - no recorded digest for v$NodeVersion; this download is NOT authenticated.") + [Console]::Error.WriteLine("fetch-node: computed sha256 $Actual - record it in this script and fetch-node.sh.") + } elseif ($Actual -ne $Expected) { + Fail "REFUSING - $Archive hashes $Actual, expected $Expected" + } else { + Write-Output 'fetch-node: sha256 verified against the recorded digest' + } + Add-Type -AssemblyName System.IO.Compression.FileSystem + $zipFile = [IO.Compression.ZipFile]::OpenRead($Zip) + try { + $entry = $zipFile.GetEntry("node-v$NodeVersion-$Target/node.exe") + if (-not $entry) { Fail "node.exe is not inside $Archive" } + New-Item -ItemType Directory -Force -Path $Dest | Out-Null + [IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $Installed, $true) + } finally { $zipFile.Dispose() } + Write-Output "fetch-node: installed at $Installed" +} finally { + Remove-Item -LiteralPath $Work -Recurse -Force -ErrorAction SilentlyContinue +} diff --git a/engine/strata/apps/desktop/scripts/fetch-node.sh b/engine/strata/apps/desktop/scripts/fetch-node.sh new file mode 100755 index 00000000..3a363233 --- /dev/null +++ b/engine/strata/apps/desktop/scripts/fetch-node.sh @@ -0,0 +1,103 @@ +#!/usr/bin/env bash +# Fetch and verify the private Node runtime the desktop bundle ships. +# +# The App Host is an ordinary Node program, and the packaging requirement is that an end user +# supplies no runtime of their own. The desktop bundle therefore carries a pinned standalone Node +# beside the host. +# +# It is NOT committed. It is a ~117 MB platform binary: committing it would bloat every clone, it +# cannot be reviewed in a diff, and it is not source. This script is the reproducible substitute — +# it downloads the official build for the target and refuses to install anything whose SHA-256 does +# not match the recorded digest. +# +# Usage: +# apps/desktop/scripts/fetch-node.sh # host platform +# apps/desktop/scripts/fetch-node.sh --target linux-x64 +# apps/desktop/scripts/fetch-node.sh --check # verify what is already installed +# +# The Node version must satisfy the App Host's own `engines.node` (>= 24.12.0). +set -euo pipefail + +NODE_VERSION="${STRATA_NODE_VERSION:-24.12.0}" +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +DEST="$HERE/../src-tauri/resources/node" + +# Published SHA-256 of each official nodejs.org archive, recorded so a tampered or truncated +# download is refused rather than shipped. Add a row when bumping the version. +# Taken from nodejs.org's own SHASUMS256.txt for v24.12.0, which is published over HTTPS beside +# the archives. Recorded here so the fetch is verified against a value that does not come from the +# same response as the payload. +digest_for() { + case "$1" in + darwin-arm64) echo "319f221adc5e44ff0ed57e8a441b2284f02b8dc6fc87b8eb92a6a93643fd8080" ;; + linux-x64) echo "6159227e0af7d7c3c6bb2fa900452b04a6cb8841a702a79acc613209d70b04d0" ;; + linux-arm64) echo "9b2a2eeb98a8eb37361224e2a1d060300ad2dd143af58dfdb16de785df0f1228" ;; + win-x64) echo "9c125f61ae947b52e779095830f9cac267846a043ef7192183c84016aaad2812" ;; + *) echo "" ;; + esac +} + +target() { + if [ "${1:-}" = "--target" ]; then echo "${2:?--target needs a value}"; return; fi + case "$(uname -s)-$(uname -m)" in + Darwin-arm64) echo darwin-arm64 ;; + Linux-x86_64) echo linux-x64 ;; + Linux-aarch64) echo linux-arm64 ;; + MINGW*|MSYS*|CYGWIN*) echo win-x64 ;; + *) echo "unsupported host: $(uname -s)-$(uname -m)" >&2; exit 2 ;; + esac +} + +TARGET="$(target "$@")" +EXE="node" +case "$TARGET" in win-*) EXE="node.exe" ;; esac +INSTALLED="$DEST/$EXE" + +if [ "${1:-}" = "--check" ]; then + if [ ! -x "$INSTALLED" ]; then echo "fetch-node: not installed at $INSTALLED" >&2; exit 1; fi + got="$("$INSTALLED" --version)" + echo "fetch-node: $INSTALLED is $got" + case "$got" in "v$NODE_VERSION") exit 0 ;; *) echo "fetch-node: expected v$NODE_VERSION" >&2; exit 1 ;; esac +fi + +# The official archive for this target. +case "$TARGET" in + darwin-arm64) ARCHIVE="node-v$NODE_VERSION-darwin-arm64.tar.gz" ;; + darwin-x64) ARCHIVE="node-v$NODE_VERSION-darwin-x64.tar.gz" ;; + linux-x64) ARCHIVE="node-v$NODE_VERSION-linux-x64.tar.gz" ;; + linux-arm64) ARCHIVE="node-v$NODE_VERSION-linux-arm64.tar.gz" ;; + win-x64) ARCHIVE="node-v$NODE_VERSION-win-x64.zip" ;; + *) echo "fetch-node: no archive known for $TARGET" >&2; exit 2 ;; +esac +URL="https://nodejs.org/dist/v$NODE_VERSION/$ARCHIVE" + +EXPECTED="$(digest_for "$TARGET")" +WORK="$(mktemp -d "${TMPDIR:-/tmp}/strata-node.XXXXXX")" # GNU mktemp needs the X template; BSD accepts it too +trap 'rm -rf "$WORK"' EXIT + +echo "fetch-node: $URL" +curl -fsSL -o "$WORK/$ARCHIVE" "$URL" + +ACTUAL="$(shasum -a 256 "$WORK/$ARCHIVE" 2>/dev/null | cut -d' ' -f1 || sha256sum "$WORK/$ARCHIVE" | cut -d' ' -f1)" +if [ -n "$EXPECTED" ]; then + if [ "$ACTUAL" != "$EXPECTED" ]; then + echo "fetch-node: REFUSING — $ARCHIVE hashes $ACTUAL, expected $EXPECTED" >&2 + exit 1 + fi + echo "fetch-node: sha256 verified against the recorded digest" +else + # Without a recorded digest the download cannot be authenticated. Say so loudly and keep the + # computed value so it can be recorded, rather than implying a verification that did not happen. + echo "fetch-node: WARNING — no recorded digest for $TARGET; this download is NOT authenticated." >&2 + echo "fetch-node: computed sha256 $ACTUAL — record it in $(basename "${BASH_SOURCE[0]}") to enable verification." >&2 +fi + +mkdir -p "$DEST" +case "$ARCHIVE" in + *.zip) unzip -q -j "$WORK/$ARCHIVE" "node-v$NODE_VERSION-win-x64/node.exe" -d "$DEST" ;; + *) tar xzf "$WORK/$ARCHIVE" -C "$WORK" + cp "$WORK/node-v$NODE_VERSION-$TARGET/bin/node" "$DEST/node" ;; +esac +chmod +x "$DEST/$EXE" + +echo "fetch-node: installed $("$DEST/$EXE" --version) at $DEST/$EXE" diff --git a/engine/strata/apps/desktop/scripts/first-run-ui.mjs b/engine/strata/apps/desktop/scripts/first-run-ui.mjs new file mode 100644 index 00000000..757905cd --- /dev/null +++ b/engine/strata/apps/desktop/scripts/first-run-ui.mjs @@ -0,0 +1,121 @@ +#!/usr/bin/env node +/** + * The first run of the installed app, headless: the host as the Tauri shell starts it (STRATA_PACKAGED=1, STRATA_NO_ACQUIRE=1, + * the staged Control, nothing installed, nothing in the per-user folders) and Chrome on its onboarding. + * + * node apps/desktop/scripts/first-run-ui.mjs [--control ] [--node ] [--work ] [--shots ] + * + * Checks, one line each (exit 1 if any fails): + * the host answers; /api/native has a real catalog (families with sizes), a recommendation and the GPUs of this PC + * (from Control's bundled installer on Control's Python); the page shows "Let's get started", and after it the model + * list with sizes (no "couldn't show this screen"); no page error; the install plan for the recommended model is a + * plan (nothing is downloaded or started: a plan changes nothing); the spy sees no pip/git/compiler/engine fetch. + * Per-user folders (STRATA_HOME, APPDATA, LOCALAPPDATA, the components and install folders) are all under --work. + * No model is downloaded and no engine runs. + */ +import { spawn } from 'node:child_process'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import { createServer } from 'node:net'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]?.startsWith('--') ? true : all[i + 1]]] : acc), [])); +const here = dirname(fileURLToPath(import.meta.url)); +const repoHost = resolve(here, '../../host'); +const staged = resolve(here, '../src-tauri/resources'); +const control = resolve(args.control ?? join(staged, 'control')); +const nodeExe = resolve(args.node ?? join(staged, 'node', process.platform === 'win32' ? 'node.exe' : 'node')); +const work = resolve(args.work ?? mkdtempSync(join(tmpdir(), 'strata-first-run-'))); +const shots = resolve(args.shots ?? join(work, 'shots')); +mkdirSync(work, { recursive: true }); mkdirSync(shots, { recursive: true }); +const spy = pathToFileURL(join(repoHost, 'tests/helpers/acquire-spy.mjs')).href; +const spyLog = join(work, 'spy.log'); writeFileSync(spyLog, ''); + +const { chromium } = await import(pathToFileURL(join(repoHost, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core')); +const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome', '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'].find(existsSync); + +let failed = false; +const check = (ok, label, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${detail ? ' ' + detail : ''}`); if (!ok) failed = true; }; +const delay = ms => new Promise(r => setTimeout(r, ms)); +const freePort = async () => { const s = createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; }; + +for (const need of [nodeExe, join(control, 'strata.py'), join(repoHost, 'dist', 'index.html')]) if (!existsSync(need)) { console.error(`missing ${need} (run stage-control.py, fetch-node and "npm run build" in apps/host first)`); process.exit(2); } + +const dirs = { home: join(work, 'home'), appdata: join(work, 'appdata'), local: join(work, 'local'), components: join(work, 'local', 'Strata', 'components') }; +for (const d of Object.values(dirs)) mkdirSync(d, { recursive: true }); +const port = await freePort(); +const env = { + ...process.env, + STRATA_PORT: String(port), STRATA_DIST: join(repoHost, 'dist'), STRATA_PACKAGED: '1', STRATA_REAL_ENGINE: '1', STRATA_NO_ACQUIRE: '1', + STRATA_CONTROL_DIR: control, STRATA_HOME: dirs.home, STRATA_MODELS_DIR: join(work, 'models'), STRATA_COMPONENTS_DIR: dirs.components, + APPDATA: dirs.appdata, LOCALAPPDATA: dirs.local, XDG_CONFIG_HOME: join(work, 'xdg'), XDG_DATA_HOME: join(work, 'xdgdata'), + STRATA_PROFILE_DIR: join(work, 'profiles'), STRATA_RUNTIME_DIR: join(work, 'runtime'), ACQUIRE_SPY_LOG: spyLog, +}; +delete env.STRATA_INSTALL_DIR; +mkdirSync(env.STRATA_MODELS_DIR, { recursive: true }); +const host = spawn(nodeExe, [...(args['no-spy'] === undefined ? ['--import', spy] : []), join(repoHost, 'server', 'index.mjs')], { cwd: repoHost, env, stdio: ['ignore', 'pipe', 'pipe'] }); +let hostLog = ''; +host.stdout.on('data', c => { hostLog += c; }); host.stderr.on('data', c => { hostLog += c; }); +const base = `http://127.0.0.1:${port}`; +const api = async (path, init) => { const r = await fetch(base + path, init); return { status: r.status, body: await r.json().catch(() => null) }; }; + +let browser; +try { + let up = false; + for (let i = 0; i < 150 && !up; i++) { try { up = (await api('/api/health')).status === 200; } catch { await delay(200); } } + check(up, 'the packaged host starts', `port ${port}`); + if (!up) throw new Error(hostLog.slice(-2000)); + + const native = await api('/api/native?refresh=1'); + const state = native.body; + check(native.status === 200 && state?.available === true, 'the host reads Control', state?.error ?? ''); + const sizes = (state?.catalog?.families ?? []).reduce((n, f) => n + (f.sizes?.length ?? 0), 0); + check((state?.catalog?.families?.length ?? 0) > 0 && sizes >= 3, 'the catalog has real families and sizes', `${state?.catalog?.families?.length} families, ${sizes} sizes`); + check(!!state?.catalog?.recommendation, 'the catalog has a recommendation', JSON.stringify(state?.catalog?.recommendation ?? null).slice(0, 120)); + check(Array.isArray(state?.hardware?.gpus), 'the hardware lists GPUs', (state?.hardware?.gpus ?? []).map(g => `${g.name} ${g.vram_gb} GB`).join('; ') || 'none on this PC'); + check(state?.installDir && realpathSync.native(state.installDir).toLowerCase().startsWith(realpathSync.native(work).toLowerCase()), 'models go to a writable per-user folder, not the bundle', state?.installDir); + const hw = (await api('/api/hardware')).body; + console.log('info host hardware probe:', JSON.stringify((hw?.gpus ?? []).map(g => ({ name: g.name, backend: g.backend, vramGb: g.vramGb, unified: g.unified })))); + check(!state?.installerError, 'the bundled installer answers', state?.installerError ?? ''); + + browser = await chromium.launch({ executablePath: CHROME, headless: true }); + const page = await browser.newPage({ viewport: { width: 1400, height: 950 } }); + const problems = []; + page.on('pageerror', e => problems.push(`pageerror: ${e.message}`)); + await page.goto(base, { waitUntil: 'domcontentloaded' }); + await page.waitForSelector('text=/Let.s get started|Choose a version|Connect your Strata/i', { timeout: 30000 }).catch(() => {}); + await page.screenshot({ path: join(shots, '1-welcome.png') }); + const broken = await page.locator('text=/couldn.t show this screen/i').count(); + check(broken === 0, 'the first screen renders (not "Strata couldn\'t show this screen")'); + const start = page.getByRole('button', { name: /get started/i }); + check(await start.count() > 0, 'the welcome step offers "Let\'s get started"'); + if (await start.count()) await start.first().click(); + await page.waitForSelector('text=/Choose a version/i', { timeout: 30000 }).catch(() => {}); + await delay(1200); + await page.screenshot({ path: join(shots, '2-models.png') }); + check(await page.locator('text=/couldn.t show this screen/i').count() === 0, 'the model step renders'); + check(await page.getByText(/Choose a version/i).count() > 0, 'the model step lists the versions'); + const labels = await page.locator('[role=radio]').allInnerTexts(); + check(labels.length >= 3, 'the versions are the real catalog\'s sizes', labels.map(l => l.replace(/\s+/g, ' ').slice(0, 40)).join(' | ')); + check(labels.some(l => /\d+\.\d\s*GB/.test(l)), 'each version shows its download size'); + check(problems.length === 0, 'no page error', problems.join('; ')); + + const recommended = state?.catalog?.recommendation; + if (recommended?.model) { + const plan = await api('/api/native/plan', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ family: recommended.family, model: recommended.model, context: recommended.context, data_dir: join(work, 'Strata-data') }) }); + check(plan.status === 200 && !!plan.body?.plan, 'the install plan for the recommended model is a plan (nothing downloaded)', plan.body?.summary?.slice(0, 100) ?? JSON.stringify(plan.body).slice(0, 150)); + check(!existsSync(join(work, 'Strata-data', 'models')), 'a plan wrote no model files'); + } +} catch (error) { + check(false, 'the run', String(error?.message ?? error).slice(0, 600)); +} finally { + await browser?.close().catch(() => {}); + host.kill(); + await new Promise(r => host.once('exit', r)); // only the PID this script started + const attempts = readFileSync(spyLog, 'utf8').split('\n').filter(Boolean); + check(attempts.length === 0, 'the spy saw no pip, git, compiler, engine or internet access', attempts.slice(0, 3).join(' ')); + console.log(`shots in ${shots}`); + if (!args.work) rmSync(work, { recursive: true, force: true, maxRetries: 3 }); +} +process.exit(failed ? 1 : 0); diff --git a/engine/strata/apps/desktop/scripts/flatten-pnpm.mjs b/engine/strata/apps/desktop/scripts/flatten-pnpm.mjs new file mode 100644 index 00000000..403d4df2 --- /dev/null +++ b/engine/strata/apps/desktop/scripts/flatten-pnpm.mjs @@ -0,0 +1,133 @@ +/** + * Turn a pnpm "isolated" node_modules (a virtual store in `.pnpm` full of links) into an ordinary hoisted tree of real folders. + * + * Why: the installer copies the Harness folder file by file. pnpm's layout is thousands of links (junctions on Windows); a copy + * that follows them duplicates every package once per dependent and one that does not breaks on the first dangling link. A hoisted + * tree has each package once (nested only where two versions of the same name are needed), no links, and Node resolves it + * exactly as it resolves any npm install. + * + * Algorithm (the one npm uses, in short): the packages the root names come first, at the top. Then, walking each placed package's + * own dependencies: look the name up from the package's own folder upwards; if the same instance is already visible, nothing to + * do; if a DIFFERENT instance of that name is visible, nest this one inside the dependent; if none is visible, hoist it to the top. + * + * @param {string} out folder holding `node_modules` + * @param {{skip?: RegExp}} [options] package names never copied (the caller removes them anyway) + * @returns {{packages:number, copied:number, nested:number}} + */ +import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync } from 'node:fs'; +import { dirname, join, relative, sep } from 'node:path'; + +export function flattenPnpm(out, { skip = null } = {}) { + const nm = join(out, 'node_modules'); + const store = join(nm, '.pnpm'); + const flatRoot = join(out, 'node_modules.flat'); + rmSync(flatRoot, { recursive: true, force: true }); + mkdirSync(join(flatRoot, 'node_modules'), { recursive: true }); + + const manifest = dir => { try { return JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')); } catch { return null; } }; + const nameOf = dir => manifest(dir)?.name ?? null; + /** + * What makes two instances "the same package": name and version. pnpm keeps one copy per set of peer packages (the same workspace + * package under many hashed folders); in one hoisted tree they are one package. + */ + const identity = dir => { const m = manifest(dir); return m ? `${m.name}@${m.version}` : dir; }; + /** The sibling links of a store instance: its dependencies, by name -> real instance folder. */ + function storeDeps(instance, name) { + const container = name.startsWith('@') ? dirname(dirname(instance)) : dirname(instance); + const found = new Map(); + for (const e of readdirSync(container, { withFileTypes: true })) { + if (e.name === '.bin') continue; + const entries = e.name.startsWith('@') ? readdirSync(join(container, e.name), { withFileTypes: true }).map(x => [`${e.name}/${x.name}`, join(container, e.name, x.name)]) : [[e.name, join(container, e.name)]]; + for (const [dep, p] of entries) { + if (dep === name) continue; + try { if (lstatSync(p).isSymbolicLink() || existsSync(p)) found.set(dep, realpathSync(p)); } catch { /* a dangling link: the package was removed on purpose */ } + } + } + return found; + } + /** Every instance in the store by package name, for packages that arrived without a store entry (copied peers). */ + const byName = new Map(); + if (existsSync(store)) { + for (const id of readdirSync(store, { withFileTypes: true })) { + if (!id.isDirectory()) continue; + const container = join(store, id.name, 'node_modules'); + if (!existsSync(container)) continue; + for (const e of readdirSync(container, { withFileTypes: true })) { + if (e.name === '.bin') continue; + const dirs = e.name.startsWith('@') ? readdirSync(join(container, e.name)).map(x => join(container, e.name, x)) : [join(container, e.name)]; + for (const d of dirs) { + let real; try { real = realpathSync(d); } catch { continue; } + if (!real.startsWith(store)) continue; // a link to a workspace package outside the store is handled through the instance table + const n = nameOf(real); + if (n && !byName.has(n)) byName.set(n, real); + } + } + } + } + + const placed = new Map(); // folder (in the flat tree) -> real instance folder it holds + let copied = 0, nested = 0; + + const visibleFrom = (chain, name) => { + for (const dir of chain) { + const slot = join(dir, 'node_modules', ...name.split('/')); + if (placed.has(slot)) return { slot, instance: placed.get(slot) }; + } + return null; + }; + const copyInto = (slot, instance) => { + mkdirSync(dirname(slot), { recursive: true }); + cpSync(instance, slot, { recursive: true, dereference: true, filter: f => !relative(instance, f).split(sep).includes('node_modules') }); + placed.set(slot, identity(instance)); + copied++; + }; + + const queue = []; // { slotDir (folder of the placed package), chain (folders searched upwards), instance, name } + const rootChain = [flatRoot]; + const place = (name, instance, chain, forceHere) => { + if (skip?.test(name)) return; + const seen = visibleFrom(chain, name); + if (seen && seen.instance === identity(instance)) return; + const hoist = !seen && !forceHere; + const base = hoist ? flatRoot : chain[0]; + const slot = join(base, 'node_modules', ...name.split('/')); + if (placed.has(slot)) return; // another instance already sits where this one would go (it nests below, handled by the caller's chain) + copyInto(slot, instance); + if (!hoist && base !== flatRoot) nested++; + queue.push({ slotDir: slot, chain: [slot, ...(hoist ? rootChain : chain)], instance, name }); + }; + + // 1. the packages the root names + const rootEntries = []; + for (const e of readdirSync(nm, { withFileTypes: true })) { + if (e.name === '.pnpm' || e.name === '.bin' || e.name.startsWith('.')) continue; + const entries = e.name.startsWith('@') ? readdirSync(join(nm, e.name)).map(x => [`${e.name}/${x}`, join(nm, e.name, x)]) : [[e.name, join(nm, e.name)]]; + for (const [name, p] of entries) rootEntries.push([name, p]); + } + for (const [name, p] of rootEntries) { + let real; try { real = realpathSync(p); } catch { continue; } + place(name, real, rootChain, true); + } + // 2. their dependencies, breadth first + while (queue.length) { + const { slotDir, chain, instance, name } = queue.shift(); + let wants; + if (instance.startsWith(store)) wants = storeDeps(instance, name); + else { + // a package copied in without a store entry: its declared requirements, taken from the store by name when not visible yet + const m = manifest(instance) ?? {}; + wants = new Map(); + for (const dep of [...Object.keys(m.dependencies ?? {}), ...Object.keys(m.peerDependencies ?? {}), ...Object.keys(m.optionalDependencies ?? {})]) { + if (visibleFrom(chain, dep)) continue; + const real = byName.get(dep); + if (real) wants.set(dep, real); + } + } + for (const [dep, real] of wants) place(dep, real, chain, false); + } + + rmSync(nm, { recursive: true, force: true }); + renameSync(join(flatRoot, 'node_modules'), nm); + rmSync(flatRoot, { recursive: true, force: true }); + return { packages: placed.size, copied, nested }; +} diff --git a/engine/strata/apps/desktop/scripts/harness-prune.mjs b/engine/strata/apps/desktop/scripts/harness-prune.mjs new file mode 100644 index 00000000..35b81124 --- /dev/null +++ b/engine/strata/apps/desktop/scripts/harness-prune.mjs @@ -0,0 +1,79 @@ +/** + * Which files and folders of the staged Harness are dropped, and the check that nothing the Harness imports is gone. + * + * The 2026-10-17 tester report: on Linux and Mac every agent chat failed ("session/create ... waiting for workflowEngine"). + * Cause: the old rule "drop any folder named after another operating system" also removed the Harness's own JavaScript package + * `@deepseek-ai/dsh-win32-process`. It is plain JS (no binary), and `dsh-subprocess-local` and `dsh-sandbox-local` import it by + * name on every platform, so those two plugins failed to load, and everything waiting on them (shell, subprocess, ptcRuntime, + * workflowEngine) never started. Windows kept it (the rule differs there), so the Windows tests passed. + */ +import { existsSync, readFileSync, readdirSync } from 'node:fs'; +import { join, sep } from 'node:path'; + +export const OTHER_OS = { + win32: /(^|[\\/._-])(darwin|linux|android|freebsd|musl)([\\/._-]|$)/i, + darwin: /(^|[\\/._-])(win32|linux|android|freebsd|musl)([\\/._-]|$)/i, + // Linux: the AppImage bundler (linuxdeploy) resolves the libraries of every ELF file under resources and stops on one it + // cannot satisfy (koffi's musl build wants libc.musl). The app is glibc x86_64, so musl and other-CPU builds are dropped. + linux: /(^|[\\/._-])(win32|darwin|android|freebsd|musl|arm64|aarch64|armv7|arm|ia32|riscv64|ppc64|s390x|loong64)([\\/._-]|$)/i, +}; +const NATIVE_FOLDER = /prebuild|bin|native|platform|-(win32|darwin|linux)/i; + +/** The Harness's own JavaScript packages (`@deepseek-ai/dsh-*`) are code every platform imports by name; never drop one. */ +export function isHarnessCodePackage(path) { + const parts = path.split(sep); + const i = parts.lastIndexOf('@deepseek-ai'); + return i >= 0 && i === parts.length - 2 && parts[i + 1].startsWith('dsh-'); +} + +/** True when the folder `path` (a directory named `name`) is another operating system's prebuilt binary and can go. */ +export function isOtherOsBinaryFolder(platform, name, path) { + const rule = OTHER_OS[platform] ?? OTHER_OS.linux; + if (isHarnessCodePackage(path)) return false; + return rule.test(name) && NATIVE_FOLDER.test(path); +} + +/** Imports the Windows copy (which works) is also without: browser-side or dev-only bundles, and the document converter the app drops on purpose. */ +const KNOWN_ABSENT = new Set([ + '@deepseek-ai/libreoffice-kit', '@deepseek-ai/dsh-client-ui-dockkit', '@deepseek-ai/dsh-client-web', + '@deepseek-ai/dsh-experimental-webworker-runtime', '@deepseek-ai/dsh-remote-mock', '@deepseek-ai/dsh-client-test-runtime', +]); + +function jsFiles(dir, out = []) { + for (const e of readdirSync(dir, { withFileTypes: true })) { + const p = join(dir, e.name); + if (e.isSymbolicLink()) continue; + if (e.isDirectory()) jsFiles(p, out); + else if (/\.(m?js|cjs)$/.test(e.name)) out.push(p); + } + return out; +} + +/** + * Every bare `@deepseek-ai/` the staged Harness's own packages import (static `from "x"` and `import("x")`) must exist + * in the staged node_modules. Returns the list of `{from, missing}` problems (empty = good). Plugins that are only loaded on + * another platform still count: Node resolves a static import whether or not the code runs. + */ +export function missingHarnessImports(harnessDir) { + const scope = join(harnessDir, 'node_modules', '@deepseek-ai'); + if (!existsSync(scope)) return [{ from: scope, missing: '@deepseek-ai (no installed packages)' }]; + const problems = []; + const seen = new Set(); + const re = /(?:from|import)\s*\(?\s*["'](@deepseek-ai\/[^"'/]+)(?:\/[^"']*)?["']/g; + for (const pkg of readdirSync(scope)) { + const lib = join(scope, pkg, 'lib'); + if (!existsSync(lib)) continue; + for (const file of jsFiles(lib)) { + const text = readFileSync(file, 'utf8'); + for (const m of text.matchAll(re)) { + const name = m[1]; + const key = `${pkg}>${name}`; + if (seen.has(key) || KNOWN_ABSENT.has(name)) continue; + seen.add(key); + if (!existsSync(join(harnessDir, 'node_modules', ...name.split('/'))) + && !existsSync(join(scope, pkg, 'node_modules', ...name.split('/')))) problems.push({ from: `${pkg}`, missing: name }); + } + } + } + return problems; +} diff --git a/engine/strata/apps/desktop/scripts/installed-flow.mjs b/engine/strata/apps/desktop/scripts/installed-flow.mjs new file mode 100644 index 00000000..7816b5c2 --- /dev/null +++ b/engine/strata/apps/desktop/scripts/installed-flow.mjs @@ -0,0 +1,310 @@ +#!/usr/bin/env node +/** + * Prove the INSTALLED app layout can start and stop an engine with nothing acquired, using a stub engine. + * + * node apps/desktop/scripts/installed-flow.mjs --install [--work ] [--spy ] + * + * It starts the installed host with the installed node.exe exactly as the Tauri shell does (STRATA_PACKAGED=1, + * STRATA_NO_ACQUIRE=1; Control found beside the host), against a scratch component folder holding a fake engine + * package and a scratch install folder holding one run config. Everything per-user (profiles, runtime state, host data, + * components) lives under --work, so the real profile of whoever runs this is never read or written. + * + * Steps (each one printed, the run exits 1 if any fails): + * host health, Control status (engine usable, acquiring forbidden), models from Control, load through the host + * (profile + `runtime start` under the owner runtime), a chat answer from the stub engine, a second client attaches to + * the same owner/instance, unload stops it, no engine for this PC is a notice with nothing started, the Tauri-style + * clean shutdown stops the engines the host started, a hard-killed host takes its engine with it. + * With --spy the host runs under tests/helpers/acquire-spy.mjs and the run fails on any attempt to reach the internet or + * run an installer. + * + * REAL mode (a test box with a GPU): --components > --models .json + * whose engine is "component:strata-engine"> --model [--backend cuda]. The same host and Control, a real engine and a + * real model: load, a real answer, ownership, unload, the missing-engine notice, load again, clean shutdown. The stub-only + * steps (the marker file, the hard-kill report) are left out. + */ +import { spawn, spawnSync } from 'node:child_process'; +import { createHash, randomBytes } from 'node:crypto'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync, chmodSync } from 'node:fs'; +import { createServer } from 'node:net'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { pathToFileURL } from 'node:url'; + +const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]?.startsWith('--') || all[i + 1] === undefined ? true : all[i + 1]]] : acc), [])); +if (!args.install) { console.error('usage: installed-flow.mjs --install [--work ] [--spy ]'); process.exit(2); } +const install = resolve(args.install); +const isWin = process.platform === 'win32'; +const node = join(install, 'node', isWin ? 'node.exe' : 'node'); +const hostEntry = join(install, 'host', 'server', 'index.mjs'); +const controlDir = join(install, 'control'); +const python = isWin ? join(controlDir, 'python', 'python.exe') : join(controlDir, 'python', 'bin', 'python3'); +const real = !!args.components; +const modelId = String(args.model ?? 'stub'); +const work = resolve(args.work ?? mkdtempSync(join(tmpdir(), 'strata-installed-flow-'))); +mkdirSync(work, { recursive: true }); +const dirs = { components: real ? resolve(args.components) : join(work, 'components'), models: real ? resolve(args.models) : join(work, 'models'), profiles: join(work, 'profiles'), runtime: join(work, 'runtime'), home: join(work, 'home') }; +// the runtime and profile folders are created by Control itself, with the owner-only ACL it insists on +for (const [name, d] of Object.entries(dirs)) if (!['runtime', 'profiles'].includes(name) && !(real && ['components', 'models'].includes(name))) mkdirSync(d, { recursive: true }); + +const steps = []; +const record = (name, ok, detail = '') => { steps.push({ name, ok: !!ok, detail: String(detail) }); console.log(`${ok ? 'ok ' : 'FAIL'} ${name}${detail ? ' ' + detail : ''}`); }; +const delay = ms => new Promise(r => setTimeout(r, ms)); +const freePort = async () => { const s = createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; }; +const sha = buf => createHash('sha256').update(buf).digest('hex'); + +// ------------------------------------------------------------------------------ fixtures +const baseEnv = { + ...process.env, + STRATA_COMPONENTS_DIR: dirs.components, STRATA_PROFILE_DIR: dirs.profiles, STRATA_RUNTIME_DIR: dirs.runtime, + STRATA_INSTALL_DIR: dirs.models, STRATA_ENGINE_BACKEND: String(args.backend ?? 'cuda'), STRATA_HOME: dirs.home, STRATA_MODELS_DIR: real ? join(work, 'models-unused') : dirs.models, + APPDATA: join(work, 'appdata'), XDG_CONFIG_HOME: join(work, 'xdg'), PYTHONDONTWRITEBYTECODE: '1', +}; +delete baseEnv.STRATA_API_KEY; +mkdirSync(baseEnv.APPDATA, { recursive: true }); +const mark = join(work, 'engine-ran.json'); + +const FAKE_ENGINE = `import os, sys, json +from pathlib import Path +Path(os.environ['FAKE_ENGINE_MARK']).write_text(json.dumps({'pid': os.getpid(), 'script': os.path.abspath(__file__), 'argv': sys.argv[1:]})) +print('READY 4096 stop', flush=True) +for line in sys.stdin: + if line.strip() == 'QUIT': break + if line.startswith(('GEN ', 'BGEN ')): + slot = int(line.split()[1]) if line.startswith('BGEN ') else None + print('T 97', flush=True) + print('DONE 1 1 1.0 1.0 length 0 0 0', flush=True) + if slot is not None: print(f'BADM {slot} 0', flush=True) +`; + +function installFakeEngine() { + const platform = isWin ? 'windows-x86_64' : 'linux-x86_64'; + const folder = join(dirs.components, 'engine', `0.1.45-${platform}-cuda`); + mkdirSync(folder, { recursive: true }); + writeFileSync(join(folder, 'engine_main.py'), FAKE_ENGINE); + const entry = isWin ? 'engine.cmd' : 'engine'; + writeFileSync(join(folder, entry), isWin + ? `@echo off\r\n"${python}" "%~dp0engine_main.py" %*\r\n` + : `#!/bin/sh\nexec "${python}" "$(dirname "$0")/engine_main.py" "$@"\n`); + if (!isWin) chmodSync(join(folder, entry), 0o755); + const files = [entry, 'engine_main.py'].map(p => { const b = readFileSync(join(folder, p)); return { path: p, sha256: sha(b), bytes: b.length }; }); + writeFileSync(join(folder, 'engine-component.json'), JSON.stringify({ schema_version: 1, id: 'strata-engine', version: '0.1.45', platform, backend: 'cuda', entrypoint: entry, files })); + return folder; +} + +function makeTokenizerAndConfig() { + const tok = join(dirs.models, 'tokenizer'); + mkdirSync(tok, { recursive: true }); + const script = `import json, sys\nfrom tools.strata_tokenizer import BYTE_TO_UNICODE\ntok = sys.argv[1]\ntokens = [BYTE_TO_UNICODE[i] for i in range(256)] + ['ab', '<|im_start|>', '<|im_end|>', '<|endoftext|>']\njson.dump({t: i for i, t in enumerate(tokens)}, open(tok + '/vocab.json', 'w'))\nopen(tok + '/merges.txt', 'w').write('a b')\njson.dump([0] * 257 + [3, 3, 3], open(tok + '/token_type.json', 'w'))\n`; + const done = spawnSync(python, ['-c', script, tok], { cwd: controlDir, env: { ...baseEnv, PYTHONNOUSERSITE: '1' }, encoding: 'utf8' }); + if (done.status !== 0) throw new Error('tokenizer fixture failed: ' + done.stderr); + writeFileSync(join(dirs.models, 'strata-stub.json'), JSON.stringify({ exe: 'component:strata-engine', backend: 'cuda', tokenizer: tok, args: [], cwd: work, model_name: 'stub', host: '127.0.0.1', port: 0 })); +} + +const control = (...argv) => spawnSync(python, [join(controlDir, 'strata.py'), ...argv, '--output', 'json'], { cwd: controlDir, env: { ...baseEnv, PYTHONNOUSERSITE: '1', STRATA_NO_ACQUIRE: '1', FAKE_ENGINE_MARK: mark }, encoding: 'utf8', timeout: 120000 }); +const controlJson = (...argv) => { const r = control(...argv); let json = null; try { json = JSON.parse(r.stdout.slice(r.stdout.indexOf('{'))); } catch { /* not json */ } return { code: r.status, json, text: r.stdout + r.stderr }; }; +const alive = pid => { try { process.kill(pid, 0); return true; } catch { return false; } }; + +// ------------------------------------------------------------------------------ the host +let host = null, port = 0, base = '', spyLog = null, shutdownToken = randomBytes(32).toString('hex'); +async function startHost() { + port = await freePort(); base = `http://127.0.0.1:${port}`; + const hostArgs = [...(args.spy ? ['--import', pathToFileURL(resolve(args.spy)).href] : []), hostEntry]; + if (args.spy) { spyLog = join(work, 'acquire-spy.log'); writeFileSync(spyLog, ''); } + host = spawn(node, hostArgs, { + cwd: join(install, 'host'), stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, + env: { ...baseEnv, STRATA_PORT: String(port), STRATA_DIST: join(install, 'host', 'dist'), NODE_ENV: 'production', STRATA_PACKAGED: '1', STRATA_REAL_ENGINE: '1', + STRATA_NO_ACQUIRE: '1', STRATA_SHUTDOWN_TOKEN: shutdownToken, FAKE_ENGINE_MARK: mark, STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()), + ...(spyLog ? { ACQUIRE_SPY_LOG: spyLog } : {}) }, + }); + let log = ''; + host.stdout.on('data', c => { log += c; }); host.stderr.on('data', c => { log += c; }); + host.hostLog = () => log; + for (let i = 0; i < 200; i++) { try { if ((await fetch(base + '/api/health')).ok) return true; } catch { /* not yet */ } await delay(150); } + return false; +} +/** The host started the way the Tauri shell starts it, by a stand-in shell (a node process) that can then be killed hard. */ +async function startHostViaShell() { + port = await freePort(); base = `http://127.0.0.1:${port}`; + const spec = { command: node, args: [hostEntry], options: { + cwd: join(install, 'host'), stdio: 'ignore', windowsHide: true, + env: { ...baseEnv, STRATA_PORT: String(port), STRATA_DIST: join(install, 'host', 'dist'), NODE_ENV: 'production', STRATA_PACKAGED: '1', STRATA_REAL_ENGINE: '1', + STRATA_NO_ACQUIRE: '1', STRATA_SHUTDOWN_TOKEN: shutdownToken, STRATA_EXIT_WITH_PARENT: '1', FAKE_ENGINE_MARK: mark, + STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()) } } }; + const shell = spawn(node, ['-e', "const s=JSON.parse(process.env.HOST_SPEC);const c=require('node:child_process').spawn(s.command,s.args,s.options);console.log(c.pid);setInterval(()=>{},1000);"], + { env: { ...process.env, HOST_SPEC: JSON.stringify(spec) }, stdio: ['ignore', 'pipe', 'inherit'], windowsHide: true }); + const hostPid = await new Promise(r => shell.stdout.once('data', c => r(Number(String(c).trim())))); + for (let i = 0; i < 200; i++) { try { if ((await fetch(base + '/api/health')).ok) return { shell, hostPid }; } catch { /* not yet */ } await delay(150); } + return { shell, hostPid, failed: true }; +} +const call = async (path, method = 'GET', body) => { + const response = await fetch(base + path, { method, headers: { 'content-type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) }); + return { status: response.status, body: await response.json().catch(() => null) }; +}; +async function waitJob(id, seconds = 120) { + for (let i = 0; i < seconds * 5; i++) { + const state = (await call('/api/native')).body; + const job = state.jobs.find(j => j.id === id); + if (job && job.state !== 'running') return { job, state }; + await delay(200); + } + throw new Error('operation did not finish'); +} +async function stopHost(hard = false) { + if (!host || host.exitCode !== null) return; + if (hard) { if (isWin) spawnSync('taskkill', ['/PID', String(host.pid), '/T', '/F'], { windowsHide: true }); else host.kill('SIGKILL'); } + else host.kill(); + for (let i = 0; i < 100 && host.exitCode === null; i++) await delay(100); +} + +async function main() { + for (const need of [node, hostEntry, python, join(controlDir, 'strata.py')]) if (!existsSync(need)) { record('installed layout', false, `missing ${need}`); return; } + record('installed layout', true, install); + if (real) { + const packages = existsSync(join(dirs.components, 'engine')) ? readdirSync(join(dirs.components, 'engine')) : []; + record('fixtures', packages.length > 0 && existsSync(join(dirs.models, `strata-${modelId}.json`)), `engine package(s) ${packages.join(', ')} in ${dirs.components}; run config strata-${modelId}.json in ${dirs.models}`); + } else { + installFakeEngine(); + makeTokenizerAndConfig(); + record('fixtures', true, `stub engine package in ${dirs.components}; run config strata-stub.json`); + } + + if (!(await startHost())) { record('host healthy', false, host.hostLog().slice(-600)); return; } + record('host healthy', true, base); + + const status = (await call('/api/control/status')).body; + record('Control status: bundled, engine usable, acquiring forbidden', status.control?.python?.startsWith(controlDir) && status.engine?.usable === true && status.acquisition?.forbidden === true, + `python=${status.control?.python}; engine=${status.engine?.engine?.version}; forbidden=${status.acquisition?.forbidden}`); + + const native = (await call('/api/native?refresh=1')).body; + const model = native.installed?.models?.find(m => m.model === modelId); + record('models come from Control', native.available && model?.ready === true && native.packaged === true, `available=${native.available}; model ready=${model?.ready}; ${native.summary ?? native.error}`); + + // ---- load + const started = (await call('/api/native/operations', 'POST', { kind: 'load', args: { model: modelId } })).body; + const loaded = await waitJob(started.id, 400); + const instance = loaded.state.instances[0]; + record('load through the host starts the engine under Control', loaded.job.state === 'done' && instance?.status === 'ready', `job=${loaded.job.state} ${loaded.job.error ?? ''}; instance=${instance?.status}`); + let ran = existsSync(mark) ? JSON.parse(readFileSync(mark, 'utf8')) : null; + if (real) { + const listed = spawnSync('ps', ['-eo', 'pid,args'], { encoding: 'utf8' }).stdout.split('\n').filter(l => l.includes(`${dirs.components}/engine/`) && l.includes('--serve')); + ran = listed.length ? { pid: Number(listed[0].trim().split(/\s+/)[0]), script: listed[0].trim().split(/\s+/)[1] } : null; + record('the engine process running is the binary from the component folder', !!ran, listed[0] ? listed[0].trim().slice(0, 160) : 'no engine process under the component folder'); + } else { + record('the engine that ran is the one in the component folder', ran && ran.script.toLowerCase().startsWith(dirs.components.toLowerCase()), ran?.script ?? 'engine never ran'); + } + + const runtime = controlJson('runtime', 'status', '--profile', 'app-1'); + record('a second client sees the same owner and instance (ownership)', runtime.json?.state === 'ready' && !!runtime.json.owner_id && !!runtime.json.instance_id && runtime.json.host_pid !== host.pid, + `state=${runtime.json?.state}; owner=${String(runtime.json?.owner_id).slice(0, 8)}; instance=${String(runtime.json?.instance_id).slice(0, 8)}; owner host pid ${runtime.json?.host_pid} is not the app host (${host.pid})`); + + // ---- answer + const chat = await call('/v1/chat/completions', 'POST', real + ? { model: instance?.apiModelId ?? modelId, messages: [{ role: 'user', content: 'Reply with exactly one word: pong' }], max_tokens: 200, temperature: 0, reasoning_effort: 'none', stream: false } + : { model: instance?.apiModelId ?? modelId, messages: [{ role: 'user', content: 'hi' }], max_tokens: 4, stream: false }); + const message = chat.body?.choices?.[0]?.message ?? {}; + const answer = `${message.content ?? ''}${message.reasoning_content ?? ''}`; // the stub emits token 97 ("a"); the server files it as reasoning + record(real ? 'the real model answers through the host (the answer text is checked)' : 'the engine answers through the host (the stub token, not an error)', + chat.status === 200 && (real ? /pong/i.test(answer) : answer === 'a'), `status=${chat.status}; answer=${JSON.stringify(answer.slice(0, 200))}${chat.status === 200 ? '' : ' ' + JSON.stringify(chat.body).slice(0, 160)}`); + + // ---- unload + const unloaded = await call(`/api/native/instances/${instance.id}/unload`, 'POST', {}); + await delay(500); + const after = controlJson('runtime', 'status', '--profile', 'app-1'); + for (let i = 0; i < 100 && ran && alive(ran.pid); i++) await delay(100); // a real engine takes a moment to release the GPU + record('unload stops the engine', unloaded.status === 200 && after.json?.state === 'stopped' && (!ran || !alive(ran.pid)), `status=${unloaded.status}; runtime=${after.json?.state}; engine pid ${ran?.pid} alive=${ran ? alive(ran.pid) : 'n/a'}`); + + // ---- no engine for this PC + const hidden = join(dirs.components, real ? 'engine.hidden-by-flow' : 'engine.gone'); + renameSync(join(dirs.components, 'engine'), hidden); + rmSync(mark, { force: true }); + const missing = await waitJob((await call('/api/native/operations', 'POST', { kind: 'load', args: { model: modelId } })).body.id); + record('no engine for this PC is a notice and nothing is started', missing.job.state === 'error' && /No engine for this PC/.test(missing.job.error) && /never downloads/.test(missing.job.error) && !existsSync(mark), + `${missing.job.state}: ${String(missing.job.error).slice(0, 160)}`); + const refused = await waitJob((await call('/api/native/operations', 'POST', { kind: 'install', args: { family: 'qwen', model: 'IQ2_XS' } })).body.id); + record('installing from the app is refused (Terminal only)', refused.job.state === 'error' && /Terminal/.test(refused.job.error), refused.job.error); + const binary = await call('/api/engine/binary', 'POST'); + record('the llama.cpp download route is refused', binary.status === 409 && /never downloads/.test(binary.body?.error ?? ''), `${binary.status} ${binary.body?.error}`); + + // ---- clean shutdown (what the Tauri shell does on exit) + renameSync(hidden, join(dirs.components, 'engine')); + rmSync(mark, { force: true }); + const again = await waitJob((await call('/api/native/operations', 'POST', { kind: 'load', args: { model: modelId } })).body.id, 400); + let ran2 = existsSync(mark) ? JSON.parse(readFileSync(mark, 'utf8')) : null; + if (real) { + const listed = spawnSync('ps', ['-eo', 'pid,args'], { encoding: 'utf8' }).stdout.split('\n').filter(l => l.includes(`${dirs.components}/engine/`) && l.includes('--serve')); + ran2 = listed.length ? { pid: Number(listed[0].trim().split(/\s+/)[0]) } : null; + } + record('load again after the engine package returns', again.job.state === 'done', again.job.error ?? ''); + const wrong = await fetch(base + '/api/control/shutdown', { method: 'POST', headers: { 'x-strata-shutdown': 'nope' } }); + record('shutdown without the shell\'s secret is refused', wrong.status === 403, String(wrong.status)); + const exited = new Promise(r => host.once('exit', code => r(code))); + const stopping = await fetch(base + '/api/control/shutdown', { method: 'POST', headers: { 'x-strata-shutdown': shutdownToken } }); + const code = await Promise.race([exited, delay(90000).then(() => 'timeout')]); + for (let i = 0; i < 100 && ran2 && alive(ran2.pid); i++) await delay(100); + const final = controlJson('runtime', 'status', '--profile', 'app-1'); + record('clean shutdown stops the engine the app started and exits', stopping.status === 202 && code === 0 && final.json?.state === 'stopped' && (!ran2 || !alive(ran2.pid)), `status=${stopping.status}; host exit=${code}; runtime=${final.json?.state}; engine alive=${ran2 ? alive(ran2.pid) : 'n/a'}`); + + // ---- hard kill: an engine whose app host dies ends with it (the owner follows the host: runtime start --die-with-pid) + if (!(await startHost())) { record('host restarts', false, host.hostLog().slice(-400)); return; } + await call('/api/native?refresh=1'); + rmSync(mark, { force: true }); + const third = await waitJob((await call('/api/native/operations', 'POST', { kind: 'load', args: { model: modelId } })).body.id, 400); + let ran3 = existsSync(mark) ? JSON.parse(readFileSync(mark, 'utf8')) : null; + if (real) { + const listed = spawnSync('ps', ['-eo', 'pid,args'], { encoding: 'utf8' }).stdout.split('\n').filter(l => l.includes(`${dirs.components}/engine/`) && l.includes('--serve')); + ran3 = listed.length ? { pid: Number(listed[0].trim().split(/\s+/)[0]) } : null; + record('(real) the engine is up before the host is killed', !!ran3, listed[0] ? listed[0].trim().slice(0, 120) : 'no engine process'); + } + await stopHost(true); + for (let i = 0; i < 600 && ran3 && alive(ran3.pid); i++) await delay(100); // the owner notices within a second, drains, stops + const orphan = controlJson('runtime', 'status', '--profile', 'app-1'); + record('a hard-killed app host takes its engine with it', third.job.state === 'done' && (!ran3 || !alive(ran3.pid)), `engine alive=${ran3 ? alive(ran3.pid) : 'n/a'}; runtime=${orphan.json?.state ?? orphan.json?.error?.message}`); + const cleanup = controlJson('runtime', 'stop', '--profile', 'app-1'); + record('nothing is left to stop afterwards', /stopped|not managed/.test(JSON.stringify(cleanup.json)) && controlJson('runtime', 'status', '--profile', 'app-1').json?.state === 'stopped', JSON.stringify(cleanup.json).slice(0, 160)); + + // ---- the shell itself is killed (what the desktop shell's crash or kill looks like to the host): the host leaves, and + // its engine with it, with nothing announced. Windows also has the job object; this is the path that works everywhere. + const started2 = await startHostViaShell(); + if (started2.failed) { record('host starts under a stand-in shell', false, ''); try { started2.shell.kill('SIGKILL'); } catch { /* gone */ } } + else { + await call('/api/native?refresh=1'); + rmSync(mark, { force: true }); + const fourth = await waitJob((await call('/api/native/operations', 'POST', { kind: 'load', args: { model: modelId } })).body.id, 400); + let ran4 = existsSync(mark) ? JSON.parse(readFileSync(mark, 'utf8')) : null; + if (real) { + const listed = spawnSync('ps', ['-eo', 'pid,args'], { encoding: 'utf8' }).stdout.split('\n').filter(l => l.includes(`${dirs.components}/engine/`) && l.includes('--serve')); + ran4 = listed.length ? { pid: Number(listed[0].trim().split(/\s+/)[0]) } : null; + } + if (isWin) spawnSync('taskkill', ['/PID', String(started2.shell.pid), '/F'], { windowsHide: true }); else started2.shell.kill('SIGKILL'); + for (let i = 0; i < 100 && alive(started2.hostPid); i++) await delay(100); + const hostGone = !alive(started2.hostPid); + for (let i = 0; i < 900 && ran4 && alive(ran4.pid); i++) await delay(100); + const engineGone = !ran4 || !alive(ran4.pid); + record('a killed shell takes the host and its engine with it', fourth.job.state === 'done' && hostGone && engineGone, + `host pid ${started2.hostPid} gone=${hostGone}; engine pid ${ran4?.pid} gone=${engineGone}; runtime=${controlJson('runtime', 'status', '--profile', 'app-1').json?.state}`); + controlJson('runtime', 'stop', '--profile', 'app-1'); + } + + await finishSpy(); +} + +async function finishSpy() { + if (spyLog) { + const attempts = readFileSync(spyLog, 'utf8').split('\n').filter(Boolean); + record('no acquisition attempt by the host during the whole run (spy)', attempts.length === 0, attempts.join(' | ')); + } +} + +try { await main(); } +catch (error) { record('flow', false, error.stack ?? error.message); } +finally { + try { const hid = join(dirs.components, 'engine.hidden-by-flow'); if (real && existsSync(hid) && !existsSync(join(dirs.components, 'engine'))) renameSync(hid, join(dirs.components, 'engine')); } catch { /* reported by the run */ } + await stopHost(true); + controlJson('runtime', 'stop', '--profile', 'app-1'); + controlJson('runtime', 'stop', '--profile', 'app-2'); +} +const failed = steps.filter(s => !s.ok); +writeFileSync(join(work, 'installed-flow.json'), JSON.stringify({ ok: failed.length === 0, install, work, steps }, null, 1)); +console.log(`\n${steps.length - failed.length}/${steps.length} ok; report ${join(work, 'installed-flow.json')}`); +if (!args.keep && !args.work && failed.length === 0) { try { rmSync(work, { recursive: true, force: true }); } catch { /* leave it */ } } +process.exit(failed.length ? 1 : 0); diff --git a/engine/strata/apps/desktop/scripts/installer-mockups.mjs b/engine/strata/apps/desktop/scripts/installer-mockups.mjs new file mode 100644 index 00000000..cc7a3c8f --- /dev/null +++ b/engine/strata/apps/desktop/scripts/installer-mockups.mjs @@ -0,0 +1,73 @@ +#!/usr/bin/env node +/** + * Mock-ups of the Windows installer in Strata's own look: four screens (welcome, where, installing, done), light and dark, drawn with + * the app's built CSS (apps/host/dist) and brand files, then photographed with Chrome. Nothing here is built or shipped: it is what + * the owner is shown before an installer is chosen. + * + * node apps/desktop/scripts/installer-mockups.mjs [--out ] + */ +import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]]] : acc), [])); +const here = dirname(fileURLToPath(import.meta.url)); +const host = resolve(here, '../../host'); +const out = resolve(args.out ?? join(here, '../installer-mockups')); +mkdirSync(out, { recursive: true }); +const dist = join(host, 'dist'); +const css = readdirSync(join(dist, 'assets')).filter(f => f.endsWith('.css')).map(f => readFileSync(join(dist, 'assets', f), 'utf8')).join('\n'); +const logo = theme => readFileSync(join(dist, 'brand', `strata-lockup-${theme}.svg`), 'utf8'); +const { chromium } = await import(pathToFileURL(join(host, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core')); +const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome'].find(existsSync); + +const check = ''; +const folder = ''; + +const screens = { + welcome: theme => `
+

State of the art. At home.

Strata runs AI on your own computer.
Setting it up takes a few minutes.

+
${check}Private${check}Fast${check}Easy to use
+
Installs for you only. No administrator needed.
`, + where: theme => `
+

Where should Strata go?

This is the right place for most people.

+
${folder}
Your Strata folderC:\\Users\\Alex\\AppData\\Local\\Strata
+

About 310 MB. Your models and chats are kept somewhere else and are never removed by an update.

+
`, + installing: theme => `
+

Installing Strata…

Copying the app and its engine room. You can keep working meanwhile.

+
+
62% · 190 / 310 MB
About 1 min left
+
Next: choose your first model inside Strata.
`, + done: theme => `
+

Strata is ready.

Open it to pick your first model. Strata downloads it for you and gets it ready.

+
A shortcut was added to your Start menu and desktop.
`, +}; + +const page = (name, theme) => `
Strata setup– ☐ ✕
+
${screens[name](theme)}
`; + +const browser = await chromium.launch({ executablePath: CHROME, headless: true }); +const written = []; +for (const theme of ['light', 'dark']) { + for (const name of Object.keys(screens)) { + const tab = await browser.newPage({ viewport: { width: 860, height: 620 }, deviceScaleFactor: 1 }); + await tab.setContent(page(name, theme)); + await tab.waitForTimeout(250); + const file = join(out, `${name}-${theme}.png`); + await tab.screenshot({ path: file }); + written.push(file); + await tab.close(); + } +} +await browser.close(); +console.log(written.join('\n')); diff --git a/engine/strata/apps/desktop/scripts/local-gguf-e2e.mjs b/engine/strata/apps/desktop/scripts/local-gguf-e2e.mjs new file mode 100644 index 00000000..32e49fa7 --- /dev/null +++ b/engine/strata/apps/desktop/scripts/local-gguf-e2e.mjs @@ -0,0 +1,126 @@ +#!/usr/bin/env node +/** + * "Use your own GGUF" end to end on a box, through the installed app layout (packaged host + bundled Control + a real engine component): + * preview a folder of a supported model, preview an unsupported GGUF (must be refused in plain terms), prepare the supported one + * (pack, from the folder, nothing copied), load it, get a chat answer, unload, shut down, and check nothing is left running. + * + * node local-gguf-e2e.mjs --root /data/ui4-e2e --good /data/141-gyro/models/IQ2_XS --bad /data/ui4-e2e/bad [--context 8192] [--backend cuda|metal] + * (the app folder is /app: node/, host/, control/ ...; /components gets the engine, from /app/engine-bundle when the app carries one) + */ +import { spawn, spawnSync } from 'node:child_process'; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { createServer } from 'node:net'; +import { join, resolve } from 'node:path'; + +const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]]] : acc), [])); +const root = resolve(args.root); +const good = args.good, bad = args.bad; +const context = Number(args.context ?? 8192); +const app = join(root, 'app'); +const dirs = { components: join(root, 'components'), install: join(root, 'install'), profiles: join(root, 'profiles'), runtime: join(root, 'runtime'), home: join(root, 'home'), xdg: join(root, 'xdg'), appdata: join(root, 'appdata') }; +for (const d of [dirs.install, dirs.home, dirs.xdg, dirs.appdata]) mkdirSync(d, { recursive: true }); +const delay = ms => new Promise(r => setTimeout(r, ms)); +const steps = []; +let failed = false; +const record = (name, ok, detail = '') => { steps.push({ name, ok: !!ok, detail: String(detail).slice(0, 400) }); console.log(`${ok ? 'ok ' : 'FAIL'} ${name}${detail ? ' ' + String(detail).slice(0, 300) : ''}`); if (!ok) failed = true; }; +const freePort = async () => { const s = createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; }; + +const env = { ...process.env, STRATA_COMPONENTS_DIR: dirs.components, STRATA_PROFILE_DIR: dirs.profiles, STRATA_RUNTIME_DIR: dirs.runtime, STRATA_INSTALL_DIR: dirs.install, STRATA_HOME: dirs.home, STRATA_MODELS_DIR: join(root, 'Strata-data'), STRATA_ENGINE_BACKEND: args.backend ?? 'cuda', XDG_CONFIG_HOME: dirs.xdg, APPDATA: dirs.appdata, PYTHONDONTWRITEBYTECODE: '1' }; +delete env.STRATA_API_KEY; +const port = await freePort(); +const base = `http://127.0.0.1:${port}`; +const host = spawn(join(app, 'node', 'node'), [join(app, 'host', 'server', 'index.mjs')], { cwd: join(app, 'host'), stdio: ['ignore', 'pipe', 'pipe'], detached: false, + env: { ...env, STRATA_PORT: String(port), STRATA_DIST: join(app, 'host', 'dist'), NODE_ENV: 'production', STRATA_PACKAGED: '1', STRATA_REAL_ENGINE: '1', STRATA_NO_ACQUIRE: '1', STRATA_EXIT_WITH_PARENT: '1', + STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()), STRATA_WORKSPACE: join(root, 'workspace') } }); +mkdirSync(join(root, 'workspace'), { recursive: true }); +let hostLog = ''; host.stdout.on('data', c => { hostLog += c; }); host.stderr.on('data', c => { hostLog += c; }); +const call = async (path, method = 'GET', body) => { const r = await fetch(base + path, { method, headers: { 'content-type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) }); return { status: r.status, body: await r.json().catch(() => null) }; }; +async function waitJob(id, seconds) { + const until = Date.now() + seconds * 1000; + let last = ''; + while (Date.now() < until) { + const state = (await call('/api/native')).body; + const job = state.jobs.find(j => j.id === id); + if (job && job.state !== 'running') return { job, state }; + if (job && job.summary !== last) { last = job.summary; console.log(' ...', String(job.summary).slice(0, 140)); } + await delay(2000); + } + throw new Error('operation did not finish in time'); +} +const engineProcs = () => spawnSync('ps', ['-eo', 'pid,args'], { encoding: 'utf8' }).stdout.split('\n').filter(l => l.includes(join(dirs.components, 'engine')) && /\/strata( |$)/.test(l)); + +async function main() { + let up = false; + for (let i = 0; i < 200 && !up; i++) { try { up = (await fetch(base + '/api/health')).ok; } catch { await delay(150); } } + record('host healthy', up, up ? base : hostLog.slice(-500)); + if (!up) return; + let status = (await call('/api/control/status')).body; + for (let i = 0; i < 180 && status?.engineSetup; i++) { await delay(1000); status = (await call('/api/control/status')).body; } // the engine that came with the app is copied on the first start + record('Control status: bundled, engine usable', status?.engine?.usable === true, `engine=${status?.engine?.engine?.version} ${status?.engine?.notice ?? ''}`); + await call('/api/native?refresh=1'); + + // ---- the unsupported GGUF: a plain refusal + const badPreview = await call('/api/native/local/preview', 'POST', { path: bad }); + const badIssues = badPreview.body?.preview?.issues ?? badPreview.body?.issues ?? []; + const badStatus = badPreview.body?.preview?.file_set_status; + console.log(' bad preview:', badPreview.status, JSON.stringify(badPreview.body).slice(0, 400)); + record('an unsupported GGUF is refused, nothing adopted', badPreview.status === 200 ? (badStatus !== 'plausible' || !badPreview.body.preview.candidate_selection) : badPreview.status >= 400, `status=${badPreview.status}; file_set_status=${badStatus}; issues=${JSON.stringify(badIssues)}`); + + // ---- the supported folder + const goodPreview = await call('/api/native/local/preview', 'POST', { path: good }); + const selection = goodPreview.body?.preview?.candidate_selection; + console.log(' good preview:', JSON.stringify(goodPreview.body).slice(0, 500)); + record('a folder of a supported model is recognised', goodPreview.status === 200 && goodPreview.body?.preview?.file_set_status === 'plausible' && !!selection, `family=${selection?.family}; model=${selection?.model}; files=${goodPreview.body?.preview?.file_count}`); + if (!selection || args.only === 'preview') return; + + // ---- prepare (what the page's button does): install from the folder, nothing copied or downloaded + const native0 = (await call('/api/native?refresh=1')).body; + const catalogSize = native0.catalog?.families?.find(f => f.family === selection.family)?.sizes.find(s => s.model === selection.model); + record('the catalog lists the recognised version', !!catalogSize, catalogSize ? `id=${catalogSize.id}` : `no ${selection.family}/${selection.model} in the catalog`); + const started = await call('/api/native/operations', 'POST', { kind: 'install', args: { family: selection.family, model: selection.model, gguf_dir: good, context, vision: 'no' } }); + record('prepare starts', started.status < 300 && !!started.body?.id, `status=${started.status} ${JSON.stringify(started.body).slice(0, 200)}`); + if (!started.body?.id) return; + const prepared = await waitJob(started.body.id, 3600); + record('prepare finishes', prepared.job.state === 'done', `${prepared.job.state}: ${prepared.job.error ?? prepared.job.summary}`); + if (prepared.job.state !== 'done') return; + const native1 = (await call('/api/native?refresh=1')).body; + const modelId = catalogSize?.id ?? `${selection.family === 'qwen' ? '' : selection.family + '-'}${String(selection.model).toLowerCase()}`; + const entry = native1.installed?.models?.find(m => m.model === modelId); + record('the model is ready and points at the folder, not a copy', entry?.ready === true, `model=${modelId}; ready=${entry?.ready}; dataFolder=${entry?.dataFolder}`); + if (!entry?.ready) return; + + // ---- load + const load = await call('/api/native/operations', 'POST', { kind: 'load', args: { model: modelId } }); + const loaded = await waitJob(load.body.id, 1800); + const instance = loaded.state.instances[0]; + record('load starts the engine from the component folder', loaded.job.state === 'done' && instance?.status === 'ready', `job=${loaded.job.state} ${loaded.job.error ?? ''}; instance=${instance?.status}`); + if (instance?.status !== 'ready') return; + record('one engine process is running', engineProcs().length === 1, engineProcs().map(l => l.trim().slice(0, 140)).join(' | ')); + + // ---- a chat answer, checked + const chat = await fetch(base + '/api/chat/stream', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ sessionId: 'e2e-chat', message: 'Reply with exactly one word: pong', history: [], nativeModelId: instance.id, thinking: 'Off', agent: false, workspaceId: null }) }); + let text = '', done = null; + for await (const chunk of chat.body) { + for (const line of Buffer.from(chunk).toString('utf8').split('\n')) { + if (!line.trim()) continue; + try { const f = JSON.parse(line); if (f.type === 'delta') text += f.text ?? ''; if (f.type === 'done') done = f; if (f.type === 'error') text += ` [error: ${f.message}]`; } catch { /* partial line */ } + } + } + record('the model answers through the app (the answer text is checked)', chat.status === 200 && /pong/i.test(text), `status=${chat.status}; answer=${JSON.stringify(text.slice(0, 120))}; tokensOut=${done?.tokensOut}; tps=${done?.tps}`); + + // ---- unload, shutdown, nothing left + const unload = await call(`/api/native/instances/${instance.id}/unload`, 'POST'); + await delay(3000); + record('unload stops the engine', unload.status < 300 && engineProcs().length === 0, `status=${unload.status}; engines left=${engineProcs().length}`); +} + +try { await main(); } catch (e) { record('the flow', false, e?.stack ?? e); } +host.kill(); +for (let i = 0; i < 100 && host.exitCode === null; i++) await delay(100); +if (host.exitCode === null) host.kill('SIGKILL'); +await delay(2000); +const left = spawnSync('ps', ['-eo', 'pid,args'], { encoding: 'utf8' }).stdout.split('\n').filter(l => (l.includes(dirs.install) || l.includes(join(app, 'host'))) && !l.includes('ps -eo')); +record('nothing of this run is left running', left.length === 0, left.join(' | ').slice(0, 300)); +writeFileSync(join(root, 'e2e-result.json'), JSON.stringify({ steps, hostLogTail: hostLog.slice(-2000) }, null, 1)); +console.log(failed ? 'FAILED' : 'ALL OK'); +process.exit(failed ? 1 : 0); diff --git a/engine/strata/apps/desktop/scripts/make-dmg.sh b/engine/strata/apps/desktop/scripts/make-dmg.sh new file mode 100755 index 00000000..909579f8 --- /dev/null +++ b/engine/strata/apps/desktop/scripts/make-dmg.sh @@ -0,0 +1,59 @@ +#!/usr/bin/env bash +# Build the Strata DMG without a Finder session. +# +# Tauri's default DMG step runs an AppleScript that asks Finder to arrange the window (icon +# positions, background). Finder AppleEvents time out in a non-GUI or sandboxed context — observed +# here as `Finder got an error: AppleEvent timed out. (-1712)` — so the default path cannot be +# relied on for an automated build. The upstream `create-dmg` script already supports exactly this +# case via `--skip-jenkins`, which produces a plain, correct DMG with the app and the Applications +# drop link and no cosmetic arrangement. +# +# Usage: scripts/make-dmg.sh [output.dmg] +set -euo pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +DESKTOP="$(cd "$HERE/.." && pwd)" +BUNDLE="$DESKTOP/src-tauri/target/release/bundle" +APP="$BUNDLE/macos/Strata.app" +VERSION="$(grep -m1 '^version = ' "$DESKTOP/src-tauri/Cargo.toml" | cut -d'"' -f2)" # the one place the app version is written +OUT="${1:-$BUNDLE/dmg/Strata_${VERSION}_aarch64.dmg}" + +if [ ! -d "$APP" ]; then + echo "error: $APP does not exist; run 'cargo tauri build --bundles app' first" >&2 + exit 1 +fi + +WORK="$(mktemp -d -t strata-dmg)" +trap 'rm -rf "$WORK"' EXIT + +# A staging folder is what create-dmg copies into the image: the app, and nothing else. +# +# The Applications drop link is created by `--app-drop-link` below. Adding one here as well makes +# create-dmg fail with "File exists", because it links into the volume it is assembling. +mkdir -p "$WORK/stage" +cp -R "$APP" "$WORK/stage/" + +# Reuse Tauri's vendored create-dmg if the bundler left it behind, otherwise take it from the +# bundle cache. Building it yourself is not necessary and not expected. +SCRIPT="$BUNDLE/dmg/bundle_dmg.sh" +if [ ! -x "$SCRIPT" ]; then + echo "error: $SCRIPT not found; run 'cargo tauri build --bundles dmg' once to vendor it" >&2 + exit 1 +fi + +mkdir -p "$(dirname "$OUT")" +rm -f "$OUT" + +# --skip-jenkins: no Finder AppleScript. Everything else is the same code path Tauri uses. +"$SCRIPT" \ + --volname "Strata $VERSION" \ + --volicon "$BUNDLE/macos/Strata.app/Contents/Resources/Strata.icns" \ + --app-drop-link 400 200 \ + --skip-jenkins \ + --no-internet-enable \ + "$OUT" "$WORK/stage" + +echo +echo "built: $OUT" +ls -lh "$OUT" | awk '{print "size: " $5}' +shasum -a 256 "$OUT" diff --git a/engine/strata/apps/desktop/scripts/make-icons.mjs b/engine/strata/apps/desktop/scripts/make-icons.mjs new file mode 100644 index 00000000..411e4b97 --- /dev/null +++ b/engine/strata/apps/desktop/scripts/make-icons.mjs @@ -0,0 +1,78 @@ +#!/usr/bin/env node +/** + * The app and installer icon, refined from the existing Strata mark (apps/host/public/brand/strata-mark-*.svg and the current + * icons/icon.png): the same three rounded bars on the same dark tile, in the same colours. Nothing is redrawn. What changes is + * how it is cut for small sizes: at 16-48 px the bars are snapped to whole pixels and made a little bolder and wider so they + * stay crisp instead of blurring; from 64 px up the geometry is the mark's own proportions. + * + * node apps/desktop/scripts/make-icons.mjs [--out ] writes icon-.png for every size and icon.ico + */ +import { existsSync, mkdirSync, writeFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]]] : acc), [])); +const here = dirname(fileURLToPath(import.meta.url)); +const host = resolve(here, '../../host'); +const out = resolve(args.out ?? join(here, '../src-tauri/icons')); +mkdirSync(out, { recursive: true }); +const { chromium } = await import(pathToFileURL(join(host, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core')); +const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome'].find(existsSync); + +const TILE = '#161a1d', LIGHT = '#eef1f3', GREEN = '#34d399'; // the colours of the current icon.png + +/** Integer geometry for the small sizes: bars on whole pixels, centred. Returns [{x,y,w,h,fill}]. */ +function hinted(size) { + const bar = Math.max(2, Math.round(size * 0.14)), gap = Math.max(2, Math.round(size * 0.1)), mid = bar + 1; + const total = 2 * bar + mid + 2 * gap, top = Math.floor((size - total) / 2); + const even = w => (w % 2 === size % 2 ? w : w + 1); + const wide = even(Math.round(size * 0.5)), long = even(Math.round(size * 0.76)); + return [ + { x: (size - wide) / 2, y: top, w: wide, h: bar, fill: LIGHT }, + { x: (size - long) / 2, y: top + bar + gap, w: long, h: mid, fill: GREEN }, + { x: (size - wide) / 2, y: top + bar + gap + mid + gap, w: wide, h: bar, fill: LIGHT }, + ]; +} +/** The mark's own proportions (from icon.png at 512): bars 34% / 50% / 34% wide, 9% high, on a tile with 21.5% corners. */ +function proportional(size) { + const k = size / 512; + return [ + { x: 170 * k, y: 156 * k, w: 173 * k, h: 46 * k, fill: LIGHT }, + { x: 128 * k, y: 232 * k, w: 256 * k, h: 48 * k, fill: GREEN }, + { x: 170 * k, y: 309 * k, w: 173 * k, h: 46 * k, fill: LIGHT }, + ]; +} +function svg(size) { + const small = size <= 48; + const bars = (small ? hinted(size) : proportional(size)); + const radius = small ? Math.round(size * 0.22) : size * 0.215; + const rects = bars.map(b => ``).join(''); + return `${rects}`; +} + +const SIZES = [16, 20, 24, 32, 40, 48, 64, 96, 128, 256, 512, 1024]; +const browser = await chromium.launch({ executablePath: CHROME, headless: true }); +const png = {}; +for (const size of SIZES) { + const page = await browser.newPage({ viewport: { width: size, height: size }, deviceScaleFactor: 1 }); + await page.setContent(`${svg(size)}`); + png[size] = await page.screenshot({ omitBackground: true, clip: { x: 0, y: 0, width: size, height: size } }); + await page.close(); + writeFileSync(join(out, `icon-${size}.png`), png[size]); +} +await browser.close(); + +// The .ico: one PNG image per size (16-256), the sizes Windows asks for at 100-250% scaling. +const ICO = [16, 20, 24, 32, 40, 48, 64, 96, 128, 256]; +const head = Buffer.alloc(6); head.writeUInt16LE(0, 0); head.writeUInt16LE(1, 2); head.writeUInt16LE(ICO.length, 4); +let offset = 6 + 16 * ICO.length; +const entries = [], blobs = []; +for (const size of ICO) { + const data = png[size], e = Buffer.alloc(16); + e.writeUInt8(size === 256 ? 0 : size, 0); e.writeUInt8(size === 256 ? 0 : size, 1); e.writeUInt8(0, 2); e.writeUInt8(0, 3); + e.writeUInt16LE(1, 4); e.writeUInt16LE(32, 6); e.writeUInt32LE(data.length, 8); e.writeUInt32LE(offset, 12); + offset += data.length; entries.push(e); blobs.push(data); +} +writeFileSync(join(out, 'icon.ico'), Buffer.concat([head, ...entries, ...blobs])); +writeFileSync(join(out, 'icon.png'), png[512]); +console.log('icons in', out, ICO.join(',')); diff --git a/engine/strata/apps/desktop/scripts/make-installer-images.mjs b/engine/strata/apps/desktop/scripts/make-installer-images.mjs new file mode 100644 index 00000000..f12d6cc1 --- /dev/null +++ b/engine/strata/apps/desktop/scripts/make-installer-images.mjs @@ -0,0 +1,66 @@ +#!/usr/bin/env node +/** + * The installer's pictures, drawn from the app's own design: the light surface and ink colours of the app (src/styles tokens), the + * brand lockup and mark files, GT Walsheim Bold for the words (baked into the pictures, because NSIS cannot use a web font). + * + * node apps/desktop/scripts/make-installer-images.mjs [--out ] [--preview ] + * + * Writes sidebar.bmp (164x314, the welcome and finish pages) and header.bmp (150x57, the other pages) as 24-bit BMPs, and with + * --preview the same as PNGs at 3x. + */ +import { spawnSync } from 'node:child_process'; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { tmpdir } from 'node:os'; + +const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]]] : acc), [])); +const here = dirname(fileURLToPath(import.meta.url)); +const host = resolve(here, '../../host'); +const out = resolve(args.out ?? join(here, '../src-tauri/nsis')); +mkdirSync(out, { recursive: true }); +const { chromium } = await import(pathToFileURL(join(host, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core')); +const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome'].find(existsSync); +const font = pathToFileURL(join(host, 'public/fonts/GTWalsheimPro-Bold.woff2')).href; +const fontMedium = pathToFileURL(join(host, 'public/fonts/GTWalsheimPro-Medium.woff2')).href; +const lockup = readFileSync(join(host, 'public/brand/strata-lockup-light.svg'), 'utf8'); +const mark = readFileSync(join(host, 'public/brand/strata-mark-light.svg'), 'utf8'); + +// the app's light tokens +const SURFACE = '#f9fafb', INK = '#171b1e', MUTED = '#5b646b', ACCENT = '#10b981', LINE = '#e3e8ea'; +const css = `@font-face{font-family:GT;font-weight:700;src:url(${font})}@font-face{font-family:GT;font-weight:500;src:url(${fontMedium})} +*{box-sizing:border-box}body{margin:0;font-family:GT,'Segoe UI',sans-serif;color:${INK};background:${SURFACE}}`; + +const pages = { + sidebar: { w: 164, h: 314, html: `
+
${lockup.replace(' +
+
State of
the art.
At home.
+
AI on your own computer.
Private. Fast. Easy.
+
+
` }, + header: { w: 150, h: 57, html: `
${lockup.replace('` }, +}; + +const browser = await chromium.launch({ executablePath: CHROME, headless: true }); +const work = join(tmpdir(), 'strata-installer-images'); mkdirSync(work, { recursive: true }); +for (const [name, page] of Object.entries(pages)) { + for (const scale of [1, 3]) { + const file = join(work, `${name}.html`); + writeFileSync(file, `${page.html}`); + const tab = await browser.newPage({ viewport: { width: page.w, height: page.h }, deviceScaleFactor: scale }); + await tab.goto(pathToFileURL(file).href); + await tab.evaluate(() => document.fonts.ready); + await tab.waitForTimeout(200); + const png = join(work, `${name}@${scale}.png`); + await tab.screenshot({ path: png, clip: { x: 0, y: 0, width: page.w, height: page.h } }); + await tab.close(); + if (scale === 3 && args.preview) { mkdirSync(resolve(args.preview), { recursive: true }); writeFileSync(join(resolve(args.preview), `${name}.png`), readFileSync(png)); } + } +} +await browser.close(); +// 24-bit BMP, the format NSIS wants: render at 3x, shrink with a good filter +const py = `import sys\nfrom PIL import Image\nfor name in ('sidebar','header'):\n im = Image.open(sys.argv[1] + '/' + name + '@3.png').convert('RGB')\n w, h = im.width // 3, im.height // 3\n im.resize((w, h), Image.LANCZOS).save(sys.argv[2] + '/' + name + '.bmp', 'BMP')\n`; +const done = spawnSync('python', ['-c', py, work, out], { encoding: 'utf8' }); +if (done.status !== 0) { console.error(done.stderr); process.exit(1); } +console.log('wrote', join(out, 'sidebar.bmp'), join(out, 'header.bmp')); diff --git a/engine/strata/apps/desktop/scripts/make-tester-readme.sh b/engine/strata/apps/desktop/scripts/make-tester-readme.sh new file mode 100644 index 00000000..e38103c8 --- /dev/null +++ b/engine/strata/apps/desktop/scripts/make-tester-readme.sh @@ -0,0 +1,85 @@ +#!/usr/bin/env bash +# Write a tester's README with the checksums and sizes of the files it names, computed from the files themselves. +# +# apps/desktop/scripts/make-tester-readme.sh